An open-source, faster Devin alternative
TypeScript
feat(cli): add offline Flue artifact builder
Igor Zalutski90f522ef3f13
diff --git a/cmd/oc/internal/commands/agent_build.go b/cmd/oc/internal/commands/agent_build.gonew file mode 100644index 00000000..2dda6158--- /dev/null+++ b/cmd/oc/internal/commands/agent_build.go@@ -0,0 +1,72 @@+package commands++import (+ "encoding/json"+ "fmt"+ "os"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/fluebuild"+ "github.com/spf13/cobra"+)++const offlineCommandAnnotation = "opencomputer.dev/offline"++var agentBuildCmd = &cobra.Command{+ Use: "build",+ Short: "Build a Flue deployment artifact without deploying it",+ Long: "Validate and build a Flue repository into bundle.tgz and deployment.json.\n\n" ++ "This command does not fetch source, install dependencies, authenticate, upload,\n" ++ "or deploy. Run npm ci before a full build. --check-only validates source and\n" ++ "configuration without executing repository code or requiring node_modules.",+ Example: " oc agent build --dir . --target cloudflare --output /tmp/flue-build --json\n" ++ " oc agent build --dir . --check-only --json",+ Args: cobra.NoArgs,+ Annotations: map[string]string{offlineCommandAnnotation: "true"},+ RunE: func(cmd *cobra.Command, _ []string) error {+ dir, _ := cmd.Flags().GetString("dir")+ target, _ := cmd.Flags().GetString("target")+ output, _ := cmd.Flags().GetString("output")+ checkOnly, _ := cmd.Flags().GetBool("check-only")+ if !checkOnly && output == "" {+ return fmt.Errorf("--output is required unless --check-only is set")+ }++ result, err := fluebuild.Build(cmd.Context(), fluebuild.Options{+ Dir: dir,+ Target: target,+ OutputDir: output,+ BuilderVersion: Version,+ CheckOnly: checkOnly,+ })+ if err != nil {+ return err+ }+ if jsonOutput {+ encoder := json.NewEncoder(os.Stdout)+ encoder.SetEscapeHTML(false)+ return encoder.Encode(result.Deployment)+ }+ if checkOnly {+ fmt.Printf("Valid Flue entrypoint %s (%s, %s/%s)\n",+ result.Deployment.Flue.Entrypoint,+ result.Deployment.Model,+ result.Deployment.Runtime.Family,+ result.Deployment.Runtime.Type)+ return nil+ }+ fmt.Printf("Built %s and %s in %s (%s, %d bytes)\n",+ fluebuild.BundleFilename,+ fluebuild.DeploymentFilename,+ output,+ result.Deployment.Bundle.Digest,+ result.Deployment.Bundle.SizeBytes)+ return nil+ },+}++func init() {+ agentBuildCmd.Flags().String("dir", ".", "Flue repository root")+ agentBuildCmd.Flags().String("target", fluebuild.TargetCloudflare, "Build target")+ agentBuildCmd.Flags().String("output", "", "Directory for bundle.tgz and deployment.json")+ agentBuildCmd.Flags().Bool("check-only", false, "Validate without executing repository code")+}diff --git a/cmd/oc/internal/commands/agent_deploy.go b/cmd/oc/internal/commands/agent_deploy.goindex d909e7dc..56c25327 100644--- a/cmd/oc/internal/commands/agent_deploy.go+++ b/cmd/oc/internal/commands/agent_deploy.go@@ -610,6 +610,7 @@ func shortDigest(d string) string {}func registerAgentDeploy() {+ agentCmd.AddCommand(agentBuildCmd)agentDeployCmd.Flags().String("agent", "", "Target agent id or name (else the manifest's [agent].id / name)")agentDeployCmd.Flags().Bool("no-activate", false, "Create the revision without activating it (stage)")agentDeployCmd.Flags().String("idempotency-key", "", "CI-safe key: a retry with the same key returns the same deployment")diff --git a/cmd/oc/internal/commands/agent_deploy_flue.go b/cmd/oc/internal/commands/agent_deploy_flue.goindex 35f3b3d7..0814adf8 100644--- a/cmd/oc/internal/commands/agent_deploy_flue.go+++ b/cmd/oc/internal/commands/agent_deploy_flue.go@@ -14,63 +14,18 @@ package commandsimport ("bytes""context"- "encoding/json"+ "errors""fmt""io"- "io/fs""net/http""os"- "os/exec"- pathpkg "path"- "path/filepath"- "regexp"- "strings""time"- "github.com/opensandbox/opensandbox/cmd/oc/internal/bundle""github.com/opensandbox/opensandbox/cmd/oc/internal/client"- "github.com/opensandbox/opensandbox/cmd/oc/internal/credscan"+ "github.com/opensandbox/opensandbox/cmd/oc/internal/fluebuild""github.com/spf13/cobra")-const (- // flueBuildOutputDir is `flue build --target cloudflare`'s output root; the tool- // writes the Cloudflare build under dist/<app>/ (wrangler.json + the entry module +- // assets/), so we discover the wrangler beneath it rather than assume a flat layout.- flueBuildOutputDir = "dist"- flueBundleMaxBytes = 64 << 20 // server caps the staged bundle at 64 MiB — fail early-)--var (- flueBindingIdentifier = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)- flueCompatibilityFlag = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)-)--type flueDOBinding struct {- Name string `json:"name"`- ClassName string `json:"class_name"`-}--type flueWranglerDescriptor struct {- Main string `json:"main"`- CompatibilityDate string `json:"compatibility_date"`- CompatibilityFlags []string `json:"compatibility_flags"`- NoBundle bool `json:"no_bundle"`- DurableObjects struct {- Bindings []flueDOBinding `json:"bindings"`- } `json:"durable_objects"`-}--type generatedFlueWrangler struct {- Main string `json:"main"`- CompatibilityDate string `json:"compatibility_date"`- CompatibilityFlags []string `json:"compatibility_flags"`- NoBundle bool `json:"no_bundle"`- DurableObjects struct {- Bindings []json.RawMessage `json:"bindings"`- } `json:"durable_objects"`-}-// artifactUploadResponse is the reply from POST /v3/agents/:id/artifacts. AlreadyUploaded// is set (and URL omitted) when the content-addressed object already exists: R2 is// write-once, so the server refuses to re-issue a PUT for a pinned digest (a re-issuable@@ -83,18 +38,16 @@ type artifactUploadResponse struct {}func deployFlue(cmd *cobra.Command, sc *client.Client, dir string, m *manifest, noActivate bool) error {- // 1. Primary credential scan over the user's source (§11.2.6): model keys come- // from the OC credential, never from committed code. Stays client-side.- findings, err := credscan.ScanDir(dir)- if err != nil {- return fmt.Errorf("credential scan: %w", err)- }- if len(findings) > 0 {- fmt.Fprintln(os.Stderr, "Refusing to deploy — possible credential(s) in source (model keys come from the OC credential, never code):")- for _, f := range findings {- fmt.Fprintf(os.Stderr, " %s:%d %s %s\n", f.Path, f.Line, f.Kind, f.Match)- }- return &ExitError{Code: 1}+ // 1. Run the same credential, manifest, engine, and lockfile projection as+ // the managed builder before any authenticated API call. --check-only+ // never executes repository code and never needs installed dependencies.+ if _, err := fluebuild.Build(cmd.Context(), fluebuild.Options{+ Dir: dir,+ Target: fluebuild.TargetCloudflare,+ BuilderVersion: Version,+ CheckOnly: true,+ }); err != nil {+ return presentFlueBuildError(err)}// 2. Resolve the target agent (create with runtime=flue + no prompt if new).@@ -112,29 +65,21 @@ func deployFlue(cmd *cobra.Command, sc *client.Client, dir string, m *manifest,return err}- // 3. Build the app with its own `flue` CLI (a devDependency).- if err := runFlueBuild(cmd.Context(), dir); err != nil {- return err- }-- // 4. Extract the strict descriptor and stage only regular module files. Raw- // wrangler.json contains build-local paths and never leaves this machine.- // The digest is sha256 of the blob the server and box will hash byte-for-byte.- files, wrangler, err := readFlueBundle(filepath.Join(dir, flueBuildOutputDir))- if err != nil {- return err- }- tarGz, err := bundle.Pack(files)+ // 3–4. Build through the shared credential-free package. It extracts only+ // strict WfP metadata + regular modules and credential-scans the final bytes.+ artifact, err := fluebuild.Build(cmd.Context(), fluebuild.Options{+ Dir: dir,+ Target: fluebuild.TargetCloudflare,+ BuilderVersion: Version,+ })if err != nil {- return fmt.Errorf("pack bundle: %w", err)- }- digest := bundle.Digest(tarGz)- if len(tarGz) > flueBundleMaxBytes {- return fmt.Errorf("bundle is %d bytes, over the %d MiB limit", len(tarGz), flueBundleMaxBytes>>20)+ return presentFlueBuildError(err)}+ digest := artifact.Deployment.Bundle.Digest+ wrangler := artifact.Deployment.Flue.Wrangler// 5. Upload: presigned PUT to R2 (the API host never sees the bytes).- if err := uploadArtifact(cmd.Context(), sc, id, digest, tarGz); err != nil {+ if err := uploadArtifact(cmd.Context(), sc, id, digest, artifact.Bundle); err != nil {return err}@@ -142,17 +87,14 @@ func deployFlue(cmd *cobra.Command, sc *client.Client, dir string, m *manifest,// module bytes in the JSON). The CP keys the flue-DO path off the agent's// runtime="flue" + the presence of flue_bundle_digest/flue_wrangler, then hands// off to the off-host runner (fetch → compose → mint → WfP-upload) → verifying.- rt := m.Runtime.Type- if rt == "" {- rt = "default"- }+ rt := artifact.Deployment.Runtime.Typeinput := map[string]interface{}{"type": "inline",- "model": m.Model,+ "model": artifact.Deployment.Model,"runtime": map[string]string{"type": rt},"flue_bundle_digest": digest, // sha256: of the tar.gz staged in R2"flue_wrangler": wrangler, // strict adapter descriptor; never raw wrangler.json- "flue_agent_name": m.Name, // entrypoint agent (agent.toml name → DO admit address)+ "flue_agent_name": artifact.Deployment.Flue.Entrypoint,}body := map[string]interface{}{"input": input, "activate": !noActivate}if idem, _ := cmd.Flags().GetString("idempotency-key"); idem != "" {@@ -187,6 +129,18 @@ func deployFlue(cmd *cobra.Command, sc *client.Client, dir string, m *manifest,return nil}+func presentFlueBuildError(err error) error {+ var credentialErr *fluebuild.CredentialError+ if !errors.As(err, &credentialErr) {+ return err+ }+ fmt.Fprintln(os.Stderr, "Refusing to deploy — possible credential(s) found (model keys come from the OpenComputer credential, never code):")+ for _, finding := range credentialErr.Findings {+ fmt.Fprintf(os.Stderr, " %s:%d %s %s\n", finding.Path, finding.Line, finding.Kind, finding.Match)+ }+ return &ExitError{Code: 1}+}+// resolveDeployAgent picks the agent a flue deploy targets: --agent > manifest// [agent].id > ensure-by-name (creating a flue agent with no prompt if absent).func resolveDeployAgent(cmd *cobra.Command, sc *client.Client, m *manifest) (string, error) {@@ -200,256 +154,6 @@ func resolveDeployAgent(cmd *cobra.Command, sc *client.Client, m *manifest) (strreturn id, err}-// runFlueBuild runs the app's own `flue` CLI: `flue build --target cloudflare`.-// Prefers the locally-installed bin; falls back to `npx --no-install`, which runs the-// package only if it is already in node_modules and NEVER fetches a same-named package-// from the registry (a supply-chain hole). Build output goes to stderr so stdout stays-// clean for --json.-func runFlueBuild(ctx context.Context, dir string) error {- args := []string{"build", "--target", "cloudflare"}- bin := filepath.Join(dir, "node_modules", ".bin", "flue")- var c *exec.Cmd- if _, err := os.Stat(bin); err == nil {- c = exec.CommandContext(ctx, bin, args...)- } else {- c = exec.CommandContext(ctx, "npx", append([]string{"--no-install", "flue"}, args...)...)- }- c.Dir = dir- c.Env = flueBuildEnv()- c.Stdout = os.Stderr- c.Stderr = os.Stderr- // No stdin: `flue build` is a non-interactive bundler, and wiring the terminal- // through would let an npx install prompt hijack it.- if err := c.Run(); err != nil {- return fmt.Errorf("flue build failed: %w\n(run `npm install` so the flue CLI is available, node >= 22.19)", err)- }- return nil-}--// flueBuildEnv keeps Wrangler's platform-deployment warnings out of `oc agent-// deploy`. OpenComputer consumes a strict subset of the generated descriptor and-// owns the eventual Worker-for-Platforms composition, so warnings about directly-// deploying that scratch Wrangler config (notably declarative Durable Object-// exports) are not actionable here. Errors still print. An explicit-// WRANGLER_LOG setting wins, which leaves a debugging escape hatch.-func flueBuildEnv() []string {- const key = "WRANGLER_LOG"- const fallback = key + "=error"- env := os.Environ()- prefix := key + "="- for i, value := range env {- if !strings.HasPrefix(value, prefix) {- continue- }- if value == prefix {- env[i] = fallback- }- return env- }- return append(env, fallback)-}--// readFlueBundle locates the generated wrangler, extracts the exact Flue descriptor,-// and reads only regular .js/.mjs modules rooted at the wrangler's directory. The raw-// wrangler resolution dump, .vite state and source maps are known control artifacts and-// are never archived; any other non-module fails loudly instead of producing a broken deploy.-func readFlueBundle(distDir string) ([]bundle.File, flueWranglerDescriptor, error) {- wranglerPath, err := findGeneratedWrangler(distDir)- if err != nil {- return nil, flueWranglerDescriptor{}, err- }- raw, err := os.ReadFile(wranglerPath)- if err != nil {- return nil, flueWranglerDescriptor{}, fmt.Errorf("read %s: %w", wranglerPath, err)- }- wrangler, err := extractFlueWranglerDescriptor(raw)- if err != nil {- return nil, flueWranglerDescriptor{}, fmt.Errorf("parse %s: %w", wranglerPath, err)- }-- bundleRoot := filepath.Dir(wranglerPath)- files, err := readBundleModules(bundleRoot)- if err != nil {- return nil, flueWranglerDescriptor{}, err- }- // The entry module wrangler.main names MUST be in the bundle (the runner uploads it- // to WfP as metadata.main_module).- mainRel := wrangler.Main- found := false- for _, f := range files {- if f.Path == mainRel {- found = true- break- }- }- if !found {- return nil, flueWranglerDescriptor{}, fmt.Errorf("entry module %q (wrangler.main) is not in the module output %s", mainRel, bundleRoot)- }- return files, wrangler, nil-}--func safeFlueModulePath(value string) bool {- if value == "" || strings.HasPrefix(value, "/") || strings.Contains(value, `\`) {- return false- }- if ext := pathpkg.Ext(value); ext != ".js" && ext != ".mjs" {- return false- }- if pathpkg.Clean(value) != value {- return false- }- for _, segment := range strings.Split(value, "/") {- if segment == "" || segment == "." || segment == ".." {- return false- }- }- return true-}--func extractFlueWranglerDescriptor(raw []byte) (flueWranglerDescriptor, error) {- var generated generatedFlueWrangler- if err := json.Unmarshal(raw, &generated); err != nil {- return flueWranglerDescriptor{}, err- }- if !safeFlueModulePath(generated.Main) {- return flueWranglerDescriptor{}, fmt.Errorf("main must be a safe relative .js/.mjs module path")- }- if parsed, err := time.Parse("2006-01-02", generated.CompatibilityDate); err != nil || parsed.Format("2006-01-02") != generated.CompatibilityDate {- return flueWranglerDescriptor{}, fmt.Errorf("compatibility_date must be a valid YYYY-MM-DD date")- }- if generated.CompatibilityFlags == nil || len(generated.CompatibilityFlags) > 64 {- return flueWranglerDescriptor{}, fmt.Errorf("compatibility_flags must be a unique array of valid flag names")- }- seenFlags := map[string]bool{}- for _, flag := range generated.CompatibilityFlags {- if !flueCompatibilityFlag.MatchString(flag) || seenFlags[flag] {- return flueWranglerDescriptor{}, fmt.Errorf("compatibility_flags must be a unique array of valid flag names")- }- seenFlags[flag] = true- }- if !generated.NoBundle {- return flueWranglerDescriptor{}, fmt.Errorf("no_bundle must be true")- }-- bindings := make([]flueDOBinding, 0, len(generated.DurableObjects.Bindings))- names := map[string]bool{}- classes := map[string]bool{}- for _, rawBinding := range generated.DurableObjects.Bindings {- var fields map[string]json.RawMessage- if err := json.Unmarshal(rawBinding, &fields); err != nil {- return flueWranglerDescriptor{}, fmt.Errorf("invalid durable-object binding: %w", err)- }- if len(fields) != 2 || fields["name"] == nil || fields["class_name"] == nil {- return flueWranglerDescriptor{}, fmt.Errorf("durable-object bindings may contain only name and class_name")- }- var binding flueDOBinding- if err := json.Unmarshal(rawBinding, &binding); err != nil {- return flueWranglerDescriptor{}, fmt.Errorf("invalid durable-object binding: %w", err)- }- if !flueBindingIdentifier.MatchString(binding.Name) || !flueBindingIdentifier.MatchString(binding.ClassName) {- return flueWranglerDescriptor{}, fmt.Errorf("durable-object binding names and class names must be non-empty JavaScript identifiers")- }- if names[binding.Name] || classes[binding.ClassName] {- return flueWranglerDescriptor{}, fmt.Errorf("durable-object binding names and class names must be unique")- }- names[binding.Name] = true- classes[binding.ClassName] = true- bindings = append(bindings, binding)- }- if len(bindings) == 0 {- return flueWranglerDescriptor{}, fmt.Errorf("at least one same-script durable-object binding is required")- }-- var descriptor flueWranglerDescriptor- descriptor.Main = generated.Main- descriptor.CompatibilityDate = generated.CompatibilityDate- descriptor.CompatibilityFlags = append([]string(nil), generated.CompatibilityFlags...)- descriptor.NoBundle = true- descriptor.DurableObjects.Bindings = bindings- return descriptor, nil-}--// findGeneratedWrangler returns the generated wrangler.json path — dist/wrangler.json-// (flat) or the single dist/<app>/wrangler.json `flue build` writes. Zero or more than-// one candidate is an error (nothing built / ambiguous output).-func findGeneratedWrangler(distDir string) (string, error) {- if info, err := os.Stat(distDir); err != nil || !info.IsDir() {- return "", fmt.Errorf("build output %s not found — did `flue build --target cloudflare` run?", distDir)- }- flat := filepath.Join(distDir, "wrangler.json")- if _, err := os.Stat(flat); err == nil {- return flat, nil- }- matches, _ := filepath.Glob(filepath.Join(distDir, "*", "wrangler.json"))- switch len(matches) {- case 0:- return "", fmt.Errorf("no wrangler.json under %s — `flue build --target cloudflare` produced no Cloudflare build", distDir)- case 1:- return matches[0], nil- default:- return "", fmt.Errorf("multiple wrangler.json under %s (%v) — ambiguous flue build output", distDir, matches)- }-}--// readBundleModules walks the output into a module-only fileset with normalized modes-// and forward-slash, root-relative paths. Symlinks, special files and unexpected regular-// files fail closed. Only the generated wrangler, source maps and .vite state are ignored.-func readBundleModules(root string) ([]bundle.File, error) {- if info, err := os.Stat(root); err != nil || !info.IsDir() {- return nil, fmt.Errorf("build output %s not found — did `flue build --target cloudflare` run?", root)- }- var files []bundle.File- err := filepath.WalkDir(root, func(p string, d fs.DirEntry, walkErr error) error {- if walkErr != nil {- return walkErr- }- if d.IsDir() {- if p != root && d.Name() == ".vite" {- return filepath.SkipDir- }- return nil- }- if d.Type()&os.ModeSymlink != 0 {- return fmt.Errorf("build output contains symlink %s; only regular modules are allowed", p)- }- rel, err := filepath.Rel(root, p)- if err != nil {- return err- }- rel = filepath.ToSlash(rel)- st, err := d.Info()- if err != nil {- return err- }- if !st.Mode().IsRegular() {- return fmt.Errorf("build output contains non-regular file %s", p)- }- if rel == "wrangler.json" || strings.HasSuffix(rel, ".map") {- return nil- }- if !safeFlueModulePath(rel) {- return fmt.Errorf("build output contains unsupported file %q; expected only .js/.mjs modules", rel)- }- content, err := os.ReadFile(p)- if err != nil {- return err- }- files = append(files, bundle.File{- Path: rel,- Mode: bundle.NormalizeMode(int(st.Mode().Perm())),- Content: content,- })- return nil- })- if err != nil {- return nil, fmt.Errorf("read %s: %w", root, err)- }- if len(files) == 0 {- return nil, fmt.Errorf("build output %s is empty", root)- }- return files, nil-}-// uploadArtifact requests a presigned PUT URL, then PUTs the bundle to it. The PUT// carries no OC auth (the signature is in the URL); Content-Type must match what the// server signed for the object (application/gzip).diff --git a/cmd/oc/internal/commands/agent_deploy_flue_test.go b/cmd/oc/internal/commands/agent_deploy_flue_test.goindex 662eb050..51f7b8ac 100644--- a/cmd/oc/internal/commands/agent_deploy_flue_test.go+++ b/cmd/oc/internal/commands/agent_deploy_flue_test.go@@ -26,6 +26,7 @@ import ("github.com/opensandbox/opensandbox/cmd/oc/internal/bundle""github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/opensandbox/opensandbox/cmd/oc/internal/fluebuild""github.com/opensandbox/opensandbox/cmd/oc/internal/output""github.com/spf13/cobra")@@ -114,6 +115,10 @@ func TestDeployFlueDoEndToEnd(t *testing.T) {dir := t.TempDir()writeFile(t, filepath.Join(dir, "agent.toml"),"name = \"e2e-flue\"\nmodel = \"anthropic/claude-sonnet-5\"\n\n[runtime]\nfamily = \"flue\"\n", 0o644)+ writeFile(t, filepath.Join(dir, "package.json"),+ `{"engines":{"node":">=18"},"devDependencies":{"@flue/cli":"1.0.0"}}`, 0o644)+ writeFile(t, filepath.Join(dir, "package-lock.json"),+ `{"lockfileVersion":3}`, 0o644)writeFile(t, filepath.Join(dir, "src", "opencomputer.ts"),"import { serveOC } from '@opencomputer/flue';\nexport default serveOC(agent);\n", 0o644)buildScript := "#!/bin/sh\nset -e\ntest \"${WRANGLER_LOG:-}\" = error\nmkdir -p dist/e2e_flue/assets dist/e2e_flue/.vite dist/e2e_flue/.flue-vite\n" +@@ -254,7 +259,7 @@ func TestDeployFlueDoEndToEnd(t *testing.T) {func TestFlueBuildEnvPreservesExplicitWranglerLog(t *testing.T) {t.Setenv("WRANGLER_LOG", "debug")- for _, value := range flueBuildEnv() {+ for _, value := range fluebuild.BuildEnv() {if value == "WRANGLER_LOG=debug" {return}@@ -305,7 +310,7 @@ func TestExtractFlueWranglerDescriptorRejectsUnsafeInput(t *testing.T) {if err != nil {t.Fatal(err)}- if _, err := extractFlueWranglerDescriptor(raw); err == nil {+ if _, err := fluebuild.ExtractWranglerDescriptor(raw); err == nil {t.Fatalf("expected %s to be rejected", tc.name)}})@@ -326,7 +331,7 @@ func TestExtractFlueWranglerDescriptorPreservesBuildProfile(t *testing.T) {if err != nil {t.Fatal(err)}- descriptor, err := extractFlueWranglerDescriptor(raw)+ descriptor, err := fluebuild.ExtractWranglerDescriptor(raw)if err != nil {t.Fatalf("extract descriptor: %v", err)}@@ -352,7 +357,7 @@ func TestReadBundleModulesRejectsSymlink(t *testing.T) {if err := os.Symlink(outside, filepath.Join(root, "leak.js")); err != nil {t.Fatal(err)}- if _, err := readBundleModules(root); err == nil || !strings.Contains(err.Error(), "symlink") {+ if _, err := fluebuild.ReadBundleModules(root); err == nil || !strings.Contains(err.Error(), "symlink") {t.Fatalf("expected symlink rejection, got %v", err)}}@@ -361,7 +366,7 @@ func TestReadBundleModulesRejectsUnexpectedRegularFile(t *testing.T) {root := t.TempDir()writeFile(t, filepath.Join(root, "index.js"), "export {};", 0o644)writeFile(t, filepath.Join(root, "runtime.wasm"), "not really wasm", 0o644)- if _, err := readBundleModules(root); err == nil || !strings.Contains(err.Error(), "unsupported file") {+ if _, err := fluebuild.ReadBundleModules(root); err == nil || !strings.Contains(err.Error(), "unsupported file") {t.Fatalf("expected unsupported-file rejection, got %v", err)}}@@ -389,6 +394,10 @@ func TestDeployFlueBlocksOnLeakedKey(t *testing.T) {dir := t.TempDir()writeFile(t, filepath.Join(dir, "agent.toml"),"name = \"leaky\"\nmodel = \"anthropic/claude-sonnet-5\"\n[runtime]\nfamily = \"flue\"\n", 0o644)+ writeFile(t, filepath.Join(dir, "package.json"),+ `{"engines":{"node":">=18"},"devDependencies":{"@flue/cli":"1.0.0"}}`, 0o644)+ writeFile(t, filepath.Join(dir, "package-lock.json"),+ `{"lockfileVersion":3}`, 0o644)writeFile(t, filepath.Join(dir, "src", "leak.ts"),"const k = \"sk-ant-api03-AbCdEf0123456789AbCdEf0123456789_-xyzTUV\";\n", 0o644)diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.goindex 74642db4..bfb70c0e 100644--- a/cmd/oc/internal/commands/root.go+++ b/cmd/oc/internal/commands/root.go@@ -25,7 +25,7 @@ var rootCmd = &cobra.Command{Version: Version,PersistentPreRunE: func(cmd *cobra.Command, args []string) error {cfg := config.Load(cmd)- if cfg.APIKey == "" && cmd.Name() != "config" && cmd.Name() != "help" && cmd.Name() != "set" && cmd.Name() != "show" {+ if cfg.APIKey == "" && !isOfflineCommand(cmd) && cmd.Name() != "config" && cmd.Name() != "help" && cmd.Name() != "set" && cmd.Name() != "show" {fmt.Fprintln(os.Stderr, "Warning: no API key configured. Set OPENCOMPUTER_API_KEY or run 'oc config set api-key <key>'")}c := client.New(cfg.APIURL, cfg.APIKey)@@ -40,6 +40,9 @@ var rootCmd = &cobra.Command{return nil},PersistentPostRun: func(cmd *cobra.Command, args []string) {+ if isOfflineCommand(cmd) {+ return+ }// One-line nag to stderr when a newer release is available. Skip// for `oc update` itself, help, and completion scaffolding — see// maybePromptUpdate for the full skip list (dev build, non-TTY,@@ -54,6 +57,10 @@ var rootCmd = &cobra.Command{SilenceErrors: true,}+func isOfflineCommand(cmd *cobra.Command) bool {+ return cmd.Annotations != nil && cmd.Annotations[offlineCommandAnnotation] == "true"+}+func init() {rootCmd.PersistentFlags().BoolVar(&jsonOutput, "json", false, "Output as JSON")rootCmd.PersistentFlags().String("api-key", "", "API key (overrides OPENCOMPUTER_API_KEY)")diff --git a/cmd/oc/internal/fluebuild/fluebuild.go b/cmd/oc/internal/fluebuild/fluebuild.gonew file mode 100644index 00000000..7aa260ad--- /dev/null+++ b/cmd/oc/internal/fluebuild/fluebuild.go@@ -0,0 +1,735 @@+// Package fluebuild validates, builds, and packages a Flue application without+// authenticating to or calling any OpenComputer service.+//+// It is shared by the local `oc agent deploy` flow and the managed repository+// builder. Keep the Deployment type as the single Go representation of the+// deployment.json handoff contract: the deploy runner must not reconstruct it+// from loosely typed maps.+package fluebuild++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "os"+ "os/exec"+ pathpkg "path"+ "path/filepath"+ "regexp"+ "strings"+ "time"++ "github.com/BurntSushi/toml"+ "github.com/Masterminds/semver/v3"+ "github.com/opensandbox/opensandbox/cmd/oc/internal/bundle"+ "github.com/opensandbox/opensandbox/cmd/oc/internal/credscan"+)++const (+ SchemaVersion = 1+ TargetCloudflare = "cloudflare"+ BundleFilename = "bundle.tgz"+ DeploymentFilename = "deployment.json"+ BuildOutputDir = "dist"+ BundleMaxBytes = 64 << 20+)++var (+ bindingIdentifier = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)+ compatibilityFlag = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)+ bundleDigest = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)+)++// Deployment is the versioned, byte-free metadata written to deployment.json.+// Wrangler and Bundle are absent only from a --check-only projection.+type Deployment struct {+ SchemaVersion int `json:"schema_version"`+ Flue Flue `json:"flue"`+ Model string `json:"model"`+ Vars Vars `json:"vars"`+ Runtime Runtime `json:"runtime"`+ Bundle *Bundle `json:"bundle,omitempty"`+ Builder Builder `json:"builder"`+}++type Flue struct {+ Entrypoint string `json:"entrypoint"`+ Wrangler *WranglerDescriptor `json:"wrangler,omitempty"`+}++type Runtime struct {+ Family string `json:"family" toml:"family"`+ Type string `json:"type" toml:"type"`+}++type Bundle struct {+ Digest string `json:"digest"`+ SizeBytes int64 `json:"size_bytes"`+}++type Builder struct {+ Version string `json:"version"`+}++// Vars is named so callers cannot accidentally replace the manifest-derived+// snapshot with an untyped map. Values are non-secret strings from agent.toml.+type Vars map[string]string++type DOBinding struct {+ Name string `json:"name"`+ ClassName string `json:"class_name"`+}++// WranglerDescriptor is the strict Worker-for-Platforms subset accepted from+// Flue's generated wrangler.json. Raw Wrangler configuration never crosses the+// builder boundary.+type WranglerDescriptor struct {+ Main string `json:"main"`+ CompatibilityDate string `json:"compatibility_date"`+ CompatibilityFlags []string `json:"compatibility_flags"`+ NoBundle bool `json:"no_bundle"`+ DurableObjects struct {+ Bindings []DOBinding `json:"bindings"`+ } `json:"durable_objects"`+}++type manifest struct {+ Name string `toml:"name"`+ Model string `toml:"model"`+ Vars Vars `toml:"vars"`+ Runtime Runtime `toml:"runtime"`+}++type packageJSON struct {+ Engines map[string]string `json:"engines"`+ Dependencies map[string]string `json:"dependencies"`+ DevDependencies map[string]string `json:"devDependencies"`+}++type packageLockJSON struct {+ LockfileVersion int `json:"lockfileVersion"`+}++type generatedWrangler struct {+ Main string `json:"main"`+ CompatibilityDate string `json:"compatibility_date"`+ CompatibilityFlags []string `json:"compatibility_flags"`+ NoBundle bool `json:"no_bundle"`+ DurableObjects struct {+ Bindings []json.RawMessage `json:"bindings"`+ } `json:"durable_objects"`+}++// Options controls one offline build. NodeVersion may be supplied by a pinned+// builder snapshot; when empty, the local node binary is queried. OutputDir is+// optional for in-process callers such as `oc agent deploy`.+type Options struct {+ Dir string+ Target string+ OutputDir string+ BuilderVersion string+ NodeVersion string+ CheckOnly bool+ BuildStdout io.Writer+ BuildStderr io.Writer+}++type Result struct {+ Deployment Deployment+ Bundle []byte+}++// CredentialError reports redacted credential findings from either source or+// built modules. It deliberately retains typed findings for CLI presentation.+type CredentialError struct {+ Stage string+ Findings []credscan.Finding+}++func (e *CredentialError) Error() string {+ var b strings.Builder+ fmt.Fprintf(&b, "possible credential(s) in %s", e.Stage)+ for _, finding := range e.Findings {+ fmt.Fprintf(&b, "\n %s:%d %s %s", finding.Path, finding.Line, finding.Kind, finding.Match)+ }+ return b.String()+}++// Build validates the repository projection and, unless CheckOnly is set,+// invokes the repository-local Flue CLI and returns the canonical artifact.+// This function performs no source fetch, network request, API authentication,+// upload, or deployment. Repository code executed by Flue is untrusted and must+// be isolated by the caller.+func Build(ctx context.Context, opts Options) (Result, error) {+ if strings.TrimSpace(opts.Dir) == "" {+ opts.Dir = "."+ }+ if opts.Target == "" {+ opts.Target = TargetCloudflare+ }+ if opts.Target != TargetCloudflare {+ return Result{}, fmt.Errorf("unsupported target %q (only %q is supported)", opts.Target, TargetCloudflare)+ }+ if opts.BuilderVersion == "" {+ opts.BuilderVersion = "dev"+ }++ projection, err := inspect(ctx, opts.Dir, opts.BuilderVersion, opts.NodeVersion)+ if err != nil {+ return Result{}, err+ }+ if opts.CheckOnly {+ if err := ValidateDeployment(projection, false); err != nil {+ return Result{}, err+ }+ return Result{Deployment: projection}, nil+ }++ stdout := opts.BuildStdout+ if stdout == nil {+ stdout = os.Stderr+ }+ stderr := opts.BuildStderr+ if stderr == nil {+ stderr = os.Stderr+ }+ if err := RunFlue(ctx, opts.Dir, stdout, stderr); err != nil {+ return Result{}, err+ }++ files, wrangler, err := ReadBundle(filepath.Join(opts.Dir, BuildOutputDir))+ if err != nil {+ return Result{}, err+ }+ if err := scanBuiltModules(files); err != nil {+ return Result{}, err+ }+ tarGz, err := bundle.Pack(files)+ if err != nil {+ return Result{}, fmt.Errorf("pack bundle: %w", err)+ }+ if len(tarGz) > BundleMaxBytes {+ return Result{}, fmt.Errorf("bundle is %d bytes, over the %d MiB limit", len(tarGz), BundleMaxBytes>>20)+ }++ projection.Flue.Wrangler = &wrangler+ projection.Bundle = &Bundle{+ Digest: bundle.Digest(tarGz),+ SizeBytes: int64(len(tarGz)),+ }+ result := Result{Deployment: projection, Bundle: tarGz}+ if err := ValidateDeployment(result.Deployment, true); err != nil {+ return Result{}, err+ }+ if opts.OutputDir != "" {+ if err := WriteOutput(opts.OutputDir, result); err != nil {+ return Result{}, err+ }+ }+ return result, nil+}++// ParseDeployment decodes deployment.json with unknown-field rejection, then+// validates either the check-only projection or the complete artifact shape.+func ParseDeployment(raw []byte, requireArtifact bool) (Deployment, error) {+ decoder := json.NewDecoder(bytes.NewReader(raw))+ decoder.DisallowUnknownFields()+ var deployment Deployment+ if err := decoder.Decode(&deployment); err != nil {+ return Deployment{}, fmt.Errorf("decode deployment metadata: %w", err)+ }+ var trailing any+ if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {+ return Deployment{}, fmt.Errorf("decode deployment metadata: trailing JSON value")+ }+ if err := ValidateDeployment(deployment, requireArtifact); err != nil {+ return Deployment{}, err+ }+ return deployment, nil+}++// ValidateDeployment enforces the frozen schema independently of Build so an+// artifact consumer can fail closed before trusting the handoff metadata.+func ValidateDeployment(deployment Deployment, requireArtifact bool) error {+ if deployment.SchemaVersion != SchemaVersion {+ return fmt.Errorf("deployment schema_version %d is unsupported", deployment.SchemaVersion)+ }+ if strings.TrimSpace(deployment.Flue.Entrypoint) == "" {+ return fmt.Errorf("deployment flue.entrypoint is required")+ }+ if strings.TrimSpace(deployment.Model) == "" {+ return fmt.Errorf("deployment model is required")+ }+ if deployment.Vars == nil {+ return fmt.Errorf("deployment vars must be an object")+ }+ if deployment.Runtime.Family != "flue" || deployment.Runtime.Type == "" {+ return fmt.Errorf("deployment runtime must contain family=flue and a type")+ }+ if strings.TrimSpace(deployment.Builder.Version) == "" {+ return fmt.Errorf("deployment builder.version is required")+ }+ if !requireArtifact {+ if deployment.Flue.Wrangler != nil || deployment.Bundle != nil {+ return fmt.Errorf("check-only deployment must omit flue.wrangler and bundle")+ }+ return nil+ }+ if deployment.Flue.Wrangler == nil || deployment.Bundle == nil {+ return fmt.Errorf("complete deployment requires flue.wrangler and bundle")+ }+ if !bundleDigest.MatchString(deployment.Bundle.Digest) || deployment.Bundle.SizeBytes <= 0 || deployment.Bundle.SizeBytes > BundleMaxBytes {+ return fmt.Errorf("deployment bundle digest/size is invalid")+ }+ wranglerJSON, err := json.Marshal(deployment.Flue.Wrangler)+ if err != nil {+ return fmt.Errorf("encode deployment wrangler: %w", err)+ }+ if _, err := ExtractWranglerDescriptor(wranglerJSON); err != nil {+ return fmt.Errorf("deployment flue.wrangler: %w", err)+ }+ return nil+}++func inspect(ctx context.Context, dir, builderVersion, nodeVersion string) (Deployment, error) {+ findings, err := credscan.ScanDir(dir)+ if err != nil {+ return Deployment{}, fmt.Errorf("credential scan: %w", err)+ }+ if len(findings) > 0 {+ return Deployment{}, &CredentialError{Stage: "source", Findings: findings}+ }++ manifestBytes, err := readRequiredRegularFile(dir, "agent.toml", 1<<20)+ if err != nil {+ return Deployment{}, err+ }+ var m manifest+ if _, err := toml.Decode(string(manifestBytes), &m); err != nil {+ return Deployment{}, fmt.Errorf("parse agent.toml: %w", err)+ }+ if strings.TrimSpace(m.Name) == "" {+ return Deployment{}, fmt.Errorf("agent.toml needs a `name` Flue entrypoint")+ }+ if strings.TrimSpace(m.Model) == "" {+ return Deployment{}, fmt.Errorf("agent.toml needs a `model`")+ }+ if m.Runtime.Family != "flue" {+ return Deployment{}, fmt.Errorf("agent.toml runtime.family must be %q", "flue")+ }+ if m.Runtime.Type == "" {+ m.Runtime.Type = "default"+ }+ if m.Vars == nil {+ m.Vars = Vars{}+ }++ packageBytes, err := readRequiredRegularFile(dir, "package.json", 2<<20)+ if err != nil {+ return Deployment{}, err+ }+ var pkg packageJSON+ if err := json.Unmarshal(packageBytes, &pkg); err != nil {+ return Deployment{}, fmt.Errorf("parse package.json: %w", err)+ }+ flueVersion := pkg.DevDependencies["@flue/cli"]+ if flueVersion == "" {+ flueVersion = pkg.Dependencies["@flue/cli"]+ }+ if strings.TrimSpace(flueVersion) == "" {+ return Deployment{}, fmt.Errorf("package.json must declare a local @flue/cli dependency")+ }+ nodeEngine := strings.TrimSpace(pkg.Engines["node"])+ if nodeEngine == "" {+ return Deployment{}, fmt.Errorf("package.json must declare engines.node")+ }+ if nodeVersion == "" {+ nodeVersion, err = installedNodeVersion(ctx)+ if err != nil {+ return Deployment{}, err+ }+ }+ if err := validateNodeEngine(nodeEngine, nodeVersion); err != nil {+ return Deployment{}, err+ }++ lockBytes, err := readRequiredRegularFile(dir, "package-lock.json", 25<<20)+ if err != nil {+ return Deployment{}, err+ }+ var lock packageLockJSON+ if err := json.Unmarshal(lockBytes, &lock); err != nil {+ return Deployment{}, fmt.Errorf("parse package-lock.json: %w", err)+ }+ if lock.LockfileVersion != 2 && lock.LockfileVersion != 3 {+ return Deployment{}, fmt.Errorf("package-lock.json lockfileVersion %d is unsupported (expected 2 or 3)", lock.LockfileVersion)+ }++ return Deployment{+ SchemaVersion: SchemaVersion,+ Flue: Flue{Entrypoint: m.Name},+ Model: m.Model,+ Vars: m.Vars,+ Runtime: m.Runtime,+ Builder: Builder{Version: builderVersion},+ }, nil+}++func readRequiredRegularFile(root, name string, maxBytes int64) ([]byte, error) {+ path := filepath.Join(root, name)+ info, err := os.Lstat(path)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return nil, fmt.Errorf("required file %s is missing", name)+ }+ return nil, fmt.Errorf("inspect %s: %w", name, err)+ }+ if !info.Mode().IsRegular() {+ return nil, fmt.Errorf("required file %s must be a regular file", name)+ }+ if info.Size() > maxBytes {+ return nil, fmt.Errorf("required file %s is %d bytes, over the %d byte limit", name, info.Size(), maxBytes)+ }+ content, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("read %s: %w", name, err)+ }+ return content, nil+}++func installedNodeVersion(ctx context.Context) (string, error) {+ cmd := exec.CommandContext(ctx, "node", "--version")+ cmd.Stdin = nil+ out, err := cmd.Output()+ if err != nil {+ return "", fmt.Errorf("read node version: %w", err)+ }+ return strings.TrimSpace(string(out)), nil+}++func validateNodeEngine(constraint, nodeVersion string) error {+ version, err := semver.NewVersion(strings.TrimPrefix(strings.TrimSpace(nodeVersion), "v"))+ if err != nil {+ return fmt.Errorf("invalid builder node version %q: %w", nodeVersion, err)+ }+ rangeConstraint, err := semver.NewConstraint(constraint)+ if err != nil {+ return fmt.Errorf("invalid package.json engines.node %q: %w", constraint, err)+ }+ if !rangeConstraint.Check(version) {+ return fmt.Errorf("node_unsupported: package engines.node %q does not admit builder node %s", constraint, version.String())+ }+ return nil+}++// RunFlue invokes only an already-installed repository-local Flue CLI. The+// npx fallback has --no-install, so this helper never fetches a package.+func RunFlue(ctx context.Context, dir string, stdout, stderr io.Writer) error {+ args := []string{"build", "--target", TargetCloudflare}+ bin, err := filepath.Abs(filepath.Join(dir, "node_modules", ".bin", "flue"))+ if err != nil {+ return fmt.Errorf("resolve local flue binary: %w", err)+ }+ var cmd *exec.Cmd+ if _, err := os.Stat(bin); err == nil {+ cmd = exec.CommandContext(ctx, bin, args...)+ } else {+ cmd = exec.CommandContext(ctx, "npx", append([]string{"--no-install", "flue"}, args...)...)+ }+ cmd.Dir = dir+ cmd.Env = BuildEnv()+ cmd.Stdin = nil+ cmd.Stdout = stdout+ cmd.Stderr = stderr+ if err := cmd.Run(); err != nil {+ return fmt.Errorf("flue build failed: %w\n(run `npm install` so the flue CLI is available and use a supported Node version)", err)+ }+ return nil+}++// BuildEnv keeps non-actionable direct-Wrangler warnings out of output while+// preserving an explicit debugging override.+func BuildEnv() []string {+ const key = "WRANGLER_LOG"+ const fallback = key + "=error"+ env := os.Environ()+ prefix := key + "="+ for i, value := range env {+ if !strings.HasPrefix(value, prefix) {+ continue+ }+ if value == prefix {+ env[i] = fallback+ }+ return env+ }+ return append(env, fallback)+}++// ReadBundle extracts a strict descriptor and only regular JavaScript modules+// from Flue's build output.+func ReadBundle(distDir string) ([]bundle.File, WranglerDescriptor, error) {+ wranglerPath, err := findGeneratedWrangler(distDir)+ if err != nil {+ return nil, WranglerDescriptor{}, err+ }+ raw, err := os.ReadFile(wranglerPath)+ if err != nil {+ return nil, WranglerDescriptor{}, fmt.Errorf("read %s: %w", wranglerPath, err)+ }+ wrangler, err := ExtractWranglerDescriptor(raw)+ if err != nil {+ return nil, WranglerDescriptor{}, fmt.Errorf("parse %s: %w", wranglerPath, err)+ }++ bundleRoot := filepath.Dir(wranglerPath)+ files, err := ReadBundleModules(bundleRoot)+ if err != nil {+ return nil, WranglerDescriptor{}, err+ }+ found := false+ for _, file := range files {+ if file.Path == wrangler.Main {+ found = true+ break+ }+ }+ if !found {+ return nil, WranglerDescriptor{}, fmt.Errorf("entry module %q (wrangler.main) is not in the module output %s", wrangler.Main, bundleRoot)+ }+ return files, wrangler, nil+}++func safeModulePath(value string) bool {+ if value == "" || strings.HasPrefix(value, "/") || strings.Contains(value, `\`) {+ return false+ }+ if ext := pathpkg.Ext(value); ext != ".js" && ext != ".mjs" {+ return false+ }+ if pathpkg.Clean(value) != value {+ return false+ }+ for _, segment := range strings.Split(value, "/") {+ if segment == "" || segment == "." || segment == ".." {+ return false+ }+ }+ return true+}++func ExtractWranglerDescriptor(raw []byte) (WranglerDescriptor, error) {+ var generated generatedWrangler+ if err := json.Unmarshal(raw, &generated); err != nil {+ return WranglerDescriptor{}, err+ }+ if !safeModulePath(generated.Main) {+ return WranglerDescriptor{}, fmt.Errorf("main must be a safe relative .js/.mjs module path")+ }+ if parsed, err := time.Parse("2006-01-02", generated.CompatibilityDate); err != nil || parsed.Format("2006-01-02") != generated.CompatibilityDate {+ return WranglerDescriptor{}, fmt.Errorf("compatibility_date must be a valid YYYY-MM-DD date")+ }+ if generated.CompatibilityFlags == nil || len(generated.CompatibilityFlags) > 64 {+ return WranglerDescriptor{}, fmt.Errorf("compatibility_flags must be a unique array of valid flag names")+ }+ seenFlags := map[string]bool{}+ for _, flag := range generated.CompatibilityFlags {+ if !compatibilityFlag.MatchString(flag) || seenFlags[flag] {+ return WranglerDescriptor{}, fmt.Errorf("compatibility_flags must be a unique array of valid flag names")+ }+ seenFlags[flag] = true+ }+ if !generated.NoBundle {+ return WranglerDescriptor{}, fmt.Errorf("no_bundle must be true")+ }++ bindings := make([]DOBinding, 0, len(generated.DurableObjects.Bindings))+ names := map[string]bool{}+ classes := map[string]bool{}+ for _, rawBinding := range generated.DurableObjects.Bindings {+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(rawBinding, &fields); err != nil {+ return WranglerDescriptor{}, fmt.Errorf("invalid durable-object binding: %w", err)+ }+ if len(fields) != 2 || fields["name"] == nil || fields["class_name"] == nil {+ return WranglerDescriptor{}, fmt.Errorf("durable-object bindings may contain only name and class_name")+ }+ var binding DOBinding+ if err := json.Unmarshal(rawBinding, &binding); err != nil {+ return WranglerDescriptor{}, fmt.Errorf("invalid durable-object binding: %w", err)+ }+ if !bindingIdentifier.MatchString(binding.Name) || !bindingIdentifier.MatchString(binding.ClassName) {+ return WranglerDescriptor{}, fmt.Errorf("durable-object binding names and class names must be non-empty JavaScript identifiers")+ }+ if names[binding.Name] || classes[binding.ClassName] {+ return WranglerDescriptor{}, fmt.Errorf("durable-object binding names and class names must be unique")+ }+ names[binding.Name] = true+ classes[binding.ClassName] = true+ bindings = append(bindings, binding)+ }+ if len(bindings) == 0 {+ return WranglerDescriptor{}, fmt.Errorf("at least one same-script durable-object binding is required")+ }++ var descriptor WranglerDescriptor+ descriptor.Main = generated.Main+ descriptor.CompatibilityDate = generated.CompatibilityDate+ descriptor.CompatibilityFlags = append([]string(nil), generated.CompatibilityFlags...)+ descriptor.NoBundle = true+ descriptor.DurableObjects.Bindings = bindings+ return descriptor, nil+}++func findGeneratedWrangler(distDir string) (string, error) {+ if info, err := os.Stat(distDir); err != nil || !info.IsDir() {+ return "", fmt.Errorf("build output %s not found — did `flue build --target cloudflare` run?", distDir)+ }+ flat := filepath.Join(distDir, "wrangler.json")+ if _, err := os.Stat(flat); err == nil {+ return flat, nil+ }+ matches, _ := filepath.Glob(filepath.Join(distDir, "*", "wrangler.json"))+ switch len(matches) {+ case 0:+ return "", fmt.Errorf("no wrangler.json under %s — `flue build --target cloudflare` produced no Cloudflare build", distDir)+ case 1:+ return matches[0], nil+ default:+ return "", fmt.Errorf("multiple wrangler.json under %s (%v) — ambiguous flue build output", distDir, matches)+ }+}++// ReadBundleModules walks one generated output into a normalized module-only+// fileset. Unsafe links and unrecognized output fail closed.+func ReadBundleModules(root string) ([]bundle.File, error) {+ if info, err := os.Stat(root); err != nil || !info.IsDir() {+ return nil, fmt.Errorf("build output %s not found — did `flue build --target cloudflare` run?", root)+ }+ var files []bundle.File+ err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if entry.IsDir() {+ if path != root && entry.Name() == ".vite" {+ return filepath.SkipDir+ }+ return nil+ }+ if entry.Type()&os.ModeSymlink != 0 {+ return fmt.Errorf("build output contains symlink %s; only regular modules are allowed", path)+ }+ rel, err := filepath.Rel(root, path)+ if err != nil {+ return err+ }+ rel = filepath.ToSlash(rel)+ info, err := entry.Info()+ if err != nil {+ return err+ }+ if !info.Mode().IsRegular() {+ return fmt.Errorf("build output contains non-regular file %s", path)+ }+ if rel == "wrangler.json" || strings.HasSuffix(rel, ".map") {+ return nil+ }+ if !safeModulePath(rel) {+ return fmt.Errorf("build output contains unsupported file %q; expected only .js/.mjs modules", rel)+ }+ content, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ files = append(files, bundle.File{+ Path: rel,+ Mode: bundle.NormalizeMode(int(info.Mode().Perm())),+ Content: content,+ })+ return nil+ })+ if err != nil {+ return nil, fmt.Errorf("read %s: %w", root, err)+ }+ if len(files) == 0 {+ return nil, fmt.Errorf("build output %s is empty", root)+ }+ return files, nil+}++func scanBuiltModules(files []bundle.File) error {+ var findings []credscan.Finding+ for _, file := range files {+ findings = append(findings, credscan.ScanBytes(file.Path, file.Content)...)+ }+ if len(findings) > 0 {+ return &CredentialError{Stage: "built modules", Findings: findings}+ }+ return nil+}++// WriteOutput atomically replaces the two files in the offline artifact+// contract. It never writes source paths or bundle bytes into deployment.json.+func WriteOutput(outputDir string, result Result) error {+ if err := ValidateDeployment(result.Deployment, true); err != nil {+ return err+ }+ if int64(len(result.Bundle)) != result.Deployment.Bundle.SizeBytes || bundle.Digest(result.Bundle) != result.Deployment.Bundle.Digest {+ return fmt.Errorf("bundle bytes do not match deployment metadata")+ }+ if err := os.MkdirAll(outputDir, 0o755); err != nil {+ return fmt.Errorf("create output directory: %w", err)+ }+ info, err := os.Lstat(outputDir)+ if err != nil {+ return fmt.Errorf("inspect output directory: %w", err)+ }+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {+ return fmt.Errorf("output must be a real directory, not a link")+ }+ metadata, err := json.MarshalIndent(result.Deployment, "", " ")+ if err != nil {+ return fmt.Errorf("encode deployment metadata: %w", err)+ }+ metadata = append(metadata, '\n')+ if err := atomicWrite(filepath.Join(outputDir, BundleFilename), result.Bundle, 0o644); err != nil {+ return err+ }+ if err := atomicWrite(filepath.Join(outputDir, DeploymentFilename), metadata, 0o644); err != nil {+ return err+ }+ return nil+}++func atomicWrite(path string, content []byte, mode os.FileMode) error {+ tmp, err := os.CreateTemp(filepath.Dir(path), ".oc-build-*")+ if err != nil {+ return fmt.Errorf("create temporary output: %w", err)+ }+ tmpPath := tmp.Name()+ defer os.Remove(tmpPath)+ if err := tmp.Chmod(mode); err != nil {+ _ = tmp.Close()+ return err+ }+ if _, err := tmp.Write(content); err != nil {+ _ = tmp.Close()+ return err+ }+ if err := tmp.Sync(); err != nil {+ _ = tmp.Close()+ return err+ }+ if err := tmp.Close(); err != nil {+ return err+ }+ if err := os.Rename(tmpPath, path); err != nil {+ return fmt.Errorf("replace %s: %w", filepath.Base(path), err)+ }+ return nil+}diff --git a/cmd/oc/internal/fluebuild/fluebuild_test.go b/cmd/oc/internal/fluebuild/fluebuild_test.gonew file mode 100644index 00000000..ba696e81--- /dev/null+++ b/cmd/oc/internal/fluebuild/fluebuild_test.go@@ -0,0 +1,216 @@+package fluebuild++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io/fs"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+)++const (+ testBuilderVersion = "0.6.0.9-test"+ testNodeVersion = "v22.19.0"+ testWrangler = `{"name":"fixture","main":"index.js","compatibility_date":"2026-07-01","compatibility_flags":["nodejs_compat"],"no_bundle":true,"durable_objects":{"bindings":[{"name":"AGENT","class_name":"FlueStarterAgent"},{"name":"FLUE_REGISTRY","class_name":"FlueRegistry"}]},"vars":{"MUST_NOT_LEAVE":"raw"},"routes":["example.com/*"]}`+)++func TestCheckOnlyMatchesFrozenProjectionWithoutExecutingRepositoryCode(t *testing.T) {+ dir := copyFixture(t)+ sentinel := filepath.Join(dir, "executed")+ installFakeFlue(t, dir, "touch "+shellQuote(sentinel))+ t.Setenv("PATH", "") // NodeVersion is pinned by the snapshot; no process is needed.++ result, err := Build(context.Background(), Options{+ Dir: dir,+ CheckOnly: true,+ BuilderVersion: testBuilderVersion,+ NodeVersion: testNodeVersion,+ })+ if err != nil {+ t.Fatalf("check-only: %v", err)+ }+ if _, err := os.Stat(sentinel); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("check-only executed repository code; stat error = %v", err)+ }+ if result.Bundle != nil || result.Deployment.Bundle != nil || result.Deployment.Flue.Wrangler != nil {+ t.Fatalf("check-only returned build-derived fields: %#v", result)+ }++ got, err := json.MarshalIndent(result.Deployment, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ got = append(got, '\n')+ want, err := os.ReadFile(filepath.Join("testdata", "check-only.json"))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(got, want) {+ t.Fatalf("check-only contract drifted\n--- got ---\n%s\n--- want ---\n%s", got, want)+ }+}++func TestBuildWritesDeterministicArtifactContract(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("fake Flue binary is a POSIX shell script")+ }+ dir := copyFixture(t)+ installFakeFlue(t, dir, fakeSuccessfulBuildScript())+ out := t.TempDir()++ first, err := Build(context.Background(), Options{+ Dir: dir,+ OutputDir: out,+ BuilderVersion: testBuilderVersion,+ NodeVersion: testNodeVersion,+ })+ if err != nil {+ t.Fatalf("build: %v", err)+ }+ second, err := Build(context.Background(), Options{+ Dir: dir,+ BuilderVersion: testBuilderVersion,+ NodeVersion: testNodeVersion,+ })+ if err != nil {+ t.Fatalf("second build: %v", err)+ }+ if !bytes.Equal(first.Bundle, second.Bundle) || first.Deployment.Bundle.Digest != second.Deployment.Bundle.Digest {+ t.Fatal("identical fixture did not produce byte-identical bundle and digest")+ }+ // This pins the canonical transport bytes, not merely the digest shape.+ const goldenDigest = "sha256:169890136b7f3080bdb27dfc7f053e9bb1c31a977febbfbdd1d69c86b00dd5fd"+ if first.Deployment.Bundle.Digest != goldenDigest {+ t.Fatalf("canonical digest = %s, want %s", first.Deployment.Bundle.Digest, goldenDigest)+ }++ bundleBytes, err := os.ReadFile(filepath.Join(out, BundleFilename))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(bundleBytes, first.Bundle) {+ t.Fatal("bundle.tgz differs from returned canonical bytes")+ }+ metadataBytes, err := os.ReadFile(filepath.Join(out, DeploymentFilename))+ if err != nil {+ t.Fatal(err)+ }+ wantMetadata, err := os.ReadFile(filepath.Join("testdata", "deployment.json"))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(metadataBytes, wantMetadata) {+ t.Fatalf("deployment.json contract drifted\n--- got ---\n%s\n--- want ---\n%s", metadataBytes, wantMetadata)+ }+ parsed, err := ParseDeployment(metadataBytes, true)+ if err != nil {+ t.Fatalf("parse deployment.json: %v", err)+ }+ if parsed.Bundle.Digest != goldenDigest || parsed.Bundle.SizeBytes != int64(len(bundleBytes)) {+ t.Fatalf("deployment bundle metadata = %#v", parsed.Bundle)+ }+ if parsed.Flue.Entrypoint != "flue-starter" || parsed.Runtime.Type != "default" || parsed.Flue.Wrangler.Main != "index.js" {+ t.Fatalf("deployment projection drifted: %#v", parsed)+ }+ for _, forbidden := range []string{dir, "MUST_NOT_LEAVE", "example.com"} {+ if strings.Contains(string(metadataBytes), forbidden) {+ t.Fatalf("deployment.json leaked %q: %s", forbidden, metadataBytes)+ }+ }+}++func TestBuildScansFinalModules(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("fake Flue binary is a POSIX shell script")+ }+ dir := copyFixture(t)+ installFakeFlue(t, dir, fakeSuccessfulBuildScript()+"\n"++ "printf '%s' 'const key=\"sk-ant-api03-AbCdEf0123456789AbCdEf0123456789_-xyzTUV\";' > dist/fixture/leak.js\n")++ _, err := Build(context.Background(), Options{+ Dir: dir, BuilderVersion: testBuilderVersion, NodeVersion: testNodeVersion,+ })+ var credentialErr *CredentialError+ if !errors.As(err, &credentialErr) || credentialErr.Stage != "built modules" {+ t.Fatalf("expected built-module credential error, got %v", err)+ }+}++func TestCheckOnlyRejectsUnsupportedBuilderNode(t *testing.T) {+ dir := copyFixture(t)+ _, err := Build(context.Background(), Options{+ Dir: dir, CheckOnly: true, BuilderVersion: testBuilderVersion, NodeVersion: "v23.0.0",+ })+ if err == nil || !strings.Contains(err.Error(), "node_unsupported") {+ t.Fatalf("expected node_unsupported, got %v", err)+ }+}++func TestParseDeploymentRejectsUnknownFields(t *testing.T) {+ raw, err := os.ReadFile(filepath.Join("testdata", "check-only.json"))+ if err != nil {+ t.Fatal(err)+ }+ raw = bytes.Replace(raw, []byte(`"schema_version": 1`), []byte(`"schema_version": 1, "source_path": "/tmp/leak"`), 1)+ if _, err := ParseDeployment(raw, false); err == nil || !strings.Contains(err.Error(), "unknown field") {+ t.Fatalf("expected unknown-field rejection, got %v", err)+ }+}++func copyFixture(t *testing.T) string {+ t.Helper()+ src := filepath.Join("testdata", "starter")+ dst := t.TempDir()+ err := filepath.WalkDir(src, func(path string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ rel, err := filepath.Rel(src, path)+ if err != nil {+ return err+ }+ target := filepath.Join(dst, rel)+ if entry.IsDir() {+ return os.MkdirAll(target, 0o755)+ }+ content, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ return os.WriteFile(target, content, 0o644)+ })+ if err != nil {+ t.Fatal(err)+ }+ return dst+}++func installFakeFlue(t *testing.T, dir, body string) {+ t.Helper()+ path := filepath.Join(dir, "node_modules", ".bin", "flue")+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ script := "#!/bin/sh\nset -eu\ntest \"$1\" = build\ntest \"$2\" = --target\ntest \"$3\" = cloudflare\n" + body + "\n"+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+}++func fakeSuccessfulBuildScript() string {+ return "mkdir -p dist/fixture/assets dist/fixture/.vite\n" ++ "cat > dist/fixture/index.js <<'JS'\nexport default { fetch() { return new Response(\"ok\"); } };\nJS\n" ++ "cat > dist/fixture/assets/chunk.mjs <<'JS'\nexport const chunk = 1;\nJS\n" ++ "printf '%s' '{\"ignored\":true}' > dist/fixture/index.js.map\n" ++ "printf '%s' '{\"ignored\":true}' > dist/fixture/.vite/manifest.json\n" ++ "cat > dist/fixture/wrangler.json <<'JSON'\n" + testWrangler + "\nJSON"+}++func shellQuote(value string) string {+ return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"+}diff --git a/cmd/oc/internal/fluebuild/testdata/check-only.json b/cmd/oc/internal/fluebuild/testdata/check-only.jsonnew file mode 100644index 00000000..c4f40411--- /dev/null+++ b/cmd/oc/internal/fluebuild/testdata/check-only.json@@ -0,0 +1,18 @@+{+ "schema_version": 1,+ "flue": {+ "entrypoint": "flue-starter"+ },+ "model": "anthropic/claude-sonnet-5",+ "vars": {+ "MAX_ITEMS": "12",+ "PUBLIC_MODE": "careful"+ },+ "runtime": {+ "family": "flue",+ "type": "default"+ },+ "builder": {+ "version": "0.6.0.9-test"+ }+}diff --git a/cmd/oc/internal/fluebuild/testdata/deployment.json b/cmd/oc/internal/fluebuild/testdata/deployment.jsonnew file mode 100644index 00000000..312cbdff--- /dev/null+++ b/cmd/oc/internal/fluebuild/testdata/deployment.json@@ -0,0 +1,42 @@+{+ "schema_version": 1,+ "flue": {+ "entrypoint": "flue-starter",+ "wrangler": {+ "main": "index.js",+ "compatibility_date": "2026-07-01",+ "compatibility_flags": [+ "nodejs_compat"+ ],+ "no_bundle": true,+ "durable_objects": {+ "bindings": [+ {+ "name": "AGENT",+ "class_name": "FlueStarterAgent"+ },+ {+ "name": "FLUE_REGISTRY",+ "class_name": "FlueRegistry"+ }+ ]+ }+ }+ },+ "model": "anthropic/claude-sonnet-5",+ "vars": {+ "MAX_ITEMS": "12",+ "PUBLIC_MODE": "careful"+ },+ "runtime": {+ "family": "flue",+ "type": "default"+ },+ "bundle": {+ "digest": "sha256:169890136b7f3080bdb27dfc7f053e9bb1c31a977febbfbdd1d69c86b00dd5fd",+ "size_bytes": 202+ },+ "builder": {+ "version": "0.6.0.9-test"+ }+}diff --git a/cmd/oc/internal/fluebuild/testdata/starter/agent.toml b/cmd/oc/internal/fluebuild/testdata/starter/agent.tomlnew file mode 100644index 00000000..c4441217--- /dev/null+++ b/cmd/oc/internal/fluebuild/testdata/starter/agent.toml@@ -0,0 +1,9 @@+name = "flue-starter"+model = "anthropic/claude-sonnet-5"++[runtime]+family = "flue"++[vars]+PUBLIC_MODE = "careful"+MAX_ITEMS = "12"diff --git a/cmd/oc/internal/fluebuild/testdata/starter/package-lock.json b/cmd/oc/internal/fluebuild/testdata/starter/package-lock.jsonnew file mode 100644index 00000000..de727113--- /dev/null+++ b/cmd/oc/internal/fluebuild/testdata/starter/package-lock.json@@ -0,0 +1,6 @@+{+ "name": "flue-starter-fixture",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {}+}diff --git a/cmd/oc/internal/fluebuild/testdata/starter/package.json b/cmd/oc/internal/fluebuild/testdata/starter/package.jsonnew file mode 100644index 00000000..7a097141--- /dev/null+++ b/cmd/oc/internal/fluebuild/testdata/starter/package.json@@ -0,0 +1,10 @@+{+ "name": "flue-starter-fixture",+ "private": true,+ "engines": {+ "node": ">=22.19.0 <23"+ },+ "devDependencies": {+ "@flue/cli": "0.1.0"+ }+}diff --git a/cmd/oc/internal/fluebuild/testdata/starter/src/agent.ts b/cmd/oc/internal/fluebuild/testdata/starter/src/agent.tsnew file mode 100644index 00000000..24ad2222--- /dev/null+++ b/cmd/oc/internal/fluebuild/testdata/starter/src/agent.ts@@ -0,0 +1 @@+export const fixture = "offline-builder";diff --git a/go.mod b/go.modindex 01224b27..1f4ae9a8 100644--- a/go.mod+++ b/go.mod@@ -9,6 +9,8 @@ require (github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4+ github.com/BurntSushi/toml v1.6.0+ github.com/Masterminds/semver/v3 v3.5.0github.com/aws/aws-sdk-go-v2 v1.41.5github.com/aws/aws-sdk-go-v2/config v1.32.10github.com/aws/aws-sdk-go-v2/credentials v1.19.10@@ -44,7 +46,6 @@ require (github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirectgithub.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 // indirectgithub.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect- github.com/BurntSushi/toml v1.6.0 // indirectgithub.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirectgithub.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 // indirectgithub.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirectdiff --git a/go.sum b/go.sumindex 8c8ce537..d3709465 100644--- a/go.sum+++ b/go.sum@@ -30,6 +30,8 @@ github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvgithub.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=+github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=+github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=