diff --git a/.github/workflows/deploy-docs.yaml b/.github/workflows/deploy-docs.yaml index 4319fe7b..96236edb 100644 --- a/.github/workflows/deploy-docs.yaml +++ b/.github/workflows/deploy-docs.yaml @@ -113,13 +113,10 @@ jobs: # so if state is ever lost/reset the deploy re-imports the existing # cloud resources instead of failing or duplicating them. # Website.Nextjs builds OpenNext itself; do not pre-run wrangler. - bunx alchemy deploy --stage ${{ needs.stage.outputs.stage }} --yes --adopt \ - 2>&1 | tee /tmp/alchemy-deploy.log - url="$(sed -nE 's/.*url: "(https:\/\/[^"]+)".*/\1/p' /tmp/alchemy-deploy.log | tail -n1)" - if [[ -z "$url" ]]; then - echo "::error::alchemy deploy produced no url output" - exit 1 - fi + bunx alchemy deploy --stage "$STAGE" --yes --adopt + # Stack output is JSON; deploy's human-readable quotes vary by CLI. + url="$(ALCHEMY_LOG_LEVEL=error bunx alchemy state read "stackpanel-docs/$STAGE/output" | + jq -er '.url | strings | select(test("^https://[A-Za-z0-9.-]+/?\\z")) | rtrimstr("/")')" echo "url=$url" >> "$GITHUB_OUTPUT" echo "Deployed $url" - name: Smoke check @@ -190,7 +187,7 @@ jobs: SOPS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY_DEV }} run: | set -euo pipefail - bunx alchemy destroy --stage ${{ needs.stage.outputs.stage }} --yes + bunx alchemy destroy --stage "$STAGE" --yes - name: Mark preview comment as torn down uses: marocchino/sticky-pull-request-comment@v3 with: diff --git a/.github/workflows/deploy-web.yaml b/.github/workflows/deploy-web.yaml index 3304b393..24f0657e 100644 --- a/.github/workflows/deploy-web.yaml +++ b/.github/workflows/deploy-web.yaml @@ -128,7 +128,7 @@ jobs: # --adopt: resources use stable physical names (stackpanel-web-), # so if state is ever lost/reset the deploy re-imports the existing # cloud resources instead of failing or duplicating them. - bunx alchemy deploy --stage ${{ needs.stage.outputs.stage }} --yes --adopt + bunx alchemy deploy --stage "$STAGE" --yes --adopt - name: Comment preview URL on PR if: github.event_name == 'pull_request' uses: marocchino/sticky-pull-request-comment@v3 @@ -158,7 +158,7 @@ jobs: SOPS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY_DEV }} run: | set -euo pipefail - bunx alchemy destroy --stage ${{ needs.stage.outputs.stage }} --yes + bunx alchemy destroy --stage "$STAGE" --yes - name: Mark preview comment as torn down uses: marocchino/sticky-pull-request-comment@v3 with: diff --git a/.github/workflows/secrets-codegen-check.yml b/.github/workflows/secrets-codegen-check.yml index ee9e0735..4937d2ee 100644 --- a/.github/workflows/secrets-codegen-check.yml +++ b/.github/workflows/secrets-codegen-check.yml @@ -62,11 +62,6 @@ jobs: extra-substituters = https://darkmatter.cachix.org extra-trusted-public-keys = darkmatter.cachix.org-1:7R5qAiOVHxDpFy7yguECfC1JqVDgMdckGc+CDKk2pWA= - - name: Setup Cachix - uses: cachix/cachix-action@v17 - with: - name: darkmatter - authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - name: Run codegen env: # Same key the deploy workflows use — it has decrypt access for every @@ -77,15 +72,11 @@ jobs: SOPS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY_DEV }} run: | set -euo pipefail - # Devshell entry runs the shell-hook which: - # 1. writes .stack/gen/codegen/env-manifest.json (the codegen input) - # 2. invokes `stack codegen build` itself - # We re-invoke `stack codegen build` explicitly afterwards as a - # belt-and-braces guarantee that the build was run with the same SOPS - # key the embedded payloads were encrypted with. - nix develop --command bash -lc ' - set -euo pipefail - stack codegen build + # A missing manifest is a valid no-op for projects without env codegen, + # but this repository has encrypted deploy payloads to verify. + nix develop --command bash -ec ' + test -s .stack/gen/codegen/env-manifest.json || { echo "Missing env codegen manifest" >&2; exit 1; } + stack codegen build env ' - name: Verify no drift @@ -103,17 +94,14 @@ jobs: packages/gen/env/src/runtime/generated-payloads/_envs ) - if git diff --quiet -- "${target_paths[@]}"; then + changes=$(git status --porcelain --untracked-files=all -- "${target_paths[@]}") + if [[ -z "$changes" ]]; then echo "OK: embedded SOPS payloads are in sync with source schemas." exit 0 fi - echo "::error title=Embedded SOPS payloads are stale::Run \`nix develop --command stackpanel codegen build\` and commit the resulting changes under packages/gen/env/." - echo - echo "===== drift detected in =====" >&2 - git diff --name-only -- "${target_paths[@]}" >&2 - echo - echo "===== diff (truncated to 200 lines) =====" >&2 - git diff -- "${target_paths[@]}" | head -200 >&2 + echo "::error title=Embedded SOPS payloads are stale::Run nix develop --command stack codegen build env and commit the changed payloads." + # Report filenames only. Never print generated secret payload contents. + printf '%s\n' "$changes" >&2 exit 1 diff --git a/.stack/config.apps.nix b/.stack/config.apps.nix index 088d2fe5..c9635442 100644 --- a/.stack/config.apps.nix +++ b/.stack/config.apps.nix @@ -154,7 +154,6 @@ in linting.oxlint = { enable = true; - fix = true; categories = { correctness = "error"; suspicious = "warn"; diff --git a/.stack/config.nix b/.stack/config.nix index 6d621ea1..f0ac81c2 100644 --- a/.stack/config.nix +++ b/.stack/config.nix @@ -6,7 +6,7 @@ # # Machine writes will sort keys alphabetically and format with nixfmt. # For config that needs pkgs/lib (computed values, custom packages), -# use .stack/modules/ (or .stackpanel/modules/) which has full NixOS module context. +# use .stack/modules/ or .stack/nix/ for the full NixOS module context. # ============================================================================== { lib, diff --git a/.stack/data/modules/oxlint.yaml b/.stack/data/modules/oxlint.yaml deleted file mode 100644 index c60ca52e..00000000 --- a/.stack/data/modules/oxlint.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# Stackpanel module configuration for oxlint -# This file is managed by the Stackpanel UI -# Re-enter devshell to apply changes - -enable: true diff --git a/apps/docs/alchemy.run.ts b/apps/docs/alchemy.run.ts index 9174111f..839a6811 100644 --- a/apps/docs/alchemy.run.ts +++ b/apps/docs/alchemy.run.ts @@ -4,7 +4,7 @@ import { selectStateBackend, } from "@stackpanel/infra/lib/deploy"; import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; const PROJECT = "stackpanel"; @@ -38,10 +38,9 @@ const program = Effect.gen(function* () { const stage = yield* Alchemy.Stage; const hostname = hostnameFor(stage); - // Website.Nextjs runs the wrangler-free OpenNext pipeline from - // `@alchemy.run/frontend-frameworks/nextjs`. Build command lives in - // `open-next.config.ts` (`buildCommand`) — the resource no longer - // accepts a `nextjs.buildCommand` prop. + // Website.Nextjs loads OpenNext from @alchemy.run/frontend-frameworks. + // Keep `bun run build` and the static cache adapter in open-next.config.ts; + // an openNext.buildCommand here would override that native config. const website = yield* Cloudflare.Website.Nextjs("Docs", { // Stable physical name prevents orphaned workers when Alchemy's // per-deploy InstanceId changes (e.g. state loss between CI runs). @@ -69,8 +68,7 @@ const program = Effect.gen(function* () { runWorkerFirst: false, }, compatibility: { - // Website.Nextjs defaults to 2026-05-12; keep explicit so node:perf_hooks - // (required by OpenNext/Next edge) stays available. + // Preserve the OpenNext runtime independently of the provider's default. date: "2026-05-12", flags: [ "nodejs_compat", diff --git a/apps/docs/content/docs/agent.mdx b/apps/docs/content/docs/agent.mdx index 1017ea1b..59a7028a 100644 --- a/apps/docs/content/docs/agent.mdx +++ b/apps/docs/content/docs/agent.mdx @@ -73,14 +73,24 @@ When triggered by a config change or manual command, the Agent writes generated ## Authentication -The Agent runs on `localhost` and uses a JWT-based authentication flow: - -1. Studio opens in the browser and initiates a pairing request -2. The Agent displays a confirmation prompt (or auto-approves in dev mode) -3. A JWT token is issued for the session -4. All subsequent API calls include the token - -This prevents other applications on your machine from accessing the Agent API without your consent. +Choose **Connect to Agent** in Studio and approve the request in the agent's browser window. +Studio saves that pairing for the exact hostname and port you approved. `localhost:9876`, +`127.0.0.1:9876`, and a module development agent on another port have separate pairings. +If you previously paired before endpoint-scoped storage was introduced, pair again once: +Studio discards the old credential rather than guessing which agent it belongs to. +Use a matching Studio and agent version for pairing. If the popup has lost its opener, +it can return to Studio with a short-lived, single-use code. The reusable JWT never +travels in a redirect or bookmark; links containing tokens do not pair a browser. + +Before sending a credential, Studio checks the agent ID reported by the public `/health` +endpoint against the ID in the JWT. A replacement agent with a different ID requires a +new pairing. The agent validates the credential before Studio enables clients. Event +streams use an authorization header, never a token in their request URL. + +Each Studio tab pins an explicit project ID. On first connect it resolves the current +repository using the agent's project registry and reported root; if there is no current +repository, it can use the registered default. Until a project is known, project-scoped +module actions are unavailable. Use the project picker to select one explicitly. The Agent only listens on `localhost`—it's never exposed to the network. The JWT auth is an additional layer of protection for multi-user machines or shared environments. diff --git a/apps/docs/content/docs/cli/debug/index.mdx b/apps/docs/content/docs/cli/debug/index.mdx index f116ca74..244ec7b7 100644 --- a/apps/docs/content/docs/cli/debug/index.mdx +++ b/apps/docs/content/docs/cli/debug/index.mdx @@ -13,7 +13,7 @@ Without subcommands (enable/disable/status), this is equivalent to: The repo path is resolved in order: 1. STACKPANEL_DEV_REPO environment variable - 2. dev_mode.repo_path from ~/.config/stackpanel/stackpanel.yaml + 2. dev_mode.repo_path from ~/.config/stackpanel/config.yaml 3. Auto-detected from the current working directory Any arguments after 'debug' are forwarded to the 'go run' invocation. diff --git a/apps/docs/content/docs/cli/project/index.mdx b/apps/docs/content/docs/cli/project/index.mdx index 6467fb61..57c008de 100644 --- a/apps/docs/content/docs/cli/project/index.mdx +++ b/apps/docs/content/docs/cli/project/index.mdx @@ -8,9 +8,7 @@ icon: Terminal Manage Stackpanel projects across your system. -Projects are stored in ~/.config/stackpanel/stackpanel.yaml and can be -accessed from any directory. Each project has a unique ID; v1 API -requests select their project by sending it in the X-Stackpanel-Project header. +Projects and local module links are stored in `~/.config/stackpanel/config.yaml` (or under `XDG_CONFIG_HOME`). Each project has a stable ID; Connect requests select it with the `X-Stackpanel-Project` header. Examples: stack project list # List all known projects diff --git a/apps/docs/content/docs/cli/setup.mdx b/apps/docs/content/docs/cli/setup.mdx index 30d98ecb..8affe93f 100644 --- a/apps/docs/content/docs/cli/setup.mdx +++ b/apps/docs/content/docs/cli/setup.mdx @@ -323,9 +323,7 @@ denials stop the experiment with the provider's diagnostic. { "version": 1, "seen": { "playwright": { "revision": 1, "answer": false, "at": "2026-09-04T01:22:11Z" } } } ``` -An offer is re-shown only when its author bumps `revision`, or with -`--reconsider`. `.stack/addons.json` from older releases is migrated -automatically. +An offer is shown again only when its author bumps `revision`, or with `--reconsider`. No decisions means no ledger write. If `.stack/reconcile.json` changes between discovery and save, setup refuses to overwrite it; rerun setup to review the current state. ## Global Flags diff --git a/apps/docs/content/docs/concepts/module-system.mdx b/apps/docs/content/docs/concepts/module-system.mdx index ad11917d..a8b409b1 100644 --- a/apps/docs/content/docs/concepts/module-system.mdx +++ b/apps/docs/content/docs/concepts/module-system.mdx @@ -74,7 +74,8 @@ All Stackpanel options live under `stackpanel.*`: | `stackpanel.services.*` | Background service definitions | | `stackpanel.globalServices.*` | Convenience services (postgres, redis, minio) | | `stackpanel.secrets.*` | Encrypted secrets and master keys | -| `stackpanel.extensions.*` | Extension registration and config | +| `stackpanel.modules.*` | Module registration, actions, settings, and activation | +| `stackpanel.panels.*` | Module-owned panels and their placement in Studio | | `stackpanel.ports.*` | Port computation settings | | `stackpanel.ide.*` | IDE integration (VS Code, Zed) | | `stackpanel.apps.*` | Application definitions | @@ -92,7 +93,7 @@ Your flake.nix → loads .stack/config.nix (your config) → loads .stack/config.local.nix (per-user overrides, gitignored) → loads all builtin modules (services, IDE, secrets, etc.) - → loads all enabled extensions + → imports local modules and discovered flake inputs; enablement gates behavior → the module system merges everything → outputs: devshell, generated files, scripts, services ``` diff --git a/apps/docs/content/docs/dev-environment/flake-inputs.mdx b/apps/docs/content/docs/dev-environment/flake-inputs.mdx index b2d5db3e..7c8cd604 100644 --- a/apps/docs/content/docs/dev-environment/flake-inputs.mdx +++ b/apps/docs/content/docs/dev-environment/flake-inputs.mdx @@ -47,14 +47,14 @@ stack flake add-input process-compose-flake \ ### Adding an Import at the Same Time -If the input provides a Stackpanel module, you probably also need to add it to `stackpanelImports` in your flake outputs. Use `--module-path` to do both in one command: +Direct inputs that export `stackpanelModules.default` are discovered when automatic imports are enabled. To import a module explicitly, pass its attribute path: ```bash stack flake add-input my-module github:author/my-module \ --module-path stackpanelModules.default ``` -This inserts the input **and** adds `inputs.my-module.stackpanelModules.default` to your `stackpanelImports` list. The command detects whether `stackpanelImports` is defined anywhere in your flake (inside `mkFlake`, in the outputs function, etc.) and inserts into the right place. +This adds the input and an explicit `inputs.my-module.stackpanelModules.default` entry to `stackpanelImports` in a supported flake. If the editor cannot locate a safe insertion point, the command fails instead of silently dropping the import. ## Previewing Changes diff --git a/apps/docs/content/docs/extensions/flake-inputs.mdx b/apps/docs/content/docs/extensions/flake-inputs.mdx index bfa0c027..24a5a0c0 100644 --- a/apps/docs/content/docs/extensions/flake-inputs.mdx +++ b/apps/docs/content/docs/extensions/flake-inputs.mdx @@ -1,170 +1,34 @@ --- -title: Flake Inputs -description: How extensions declare, detect, and auto-install required flake inputs +title: Flake inputs and discovery +description: How modules enter the Nix evaluation and where their versions are locked. icon: git-branch --- -import { Callout } from "fumadocs-ui/components/callout"; - -Some extensions need additional Nix flake inputs to work. For example, the **Process Compose** extension requires the `process-compose-flake` input, and **Git Hooks** requires `git-hooks`. Stackpanel can detect when these inputs are missing and help you add them. - -## How It Works - -Every extension can declare the flake inputs it needs in its `meta.nix` file. When you enable an extension whose inputs aren't in your `flake.nix`, Stackpanel: - -1. Detects the missing inputs during Nix evaluation -2. Warns you in the MOTD when you enter the devshell -3. Provides the exact command to fix it - -The warning looks like: - -``` - Module "process-compose" requires flake input "process-compose-flake" - Fix: stackpanel flake add-input process-compose-flake github:Platonic-Systems/process-compose-flake -``` - -## Declaring Flake Inputs in an Extension - -If you're [writing an extension](/docs/extensions/writing-extensions) that depends on a flake input, declare it in `meta.nix`: +A consumer imports an external module by adding its flake as an input. For example: ```nix -# meta.nix { - id = "my-extension"; - name = "My Extension"; - # ... other metadata ... + inputs.stackpanel.url = "github:darkmatter/stackpanel"; + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + inputs.playwright.url = "github:darkmatter/stackpanel-registry?dir=modules/playwright"; - flakeInputs = [ - { - name = "some-flake"; # Input name in flake.nix - url = "github:someone/some-flake"; # Flake URL - followsNixpkgs = true; # Add inputs.nixpkgs.follows - } - ]; + outputs = inputs: inputs.stackpanel.lib.mkFlake { inherit inputs; }; } ``` -Then wire it into the module registration in `module.nix`: - -```nix -# module.nix -stackpanel.modules.${meta.id} = { - enable = true; - meta = { inherit (meta) name description icon category author version homepage; }; - source.type = "builtin"; - features = meta.features; - flakeInputs = meta.flakeInputs or []; # Required line - tags = meta.tags; - priority = meta.priority; -}; -``` - - -Every `module.nix` that registers via `stackpanel.modules` **must** include the `flakeInputs = meta.flakeInputs or [];` line. Without it, declared inputs won't flow through the detection pipeline. - - -### Field Reference - -| Field | Type | Default | Description | -|-------|------|---------|-------------| -| `name` | `string` | required | The input attribute name as it appears in `flake.nix` (e.g., `"process-compose-flake"`) | -| `url` | `string` | required | The flake URL (e.g., `"github:Platonic-Systems/process-compose-flake"`) | -| `followsNixpkgs` | `bool` | `true` | Whether to add `inputs..inputs.nixpkgs.follows = "nixpkgs"` | - -## Adding Missing Inputs - -### Using the CLI - -The MOTD warning includes the fix command. You can also run it manually. See [Managing Flake Inputs](/docs/dev-environment/flake-inputs) for a full guide on the `stack flake` command. - -```bash -# Add a flake input -stack flake add-input process-compose-flake github:Platonic-Systems/process-compose-flake - -# Add with --no-follows to skip the nixpkgs.follows line -stack flake add-input some-input github:someone/some-input --no-follows - -# Preview the changes without writing -stack flake add-input some-input github:someone/some-input --dry-run -``` - -The `flake add-input` command: - -1. Parses your `flake.nix` using tree-sitter (preserving comments and formatting) -2. Inserts the input declaration into the `inputs` block -3. Optionally adds `inputs..inputs.nixpkgs.follows = "nixpkgs"` -4. Runs `nix flake lock --update-input ` to fetch the input -5. Creates a `.bak` backup and rolls back if `nix flake lock` fails +Stackpanel inspects direct inputs other than `self` and `stackpanel`, importing each `stackpanelModules.default`. A project can also contribute tracked modules under `.stack/modules/` and `.stack/nix/`. Imports extend the *option schema* even before the module contributes enabled behavior. Put behavior and derivations behind the module's activation condition. -### Using the CLI with stackpanelImports - -If the extension also needs to be imported into your flake's `stackpanelImports` list, use `--module-path`: - -```bash -stack flake add-input my-ext github:someone/my-ext \ - --module-path "inputs.my-ext.stackpanelModules.default" -``` - -This adds both the input and the import entry in a single operation. - -### From Studio - -When installing an extension from the [registry](/docs/extensions/registry), Studio's install flow automatically adds the required flake inputs to your `flake.nix` and runs `nix flake lock`. No manual steps needed. - -### Manually - -You can always add inputs by hand: - -```nix -# flake.nix -{ - inputs = { - # ... existing inputs ... - process-compose-flake.url = "github:Platonic-Systems/process-compose-flake"; - }; -} -``` - -Then run `nix flake lock --update-input process-compose-flake`. - -## Builtin Extensions with Flake Inputs - -These builtin extensions require flake inputs that may not be in your `flake.nix`: - -| Extension | Input Name | URL | Follows Nixpkgs | -|-----------|-----------|-----|-----------------| -| Process Compose | `process-compose-flake` | `github:Platonic-Systems/process-compose-flake` | No | -| Git Hooks | `git-hooks` | `https://flakehub.com/f/cachix/git-hooks.nix/*` | Yes | - -If you enable either of these and the input is missing, you'll see a warning in the MOTD with the fix command. - - -Extensions that don't need flake inputs (most builtin extensions like Bun, Turbo, Go, OxLint) work out of the box with no additional setup. - - -## How Detection Works - -The detection pipeline spans Nix evaluation and the Go CLI: - -``` -meta.nix (declares flakeInputs) - -> module.nix (wires into stackpanel.modules.*.flakeInputs) - -> core/options/modules.nix (serializes to JSON via computeSerializableModule) - -> core/cli.nix (compares against flake inputs, computes missingFlakeInputs) - -> state file (.stack/state/stackpanel.json) - -> Go CLI (nixconfig.Config.MissingFlakeInputs) - -> MOTD (CollectIssues generates warnings) -``` +For explicit selection, set `stackpanel.autoImportInputs = false` in the **flake-parts configuration** and provide `stackpanel.imports = [ inputs.playwright.stackpanelModules.default ];`. With `stackpanel.lib.mkFlake`, `stackpanelImports` supplies the same explicit imports. A module can have another output path; the catalog's `flakePath` is an attribute path within that input, not a filesystem path in the consumer. `?dir=...` selects the directory containing `flake.nix`. -During Nix evaluation, `cli.nix` receives the flake's `inputs` via `specialArgs` and checks each enabled module's `flakeInputs` list against it. Any input that an enabled module declares but isn't present in `inputs` is added to the `missingFlakeInputs` array in the state file. The Go CLI reads this on `stack motd` and renders warnings with fix commands. +### Flake-level contributions -## How Auto-Install Works +An extension may export `stackpanelModuleMeta.overlays` and `stackpanelModuleMeta.flakeModules`. These are known *before* the consumer creates `pkgs` or evaluates its project options. Keep them independent of the consumer's module enable flag. A `stackpanelModuleMeta.followsNixpkgs` declaration describes the preferred input wiring; never add a `nixpkgs` follow to a flake that has no such input. -The `stack flake add-input` command and the agent's registry install endpoint both use the `flakeedit` package (`apps/stackpanel-go/internal/flakeedit/`), which parses `flake.nix` with a vendored tree-sitter-nix grammar. This enables surgical byte-offset insertions that preserve all comments, whitespace, and formatting in the file. +Declare dependencies of the extension itself in its flake. If a module also needs inputs on the **consumer** flake, list them in the module's `flakeInputs` and the corresponding catalog version. The installer reconciles those declarations before enabling the module. It rolls back an install that still reports missing inputs rather than fetching additional sources the catalog did not advertise. -Key operations: -- **`AddInput`** -- Finds the `inputs = { ... }` binding in the AST, inserts the new input before the closing `}` -- **`AddStackpanelImport`** -- Finds the `stackpanelImports = [ ... ]` list anywhere in the tree, inserts the import expression -- **`HasInput`** -- Checks if an input already exists (idempotent, no-op if present) +### Version control -The agent endpoint (`handleRegistryInstall`) combines both operations atomically: it adds the input, adds the import, writes the file, and runs `nix flake lock`. If any step fails, it falls back to returning code snippets for manual installation. +- `flake.nix` names inputs, selected refs, follows, and any explicit imports. `flake.lock` records resolved revisions and content hashes. Commit both. +- `stack module update` changes the selected project's lock; reading a catalog does not update anything. +- During development, `stack module link` supplies a machine-local `--override-input` for an existing input. Other developers and CI keep using the lock. Unlink and test the locked version before releasing. +- A file in the working tree of a Git flake must be tracked to be visible in a pure evaluation. No `--impure` flag is required for authoring or installing a module. diff --git a/apps/docs/content/docs/extensions/index.mdx b/apps/docs/content/docs/extensions/index.mdx index 853c3513..24e09a16 100644 --- a/apps/docs/content/docs/extensions/index.mdx +++ b/apps/docs/content/docs/extensions/index.mdx @@ -1,195 +1,22 @@ --- -title: Extensions -description: Add capabilities to your project with extensions +title: Modules and extensions +description: Add tools, app runtimes, deployment backends, and Studio panels with Nix modules. icon: puzzle --- -import { Cards, Card } from "fumadocs-ui/components/card"; -import { Callout } from "fumadocs-ui/components/callout"; +A Stackpanel extension is a **Nix module**. A local module, a bundled module, and a flake from a registry all use the same options and `lib.stackpanel` helpers. A module can add an app runtime, generate a file, provide a service, or put a panel in Studio without changes to Stackpanel's Go binary or web app. -Extensions are the primary way to add new capabilities to a Stackpanel project. They're Nix modules that compose core features—file generation, scripts, services, packages, and more—into cohesive, reusable units. +There are three separate decisions: -## What's an Extension? +1. **Install** makes a module's definitions available. A remote module is a flake input pinned by your project's `flake.lock`. +2. **Enable** turns on the module's behavior. Studio and the CLI patch the Nix configuration that the project actually evaluates. An installed but disabled module is still visible in **Studio → Modules**. +3. **Apply** materializes generated files and rebuilds the shell when necessary. Evaluating a preview does neither. -An extension is a Nix module that: +The registry is a **catalog**, not a Nix package manager. It helps people find the input and a version. Nix does not consult the catalog, the network API, or the agent during module evaluation. -1. **Defines its own configuration options** under `stackpanel..*` -2. **Registers itself** in the extensions system for visibility in the CLI and Studio UI -3. **Uses core Stackpanel features** to implement its functionality +Studio generates a module's settings, action controls, outputs, and documentation from its declaration. For a custom layout, [declare widgets in Nix](./writing-extensions#author-a-panel-in-nix); the module starter supplies editor completion and hover from its locked SDK. Standalone HTML panels can import the same Web Components without React. -For example, the SST extension adds AWS infrastructure provisioning. When you enable it, it: - -- Adds the SST CLI to your `PATH` -- Generates an `sst.config.ts` file from your Nix config -- Registers scripts like `sst:deploy` and `sst:dev` -- Configures IAM roles and KMS keys for secrets -- Adds a status panel to Studio showing deployment state - -All of this happens through the same core features your own config uses—`stackpanel.devshell.packages`, `stackpanel.scripts`, `stackpanel.files.entries`, and so on. Extensions are just well-organized modules. - -## Extension Types - -| Type | Where It Lives | Use Case | -|------|---------------|----------| -| **Builtin** | Shipped with Stackpanel | Core integrations (SST, Docker, CI, Git hooks) | -| **Local** | In your project's Nix config | Project-specific modules you write yourself | -| **External** | GitHub repos or other sources | Community-published extensions | - -## Quick Start - -### Enable a Builtin Extension - -Builtin extensions are already available—you just enable them: - -```nix -stackpanel.sst = { - enable = true; - project-name = "myapp"; - region = "us-west-2"; -}; -``` - -### Browse Available Extensions - -Use Studio to browse, enable, and configure extensions through a visual interface. Or list them from the CLI: - -```bash -stack commands -``` - -### Create a Local Extension - -For project-specific logic, create a module in your config: - -```nix -# .stack/modules/seed-data.nix -{ config, lib, pkgs, ... }: -let - cfg = config.stackpanel.seed-data; -in -{ - options.stackpanel.seed-data = { - enable = lib.mkOption { - type = lib.types.bool; - default = false; - description = "Enable database seed data management"; - }; - }; - - config = lib.mkIf cfg.enable { - stackpanel.scripts."db:seed" = { - path = ./scripts/seed.sh; - description = "Seed the database with test data"; - runtimeInputs = [ pkgs.postgresql ]; - }; - - stackpanel.scripts."db:reset" = { - exec = "dropdb myapp && createdb myapp && db:seed"; - description = "Reset and re-seed the database"; - }; - }; -} -``` - -Then import and enable it: - -```nix -# .stack/config.nix -{ - imports = [ ./modules/seed-data.nix ]; - stackpanel.seed-data.enable = true; -} -``` - -## Core Features Available to Extensions - -Extensions can use any of these core Stackpanel features: - -| Feature | Option Path | Description | -|---------|-------------|-------------| -| **File Generation** | `stackpanel.files.entries` | Generate files into the project workspace | -| **Scripts** | `stackpanel.scripts` | Add CLI commands to the devshell | -| **Packages** | `stackpanel.devshell.packages` | Add tools to the shell PATH | -| **Tasks** | `stackpanel.tasks` | Define runnable tasks | -| **Shell Hooks** | `stackpanel.devshell.hooks` | Run code on shell entry | -| **Variables** | `stackpanel.variables` | Manage secrets and config values | -| **Services** | `stackpanel.services` | Configure background services | -| **MOTD** | `stackpanel.motd` | Add entries to the shell welcome message | -| **Health Checks** | `stackpanel.healthchecks` | Register health check commands | - -Because extensions use the [module system](/docs/concepts/module-system), multiple extensions can contribute to the same features without conflicts. Two extensions can both add `.gitignore` entries, both register scripts, and both add packages—the module system merges everything. - -## Extension Categories - -Extensions are grouped by category in the Studio UI: - -| Category | Examples | -|----------|---------| -| Infrastructure | AWS, SST, cloud resources | -| CI/CD | GitHub Actions, deployment pipelines | -| Database | Database management, migrations | -| Secrets | Secret and variable management | -| Deployment | Docker, Cloudflare, Fly.io | -| Development | Linters, formatters, dev tools | -| Monitoring | Logging, metrics | -| Integration | Third-party service integrations | - -## Sections - - - - Install, enable, and configure extensions for your project - - - Build your own extensions with the full extension schema - - - Browse and discover extensions through Studio - - - -## How Extensions Compose - -Extensions follow the same composition model as everything else in Stackpanel. When you enable multiple extensions, their contributions are merged by the module system: - -``` -SST Extension - → adds sst CLI to PATH - → generates sst.config.ts - → registers sst:deploy, sst:dev scripts - → adds .sst to .gitignore - -Docker Extension - → adds docker CLI to PATH - → generates Dockerfile - → registers docker:build, docker:push scripts - → adds .docker to .gitignore - -CI Extension - → generates .github/workflows/ci.yml - → includes SST deploy steps (because SST is enabled) - → includes Docker build steps (because Docker is enabled) - → adds CI-specific .gitignore entries - -Your config - → adds project-specific packages - → sets environment variables - → defines custom scripts - - ↓ Module system merges everything ↓ - -Final devshell: all packages, all scripts, all env vars -Generated files: sst.config.ts, Dockerfile, ci.yml, .gitignore (merged) -``` - -No extension needs to know about the others. Each declares what it needs, and the module system handles the rest. - - -Extensions can declare dependencies on other extensions. If an extension requires PostgreSQL, it can specify `dependencies = [ "postgres" ]` and Stackpanel will ensure the dependency is satisfied before the extension loads. - - -## Reference - -- [Options Reference → Extensions](/docs/reference/extensions) for all extension configuration options -- [Options Reference → Modules](/docs/reference/modules) for the module system options -- [Core Concepts → Module System](/docs/concepts/module-system) for how module composition works \ No newline at end of file +- [Install and configure a module](./using-extensions) +- [Write a module and add Studio panels](./writing-extensions) +- [Understand discovery, overlays, and pins](./flake-inputs) +- [Publish or host a registry](./registry) diff --git a/apps/docs/content/docs/extensions/registry.mdx b/apps/docs/content/docs/extensions/registry.mdx index 536b5d85..2b6c67a2 100644 --- a/apps/docs/content/docs/extensions/registry.mdx +++ b/apps/docs/content/docs/extensions/registry.mdx @@ -1,178 +1,32 @@ --- -title: Extension Registry -description: Discover and install extensions through Studio's registry +title: Publishing a module catalog +description: Host an ordered, cacheable registry.v1.json index for public or organization modules. icon: package --- -import { Callout } from "fumadocs-ui/components/callout"; +The [official registry](https://github.com/darkmatter/stackpanel-registry) hosts two unrelated formats: `registry.json` maps Nix short names to flakes, while **`registry.v1.json`** lists installable Stackpanel modules. Publish the latter as ordinary JSON over HTTPS. It requires no database or Stackpanel server. A future marketplace can serve the same catalog. -The Extension Registry is a catalog of available extensions that you can browse and install through [Studio](/docs/studio). It provides a visual interface for discovering capabilities, reading documentation, and enabling extensions with a single click—no Nix knowledge required. +### Catalog contract -## Browsing the Registry +The document has `schemaVersion: 1` and a `modules` array. Each listing contains its identity (`id`, `slug`), display metadata (`name`, `description`, `icon`, `category`, `author`, `tier`), `latestVersion`, `versions`, `features`, `uiSlots`, and documentation links (`homepage`, `readmeUrl`). `tier` is `official`, `verified`, or `community`; it conveys provenance, not additional permissions. -Open Studio and navigate to the Extensions panel. The registry shows all available extensions organized by category: +Each version describes a **real module flake**: `version`, `flakeUrl`, `ref` or `rev`, `followsNixpkgs`, the `flakePath` output (normally `stackpanelModules.default`), and any additional `flakeInputs` required by the consumer. Use a unique slug that is a valid Nix input name. Publish immutable tags or revisions for released versions, retain older versions, and point `latestVersion` at a listed version. The JSON Schema and a complete catalog live beside the official index. -| Category | What It Covers | -|----------|---------------| -| **Infrastructure** | AWS, cloud resources, IAM roles | -| **CI/CD** | GitHub Actions, deployment pipelines | -| **Database** | Database management and migrations | -| **Secrets** | Secret and variable management | -| **Deployment** | Deployment tools (Cloudflare, Fly, SST) | -| **Development** | Dev tools, linters, formatters | -| **Monitoring** | Logging, metrics, observability | -| **Integration** | Third-party service integrations | +1. Put a module flake, README, and any UI build in a repository. Validate the module with Stackpanel's exported SDK and run a pure consumer `nix flake check`. +2. Make the flake reachable at its published ref **before** listing it. Check the `?dir=` URL if the repository contains several modules. +3. Add the listing and version to the catalog. Validate the JSON and ensure the README is reachable. Serve an `ETag` so unchanged indexes do not need to be downloaded again. -Each extension card shows its name, description, category, and whether it's currently enabled. Click an extension to see its full documentation, configuration options, and what it adds to your environment (packages, scripts, files, services). - -## Installing an Extension - -### From Studio - -1. Open the Extensions panel in Studio -2. Find the extension you want -3. Click **Enable** -4. Configure any required options in the form that appears -5. Studio writes the configuration to your `.stack/config.nix` - -That's it. The next time your shell reloads, the extension is active—its packages are on your `PATH`, its scripts are available, and its generated files are written to disk. - -### From Nix Config - -You can also enable extensions directly in your configuration: +### Choosing sources ```nix # .stack/config.nix { - stackpanel.extensions.sst = { - enabled = true; - }; - - # Extension-specific options (if any) - stackpanel.sst = { - project-name = "myapp"; - region = "us-west-2"; - }; + registries = [ "https://modules.example.org/registry.v1.json" ]; } ``` -Both approaches produce the same result. Studio is a convenience layer over the same Nix config you'd write by hand. - -## Extension Sources - -Extensions can come from three places: - -### Builtin Extensions - -Shipped with Stackpanel. These are always available in the registry and don't require any additional setup. - -Examples: `sst`, `ci`, `docker`, `bun`, `turbo`, `oxlint`, `git-hooks`, `process-compose`, `env-codegen`. - -### Local Extensions - -Defined in your project's Nix configuration. These are project-specific and not shared through the registry: - -```nix -stackpanel.extensions.my-feature = { - name = "My Feature"; - enabled = true; - source.type = "EXTENSION_SOURCE_TYPE_LOCAL"; - source.path = "./nix/extensions/my-feature.nix"; -}; -``` - -### External Extensions - -Installed from GitHub or other remote sources. These can be shared across projects and teams: - -```nix -# In your flake.nix inputs -inputs.stackpanel-stripe.url = "github:someone/stackpanel-stripe"; - -# In your flake.nix imports -imports = [ - inputs.stackpanel.flakeModules.default - inputs.stackpanel-stripe.flakeModules.default -]; -``` - -External extensions appear in the registry alongside builtin ones once they're added to your flake inputs. - -## What an Extension Provides - -Each extension in the registry declares which core features it uses. This is visible in the extension detail view: - -| Feature | What It Means | -|---------|---------------| -| **Files** | The extension generates configuration files | -| **Scripts** | The extension adds CLI commands to your shell | -| **Packages** | The extension adds tools to your `PATH` | -| **Tasks** | The extension defines runnable tasks | -| **Services** | The extension manages background processes | -| **Shell Hooks** | The extension runs code on shell entry | -| **Secrets** | The extension uses the secrets/variables system | -| **Checks** | The extension provides health checks | - -This helps you understand what enabling an extension will do before you install it. - -## Extension Panels - -Many extensions register **panels**—UI components that appear in Studio. Panels provide visibility into extension state without needing the terminal: - -| Panel Type | Description | -|------------|-------------| -| **Status** | Key-value status display (e.g., "Region: us-west-2", "Status: healthy") | -| **Apps Grid** | Visual grid of applications | -| **Form** | Configuration form for extension options | -| **Table** | Tabular data display | -| **Custom** | Extension-specific React component | - -Panels update in real time through the [Agent's](/docs/agent) SSE event stream, so status changes appear immediately. - -## Dependencies Between Extensions - -Extensions can declare dependencies on other extensions. The registry shows these relationships, and Stackpanel ensures dependencies are enabled before the extension that requires them: - -```nix -stackpanel.extensions.my-deploy = { - name = "My Deploy Extension"; - dependencies = [ "sst" "docker" ]; -}; -``` - -If you try to enable `my-deploy` without `sst` and `docker`, Studio will prompt you to enable the dependencies first. - -## Filtering and Search - -The registry supports filtering by: - -- **Category** — Show only infrastructure extensions, only CI/CD extensions, etc. -- **Status** — Show only enabled extensions, only disabled, or all -- **Tags** — Extensions can be tagged with keywords like `aws`, `typescript`, `deployment` -- **Source** — Filter by builtin, local, or external - -Use the search bar to find extensions by name or description. - - -The registry is served locally by the Stackpanel [Agent](/docs/agent). No internet connection is required to browse builtin extensions. External extensions need network access only during initial installation (adding the flake input). - - -## Publishing Extensions - -If you've built an extension that others might find useful, you can publish it as a flake. See [Writing Extensions](/docs/extensions/writing-extensions) for the full guide on creating extensions, and the extension schema reference for the metadata fields that make your extension discoverable in the registry. - -A well-published extension includes: - -- A descriptive `name` and `description` -- An appropriate `category` for registry grouping -- Relevant `tags` for search discoverability -- Feature flags indicating which core features it uses -- At least one panel for Studio visibility +Project sources are searched first, followed by sources in the user's `~/.config/stackpanel/config.yaml` (`registries`, an ordered list of URLs). With neither configured, the agent uses the official index. The first source to list an ID wins. To use both a private and the official index, list both. For a private index, set `registryHeaders` in the **user file**: the key is its exact index URL, and the value is a map of HTTP header names to values. Never put registry credentials in `.stack/config.nix`, locked URLs, or catalog entries. -## Reference +### Offline behavior -- [Writing Extensions](/docs/extensions/writing-extensions) for creating your own extensions -- [Flake Inputs](./flake-inputs) for how extensions declare and auto-install required flake inputs -- [Using Extensions](./using-extensions) for day-to-day extension management -- [Studio](/docs/studio) for the web interface that hosts the registry -- [Options Reference → Extensions](/docs/reference/extensions) for all extension configuration options \ No newline at end of file +The agent keeps a TTL and ETag cache under the user's cache directory and ships a snapshot of the official catalog. Reading a cached listing does not guarantee its flake sources or binary dependencies are in the Nix store. An install still fails if Nix cannot lock the requested inputs. A broken private registry must not silently resolve its module ID to an unrelated sample. diff --git a/apps/docs/content/docs/extensions/using-extensions.mdx b/apps/docs/content/docs/extensions/using-extensions.mdx index 7a8d2303..ee39859e 100644 --- a/apps/docs/content/docs/extensions/using-extensions.mdx +++ b/apps/docs/content/docs/extensions/using-extensions.mdx @@ -1,209 +1,49 @@ --- -title: Using Extensions -description: Install, enable, and configure extensions to add capabilities to your project +title: Using modules +description: Install, preview, enable, update, and remove a module in a project. icon: puzzle --- -import { Callout } from "fumadocs-ui/components/callout"; +Run the CLI in the consumer project. In Studio, select that project before opening **Modules**. Search is a catalog operation; **List all** also shows the local and bundled modules that this project can enable. -Extensions are the primary way to add new capabilities to a Stackpanel project. Each extension is a Nix module that bundles together packages, scripts, generated files, services, and UI panels into a single, toggleable unit. - -## What Extensions Provide - -When you enable an extension, it can contribute any combination of: - -| Feature | Description | -|---------|-------------| -| **Packages** | CLI tools and runtimes added to your `PATH` | -| **Scripts** | Named commands available in the devshell | -| **Files** | Generated config files written to your project | -| **Services** | Background processes managed by process-compose | -| **Shell hooks** | Code that runs on shell entry | -| **Variables** | Environment variables and secrets | -| **Tasks** | Runnable task definitions | -| **Panels** | UI panels visible in [Studio](/docs/studio) | - -Everything composes through the [module system](/docs/concepts/module-system). Enabling an extension merges its contributions with the rest of your configuration—no conflicts, no manual wiring. - -## Builtin Extensions - -Stackpanel ships with several builtin extensions that cover common use cases: - -| Extension | What it does | -|-----------|-------------| -| **SST** | AWS infrastructure provisioning with SST | -| **CI** | GitHub Actions workflow generation | -| **Docker** | Dockerfile and docker-compose generation | -| **Git Hooks** | Pre-commit and other Git hooks via Nix | -| **Bun** | Bun package manager integration | -| **Turbo** | Turborepo configuration and caching | -| **OxLint** | Fast JavaScript/TypeScript linting | -| **Process Compose** | Process orchestration for dev services | -| **Env Codegen** | Type-safe environment variable generation | - -Builtin extensions are always available—you just need to enable them in your config. - -## Enabling an Extension - -Most extensions follow the same pattern: set `enable = true` under their namespace. - -```nix -# .stack/config.nix -{ - stackpanel.modules.turbo.enable = true; - stackpanel.modules.bun.enable = true; - stackpanel.modules.git-hooks.enable = true; - - stackpanel.sst = { - enable = true; - project-name = "myapp"; - region = "us-west-2"; - }; -} -``` - -When you enter your dev shell after enabling an extension, the module system evaluates it and merges its contributions into your environment. Disable it by setting `enable = false`, and everything it contributed is cleanly removed. - - -You can also enable and configure extensions through [Studio](/docs/studio), which provides a visual interface for browsing the extension registry and toggling extensions on and off. - - -## Configuring Extensions - -Each extension declares its own set of options. These are documented in the extension's config schema and visible in Studio. A typical extension might look like: - -```nix -stackpanel.sst = { - enable = true; - project-name = "myapp"; - region = "us-west-2"; - - kms.enable = true; - - oidc = { - provider = "github-actions"; - github-actions = { - org = "my-org"; - repo = "my-repo"; - }; - }; -}; +```sh +stack module search playwright +stack module install playwright +stack module list --all +stack module info playwright ``` -Extensions that generate files or register scripts will do so automatically based on the options you set. You don't need to wire anything together manually. - -## Discovering Available Extensions +In Studio, open **Explore Modules**, choose a registry entry, and click **Install**. This adds and locks the flake input; it does not enable the module or mount its panels. Review the adoption and file plan, then click **Enable** to see the module’s UI. Module-detail panels appear in **Installed → Configure module → Overview**; a sidebar panel such as Fly appears under its declared navigation section. Inspect `flake.nix`, `flake.lock`, and `.stack/config.nix` in your diff. Rebuild the devshell when Studio prompts. -### In Studio +The CLI asks about each optional offer, previews the effects of your answers, and asks for final approval before enabling. Press Enter at an offer to leave it unanswered. Cancelling the final preview leaves the locked input installed but does not save answers, enable the module, or materialize files. -The [Studio](/docs/studio) web UI includes an extension registry where you can browse all available extensions—builtin and external—with descriptions, categories, and one-click enable/disable. +For automation, `--yes` on `install` or `enable` approves enabling and reconciling **without adopting unspecified offers**. Add `--adopt-defaults` to accept the declared defaults, `--with ` to accept an offer, `--without ` to record a decline, or `--addon =` for a boolean, choice value, or comma-separated selection. Offer decisions are recorded at the revision you reviewed. -### In the CLI - -```bash -# List all configured extensions -stack commands +```sh +stack module enable playwright +stack module disable playwright +stack module update playwright +stack module uninstall playwright ``` -### In Nix - -All registered extensions are available on the config object: - -```nix -config.stackpanel.extensions # All extensions -config.stackpanel.extensionsComputed # Only enabled extensions -config.stackpanel.extensionsBuiltin # Only builtin extensions -config.stackpanel.extensionsExternal # Only external/local extensions -``` - -## Extension Categories - -Extensions are organized into categories for easier discovery: +Disabling leaves the input installed. Uninstalling removes the input and its explicit module import, if it had one. Neither is permission to delete files you own. Check the reconciliation plan for generated files. To install a catalog version other than the latest, select it in Studio or use `stack module install @`. -| Category | Examples | -|----------|---------| -| **Infrastructure** | AWS, SST, cloud resources | -| **CI/CD** | GitHub Actions, deployment pipelines | -| **Database** | Database management, migrations | -| **Secrets** | Secret and variable management | -| **Deployment** | Docker, Cloudflare, Fly.io | -| **Development** | Linters, formatters, dev tools | -| **Monitoring** | Logging, metrics | -| **Integration** | Third-party service integrations | +### Where settings live -## External Extensions - -Extensions don't have to be builtin. You can install extensions from GitHub or other sources by adding them as flake inputs: +`.stack/config.nix` is the source of truth; entries in this file are relative to `stackpanel`. For a module using the default paths: ```nix -# flake.nix { - inputs = { - stackpanel.url = "github:darkmatter/stackpanel"; - stackpanel-stripe.url = "github:someone/stackpanel-stripe"; - }; - - outputs = inputs @ { self, stackpanel, ... }: - stackpanel.lib.mkFlake { - inherit inputs self; - - imports = [ - inputs.stackpanel-stripe.flakeModules.default - ]; - }; + modules.playwright.enable = true; } ``` -Once imported, the extension's options are available under `stackpanel.` just like builtin extensions. - -## Local Extensions - -For project-specific extensions that don't need to be shared, define them directly in your Nix configuration: - -```nix -stackpanel.extensions.my-feature = { - name = "My Feature"; - enabled = true; - source.type = "EXTENSION_SOURCE_TYPE_LOCAL"; - source.path = "./nix/extensions/my-feature.nix"; -}; -``` - -Local extensions are useful for encapsulating project-specific logic—things that don't make sense as a general-purpose extension but still benefit from the extension system's structure (UI panels, feature flags, clean enable/disable). - -## Extension Dependencies - -Extensions can declare dependencies on other extensions. When you enable an extension that depends on another, the dependency is checked and an error is raised if it's missing: - -```nix -stackpanel.extensions.my-deploy = { - name = "My Deploy"; - enabled = true; - dependencies = [ "sst" "docker" ]; -}; -``` - -This prevents configuration errors from incomplete setups—you'll know immediately if a required extension isn't enabled. - -## What Happens When You Disable an Extension - -Disabling an extension (`enable = false`) removes everything it contributed: - -- Its packages are removed from `PATH` -- Its scripts are no longer available -- Its generated files stop being produced -- Its services are removed from process-compose -- Its shell hooks stop running -- Its UI panels disappear from Studio +The module can declare a different `enablePath` or `configPath` when it owns another option namespace. Use the module’s README and configuration form rather than guessing a path from its name. Per-app options belong in `apps.`. -Because of how the [module system](/docs/concepts/module-system) works (specifically `lib.mkIf`), disabled extensions have zero impact on your environment. They're not just hidden—they're not evaluated at all. +### Running an action - -Generated files that an extension previously created will still exist on disk after disabling it. Run a rebuild to clean up stale generated files, or delete them manually. - +`stack module info ` lists the available actions. Run one with `stack module run ` or use its button in Studio. A module defines the accepted arguments, the command, and whether the result is a stream of output or JSON. Panels do not submit arbitrary shell commands. -## Next Steps +### Trust -- [Writing Extensions](./writing-extensions) to create your own extensions -- [Extension Registry](./registry) for the Studio extension browser -- [The Module System](/docs/concepts/module-system) to understand how extensions compose \ No newline at end of file +Read the source before adding a new input. A pinned module is reproducible, **not** sandboxed project code: it can contribute build steps and commands that you may later execute as your user. The iframe sandbox limits a module's *frontend*; it does not make an untrusted flake, action, or daemon safe to adopt. diff --git a/apps/docs/content/docs/extensions/writing-extensions.mdx b/apps/docs/content/docs/extensions/writing-extensions.mdx index 67117e64..75864884 100644 --- a/apps/docs/content/docs/extensions/writing-extensions.mdx +++ b/apps/docs/content/docs/extensions/writing-extensions.mdx @@ -1,482 +1,244 @@ --- -title: Writing Extensions -description: Build reusable modules that add capabilities to any Stackpanel project +title: Writing a module +description: Use the public Nix SDK to contribute settings, actions, services, and Studio UI. icon: puzzle --- -import { Callout } from "fumadocs-ui/components/callout"; +Start with a flake and a module. The module receives the project's `pkgs`, `config`, and `lib.stackpanel`; it does not import any files from Stackpanel's source tree. -Extensions are the primary way to package reusable functionality in Stackpanel. An extension is a Nix module that registers itself in the extension system and uses core Stackpanel features—file generation, scripts, services, packages, and more—to provide integrated capabilities. +To start with editor support, run these commands in an empty directory with flake-enabled Nix: -If you've written any Nix configuration for Stackpanel, you already know 90% of what you need. An extension is just a module with some extra metadata so the registry and [Studio](/docs/studio) can discover and display it. - -## Anatomy of an Extension - -Every extension does three things: - -1. **Declares options** — configuration knobs for the extension -2. **Registers itself** — metadata for discovery, categorization, and UI -3. **Uses core features** — contributes files, scripts, packages, services, etc. +```sh +nix flake init -t github:darkmatter/stackpanel#module +nix flake lock ./dev +``` -Here's a minimal example: +In a Git repository, track the starter files before locking. Commit `dev/flake.lock`, then open and trust the **module root** in VS Code with Nix IDE or Zed with the Nix extension. The workspace launches nixd and loads option descriptions from that lock; it needs `nix` on the editor’s PATH, not a global nixd installation. The published module has no SDK input: consumers supply their own Stackpanel version. Update the editor pin with `nix flake update stackpanel --flake ./dev` and restart the language server when you adopt a newer SDK. ```nix -# nix/stackpanel/my-extension/my-extension.nix -{ pkgs, lib, config, ... }: -let - cfg = config.stackpanel.my-extension; -in +# flake.nix { - options.stackpanel.my-extension = { - enable = lib.mkOption { - type = lib.types.bool; - default = false; - description = "Enable my extension"; - }; + description = "Workspace report"; + outputs = _: { stackpanelModules.default = import ./module.nix; }; +} +``` - greeting = lib.mkOption { - type = lib.types.str; - default = "Hello from my extension!"; - description = "A greeting message"; +```nix +# module.nix +{ lib, pkgs, config, ... }@args: +let + fields = { + title = lib.stackpanel.spField.string { + index = 1; + description = "Report title"; + default = "Workspace"; + ui.label = "Title"; }; }; - - config = lib.mkIf cfg.enable { - # Register the extension - stackpanel.extensions.my-extension = { - name = "My Extension"; - enabled = true; - builtin = true; - description = "An example extension"; - tags = [ "example" ]; - - features = { - scripts = true; - packages = true; - }; - }; - - # Use core features - stackpanel.scripts."my-ext:hello" = { - exec = "echo '${cfg.greeting}'"; - description = "Print a greeting"; + report = pkgs.writeShellApplication { + name = "workspace-report"; + runtimeInputs = [ pkgs.jq ]; + text = ''jq -c '{title: (.title // "Workspace")}' ''; + }; +in +lib.stackpanel.mkModule { + name = "report"; + meta = { name = "Workspace report"; category = "development"; icon = "clipboard-list"; }; + settings = fields; + readme = ./README.md; + packages = [ report ]; + actions.report = { + label = "Run report"; + script = lib.getExe report; + argsSchema = { + type = "object"; + properties.title.type = "string"; + additionalProperties = false; }; - - stackpanel.devshell.packages = [ pkgs.cowsay ]; - - stackpanel.motd.features = [ "My Extension" ]; + outputMode = "json"; }; -} +} args ``` -Enable it in your config: +`settings` becomes a typed Nix option tree and a runtime JSON Schema. There is no per-extension `.proto` generation step. `mkModule` registers the metadata even while the module is disabled. Use its `config = cfg: { ... };` for enabled behavior. For files, scripts, tasks and services contributed there, set `module = "report";` so the agent can show the outputs without guessing from names. -```nix -stackpanel.my-extension = { - enable = true; - greeting = "Howdy, partner!"; -}; -``` +**You don't need to write a UI.** Studio builds the configuration form from `settings`, lists the module's actions with their argument forms, attributes outputs to the module, and shows its README. Start there. -And you've got a `my-ext:hello` command in your shell, `cowsay` on your PATH, and "My Extension" listed in the welcome message. +### Actions and daemons -## Extension Registration +An action's executable reads a JSON object on **stdin**. The agent validates it against `argsSchema`. `outputMode = "stream"` sends stdout, stderr and the exit code; `"json"` expects one JSON document on stdout. Never form a shell command from a panel field. Use `confirm` on actions that modify project or external state. A table or status panel can reference a read-only JSON action with `dataAction`; the user runs it to refresh the panel. -The `stackpanel.extensions.` attribute set is how Stackpanel discovers your extension. It controls what appears in Studio, how the extension is categorized, and what features it advertises. +A service can opt into the local HTTP/WebSocket proxy with `module = "report"; proxy = { enable = true; port = 9070; };` on the evaluated `stackpanel.services.` entry. This declares an existing module-managed daemon, not an arbitrary hostname. Bind it to loopback. Anyone using the extension UI may be able to call this service; do not proxy an unrestricted admin API. -### Required Fields +### App extensions -```nix -stackpanel.extensions.my-extension = { - name = "My Extension"; # Human-readable display name - enabled = true; # Whether the extension is active -}; -``` - -### Optional Fields - -```nix -stackpanel.extensions.my-extension = { - name = "My Extension"; - enabled = true; - - # Identity - description = "What this extension does"; - builtin = false; # true for extensions shipped with Stackpanel - category = "EXTENSION_CATEGORY_DEVELOPMENT"; - tags = [ "tooling" "linting" ]; - priority = 100; # Load order (lower = earlier) - dependencies = [ "other-ext" ]; # Required extensions - - # Feature flags (what core features this uses) - features = { - files = true; - scripts = true; - tasks = false; - secrets = false; - shell-hooks = false; - packages = true; - services = false; - checks = false; - }; - - # Source (for non-builtin extensions) - source = { - type = "EXTENSION_SOURCE_TYPE_GITHUB"; - repo = "myorg/stackpanel-my-ext"; - ref = "main"; - }; -}; -``` - -### Categories - -Use categories to group extensions in the Studio UI: - -| Category | Use Case | -|----------|----------| -| `EXTENSION_CATEGORY_INFRASTRUCTURE` | AWS, cloud resources, networking | -| `EXTENSION_CATEGORY_CI_CD` | GitHub Actions, deployment pipelines | -| `EXTENSION_CATEGORY_DATABASE` | Database management and tooling | -| `EXTENSION_CATEGORY_SECRETS` | Secret and variable management | -| `EXTENSION_CATEGORY_DEPLOYMENT` | Deployment tools and platforms | -| `EXTENSION_CATEGORY_DEVELOPMENT` | Dev tools, linters, formatters | -| `EXTENSION_CATEGORY_MONITORING` | Logging, metrics, observability | -| `EXTENSION_CATEGORY_INTEGRATION` | Third-party service integrations | - -## Core Features Available to Extensions +Use `appOptions` for per-app settings and `panels.mkPanelFromSpFields` to make an app form. A runtime registers `appRuntimes`, build derivations under `appBuildProviders..`, a container builder if appropriate, and the resolved deployment command. A framework registers `appFrameworks.` with its compatible runtimes, default tasks, and deployment metadata. The [registry's Rust and Next.js modules](https://github.com/darkmatter/stackpanel-registry/tree/main/modules) demonstrate the two different contracts. -Extensions compose core Stackpanel features to build integrated functionality. Here's what you can use: +### Author a panel in Nix -### File Generation - -Generate files into the project workspace. Multiple extensions can contribute to the same file through the [module system](/docs/concepts/module-system). +Inside `lib.stackpanel.mkModule`, give each widget a name and one kind. In the starter’s `module.nix`, typing `ui.widgets.appCount.me` suggests `metric`. Inside that widget, `la` suggests `label`; hovering shows its type and documentation. A single widget needs no explicit root: ```nix -stackpanel.files.entries."path/to/generated-file.ts" = { - text = '' - // Generated by my-extension - export const setting = "${cfg.some-setting}"; - ''; -}; - -stackpanel.files.entries.".gitignore" = { - type = "line-set"; - content = [ ".my-extension-cache" ]; +ui.widgets.appCount.metric = { + label = "Configured apps"; + value = builtins.length (builtins.attrNames config.stackpanel.apps); }; ``` -### Scripts - -Add CLI commands to the devshell. Use the `:` namespace convention to avoid collisions: +For multiple widgets, list child IDs in display order on a stack or section. The compiler infers the only widget without a parent as the root; setting `ui.root` explicitly does not hide disconnected widgets. Each kind also has a `lib.stackpanel.ui` constructor for composing fragments: ```nix -# Inline script -stackpanel.scripts."my-ext:run" = { - exec = "echo 'Running with ${cfg.some-setting}'"; - description = "Run my extension command"; -}; - -# File-based script (recommended for anything longer than a one-liner) -stackpanel.scripts."my-ext:deploy" = { - path = ./src/scripts/deploy.sh; - description = "Deploy using my extension"; - runtimeInputs = [ pkgs.awscli2 pkgs.jq ]; - env.MY_SETTING = cfg.some-setting; +ui.widgets = { + report.section = { title = "Workspace report"; children = [ "hint" "run" ]; }; + hint.text.content = "Inspect the current workspace configuration."; + run = lib.stackpanel.ui.actions { ids = [ "report" ]; }; }; ``` -File-based scripts get better editor support and are easier to test in isolation. Use the `env` option to pass Nix-evaluated configuration values into the script. +The option path is the editor-friendly form: nixd can describe `run.actions.ids` without inferring a function argument. A larger layout can live in `ui = import ./studio.nix { inherit lib config; };`, but a bare imported attrset does not necessarily give nixd the same enclosing option path. -### Packages +| Widget kind | Fields | +| --- | --- | +| `stack`, `section` | Group `children`. `stack.direction` is `vertical` or `horizontal`; `section.title` labels the group. | +| `text`, `badge`, `metric` | `content`; `text`; or `label` and a string/number `value`. | +| `table` | Ordered `columns` with `key` and `label`, and `rows` of scalar cells. | +| `actions` | Optional `ids`. Omit to show all **declared actions of the owning module**; an empty list shows none. | +| `appPicker` | `apps` (app IDs), optional `label`, and `value` bound to local state. | +| `statusView` | Literal `action` and optional `app`. Runs on request; results stay inside the panel. | -Add tools to the devshell PATH: +Only expose data intended for display, not all of `config`. `lib.stackpanel.ui.read` builds a read-only binding; `bindLocal` builds a picker’s writable binding. For example: ```nix -stackpanel.devshell.packages = [ - pkgs.some-tool - pkgs.another-tool -]; -``` - -### Services - -Register background services managed by [process-compose](/docs/services/process-compose): - -```nix -stackpanel.services."my-ext-server" = { - enable = true; - description = "My extension background server"; - command = "${pkgs.my-tool}/bin/my-tool serve --port ${toString cfg.port}"; - readiness_probe = { - http_get = { port = cfg.port; path = "/health"; }; - initial_delay_seconds = 2; +ui = { + state.data.appIds = [ "api" "web" ]; + state.local.app = "api"; + widgets = { + health.stack.children = [ "target" "status" ]; + target.appPicker = { + apps = lib.stackpanel.ui.read "/data/appIds"; + value = lib.stackpanel.ui.bindLocal "app"; + }; + status.statusView = { action = "status"; app = lib.stackpanel.ui.read "/local/app"; }; }; }; ``` -### Shell Hooks +Nix turns the layout into the [json-render document](https://json-render.dev/docs/specs) Studio consumes. There is no contributor codegen step. Tools may still supply a raw `{ root, elements, state? }` document or `ui = ./studio.json;`; a bare file path is read as JSON. Do not mix raw `elements` and typed `widgets`. Nix catches missing fields, typos and invalid trees; Studio still validates the evaluated document, and the agent still verifies live actions and targets. -Run code on shell entry: +`Load once` executes for the selected app. Updating on selection changes is a separate, stoppable opt-in, not permission to poll in the background. The agent binds live calls to the project, panel, evaluated spec and executable. A changed grant requires new approval. An action with a confirmation requirement belongs in `Actions`, never in `StatusView`. A status command can use the network: approving the command is **not** a per-host firewall for its process. -```nix -stackpanel.devshell.hooks.my-extension = [ - '' - echo "My extension is active" - '' -]; -``` +### Placing a panel -### Tasks +For another surface, use `panels.report-summary = { title = "Report"; slot = "overview"; spec.widgets.run.actions.ids = [ "report" ]; };` inside `mkModule`. The same widget declarations work in any slot. `mkModule` supplies the owner; directly registered `stackpanel.panels` also need `module`. No `type` is needed with `spec`. -Define runnable tasks: +| Slot | Surface | +| --- | --- | +| `module` | Module detail and filtered panels (default) | +| `sidebar` | Navigation to `/studio/m/`; `nav` selects the section | +| `overview`, `configuration`, `setup` | Summary cards, settings, onboarding | +| `app:runtime`, `app:framework` | App runtime and compatible framework configuration | +| `app:container`, `app:deployment`, `app:tab` | App-specific tabs | -```nix -stackpanel.tasks."my-ext:setup" = { - description = "Initial setup for my extension"; - exec = "my-tool init --config ${cfg.configPath}"; -}; -``` +Stock forms and tables can also use `actions`, `rowActions` and `tabs`. Reference only actions and child panels of the same module. A secret-reference field carries a reference name, never decrypted secret data. -### MOTD +### Use the same Web Components from HTML -Register features in the shell welcome message: +Use a sandboxed HTML panel only when the document cannot express the interaction. The SDK exports actual browser elements; contributors do not import Studio's React components. Place `index.html`, `panel.js` and the SDK's prebuilt `dist/extension-sdk.js` in the evaluated static package. Load a **local** module script, not a CDN or inline handler: -```nix -stackpanel.motd.features = [ "My Extension" ]; +```html + + + ``` -## File-Based Scripts with `srcDir` - -For extensions with multiple scripts and health checks, use the `srcDir` option to enable auto-discovery: - -``` -nix/stackpanel/my-extension/ -├── my-extension.nix -└── src/ - ├── scripts/ - │ ├── deploy.sh # → my-ext:deploy - │ ├── build.sh # → my-ext:build - │ └── status.sh # → my-ext:status - └── checks/ - └── health.sh # → my-ext:health +```js +// panel.js — or import from "@stackpanel/extension-sdk/elements" in a bundler. +import { registerPanelElements } from "./extension-sdk.js"; +registerPanelElements(); +const picker = document.querySelector("#target"); +const status = document.querySelector("#status"); +picker.apps = ["api", "web"]; +picker.value = "api"; +const select = () => { status.args = { app: picker.value }; }; +picker.addEventListener("change", select); +select(); ``` -Register the `srcDir` in your extension metadata: +`sp-metric` takes `label` and `value`; `sp-data-table` takes `columns` and `rows` as DOM properties. `sp-action` takes an `action` ID and optional `args` property. Neither an element nor a synthetic DOM event authorizes a request. Module HTML executes in its own iframe; register only Stackpanel's elements on the Studio page. -```nix -stackpanel.extensions.my-extension = { - name = "My Extension"; - enabled = true; - srcDir = ./src; # Enables auto-discovery - # ... -}; -``` +### Sandbox permissions -Scripts in `src/scripts/` are automatically namespaced with the extension name. A file called `deploy.sh` becomes the command `my-ext:deploy`. Health checks in `src/checks/` are registered as Stackpanel health checks. - -This approach is recommended over inline scripts because: - -- Better editor support (syntax highlighting, shellcheck, linting) -- Easier to test scripts in isolation -- Cleaner separation of Nix configuration and shell logic -- Scripts become Nix derivations (immutable, cached) - -## Studio Panels - -Extensions can define UI panels that appear in [Studio](/docs/studio): +Declare the bundle and the smallest set of capabilities it needs: ```nix -stackpanel.extensions.my-extension = { - name = "My Extension"; - enabled = true; - - panels = [ - { - id = "my-ext-status"; - title = "My Extension Status"; - type = "PANEL_TYPE_STATUS"; - order = 1; - fields = [ - { - name = "metrics"; - type = "FIELD_TYPE_STRING"; - value = builtins.toJSON [ - { label = "Setting"; value = cfg.some-setting; status = "ok"; } - { label = "Version"; value = "1.2.3"; status = "ok"; } - ]; - } - ]; - } - ]; +stackpanel.panels.report-ui = { + module = "report"; + title = "Report viewer"; + type = "PANEL_TYPE_CUSTOM"; + slot = "sidebar"; + uiBundle = { package = reportUi; entry = "index.html"; permissions = [ "actions:run" ]; actionIds = [ "report" ]; }; }; ``` -### Panel Types - -| Type | Description | Use Case | -|------|-------------|----------| -| `PANEL_TYPE_STATUS` | Key-value status display | Show configuration state, health status | -| `PANEL_TYPE_APPS_GRID` | Grid of applications | Display managed apps with status indicators | -| `PANEL_TYPE_FORM` | Configuration form | Let users edit extension settings in Studio | -| `PANEL_TYPE_TABLE` | Tabular data | Lists of items, log entries, etc. | -| `PANEL_TYPE_CUSTOM` | Custom React component | Advanced UIs that need full control | - -## Conditional Configuration with `mkIf` +The local agent serves the evaluated bundle. Studio runs it in an opaque-origin iframe with scripts enabled, without same-origin access. Bundle JavaScript and styles locally; use the `@stackpanel/extension-sdk` bridge instead of fetching the agent directly: -Always wrap your `config` block with `lib.mkIf cfg.enable` so the extension does nothing when disabled: +```ts +import { getContext, runAction } from "@stackpanel/extension-sdk"; -```nix -config = lib.mkIf cfg.enable { - # Everything here only takes effect when enable = true - stackpanel.extensions.my-extension = { ... }; - stackpanel.scripts."my-ext:run" = { ... }; - stackpanel.devshell.packages = [ ... ]; -}; +const context = await getContext(); +if (context.permissions.includes("actions:run")) { + const result = await runAction("report", { title: "Nightly" }); + if (result.exitCode !== 0) throw new Error(result.stderr); + document.body.textContent = JSON.stringify(result.json); +} ``` -This ensures that disabling the extension cleanly removes all of its contributions—packages, scripts, generated files, services, everything. - -## Practical Example: Oxlint Extension - -Here's a real-world pattern based on the builtin oxlint extension: - -```nix -{ pkgs, lib, config, ... }: -let - cfg = config.stackpanel.oxlint; -in -{ - options.stackpanel.oxlint = { - enable = lib.mkOption { - type = lib.types.bool; - default = false; - description = "Enable oxlint for fast JavaScript/TypeScript linting"; - }; +Request the fewest permissions needed: `config:read`, `config:patch`, `actions:run`, `service:proxy`. For example, `patchModuleConfig({ title: "Nightly" })` changes settings under the host-bound module; it takes neither an absolute Nix path nor a module ID. `proxyFetch` takes a declared service name and a relative request path. `onConfigChange`, theme CSS variables, and React hooks are also available. Do not pass agent tokens or plaintext secrets through the bridge. - config-file = lib.mkOption { - type = lib.types.str; - default = "oxlint.json"; - description = "Path to the oxlint configuration file"; - }; - }; +Opening executable UI is a separate operator choice. **Deny** does not prepare the bundle or contact the linked development server. **Open panel once** authorizes preparation (which may download or build the bundle). The agent checks that the source and executable revision still match the displayed project snapshot before proceeding. If the agent cannot supply a matching review, refresh the project or update the agent; Studio does not fall back to an unreviewed launch. - config = lib.mkIf cfg.enable { - stackpanel.extensions.oxlint = { - name = "Oxlint"; - enabled = true; - builtin = true; - category = "EXTENSION_CATEGORY_DEVELOPMENT"; - tags = [ "linting" "javascript" "typescript" ]; - srcDir = ./src; - - features = { - packages = true; - scripts = true; - files = true; - }; - - panels = [ - { - id = "oxlint-status"; - title = "Oxlint"; - type = "PANEL_TYPE_STATUS"; - order = 10; - fields = [ - { - name = "metrics"; - type = "FIELD_TYPE_STRING"; - value = builtins.toJSON [ - { label = "Config"; value = cfg.config-file; status = "ok"; } - ]; - } - ]; - } - ]; - }; - - stackpanel.devshell.packages = [ pkgs.oxlint ]; +Each iframe request to run an action or contact a module service is reviewed **in Studio before dispatch**. Deny sends nothing to the service; allowing a request does not allow the next one. Stop the panel to remove the frame and cancel outstanding work. Production asset policy blocks direct fetch and WebSocket connections. A linked development server supplies its own headers: open only one you trust. To forbid module-supplied JavaScript entirely, start the agent with `STACKPANEL_DISABLE_CUSTOM_UI=1`. This leaves native spec panels available; it does not sandbox Nix evaluation or a module's native processes. - stackpanel.scripts."oxlint:lint" = { - exec = "oxlint --config ${cfg.config-file} ."; - description = "Run oxlint on the project"; - }; +Studio renders images in module Markdown as their alt text. Use an explicit link to a diagram or badge rather than requiring a third-party request just to open a module. - stackpanel.scripts."oxlint:fix" = { - exec = "oxlint --config ${cfg.config-file} --fix ."; - description = "Run oxlint with auto-fix"; - }; +#### Exposing settings for one app - stackpanel.files.entries.".gitignore" = { - type = "line-set"; - content = [ ".oxlint-cache" ]; - }; +An app-slot panel can edit **only the app that Studio used to open it**. To make a setting public, include its key in that app's enabled `panel.apps` entry. For example, suppose the evaluated `apps.shop.report.workers` option is the number `2`: - stackpanel.motd.features = [ "Oxlint" ]; - }; -} +```nix +stackpanel.panels.report-settings = { + module = "report"; + title = "Report workers"; + type = "PANEL_TYPE_CUSTOM"; + slot = "app:tab"; + apps.shop = { enabled = true; config.workers = "2"; }; + uiBundle = { package = reportUi; entry = "index.html"; permissions = [ "config:read" "config:patch" ]; }; +}; ``` -## Extension Types +The public settings are the intersection of keys in `panel.apps.shop.config` and portable values actually present in `apps.shop.report`. The panel declaration names the keys; its string metadata does **not** supply the values or their types. Here `getConfig()` returns `{ workers: 2 }`, not `{ workers: "2" }`. Do not include secrets. Declaring a panel field alone does not expose an app option. -### Builtin Extensions +Call `await patchModuleConfig({ workers: 4 })` to update `apps.shop.report.workers`. There is no app, module, or path argument: Studio sends the relative patch with the original document grant, and the agent checks the current public settings before writing. A patch cannot add undeclared keys, switch apps, or fall back to module-global config. With both grants, `onConfigChange` receives the refreshed app settings; a patch-only panel receives no values. In React, `useAppModuleConfig()` from `@stackpanel/extension-sdk/react` returns the bound `appId`, `settings`, and a `patchModuleConfig` function only when `config:patch` is granted. -Shipped with Stackpanel itself. These live in `nix/stackpanel/` and set `builtin = true`. If you're contributing to the Stackpanel project, this is what you'd write. +#### Exposing a service to a panel -### Local Extensions - -Defined in your project's Nix configuration. Good for project-specific automation that doesn't need to be shared: +For a panel with `service:proxy`, declare an owned service and an explicit loopback target. Setting the service's primary `port` alone does **not** grant access. ```nix -stackpanel.extensions.my-project-tooling = { - name = "My Project Tooling"; - enabled = true; - source.type = "EXTENSION_SOURCE_TYPE_LOCAL"; - source.path = "./nix/extensions/my-tooling.nix"; +stackpanel.services.report = { + enable = true; + module = "report"; + command = "exec ${reportServer}/bin/report-server --listen 127.0.0.1:8765"; + proxy = { enable = true; port = 8765; }; }; ``` -### External Extensions - -Installed from GitHub or other sources. These are distributed as flake inputs: +Start process-compose from the project root. Its launcher opens `.stack/state/proxy/report/report.identity` read-only on file descriptor 9 before starting the service. The file must be a regular, single-link file owned by the current user with mode `0600`; directories below the project root must not be symlinks or writable by others. The process serving the connection must retain FD 9. If a supervisor closes extra descriptors, configure it to pass FD 9 through or launch the server directly with `exec`. Listening on the right port without the descriptor is not sufficient. The marker is local process identity, not a token to send to Studio. -```nix -# flake.nix -inputs.my-extension.url = "github:someorg/stackpanel-my-extension"; - -# In your flake modules -imports = [ - inputs.my-extension.flakeModules.default -]; -``` +Panel code uses `proxyFetch("report", "/status")` for HTTP. Studio supplies the project and authorization headers plus the panel's `X-Stackpanel-UI-Grant`; none of these belong in iframe code. The bridge does not expose WebSockets. Direct HTTP clients and native WebSocket clients must send `Authorization: Bearer …` and `X-Stackpanel-Project` as headers. A browser WebSocket cannot supply them; do not put credentials in URLs, cookies, or subprotocols. The proxy does not accept query strings, follow redirects, or forward agent credentials to the service. -The extension registers itself when imported—users just need to enable it: +### Develop, link, and release -```nix -stackpanel.my-extension.enable = true; -``` +From the extension checkout, run `stack module dev` (use `--id example` for the unrenamed starter). It creates a scratch **consumer** project, evaluates your checkout as a local override and opens the module in Studio. Editing tracked Nix or JSON panel sources triggers reevaluation; no UI dev server is needed. For a trusted sandbox development server, `stack module dev --ui-url http://localhost:5174` uses the same host bridge permissions, but not the production asset server's CSP. -## Best Practices - -1. **Always use `mkIf`** — Wrap your entire `config` block so the extension is inert when disabled. -2. **Namespace scripts** — Use the `:` convention to avoid collisions with other extensions. -3. **Use file-based scripts** — Prefer `path = ./src/scripts/foo.sh` over inline `exec` for anything beyond a one-liner. -4. **Set `srcDir`** — Enable auto-discovery for scripts and health checks. -5. **Declare feature flags** — Tell the registry which core features your extension uses. -6. **Provide sensible defaults** — Extensions should work with minimal configuration. -7. **Add MOTD entries** — Help users discover your extension's commands on shell entry. -8. **Add status panels** — Give users visibility into extension state through Studio. -9. **Pass config via `env`** — Use `env.MY_VAR = cfg.some-value` to pass Nix values into file-based scripts. -10. **Document options** — Every `mkOption` should have a meaningful `description`. - - -Extensions are just Nix modules with metadata. If you already know how to write Stackpanel config, you already know how to write extensions. The registration metadata is the only new concept. - - -## Reference - -- [Using Extensions](./using-extensions) for how users install and configure extensions -- [Flake Inputs](./flake-inputs) for declaring and auto-installing required flake inputs -- [Extension Registry](./registry) for discovering and distributing extensions -- [Core Concepts → Module System](/docs/concepts/module-system) for the underlying Nix module system -- [Options Reference → Extensions](/docs/reference/extensions) for all extension-related options \ No newline at end of file +To test against an existing project, install its module input once, then run `stack module link /path/to/report --id report` from the consumer. Edit the linked module; watch Studio for evaluation errors. Run `stack module unlink report` to return to the locked version. Use `stack module eject report ../report` to copy a local `.stack/modules/report/` into a standalone flake. Test the standalone input and use the [registry publishing guide](./registry) before announcing a release. diff --git a/apps/docs/content/docs/internal/core.mdx b/apps/docs/content/docs/internal/core.mdx index a4a70a7f..5676024d 100644 --- a/apps/docs/content/docs/internal/core.mdx +++ b/apps/docs/content/docs/internal/core.mdx @@ -25,13 +25,12 @@ Feature-specific options live in their own directories (`apps/`, `services/`, `n | `cli-options.nix` | CLI enable/quiet options | | `state.nix` | Legacy state file generation | | `state-options.nix` | State file options | -| `user-packages.nix` | User-installed packages from `.stackpanel/data/packages.nix` | +| `user-packages.nix` | User-installed packages from `.stack/data/packages.nix` | | `users-options.nix` | Team member definitions | -| `panels.nix` | UI panel system for the web studio | +| `options/panels.nix` | Module-owned Studio panels and their serialized list | | `tasks.nix` | Turborepo task definitions | | `ci.nix` | CI/CD workflow generation | -| `modules-options.nix` | Module registry schema | -| `extensions.nix` | Extension system (backward compat alias to modules) | +| `options/modules.nix` | Module registry schema | | `aliases.nix` | Shell alias management | | `util.nix` | Internal logging utilities | @@ -43,6 +42,6 @@ The core module is imported automatically via `nix/stackpanel/default.nix`. Conf stackpanel = { enable = true; name = "my-project"; - dirs.home = ".stackpanel"; + dirs.home = ".stack"; }; ``` diff --git a/apps/docs/content/docs/internal/db.mdx b/apps/docs/content/docs/internal/db.mdx index c8c95606..03de147c 100644 --- a/apps/docs/content/docs/internal/db.mdx +++ b/apps/docs/content/docs/internal/db.mdx @@ -43,7 +43,6 @@ db/ ├── config.proto.nix # Root project configuration ├── databases.proto.nix # Database connections ├── dns.proto.nix # DNS configuration - ├── extensions.proto.nix # IDE/editor extensions ├── onboarding.proto.nix # Onboarding steps ├── secrets.proto.nix # Secrets management ├── services.proto.nix # Local services (postgres, redis, etc.) @@ -87,14 +86,13 @@ nix develop --impure -c ./packages/proto/generate.sh ### List All Schemas ```bash -nix eval --impure --json -f nix/stackpanel/db '.entityNames' -# ["apps","aws","commands","config","databases","dns","extensions",...] +nix eval --impure --json -f nix/stackpanel/db entityNames ``` ### Render a Proto File ```bash -nix eval --impure --raw -f nix/stackpanel/db '.render.users' +nix eval --impure --raw -f nix/stackpanel/db render.users ``` ## Writing Schemas diff --git a/apps/docs/content/docs/internal/deployment/fly.mdx b/apps/docs/content/docs/internal/deployment/fly.mdx index 8657e702..624d5a99 100644 --- a/apps/docs/content/docs/internal/deployment/fly.mdx +++ b/apps/docs/content/docs/internal/deployment/fly.mdx @@ -5,27 +5,18 @@ description: Documentation for the fly module Container-based deployment to [Fly.io](https://fly.io) with generated `fly.toml`. -## Files - -| File | Description | -|------|-------------| -| `default.nix` | Entry point | -| `module.nix` | Per-app deployment options and config generation | -| `schema.nix` | Proto-derived Fly.io config schema | -| `container.nix` | Container build integration | -| `ui.nix` | Web studio panel | -| `lib/fly-oidc.nix` | Fly.io OIDC authentication helpers | +The external [Fly module](https://github.com/darkmatter/stackpanel-registry/tree/main/modules/fly) declares its app options, actions, and Studio panels. The Cloud panel displays evaluated configuration without contacting Fly. A live status request runs the module's `status` action for the selected app; deployment is a separate confirmed action. ## Usage ```nix stackpanel.apps.web.deployment = { enable = true; - provider = "fly"; + host = "fly"; fly = { appName = "my-web-app"; region = "iad"; - memory = 256; + memory = "256mb"; minMachines = 1; }; container = { type = "bun"; port = 3000; }; diff --git a/apps/docs/content/docs/internal/modules.mdx b/apps/docs/content/docs/internal/modules.mdx index 6836a244..8520d62a 100644 --- a/apps/docs/content/docs/internal/modules.mdx +++ b/apps/docs/content/docs/internal/modules.mdx @@ -1,26 +1,10 @@ --- -title: "Module Discovery and Auto-Import" -description: "This file handles module imports in two ways:" +title: Module discovery and auto-import +description: How bundled, local, and external module definitions enter the project evaluation. --- -This file handles module imports in two ways: +The flake adapter composes the Stackpanel schema with the consumer's explicit imports, local `.stack/modules/` and `.stack/nix/` directories, and the `stackpanelModules.default` outputs discovered on direct inputs. The bundled module loader imports non-private directories under `nix/stackpanel/modules/`; a leading dot or underscore marks a private directory. -1. AUTO-DISCOVERY: Directory modules (new structure) are auto-imported -```nix - - module-name/default.nix - - Excludes directories starting with _ or . -``` +All of these definitions register in `stackpanel.modules`. Studio reads `modulesListAll` for descriptors (including disabled modules) and `panelsList` for evaluated panels. Each panel names its owner; Studio mounts it only when the panel and its module are enabled. - -2. EXPLICIT IMPORTS: Legacy single-file modules are imported explicitly -```nix - - These are listed below and should be migrated to directory structure -``` - - -The `_template/` directory provides the template for new modules. - -For fast metadata access without full evaluation, use: -```nix -config.stackpanel._moduleMetas. -``` +See [Flake inputs and discovery](/docs/extensions/flake-inputs) for hooks and opt-out behavior and [Writing a module](/docs/extensions/writing-extensions) for the public SDK. diff --git a/apps/docs/content/docs/modules/env-codegen.mdx b/apps/docs/content/docs/modules/env-codegen.mdx index 99c00447..853ae34c 100644 --- a/apps/docs/content/docs/modules/env-codegen.mdx +++ b/apps/docs/content/docs/modules/env-codegen.mdx @@ -39,3 +39,7 @@ stackpanel.apps.web.environments.dev.env = { stackpanel.env.output-dir = "packages/custom-env"; stackpanel.env.package-name = "@myorg/env"; ``` + +## Verify encrypted deploy payloads + +Stackpanel's **Secrets codegen drift check** regenerates the deploy-scope payload and its TypeScript wrapper. To reproduce it, run `nix develop --command stack codegen build env` with access to the project's SOPS key. Review changes under `packages/gen/env/data/_envs/` and `packages/gen/env/src/runtime/generated-payloads/_envs/`, including new files. The runner reads the signed Nix cache; verification does not require a cache write token. diff --git a/apps/docs/content/docs/modules/index.mdx b/apps/docs/content/docs/modules/index.mdx index 2b2647a6..dc9650e4 100644 --- a/apps/docs/content/docs/modules/index.mdx +++ b/apps/docs/content/docs/modules/index.mdx @@ -6,20 +6,14 @@ icon: blocks import { Cards, Card } from "fumadocs-ui/components/card"; -Stackpanel ships with a set of builtin modules that provide integrated tooling for common development workflows. Each module is a directory under `nix/stackpanel/modules/` with a standard structure: +Bundled Stackpanel modules provide tooling for common development workflows. Within the Stackpanel repository they generally have this structure: - **`meta.nix`** — Pure data: name, description, icon, category, tags, feature flags, flake inputs - **`module.nix`** — Options and configuration logic - **`ui.nix`** — Studio panel definitions - **`default.nix`** — Entry point that imports the above -Modules are auto-discovered — drop a new directory into `nix/stackpanel/modules/` and it's available immediately. - -For fast metadata access without full Nix evaluation: - -```nix -config.stackpanel._moduleMetas. -``` +A consumer project does **not** copy its module into the Stackpanel repository. Publish `stackpanelModules.default` from a flake or put a project-local module in `.stack/modules/`. Studio and `stack module list --all` use `stackpanel.modulesListAll` for both bundled and external modules. ## Builtin Modules @@ -39,9 +33,6 @@ config.stackpanel._moduleMetas. Bun package manager integration and workspace support - - Fast JavaScript/TypeScript linting with per-app configuration - Pre-commit hooks with auto-discovered linters and formatters @@ -65,6 +56,8 @@ config.stackpanel._moduleMetas. +OxLint is an [installable registry module](https://github.com/darkmatter/stackpanel-registry/tree/main/modules/oxlint); see [the user guide](/docs/extensions/using-extensions) for installation and adoption. + ## Writing a New Module Use the `_template/` directory as a starting point: diff --git a/apps/docs/content/docs/modules/oxlint.mdx b/apps/docs/content/docs/modules/oxlint.mdx index 466d3723..89ad9a31 100644 --- a/apps/docs/content/docs/modules/oxlint.mdx +++ b/apps/docs/content/docs/modules/oxlint.mdx @@ -3,8 +3,7 @@ title: OxLint Module Entry Point description: OxLint is a blazing fast JavaScript/TypeScript linter written in Rust. --- -OxLint is a blazing fast JavaScript/TypeScript linter written in Rust. -Part of the Oxc project (https://oxc.rs). +Install the external OxLint module with `stack module install oxlint`, then select the apps it should lint. It uses the [Oxc](https://oxc.rs) JavaScript and TypeScript linter. This module provides: ```nix diff --git a/apps/docs/content/docs/reference/modules.mdx b/apps/docs/content/docs/reference/modules.mdx index 875e8cca..6b455705 100644 --- a/apps/docs/content/docs/reference/modules.mdx +++ b/apps/docs/content/docs/reference/modules.mdx @@ -6,17 +6,6 @@ icon: Settings # Modules Options -## `_moduleMetas` - -Fast module metadata for discovery without full module evaluation. Each key is a module ID, value is the contents of that module's meta.nix. This is set automatically by the module auto-discovery in modules/default.nix. - -| Property | Value | -|----------|-------| -| **Type** | `attribute set of unspecified value` | -| **Default** | `{ }` | - ---- - ## `modules` Stackpanel modules that provide features and UI panels. @@ -29,7 +18,7 @@ Modules can be: | Property | Value | |----------|-------| -| **Type** | `open submodule of attribute set of (submodule)` | +| **Type** | `attribute set of (submodule)` | | **Default** | `{ }` | **Example:** @@ -51,16 +40,6 @@ Modules can be: packages = true; }; healthcheckModule = "postgres"; - panels = [{ - id = "postgres-status"; - title = "PostgreSQL Status"; - type = "PANEL_TYPE_STATUS"; - fields = [{ - name = "metrics"; - type = "FIELD_TYPE_JSON"; - value = "[{\"label\":\"Status\",\"value\":\"Running\",\"status\":\"ok\"}]"; - }]; - }]; }; my-custom-module = { @@ -358,7 +337,7 @@ Category for grouping in the UI | Property | Value | |----------|-------| -| **Type** | `one of "unspecified", "infrastructure", "ci-cd", "database", "secrets", "deployment", "development", "monitoring", "integration", "language", "service"` | +| **Type** | `string` (open category ID) | | **Default** | `"unspecified"` | --- @@ -418,126 +397,17 @@ Module version --- -## `modules..panels` - -UI panels provided by this module - -| Property | Value | -|----------|-------| -| **Type** | `list of (submodule)` | -| **Default** | `[ ]` | - ---- - -## `modules..panels.*.description` - -Panel description - -| Property | Value | -|----------|-------| -| **Type** | `null or string` | -| **Default** | `null` | - ---- - -## `modules..panels.*.fields` - -Panel configuration fields - -| Property | Value | -|----------|-------| -| **Type** | `list of (submodule)` | -| **Default** | `[ ]` | - ---- - -## `modules..panels.*.fields.*.name` +## `modules..actions` -Field name (maps to component prop) +An attribute set keyed by action ID. An action declares an executable `script`, display metadata, optional `confirm`, a JSON object `argsSchema`, `outputMode` (`stream` or `json`), and collections to refresh on success. Reference action IDs from panels; panel controls never contain shell commands. -| Property | Value | -|----------|-------| -| **Type** | `string` | -| **Default** | _none_ | - ---- - -## `modules..panels.*.fields.*.options` - -Options for select fields - -| Property | Value | -|----------|-------| -| **Type** | `list of string` | -| **Default** | `[ ]` | - ---- - -## `modules..panels.*.fields.*.type` - -Field type - -| Property | Value | -|----------|-------| -| **Type** | `one of "FIELD_TYPE_UNSPECIFIED", "FIELD_TYPE_STRING", "FIELD_TYPE_NUMBER", "FIELD_TYPE_BOOLEAN", "FIELD_TYPE_SELECT", "FIELD_TYPE_MULTISELECT", "FIELD_TYPE_APP_FILTER", "FIELD_TYPE_COLUMNS", "FIELD_TYPE_JSON"` | -| **Default** | `"FIELD_TYPE_STRING"` | - ---- - -## `modules..panels.*.fields.*.value` - -Field value (JSON-encoded for complex types) - -| Property | Value | -|----------|-------| -| **Type** | `string` | -| **Default** | `""` | - ---- +## `modules..enablePath` and `configPath` -## `modules..panels.*.id` +Paths relative to `stackpanel`. The defaults are `modules..enable` and `modules..settings`. The agent writes these options in the evaluated project configuration. `readme` supplies Markdown documentation for the installed module. -Unique panel identifier +## Module-owned panels -| Property | Value | -|----------|-------| -| **Type** | `string` | -| **Default** | _none_ | - ---- - -## `modules..panels.*.order` - -Display order (lower = first) - -| Property | Value | -|----------|-------| -| **Type** | `signed integer` | -| **Default** | `100` | - ---- - -## `modules..panels.*.title` - -Display title - -| Property | Value | -|----------|-------| -| **Type** | `string` | -| **Default** | _none_ | - ---- - -## `modules..panels.*.type` - -Panel type (determines which component to render) - -| Property | Value | -|----------|-------| -| **Type** | `one of "PANEL_TYPE_UNSPECIFIED", "PANEL_TYPE_STATUS", "PANEL_TYPE_APPS_GRID", "PANEL_TYPE_FORM", "PANEL_TYPE_TABLE", "PANEL_TYPE_CUSTOM"` | -| **Default** | `"PANEL_TYPE_STATUS"` | - ---- +No panel is required for the standard module UI. `mkModule.ui.widgets..` adds a [Nix-authored layout](/docs/extensions/writing-extensions#author-a-panel-in-nix). Additional panels live under [`stackpanel.panels`](./panels), not inside the module descriptor; `mkModule` sets their owner. ## `modules..priority` @@ -638,66 +508,6 @@ Tags for categorizing/filtering modules --- -## `modulesBuiltin` - -Builtin modules shipped with stackpanel - -| Property | Value | -|----------|-------| -| **Type** | `attribute set of unspecified value` | -| **Default** | `{ }` | -| **Read Only** | `true` | - ---- - -## `modulesComputed` - -Computed module configurations (only enabled modules, serializable) - -| Property | Value | -|----------|-------| -| **Type** | `attribute set of unspecified value` | -| **Default** | `{ }` | -| **Read Only** | `true` | - ---- - -## `modulesComputedAll` - -Computed module configurations (all modules including disabled, serializable) - -| Property | Value | -|----------|-------| -| **Type** | `attribute set of unspecified value` | -| **Default** | `{ }` | -| **Read Only** | `true` | - ---- - -## `modulesExternal` - -External modules (local, flake-input, or registry) - -| Property | Value | -|----------|-------| -| **Type** | `attribute set of unspecified value` | -| **Default** | `{ }` | -| **Read Only** | `true` | - ---- - -## `modulesList` - -Flat list of enabled modules (for API consumption) - -| Property | Value | -|----------|-------| -| **Type** | `list of unspecified value` | -| **Default** | `[ ]` | -| **Read Only** | `true` | - ---- - ## `modulesListAll` Flat list of all modules including disabled (for API consumption) diff --git a/apps/docs/content/docs/reference/panels.mdx b/apps/docs/content/docs/reference/panels.mdx index 885c563c..d1f3fdf1 100644 --- a/apps/docs/content/docs/reference/panels.mdx +++ b/apps/docs/content/docs/reference/panels.mdx @@ -6,25 +6,9 @@ icon: Settings # Panels Options -## `panelModules` - -List of module names that have registered panels - -| Property | Value | -|----------|-------| -| **Type** | `list of string` | -| **Default** | _none_ | -| **Read Only** | `true` | - ---- - ## `panels` -UI panels for core Stackpanel modules. - -Panels are UI components that display information about a module's state, configuration, or managed resources. Unlike extension panels, these belong to built-in modules like Go, Caddy, Healthchecks, etc. - -Example: stackpanel.panels.go-status = \{ module = "go"; title = "Go Environment"; type = "PANEL_TYPE_STATUS"; order = 10; fields = [ \{ name = "metrics"; type = "FIELD_TYPE_STRING"; value = "..."; \} ]; \}; +UI panels for installed Stackpanel modules. Each panel declares an owning `module` and optionally a placement `slot`. Declare named widgets under `spec.widgets`; Studio infers the renderer. Built-in and external modules use the same panel catalog. | Property | Value | |----------|-------| @@ -35,28 +19,11 @@ Example: stackpanel.panels.go-status = \{ module = "go"; title = "Go Environment ```nix { - go-status = { - module = "go"; - title = "Go Environment"; - type = "PANEL_TYPE_STATUS"; - order = 10; - fields = [ - { - name = "metrics"; - type = "FIELD_TYPE_STRING"; - value = builtins.toJSON [ - { label = "Go Version"; value = "1.22"; status = "ok"; } - { label = "Apps"; value = "3"; status = "ok"; } - ]; - } - ]; - }; - caddy-status = { - module = "caddy"; - title = "Reverse Proxy"; - type = "PANEL_TYPE_STATUS"; - order = 20; - fields = [ ... ]; + report-summary = { + module = "report"; + title = "Workspace report"; + slot = "overview"; + spec.widgets.run.actions.ids = [ "report" ]; }; } ``` @@ -339,6 +306,12 @@ Row data for table panels --- +## `panels..spec` + +A native layout, mutually exclusive with `uiBundle`. [Named widgets](/docs/extensions/writing-extensions#author-a-panel-in-nix) use `spec.widgets..` with typed, documented fields from the Studio catalog. Use ordered child IDs on stacks and sections. `mkModule.ui` accepts the same layout for its module-detail panel. Tools can also supply a raw `{ root, elements, state? }` document or a tracked JSON file path. + +--- + ## `panels..title` Display title for the panel @@ -356,38 +329,14 @@ Panel type (determines which component to render) | Property | Value | |----------|-------| -| **Type** | `one of "PANEL_TYPE_UNSPECIFIED", "PANEL_TYPE_STATUS", "PANEL_TYPE_APPS_GRID", "PANEL_TYPE_FORM", "PANEL_TYPE_TABLE", "PANEL_TYPE_CUSTOM", "PANEL_TYPE_APP_CONFIG"` | -| **Default** | `"PANEL_TYPE_STATUS"` | - ---- - -## `panelsByModule` - -Panels grouped by their parent module - -| Property | Value | -|----------|-------| -| **Type** | `attribute set of attribute set of unspecified value` | -| **Default** | _none_ | -| **Read Only** | `true` | - ---- - -## `panelsComputed` - -Serializable panels for UI consumption - -| Property | Value | -|----------|-------| -| **Type** | `attribute set of unspecified value` | -| **Default** | _none_ | -| **Read Only** | `true` | +| **Type** | `one of "PANEL_TYPE_UNSPECIFIED", "PANEL_TYPE_STATUS", "PANEL_TYPE_APPS_GRID", "PANEL_TYPE_FORM", "PANEL_TYPE_TABLE", "PANEL_TYPE_CUSTOM", "PANEL_TYPE_APP_CONFIG", "PANEL_TYPE_TABS", "PANEL_TYPE_SPEC"` | +| **Default** | `PANEL_TYPE_SPEC` with `spec`, otherwise `PANEL_TYPE_STATUS` | --- ## `panelsList` -List of all panels sorted by order +Evaluated module-owned panels in display order. Studio selects panels by owner, enabled state, and slot. | Property | Value | |----------|-------| diff --git a/apps/docs/package.json b/apps/docs/package.json index 363b89ee..cbe73ecb 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -23,7 +23,7 @@ "@fontsource-variable/google-sans-code": "^5.2.3", "@fontsource-variable/inter": "^5.2.8", "@fontsource/monaspace-neon": "^5.2.5", - "@opennextjs/cloudflare": "1.20.1", + "@opennextjs/cloudflare": "1.20.13", "@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-popover": "^1.1.15", "@radix-ui/react-presence": "^1.1.5", @@ -35,7 +35,7 @@ "fumadocs-typescript": "5.2.6", "fumadocs-ui": "16.8.8", "lucide-react": "^1.14.0", - "next": "16.2.6", + "next": "16.4.6", "next-themes": "^0.4.6", "react": "catalog:", "react-dom": "catalog:", @@ -45,7 +45,8 @@ "unist-util-visit": "^5.0.0" }, "devDependencies": { - "@alchemy.run/frontend-frameworks": "2.0.0-beta.76", + "@alchemy.run/cloudflare": "catalog:", + "@alchemy.run/frontend-frameworks": "catalog:", "@stackpanel/infra": "workspace:*", "@tailwindcss/postcss": "^4.1.16", "@types/mdast": "^4.0.4", @@ -61,6 +62,6 @@ "postcss": "^8.5.6", "tailwindcss": "catalog:", "typescript": "^6.0.3", - "wrangler": "^4.90.0" + "wrangler": "^4.149.0" } } diff --git a/apps/stackpanel-go/cmd/cli/deploy.go b/apps/stackpanel-go/cmd/cli/deploy.go index dea8bc1a..42969591 100644 --- a/apps/stackpanel-go/cmd/cli/deploy.go +++ b/apps/stackpanel-go/cmd/cli/deploy.go @@ -1,9 +1,8 @@ // deploy.go implements multi-backend deployment for stackpanel apps. // -// Supported backends: colmena (NixOS multi-host), nixos-rebuild (single-host), -// alchemy (Cloudflare Workers), and fly (Fly.io). The deploy config is loaded -// live from the Nix flake via nix eval, not from the state file, so it always -// reflects the current flake. +// Modules supply deploy executables alongside the built-in colmena, +// nixos-rebuild and alchemy backends. Read the selected backend from the live +// project configuration, not the previous deployment record. package cmd import ( @@ -17,6 +16,7 @@ import ( "time" "github.com/darkmatter/stackpanel/stackpanel-go/internal/output" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" "github.com/spf13/cobra" ) @@ -37,7 +37,6 @@ type DeployMachineConfig struct { type AppDeploymentOptions struct { Enable bool `json:"enable"` - Host string `json:"host"` Backend string `json:"backend"` Targets []string `json:"targets"` DefaultEnv string `json:"defaultEnv"` @@ -52,9 +51,16 @@ type DeployFlakeOutputsConfig struct { FlakeDir string `json:"flakeDir"` } +type DeployBackend struct { + Script *string `json:"script"` + DrvPaths []string `json:"drvPaths"` +} + type DeployStackpanelConfig struct { - Apps map[string]DeployAppConfig `json:"apps"` - Deployment struct { + projectRoot string + DeployBackends map[string]DeployBackend `json:"deployBackends"` + Apps map[string]DeployAppConfig `json:"apps"` + Deployment struct { Machines map[string]DeployMachineConfig `json:"machines"` FlakeOutputs DeployFlakeOutputsConfig `json:"flakeOutputs"` } `json:"deployment"` @@ -89,38 +95,32 @@ var deployCmd = &cobra.Command{ Without arguments, lists configured deployments. With an app name, deploys that app to its configured targets. -Backends: +Project modules can declare deployBackends..script. The CLI runs that +executable from the project root with arguments APP ENV [TARGET ...], without +a shell. A declared script takes precedence over these built-in backends: colmena - NixOS via colmena (multi-host) nixos-rebuild - NixOS via nixos-rebuild switch (single-host) alchemy - Cloudflare Workers via Alchemy - fly - Fly.io containers Examples: stack deploy # List configured deployments stack deploy my-api # Deploy my-api to all targets stack deploy my-api --dry-run # Print command without executing it`, - Run: func(cmd *cobra.Command, args []string) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - cfg, err := loadDeployConfig(ctx) + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + cfg, err := loadDeployConfig(cmd.Context()) if err != nil { - output.Error(fmt.Sprintf("Failed to load deploy config: %v", err)) - os.Exit(1) + return fmt.Errorf("load deploy config: %w", err) } - if len(args) == 0 { listDeployments(cfg) - return + return nil } - - appName := args[0] - dryRun, _ := cmd.Flags().GetBool("dry-run") - - if err := runDeploy(ctx, cfg, appName, dryRun); err != nil { - output.Error(fmt.Sprintf("Deploy failed: %v", err)) - os.Exit(1) + dryRun, err := cmd.Flags().GetBool("dry-run") + if err != nil { + return err } + return runDeploy(cmd.Context(), cfg, args[0], dryRun) }, } @@ -161,21 +161,26 @@ func init() { // need, avoiding the full filterSerializable traversal that forces expensive // derivation instantiation (e.g. bun.nix with ~5000 fetchurl calls). const deployConfigExpr = ` +sp: +if !sp.modules.deploy.enable then throw "The Stackpanel deploy module is disabled" else let - flake = builtins.getFlake (toString ./.); - sys = builtins.currentSystem; - sp = flake.legacyPackages.${sys}.stackpanelFullConfig; serializeApp = name: app: { deployment = { enable = app.deployment.enable or false; - host = app.deployment.host or ""; - backend = app.deployment.backend or "colmena"; + inherit (app.deployment) backend; targets = app.deployment.targets or []; defaultEnv = app.deployment.defaultEnv or "prod"; }; }; -in builtins.toJSON { +in { apps = builtins.mapAttrs serializeApp (sp.apps or {}); + deployBackends = builtins.mapAttrs (_: b: let + script = if (b.script or null) == null then null else toString b.script; + context = if script == null then {} else builtins.getContext script; + in { + inherit script; + drvPaths = builtins.filter (p: context.${p} ? outputs) (builtins.attrNames context); + }) (sp.deployBackends or {}); deployment = { machines = builtins.mapAttrs (name: m: { host = m.host or ""; @@ -195,14 +200,13 @@ in builtins.toJSON { ` func loadDeployConfig(ctx context.Context) (*DeployStackpanelConfig, error) { - root := detectStackpanelProject() - if root == "" { - return nil, fmt.Errorf( - "could not find stackpanel project root (look for .stack/config.nix or flake.nix under cwd); try running from the repo root or set STACKPANEL_ROOT", - ) + root, err := findProjectRoot() + if err != nil { + return nil, err } result, err := nixeval.EvalOnce(ctx, nixeval.EvalOnceParams{ - Expression: deployConfigExpr, + Expression: ".#legacyPackages." + nixeval.CurrentSystem() + ".stackpanelFullConfig", + Apply: deployConfigExpr, ProjectRoot: root, // Flake eval can exceed the default 10s on cold cache or large trees. Timeout: 10 * time.Minute, @@ -211,20 +215,8 @@ func loadDeployConfig(ctx context.Context) (*DeployStackpanelConfig, error) { return nil, fmt.Errorf("nix eval failed: %w", err) } - // The expression returns a JSON string via builtins.toJSON, so the - // outer result is a JSON-encoded string that we need to unwrap. - var jsonStr string - if err := json.Unmarshal(result, &jsonStr); err != nil { - // If it's not a wrapped string, try parsing directly - var cfg DeployStackpanelConfig - if err2 := json.Unmarshal(result, &cfg); err2 != nil { - return nil, fmt.Errorf("failed to parse deploy config: %w", err) - } - return &cfg, nil - } - - var cfg DeployStackpanelConfig - if err := json.Unmarshal([]byte(jsonStr), &cfg); err != nil { + cfg := DeployStackpanelConfig{projectRoot: root} + if err := json.Unmarshal(result, &cfg); err != nil { return nil, fmt.Errorf("failed to parse deploy config: %w", err) } @@ -297,9 +289,8 @@ func listDeployments(cfg *DeployStackpanelConfig) { fmt.Println("Deployments:") for _, name := range deployableApps { app := cfg.Apps[name] - backend := resolveBackend(app.Deployment) fmt.Printf(" %s\n", output.Purple.Sprint(name)) - output.Dimmed(fmt.Sprintf(" backend: %s", backend)) + output.Dimmed(fmt.Sprintf(" backend: %s", app.Deployment.Backend)) if len(app.Deployment.Targets) > 0 { output.Dimmed(fmt.Sprintf(" targets: %v", app.Deployment.Targets)) } @@ -321,7 +312,7 @@ func runDeploy( return fmt.Errorf("app %q does not have deployment.enable = true", appName) } - backend := resolveBackend(app.Deployment) + backend := app.Deployment.Backend env := app.Deployment.DefaultEnv if env == "" { env = "prod" @@ -332,14 +323,26 @@ func runDeploy( var target string var deployErr error - switch backend { - case "colmena": + declared := cfg.DeployBackends[backend] + switch { + case declared.Script != nil: + target = joinTargets(app.Deployment.Targets) + deployErr = deployModuleBackend( + ctx, + cfg.projectRoot, + declared, + appName, + env, + app.Deployment.Targets, + dryRun, + ) + case backend == "colmena": target = joinTargets(app.Deployment.Targets) deployErr = deployColmena(ctx, cfg, appName, app, dryRun, env) - case "nixos-rebuild": + case backend == "nixos-rebuild": target = joinTargets(app.Deployment.Targets) deployErr = deployNixosRebuild(ctx, cfg, appName, app, dryRun) - case "alchemy": + case backend == "alchemy": target = env deployErr = deployAlchemy(ctx, appName, app, dryRun) default: @@ -354,14 +357,58 @@ func runDeploy( } if !dryRun { - if err := recordDeployment(appName, env, backend, target); err != nil { - output.Warning(fmt.Sprintf("Failed to record deployment state: %v", err)) + if err := recordDeployment( + cfg.projectRoot, + appName, + env, + backend, + target, + ); err != nil { + return fmt.Errorf( + "deployed %s but could not record deployment state: %w", + appName, + err, + ) } output.Success(fmt.Sprintf("Deployed %s (%s → %s)", appName, backend, target)) } return nil } +// The backend contract is executable APP ENV [TARGET ...], run from the +// project root. In particular, neither the script nor any argument is shell text. +func deployModuleBackend( + ctx context.Context, + root string, + b DeployBackend, + app, env string, + targets []string, + dryRun bool, +) error { + if !filepath.IsAbs(*b.Script) { + return fmt.Errorf("deploy backend script must be an absolute executable path") + } + args := append([]string{app, env}, targets...) + if dryRun { + output.Info(fmt.Sprintf("dry-run: %q %q", *b.Script, args)) + return nil + } + // Evaluation provides a path, not necessarily a realized output. Build + // only the derivations from this script's Nix string context. + if len(b.DrvPaths) > 0 { + if _, err := reconcile.RealizeOutputs(ctx, root, b.DrvPaths...); err != nil { + return fmt.Errorf("realize deploy backend: %w", err) + } + } + cmd := exec.CommandContext(ctx, *b.Script, args...) + cmd.Dir = root + // Preserve provider credentials, not the caller's agent pairing secrets + // or stale config/state locations from a different devshell. + cmd.Env = append(freshSetupEnvironment(cmd.Environ()), "STACKPANEL_ROOT="+root) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + return cmd.Run() +} + func joinTargets(targets []string) string { result := "" for i, t := range targets { @@ -373,22 +420,6 @@ func joinTargets(targets []string) string { return result } -// resolveBackend derives the effective backend from the app's config. -// New: uses deployment.backend directly. -// Legacy fallback: maps deployment.host (cloudflare -> alchemy, fly -> fly). -func resolveBackend(d AppDeploymentOptions) string { - if d.Backend != "" { - return d.Backend - } - switch d.Host { - case "cloudflare": - return "alchemy" - case "fly": - return "fly" - } - return "colmena" -} - func deployColmena( ctx context.Context, cfg *DeployStackpanelConfig, @@ -531,7 +562,11 @@ func runExternalCommand( // --------------------------------------------------------------------------- func showDeployStatus(appFilter string) error { - state, err := readDeployState() + root, err := findProjectRoot() + if err != nil { + return err + } + state, err := readDeployState(root) if err != nil { if os.IsNotExist(err) { output.Dimmed("No deployments recorded.") @@ -585,19 +620,12 @@ func showDeployStatus(appFilter string) error { // State file helpers // --------------------------------------------------------------------------- -func deployStateFile() string { - root := os.Getenv("STACKPANEL_ROOT") - if root == "" { - root = detectStackpanelProject() - } - if root == "" { - root = "." - } +func deployStateFile(root string) string { return filepath.Join(root, ".stack", "state", "deployments.json") } -func readDeployState() (DeploymentsState, error) { - data, err := os.ReadFile(deployStateFile()) +func readDeployState(root string) (DeploymentsState, error) { + data, err := os.ReadFile(deployStateFile(root)) if err != nil { return nil, err } @@ -608,8 +636,8 @@ func readDeployState() (DeploymentsState, error) { return state, nil } -func writeDeployState(state DeploymentsState) error { - stateFile := deployStateFile() +func writeDeployState(root string, state DeploymentsState) error { + stateFile := deployStateFile(root) if err := os.MkdirAll(filepath.Dir(stateFile), 0o755); err != nil { return err } @@ -620,8 +648,8 @@ func writeDeployState(state DeploymentsState) error { return os.WriteFile(stateFile, data, 0o644) } -func recordDeployment(appName, env, backend, target string) error { - state, err := readDeployState() +func recordDeployment(root, appName, env, backend, target string) error { + state, err := readDeployState(root) if err != nil && !os.IsNotExist(err) { return err } @@ -639,7 +667,7 @@ func recordDeployment(appName, env, backend, target string) error { Target: target, NixRevision: rev, } - return writeDeployState(state) + return writeDeployState(root, state) } func gitRevision() string { diff --git a/apps/stackpanel-go/cmd/cli/deploy_module_test.go b/apps/stackpanel-go/cmd/cli/deploy_module_test.go new file mode 100644 index 00000000..8d79ce72 --- /dev/null +++ b/apps/stackpanel-go/cmd/cli/deploy_module_test.go @@ -0,0 +1,106 @@ +package cmd + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" +) + +func TestDeclaredDeployShadowsBuiltinAndPreservesArgv(t *testing.T) { + root := t.TempDir() + t.Setenv("STACKPANEL_ROOT", t.TempDir()) // stale shell, not the deployment's project + t.Setenv("STACKPANEL_TEST_PAIRING_TOKEN", "test-only-not-for-children") + script := filepath.Join(root, "backend;literal") + if err := os.WriteFile( + script, + []byte( + "#!/bin/sh\n[ -z \"${STACKPANEL_TEST_PAIRING_TOKEN+x}\" ] || exit 3\nprintf '%s\\n' \"$@\" > args\n", + ), + 0o755, + ); err != nil { + t.Fatal(err) + } + app := "api; echo unsafe" + env := "test stage" + targets := []string{"$(touch injected)", "two words"} + cfg := &DeployStackpanelConfig{ + projectRoot: root, + Apps: map[string]DeployAppConfig{ + app: { + Deployment: AppDeploymentOptions{ + Enable: true, + Backend: "colmena", + DefaultEnv: env, + Targets: targets, + }, + }, + }, + DeployBackends: map[string]DeployBackend{"colmena": {Script: &script}}, + } + if err := runDeploy(t.Context(), cfg, app, true); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(root, "args")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("dry-run executed backend: %v", err) + } + if err := runDeploy(t.Context(), cfg, app, false); err != nil { + t.Fatal(err) + } + read, err := os.ReadFile(filepath.Join(root, "args")) + if err != nil { + t.Fatal(err) + } + if got := strings.Split( + strings.TrimSuffix(string(read), "\n"), + "\n", + ); !slices.Equal( + got, + append([]string{app, env}, targets...), + ) { + t.Errorf("backend args = %q", got) + } + if _, err := os.Stat( + filepath.Join(root, "injected"), + ); !errors.Is( + err, + os.ErrNotExist, + ) { + t.Fatalf("shell expansion: %v", err) + } + state, err := readDeployState(root) + if err != nil || state[app][env].Backend != "colmena" { + t.Errorf("deployment was not recorded: %v %v", state, err) + } + if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 9\n"), 0o755); err != nil { + t.Fatal(err) + } + var failed *exec.ExitError + if err := runDeploy( + t.Context(), + cfg, + app, + false, + ); !errors.As(err, &failed) || + failed.ExitCode() != 9 { + t.Fatalf("backend failure was not returned: %v", err) + } +} + +func TestDeclaredDeployRejectsCommandText(t *testing.T) { + script := "sh -c echo" + if err := deployModuleBackend( + t.Context(), + t.TempDir(), + DeployBackend{Script: &script}, + "api", + "prod", + nil, + true, + ); err == nil { + t.Fatal("accepted command text as an executable") + } +} diff --git a/apps/stackpanel-go/cmd/cli/devmode.go b/apps/stackpanel-go/cmd/cli/devmode.go index 884bc7ba..3b826a2d 100644 --- a/apps/stackpanel-go/cmd/cli/devmode.go +++ b/apps/stackpanel-go/cmd/cli/devmode.go @@ -33,7 +33,7 @@ Without subcommands (enable/disable/status), this is equivalent to: The repo path is resolved in order: 1. STACKPANEL_DEV_REPO environment variable - 2. dev_mode.repo_path from ~/.config/stackpanel/stackpanel.yaml + 2. dev_mode.repo_path from ~/.config/stackpanel/config.yaml 3. Auto-detected from the current working directory Any arguments after 'debug' are forwarded to the 'go run' invocation. diff --git a/apps/stackpanel-go/cmd/cli/flake.go b/apps/stackpanel-go/cmd/cli/flake.go index e2464144..83128ced 100644 --- a/apps/stackpanel-go/cmd/cli/flake.go +++ b/apps/stackpanel-go/cmd/cli/flake.go @@ -100,12 +100,6 @@ func runFlakeAddInput(cmd *cobra.Command, args []string) { } defer editor.Close() - // Build import expression if module-path is specified - importExpr := "" - if flakeAddInputModulePath != "" { - importExpr = fmt.Sprintf("inputs.%s.%s", inputName, flakeAddInputModulePath) - } - // Perform the edit result, err := editor.AddInputAndImport( flakeedit.FlakeInput{ @@ -113,7 +107,7 @@ func runFlakeAddInput(cmd *cobra.Command, args []string) { URL: inputURL, FollowsNixpkgs: flakeAddInputFollows, }, - importExpr, + flakeAddInputModulePath, ) if err != nil { output.Error(fmt.Sprintf("Failed to edit flake.nix: %v", err)) @@ -128,7 +122,7 @@ func runFlakeAddInput(cmd *cobra.Command, args []string) { output.Success(fmt.Sprintf("Added input: %s = \"%s\"", inputName, inputURL)) } if result.ImportAdded { - output.Success(fmt.Sprintf("Added import: %s", importExpr)) + output.Success(fmt.Sprintf("Added module import from %s: %s", inputName, flakeAddInputModulePath)) } if !result.InputAdded && !result.ImportAdded { output.Info("No changes needed") diff --git a/apps/stackpanel-go/cmd/cli/init_test.go b/apps/stackpanel-go/cmd/cli/init_test.go index 53f542bb..28f5e9d0 100644 --- a/apps/stackpanel-go/cmd/cli/init_test.go +++ b/apps/stackpanel-go/cmd/cli/init_test.go @@ -132,20 +132,16 @@ func TestDecideOffers_DeclineWritesNoMutation(t *testing.T) { } } -// TestRecordDecisions_LedgerMigratesLegacyMarker exercises the addons.json -> -// reconcile.json migration through the setup helper. -func TestRecordDecisions_LedgerMigratesLegacyMarker(t *testing.T) { +func TestRecordDecisionsIgnoresOldMarker(t *testing.T) { t.Parallel() dir := t.TempDir() if err := os.MkdirAll(filepath.Join(dir, ".stack"), 0o755); err != nil { t.Fatal(err) } - if err := os.WriteFile( - filepath.Join(dir, ".stack", "addons.json"), - []byte(`{"version":1,"addons":{"vscode":true,"zed":false}}`), - 0o644, - ); err != nil { + oldPath := filepath.Join(dir, ".stack", "addons.json") + const oldData = `{"version":1,"addons":{"vscode":true,"zed":false}}` + if err := os.WriteFile(oldPath, []byte(oldData), 0o644); err != nil { t.Fatal(err) } pw := nixeval.AddonSpec{ @@ -153,34 +149,22 @@ func TestRecordDecisions_LedgerMigratesLegacyMarker(t *testing.T) { Revision: 2, Question: nixeval.AddonQuestion{Type: "bool"}, } - vscode := nixeval.AddonSpec{ - ID: "vscode", - Revision: 1, - Question: nixeval.AddonQuestion{Type: "bool"}, - } - addons := []nixeval.AddonSpec{pw, vscode} - if err := recordDecisions( dir, - addons, []offerDecision{{addon: pw, answer: reconcile.Answer{Bool: false}}}, ); err != nil { t.Fatal(err) } - if _, err := os.Stat( - filepath.Join(dir, ".stack", "addons.json"), - ); !os.IsNotExist( - err, - ) { - t.Error("legacy addons.json should be removed after migration") - } - ledger, err := reconcile.LoadLedger(dir, reconcile.RevisionsOf(addons)) + if data, err := os.ReadFile(oldPath); err != nil || string(data) != oldData { + t.Fatalf("old file = %q, %v; want unchanged", data, err) + } + ledger, err := reconcile.LoadLedger(dir) if err != nil { t.Fatal(err) } - if e := ledger.Seen["vscode"]; e.Revision != 1 || e.Answer != true { - t.Errorf("migrated vscode entry = %+v", e) + if len(ledger.Seen) != 1 { + t.Fatalf("setup recorded more than the current decision: %+v", ledger.Seen) } if e := ledger.Seen["playwright"]; e.Revision != 2 || e.Answer != false || e.At == "" { diff --git a/apps/stackpanel-go/cmd/cli/module.go b/apps/stackpanel-go/cmd/cli/module.go new file mode 100644 index 00000000..c3f2b810 --- /dev/null +++ b/apps/stackpanel-go/cmd/cli/module.go @@ -0,0 +1,642 @@ +package cmd + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "path/filepath" + "sort" + "strings" + "text/tabwriter" + + "connectrpc.com/connect" + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1/agentv1connect" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/server" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + "github.com/spf13/cobra" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/structpb" +) + +type moduleAPI interface { + agentv1connect.ModuleServiceHandler + ExecuteAction( + context.Context, + *agentv1.RunModuleActionRequest, + func(*agentv1.RunModuleActionResponse) error, + ) error +} + +type moduleCLI struct { + open func(context.Context, string) (context.Context, moduleAPI, error) + reconcile func(context.Context, string) error +} + +func newModuleCmd() *cobra.Command { + cli := moduleCLI{ + open: func(ctx context.Context, root string) (context.Context, moduleAPI, error) { + return server.NewLocalModules(ctx, root) + }, + reconcile: reconcileModuleFiles, + } + cmd := cli.command() + addModuleDevCommands(cmd) + return cmd +} + +func moduleProjectRoot(cmd *cobra.Command) (string, error) { + flag, err := cmd.Flags().GetString("project-root") + if err != nil { + return "", err + } + if flag != "" { + return filepath.Abs(flag) + } + // A caller may have cd'd to another project without leaving its old + // devshell. Never adopt into that shell's project (or a saved active one). + return findProjectRoot() +} + +type moduleInvocation struct { + ctx context.Context + cmd *cobra.Command + root string + api moduleAPI +} + +func (cli moduleCLI) command() *cobra.Command { + module := &cobra.Command{ + Use: "module", + Short: "Discover, adopt, and run project modules", + } + module.PersistentFlags(). + String("project-root", "", "Project directory (default: current stackpanel project)") + add := func(use, short string, positional cobra.PositionalArgs, run func(moduleInvocation, []string) error) *cobra.Command { + cmd := &cobra.Command{ + Use: use, + Short: short, + Args: positional, + RunE: func(cmd *cobra.Command, args []string) error { + root, err := moduleProjectRoot(cmd) + if err != nil { + return err + } + ctx, api, err := cli.open(cmd.Context(), root) + if err != nil { + return err + } + return run(moduleInvocation{ctx, cmd, root, api}, args) + }, + } + module.AddCommand(cmd) + return cmd + } + var category, tag string + search := add( + "search [query]", + "Search the module registry", + cobra.MaximumNArgs(1), + func(m moduleInvocation, args []string) error { + req := &agentv1.ListRegistryModulesRequest{Category: category, Tag: tag} + if len(args) > 0 { + req.Query = args[0] + } + r, err := m.api.ListRegistryModules(m.ctx, connect.NewRequest(req)) + if err != nil { + return err + } + w := tabwriter.NewWriter(m.cmd.OutOrStdout(), 0, 4, 2, ' ', 0) + if _, err := fmt.Fprintln(w, "ID\tVERSION\tCATEGORY\tDESCRIPTION"); err != nil { + return err + } + for _, mod := range r.Msg.Modules { + if _, err := fmt.Fprintf( + w, + "%s\t%s\t%s\t%s\n", + mod.GetId(), + mod.GetLatestVersion(), + mod.GetCategory(), + mod.GetDescription(), + ); err != nil { + return err + } + } + return w.Flush() + }, + ) + search.Flags().StringVar(&category, "category", "", "Filter by category") + search.Flags().StringVar(&tag, "tag", "", "Filter by tag") + + var all bool + list := add( + "list", + "List enabled project modules", + cobra.NoArgs, + func(m moduleInvocation, _ []string) error { + r, err := m.api.ListModules( + m.ctx, + connect.NewRequest(&agentv1.ListModulesRequest{}), + ) + if err != nil { + return err + } + for _, mod := range r.Msg.Modules { + status := "enabled" + if !mod.GetEnabled() { + if !all { + continue + } + status = "disabled" + } + if _, err := fmt.Fprintf( + m.cmd.OutOrStdout(), + "%s\t%s\t%s\n", + mod.GetId(), + status, + mod.GetMeta().GetDescription(), + ); err != nil { + return err + } + } + return nil + }, + ) + list.Flags().BoolVar(&all, "all", false, "Include disabled modules") + add( + "info ", + "Show module metadata, actions, and attributed outputs", + cobra.ExactArgs(1), + moduleInfo, + ) + + var adopt moduleAdoptionOptions + install := add( + "install ", + "Install a registry module and offer to enable it", + cobra.ExactArgs(1), + func(m moduleInvocation, args []string) error { + id, version, err := moduleVersion(args[0]) + if err != nil { + return err + } + r, err := m.api.InstallModule( + m.ctx, + connect.NewRequest( + &agentv1.InstallModuleRequest{ModuleId: id, Version: version}, + ), + ) + if err != nil { + return err + } + if _, err := fmt.Fprintln(m.cmd.OutOrStdout(), r.Msg.GetMessage()); err != nil { + return err + } + if r.Msg.GetModuleId() == "" { + return errors.New("installed module has no canonical Nix module id") + } + return cli.enable(m, r.Msg.GetModuleId(), adopt) + }, + ) + install.Long = "Install and lock the registry input first, then preview adoption. Declining the preview leaves the input installed but does not enable it or reconcile files." + adopt.bind(install) + var enableOptions moduleAdoptionOptions + enable := add( + "enable ", + "Preview, enable, and reconcile a module", + cobra.ExactArgs(1), + func(m moduleInvocation, args []string) error { + return cli.enable(m, args[0], enableOptions) + }, + ) + enableOptions.bind(enable) + add( + "disable ", + "Disable a module and reconcile files", + cobra.ExactArgs(1), + func(m moduleInvocation, args []string) error { + r, err := m.api.DisableModule( + m.ctx, + connect.NewRequest(&agentv1.DisableModuleRequest{ModuleId: args[0]}), + ) + if err != nil { + return err + } + return cli.finishMutation(m, r.Msg.GetMessage()) + }, + ) + add( + "uninstall ", + "Remove a registry module from the project", + cobra.ExactArgs(1), + func(m moduleInvocation, args []string) error { + r, err := m.api.UninstallModule( + m.ctx, + connect.NewRequest(&agentv1.UninstallModuleRequest{ModuleId: args[0]}), + ) + if err != nil { + return err + } + return cli.finishMutation(m, r.Msg.GetMessage()) + }, + ) + var updateAll bool + update := add( + "update [id[@version]]", + "Update one or all installed registry modules", + cobra.MaximumNArgs(1), + func(m moduleInvocation, args []string) error { + if updateAll && len(args) != 0 { + return errors.New("use either a module id or --all") + } + if len(args) == 0 { + r, err := m.api.ListRegistryModules( + m.ctx, + connect.NewRequest(&agentv1.ListRegistryModulesRequest{}), + ) + if err != nil { + return err + } + for _, mod := range r.Msg.Modules { + if mod.GetInstalled() { + args = append(args, mod.GetId()) + } + } + sort.Strings(args) + } + for _, arg := range args { + id, version, err := moduleVersion(arg) + if err != nil { + return err + } + r, err := m.api.UpdateModule( + m.ctx, + connect.NewRequest( + &agentv1.UpdateModuleRequest{ModuleId: id, Version: version}, + ), + ) + if err != nil { + return fmt.Errorf("update %s: %w", id, err) + } + if _, err := fmt.Fprintln(m.cmd.OutOrStdout(), r.Msg.GetMessage()); err != nil { + return err + } + } + if len(args) == 0 { + _, err := fmt.Fprintln( + m.cmd.OutOrStdout(), + "No installed registry modules to update.", + ) + return err + } + return cli.reconcile(m.ctx, m.root) + }, + ) + update.Flags(). + BoolVar(&updateAll, "all", false, "Update every installed registry module (default if no id is given)") + var jsonArgs string + var approve bool + run := add( + "run [-- --key=value ...]", + "Run a declared module action", + cobra.MinimumNArgs(2), + func(m moduleInvocation, args []string) error { + return runModuleAction(m, args, jsonArgs, approve) + }, + ) + run.Example = ` stack module run db inspect -- --table=users --limit 5 + stack module run db inspect --json '{"table":"users","limit":5}'` + run.Flags(). + StringVar(&jsonArgs, "json", "", "Action arguments as a JSON object instead of flags after --") + run.Flags(). + BoolVarP(&approve, "yes", "y", false, "Approve the action's declared confirmation without prompting") + return module +} + +func moduleVersion(arg string) (string, string, error) { + id, version, pin := strings.Cut(arg, "@") + if id == "" || (pin && version == "") || strings.Contains(version, "@") || + strings.TrimSpace(arg) != arg { + return "", "", errors.New("expected a module id or id@version") + } + return id, version, nil +} + +func (cli moduleCLI) enable( + m moduleInvocation, + id string, + opts moduleAdoptionOptions, +) error { + r, err := m.api.PreviewModuleEnable( + m.ctx, + connect.NewRequest(&agentv1.PreviewModuleEnableRequest{ModuleId: id}), + ) + if err != nil { + return fmt.Errorf("preview %s before enabling: %w", id, err) + } + if r.Msg.GetPreview() == nil { + return errors.New("missing module adoption preview") + } + input := bufio.NewScanner(m.cmd.InOrStdin()) + answers, err := opts.answers( + id, + r.Msg.GetPreview().GetOffers(), + input, + m.cmd.ErrOrStderr(), + ) + if err != nil { + return err + } + if len(answers) != 0 { + r, err = m.api.PreviewModuleEnable( + m.ctx, + connect.NewRequest( + &agentv1.PreviewModuleEnableRequest{ModuleId: id, Answers: answers}, + ), + ) + if err != nil { + return fmt.Errorf("preview selected adoption answers: %w", err) + } + if r.Msg.GetPreview() == nil { + return errors.New("missing answered adoption preview") + } + } + if err := printModuleProto(m.cmd.OutOrStdout(), r.Msg.GetPreview()); err != nil { + return err + } + if !opts.yes { + ok, err := confirmModuleInput( + m.cmd, + input, + fmt.Sprintf("Enable %s with the reviewed answers and reconcile files?", id), + ) + if err != nil { + return err + } + if !ok { + _, err := fmt.Fprintln( + m.cmd.OutOrStdout(), + "Enable skipped; no adoption changes applied.", + ) + return err + } + } + enabled, err := m.api.EnableModule( + m.ctx, + connect.NewRequest(&agentv1.EnableModuleRequest{ModuleId: id, Answers: answers}), + ) + if err != nil { + return err + } + return cli.finishMutation(m, enabled.Msg.GetMessage()) +} + +func confirmModule(cmd *cobra.Command, question string) (bool, error) { + return confirmModuleInput(cmd, bufio.NewScanner(cmd.InOrStdin()), question) +} + +func confirmModuleInput( + cmd *cobra.Command, + r *bufio.Scanner, + question string, +) (bool, error) { + if _, err := fmt.Fprintf(cmd.ErrOrStderr(), "%s [y/N] ", question); err != nil { + return false, err + } + if !r.Scan() { + if err := r.Err(); err != nil { + return false, err + } + return false, errors.New( + "no confirmation received; use --yes to approve non-interactively", + ) + } + switch strings.ToLower(strings.TrimSpace(r.Text())) { + case "y", "yes": + return true, nil + case "", "n", "no": + return false, nil + default: + return false, errors.New("expected yes or no; no changes approved") + } +} + +func (cli moduleCLI) finishMutation(m moduleInvocation, message string) error { + if _, err := fmt.Fprintln(m.cmd.OutOrStdout(), message); err != nil { + return err + } + if err := cli.reconcile(m.ctx, m.root); err != nil { + return fmt.Errorf("module change saved, file reconciliation failed: %w", err) + } + return nil +} + +func reconcileModuleFiles(ctx context.Context, root string) error { + rc, err := reconcile.NewContext(ctx, root) + if err != nil { + return err + } + // Evaluate the committed configuration rather than the old shell's manifest. + spec, err := reconcile.Speculate(ctx, root, map[string]any{}, 0) + if err != nil { + return err + } + return reconcileAfterMutation(rc, spec) +} + +func printModuleProto(w io.Writer, msg proto.Message) error { + b, err := (protojson.MarshalOptions{Indent: " "}).Marshal(msg) + if err != nil { + return err + } + _, err = w.Write(append(b, '\n')) + return err +} + +func moduleInfo(m moduleInvocation, args []string) error { + id := args[0] + r, err := m.api.GetModule( + m.ctx, + connect.NewRequest(&agentv1.GetModuleRequest{ModuleId: id}), + ) + if err != nil { + return err + } + out, err := m.api.GetModuleOutputs( + m.ctx, + connect.NewRequest(&agentv1.GetModuleOutputsRequest{ModuleId: id}), + ) + if err != nil { + return err + } + mod := r.Msg.GetModule() + if mod == nil || out.Msg.GetOutputs() == nil { + return errors.New("incomplete module metadata") + } + // Do not dump the full config: settings and app overrides may be private. + w := m.cmd.OutOrStdout() + if _, err := fmt.Fprintf( + w, + "%s (%s)\n%s\nCategory: %s\nEnabled: %t\nActions:\n", + mod.GetMeta().GetName(), + mod.GetId(), + mod.GetMeta().GetDescription(), + mod.GetMeta().GetCategory(), + mod.GetEnabled(), + ); err != nil { + return err + } + for _, name := range sortedKeys(mod.Actions) { + a := mod.Actions[name] + if _, err := fmt.Fprintf( + w, + " %s\t%s\t%s\n", + name, + a.GetLabel(), + a.GetDescription(), + ); err != nil { + return err + } + } + if _, err := fmt.Fprintln(w, "Outputs:"); err != nil { + return err + } + return printModuleProto(w, out.Msg.GetOutputs()) +} + +func runModuleAction(m moduleInvocation, args []string, raw string, yes bool) error { + if pos := m.cmd.ArgsLenAtDash(); pos >= 0 && pos != 2 { + return errors.New("expected before --") + } + r, err := m.api.GetModule( + m.ctx, + connect.NewRequest(&agentv1.GetModuleRequest{ModuleId: args[0]}), + ) + if err != nil { + return err + } + action := r.Msg.GetModule().GetActions()[args[1]] + if action == nil { + return fmt.Errorf("module %q has no action %q", args[0], args[1]) + } + if m.cmd.Flags().Changed("json") && raw == "" { + return errors.New("--json requires a JSON object") + } + params, err := moduleActionArgs(raw, args[2:], action.GetArgsSchema()) + if err != nil { + return err + } + if !yes && action.GetConfirm() != "" { + ok, err := confirmModule(m.cmd, action.GetConfirm()) + if err != nil { + return err + } + if !ok { + return errors.New("action cancelled") + } + } + req := &agentv1.RunModuleActionRequest{ + ModuleId: args[0], + ActionId: args[1], + Args: params, + } + var exited bool + var code int32 + err = m.api.ExecuteAction( + m.ctx, + req, + func(ev *agentv1.RunModuleActionResponse) error { + if exited { + return errors.New("received event after action exit") + } + switch e := ev.GetEvent().(type) { + case *agentv1.RunModuleActionResponse_Stdout: + _, err := io.WriteString(m.cmd.OutOrStdout(), e.Stdout) + return err + case *agentv1.RunModuleActionResponse_Stderr: + _, err := io.WriteString(m.cmd.ErrOrStderr(), e.Stderr) + return err + case *agentv1.RunModuleActionResponse_Json: + return printModuleProto(m.cmd.OutOrStdout(), e.Json) + case *agentv1.RunModuleActionResponse_ExitCode: + exited, code = true, e.ExitCode + return nil + default: + return errors.New("unknown module action event") + } + }, + ) + if err != nil { + return err + } + if !exited { + return errors.New("action ended without exit status") + } + if code != 0 { + return fmt.Errorf("action exited with status %d", code) + } + return nil +} + +func moduleActionArgs( + raw string, + flags []string, + schema *structpb.Struct, +) (*structpb.Struct, error) { + if raw == "" && len(flags) == 1 && + strings.HasPrefix(strings.TrimSpace(flags[0]), "{") { + raw, flags = flags[0], nil + } + if raw != "" { + if len(flags) > 0 { + return nil, errors.New("provide a JSON object or -- flags, not both") + } + var args structpb.Struct + if err := protojson.Unmarshal([]byte(raw), &args); err != nil { + return nil, errors.New("action arguments must be a JSON object") + } + return &args, nil + } + values := map[string]any{} + properties := schema.GetFields()["properties"].GetStructValue().GetFields() + for len(flags) > 0 { + flag, rest := flags[0], flags[1:] + if !strings.HasPrefix(flag, "--") { + return nil, errors.New("expected --key=value, --key value, or a JSON object") + } + key, val, explicit := strings.Cut(flag[2:], "=") + if key == "" { + return nil, errors.New("empty argument name") + } + if _, exists := values[key]; exists { + return nil, fmt.Errorf("duplicate action argument %q", key) + } + typ := properties[key].GetStructValue().GetFields()["type"].GetStringValue() + if !explicit && len(rest) > 0 && !strings.HasPrefix(rest[0], "--") { + val, rest, explicit = rest[0], rest[1:], true + } + switch { + case !explicit && (typ == "" || typ == "boolean"): + values[key] = true + case !explicit: + return nil, fmt.Errorf("missing value for --%s", key) + case typ == "string": + values[key] = val + default: + var decoded any + if err := json.Unmarshal([]byte(val), &decoded); err != nil { + if typ != "" { + return nil, fmt.Errorf("--%s expects a JSON %s", key, typ) + } + decoded = val + } + values[key] = decoded + } + flags = rest + } + return structpb.NewStruct(values) +} diff --git a/apps/stackpanel-go/cmd/cli/module_adoption.go b/apps/stackpanel-go/cmd/cli/module_adoption.go new file mode 100644 index 00000000..55a278ba --- /dev/null +++ b/apps/stackpanel-go/cmd/cli/module_adoption.go @@ -0,0 +1,248 @@ +package cmd + +import ( + "bufio" + "errors" + "fmt" + "io" + "strings" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/structpb" +) + +type moduleAdoptionOptions struct { + yes, defaults bool + inputs reconcile.AnswerInputs +} + +func (o *moduleAdoptionOptions) bind(cmd *cobra.Command) { + f := cmd.Flags() + f.BoolVarP( + &o.yes, + "yes", + "y", + false, + "Approve enable and reconciliation without prompting; leave unspecified optional offers unanswered unless --adopt-defaults", + ) + f.BoolVar( + &o.defaults, + "adopt-defaults", + false, + "Use declared defaults for pending offers not explicitly answered", + ) + f.StringSliceVar(&o.inputs.With, "with", nil, "Accept an offer by id (repeatable)") + f.StringSliceVar( + &o.inputs.Without, + "without", + nil, + "Record a decline for an offer (repeatable)", + ) + f.StringArrayVar( + &o.inputs.Values, + "addon", + nil, + "Answer id=value (boolean, choice, or comma-separated choices; repeatable)", + ) +} + +// answers collects decisions, not config mutations. Only the service may derive +// patches and persist the ledger from the reviewed answers and their revisions. +func (o moduleAdoptionOptions) answers( + id string, + offers []*agentv1.ModuleAdoptionOffer, + input *bufio.Scanner, + w io.Writer, +) ([]*agentv1.ModuleAdoptionAnswer, error) { + byID := make(map[string]*agentv1.ModuleAdoptionOffer, len(offers)) + for _, offer := range offers { + if offer.GetId() == "" || offer.GetRevision() == "" { + return nil, fmt.Errorf("invalid adoption offer for module %q", id) + } + if byID[offer.Id] != nil { + return nil, fmt.Errorf("duplicate adoption offer %q", offer.Id) + } + byID[offer.Id] = offer + } + explicit := map[string]bool{} + selectID := func(key string) error { + if byID[key] == nil { + return fmt.Errorf("no pending adoption offer %q for %s", key, id) + } + if explicit[key] { + return fmt.Errorf("multiple answers for adoption offer %q", key) + } + explicit[key] = true + return nil + } + for _, group := range [][]string{o.inputs.With, o.inputs.Without} { + for _, key := range group { + if err := selectID(key); err != nil { + return nil, err + } + } + } + for _, pair := range o.inputs.Values { + key, raw, ok := strings.Cut(pair, "=") + if !ok { + return nil, errors.New("--addon expects id=value") + } + if err := selectID(key); err != nil { + return nil, err + } + if err := checkAddonInput(byID[key], raw); err != nil { + return nil, err + } + } + var answers []*agentv1.ModuleAdoptionAnswer + for _, offer := range offers { + if o.defaults && !explicit[offer.Id] && offer.GetDefault() == nil { + continue // No declared default: leave this offer pending. + } + q := nixeval.AddonQuestion{ + Type: offer.GetType(), + Label: offer.Label, + Description: offer.Description, + } + if def := offer.GetDefault(); def != nil { + q.Default = def.AsInterface() + } + for _, c := range offer.GetChoices() { + q.Choices = append( + q.Choices, + nixeval.AddonChoice{Value: c.GetValue(), Label: c.GetLabel()}, + ) + } + inputs := o.inputs + if !explicit[offer.Id] && !o.defaults { + if o.yes { + continue + } + raw, err := promptModuleOffer(input, w, offer) + if err != nil { + return nil, err + } + if raw == "" { + continue + } // skip without recording a decline + inputs.Values = []string{offer.Id + "=" + raw} + } + a, err := reconcile.ResolveAnswer( + inputs, + nixeval.AddonSpec{ID: offer.Id, Question: q}, + ) + if err != nil { + return nil, err + } + if q.Type == "select" { + if _, ok := reconcile.FindChoice(q, a.Select); !ok { + return nil, fmt.Errorf( + "offer %q has no choice %q; use --addon %s= or leave it unanswered", + offer.Id, + a.Select, + offer.Id, + ) + } + } + var record any = a.Record(q) + if multi, ok := record.([]string); ok { + values := make([]any, len(multi)) + for i, v := range multi { + values[i] = v + } + record = values + } + if record == nil { + return nil, fmt.Errorf("unsupported adoption question type %q", q.Type) + } + v, err := structpb.NewValue(record) + if err != nil { + return nil, err + } + answers = append( + answers, + &agentv1.ModuleAdoptionAnswer{Id: offer.Id, Revision: offer.Revision, Answer: v}, + ) + if _, err := fmt.Fprintf( + w, + "Selected %s (revision %s): %v\n", + offer.Id, + offer.Revision, + record, + ); err != nil { + return nil, err + } + } + return answers, nil +} + +func promptModuleOffer( + input *bufio.Scanner, + w io.Writer, + offer *agentv1.ModuleAdoptionOffer, +) (string, error) { + if _, err := fmt.Fprintf( + w, + "Optional: %s (%s, module %s)\n%s\n", + offer.Label, + offer.Id, + offer.Module, + offer.Description, + ); err != nil { + return "", err + } + for _, c := range offer.Choices { + if _, err := fmt.Fprintf(w, " %s: %s\n", c.GetValue(), c.GetLabel()); err != nil { + return "", err + } + } + var hint string + switch offer.GetType() { + case "bool": + hint = "yes or no" + case "select": + hint = "choice value" + case "multiselect": + hint = "comma-separated choice values" + default: + return "", fmt.Errorf("unknown adoption question type %q", offer.GetType()) + } + if _, err := fmt.Fprintf( + w, + "Answer (%s; Enter to leave unanswered): ", + hint, + ); err != nil { + return "", err + } + if !input.Scan() { + if err := input.Err(); err != nil { + return "", err + } + return "", errors.New("no adoption input received; nothing approved") + } + raw := strings.TrimSpace(input.Text()) + if raw == "" { + return "", nil + } + if err := checkAddonInput(offer, raw); err != nil { + return "", err + } + return raw, nil +} + +func checkAddonInput(offer *agentv1.ModuleAdoptionOffer, raw string) error { + if offer.GetType() == "bool" { + switch strings.ToLower(raw) { + case "1", "0", "true", "false", "yes", "no": + return nil + default: + return fmt.Errorf("offer %q expects yes or no", offer.Id) + } + } + // The service validates choices and revision against the live module on + // both preview and enable. Do not duplicate its catalog validation here. + return nil +} diff --git a/apps/stackpanel-go/cmd/cli/module_dev.go b/apps/stackpanel-go/cmd/cli/module_dev.go new file mode 100644 index 00000000..926b81b0 --- /dev/null +++ b/apps/stackpanel-go/cmd/cli/module_dev.go @@ -0,0 +1,825 @@ +package cmd + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "net/url" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + + "github.com/darkmatter/stackpanel/stackpanel-go/internal/flakeedit" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/setupsession" + nixgrammar "github.com/darkmatter/stackpanel/stackpanel-go/internal/treesitter/nix" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nix" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" + "github.com/spf13/cobra" + treesitter "github.com/tree-sitter/go-tree-sitter" +) + +func addModuleDevCommands(module *cobra.Command) { + var linkID, linkUI string + link := &cobra.Command{ + Use: "link ", + Short: "Override an installed flake input with a local module checkout", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + root, err := moduleProjectRoot(cmd) + if err != nil { + return err + } + id, local, err := moduleCheckout(args[0], linkID, linkUI) + if err != nil { + return err + } + // Nix only warns about an unknown --override-input. Do not persist + // an override that evaluation will ignore. Ask Nix rather than + // guessing the flake's inputs from its source or a stale lock. + if err := checkModuleInput(cmd, root, id, local.Path); err != nil { + return err + } + mgr, err := userconfig.NewManager() + if err != nil { + return err + } + if err := mgr.SetLinkedModule(root, id, local); err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Linked %s to %s in %s\n", id, local.Path, root) + return nil + }, + } + link.Flags(). + StringVar(&linkID, "id", "", "Module ID / flake input name (defaults to checkout directory name)") + link.Flags(). + StringVar(&linkUI, "ui-url", "", "Loopback URL of the module's custom UI dev server") + unlink := &cobra.Command{ + Use: "unlink ", + Short: "Remove a project's local module override", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + root, err := moduleProjectRoot(cmd) + if err != nil { + return err + } + mgr, err := userconfig.NewManager() + if err != nil { + return err + } + if err := mgr.UnlinkModule(root, args[0]); err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Unlinked %s in %s\n", args[0], root) + return nil + }, + } + var dev moduleDevOptions + preview := &cobra.Command{ + Use: "dev", + Short: "Preview this module in Studio using an isolated scratch consumer", + Args: cobra.NoArgs, + Long: "Open this module in Studio using an isolated scratch consumer. If dev starts a local agent, it stays in the foreground until you press Ctrl-C. A previously running agent and any UI dev server remain under their original owner's control.", + RunE: func(cmd *cobra.Command, _ []string) error { return runModuleDev(cmd, dev) }, + } + preview.Flags(). + StringVar(&dev.id, "id", "", "Module ID / flake input name (defaults to checkout directory name)") + preview.Flags(). + StringVar(&dev.uiURL, "ui-url", "", "Loopback URL of the module's custom UI dev server") + preview.Flags(). + StringVar(&dev.flake, "flake", "", "Stackpanel framework flake ref (default $STACKPANEL_FLAKE or github:darkmatter/stackpanel)") + preview.Flags(). + StringVar(&dev.studio, "studio-url", setupsession.DefaultStudioURL, "Official Studio URL or a loopback Studio dev server") + preview.Flags(). + IntVar(&dev.port, "agent-port", 0, "Local agent port (defaults to a per-consumer port)") + preview.Flags(). + BoolVar(&dev.noBrowser, "no-browser", false, "Print the Studio link without launching a browser") + eject := &cobra.Command{ + Use: "eject ", + Short: "Copy a project-local module into a new standalone Git flake", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + root, err := moduleProjectRoot(cmd) + if err != nil { + return err + } + if err := ejectLocalModule(cmd.Context(), root, args[0], args[1]); err != nil { + return err + } + fmt.Fprintf( + cmd.OutOrStdout(), + "Created %s. Review the staged files before committing; the original module is unchanged.\n", + args[1], + ) + return nil + }, + } + module.AddCommand(link, unlink, preview, eject) +} + +func moduleCheckout(path, id, uiURL string) (string, userconfig.LinkedModule, error) { + var link userconfig.LinkedModule + path, err := filepath.Abs(path) + if err != nil { + return "", link, err + } + path, err = filepath.EvalSymlinks(path) + if err != nil { + return "", link, err + } + if id == "" { + id = filepath.Base(path) + } + if !userconfig.ValidModuleID(id) { + return "", link, fmt.Errorf( + "invalid module ID %q; specify the module's input name with --id", + id, + ) + } + if err := userconfig.ValidateUIDevURL(uiURL); err != nil { + return "", link, err + } + if err := moduleRegularFile(filepath.Join(path, "flake.nix")); err != nil { + return "", link, fmt.Errorf("module checkout: %w", err) + } + return id, userconfig.LinkedModule{Path: path, UIDevURL: uiURL}, nil +} + +func moduleRegularFile(path string) error { + st, err := os.Lstat(path) + if err != nil { + return err + } + if !st.Mode().IsRegular() { + return fmt.Errorf("expected a regular file at %s", path) + } + return nil +} + +func modulePathRef(path string) string { + return "path:" + (&url.URL{Path: path}).EscapedPath() +} + +func checkModuleInput(cmd *cobra.Command, root, id, path string) error { + links, err := userconfig.LoadLinkedModules(root) + if err != nil { + return err + } + if links == nil { + links = make(map[string]userconfig.LinkedModule) + } + links[id] = userconfig.LinkedModule{Path: path} + args := []string{"flake", "metadata", "--json", "--no-write-lock-file"} + for _, name := range sortedKeys(links) { + args = append(args, "--override-input", name, modulePathRef(links[name].Path)) + } + probe := exec.CommandContext(cmd.Context(), "nix", append(args, ".")...) + probe.Dir, probe.Stderr = root, cmd.ErrOrStderr() + data, err := probe.Output() + if err != nil { + return fmt.Errorf("resolve inputs of %s: %w", root, err) + } + var metadata struct { + Locks struct { + Root string + Nodes map[string]struct{ Inputs map[string]json.RawMessage } + } + } + if err := json.Unmarshal(data, &metadata); err != nil { + return fmt.Errorf("read Nix input graph: %w", err) + } + if _, ok := metadata.Locks.Nodes[metadata.Locks.Root].Inputs[id]; !ok { + return fmt.Errorf( + "%s has no input %q; install the module first or use --id to select its input", + root, + id, + ) + } + // An enabled modules. setting can itself produce a placeholder row + // even when the input exports nothing. Check the actual import selected + // by this consumer, then evaluate the whole proposed graph before saving. + source, err := os.ReadFile(filepath.Join(root, "flake.nix")) + if err != nil { + return err + } + editor, err := flakeedit.NewFlakeEditor(source) + if err != nil { + return err + } + defer editor.Close() + export, err := editor.ModuleImportPath(id) + if err != nil { + return fmt.Errorf("determine module import for %s: %w", id, err) + } + shape, err := nixeval.EvalOnce(cmd.Context(), nixeval.EvalOnceParams{ + Expression: modulePathRef(path) + "#" + export, + Apply: "m: builtins.isFunction m || builtins.isAttrs m || builtins.isPath m", + }) + if err != nil { + return fmt.Errorf("read module export %s in %s: %w", export, path, err) + } + if string(bytes.TrimSpace(shape)) != "true" { + return fmt.Errorf("%s in %s is not a Nix module", export, path) + } + state, err := nixeval.EvalProspectiveModuleState(cmd.Context(), root, links) + if err != nil { + return fmt.Errorf("evaluate proposed link in %s: %w", root, err) + } + var result struct { + Modules []struct { + ID string `json:"id"` + } `json:"modulesListAll"` + } + if err := json.Unmarshal(state, &result); err != nil { + return fmt.Errorf("read module list: %w", err) + } + for _, mod := range result.Modules { + if mod.ID == id { + return nil + } + } + return fmt.Errorf("proposed input does not register module %q in %s", id, root) +} + +type moduleDevOptions struct { + id, uiURL, flake, studio string + port int + noBrowser bool +} + +func runModuleDev(cmd *cobra.Command, opts moduleDevOptions) error { + if cmd.Flags().Changed("project-root") { + return errors.New( + "module dev creates its own scratch project; use module link to preview in an existing project", + ) + } + parent := cmd.Context() + ctx, cancel := signal.NotifyContext(parent, os.Interrupt, syscall.SIGTERM) + defer cancel() + cmd.SetContext(ctx) + defer cmd.SetContext(parent) + id, local, err := moduleCheckout(".", opts.id, opts.uiURL) + if err != nil { + return err + } + if id == "self" || id == "nixpkgs" || id == "stackpanel" || id == "flake-parts" { + return fmt.Errorf("module ID %q collides with a framework input", id) + } + if opts.port < 0 || opts.port > 65535 { + return errors.New("agent port must be between 1 and 65535 (or 0 for automatic)") + } + cache := os.Getenv("XDG_CACHE_HOME") + if !filepath.IsAbs(cache) { + home, err := os.UserHomeDir() + if err != nil { + return err + } + cache = filepath.Join(home, ".cache") + } + framework := resolveFlakeRef(opts.flake) + if filepath.IsAbs(framework) || strings.HasPrefix(framework, "./") || + strings.HasPrefix(framework, "../") || + framework == "." { + abs, err := filepath.Abs(framework) + if err != nil { + return err + } + framework = modulePathRef(abs) + } + studio, err := url.Parse(opts.studio) + official, _ := url.Parse(setupsession.DefaultStudioURL) + if err != nil || studio.Host == "" || studio.User != nil || + !(studio.Scheme == official.Scheme && studio.Host == official.Host || userconfig.ValidateUIDevURL(opts.studio) == nil) { + return errors.New( + "Studio must use the official Studio origin or a loopback HTTP(S) dev server", + ) + } + origin := studio.Scheme + "://" + studio.Host + // Checkouts of two modules with the same basename must not share a + // lockfile, project ID, settings, or running agent. + hash := sha256.Sum256([]byte(local.Path + "\x00" + framework + "\x00" + origin)) + root := filepath.Join( + cache, + "stackpanel", + "dev-harness", + id, + fmt.Sprintf("%x", hash[:8]), + ) + if opts.port == 0 { + opts.port = 20000 + int(binary.BigEndian.Uint16(hash[:2]))%20000 + } + endpoint := "http://127.0.0.1:" + strconv.Itoa(opts.port) + executable, err := os.Executable() + if err != nil { + return err + } + root, err = prepareModuleConsumer(cmd, root, id, local.Path, framework) + if err != nil { + return err + } + mgr, err := userconfig.NewManager() + if err != nil { + return err + } + if err := mgr.SetLinkedModule(root, id, local); err != nil { + return err + } + fmt.Fprintf( + cmd.ErrOrStderr(), + "Preparing the Nix devshell and local agent for %s. Ctrl+C to cancel. Log: %s\n", + id, + setupAgentLogPath(), + ) + _, started, err := ensureLocalAgent( + ctx, + root, + executable, + endpoint, + origin, + opts.port, + ) + if err != nil { + return err + } + if started != nil { + defer started.stop() + } + studio = &url.URL{Scheme: studio.Scheme, Host: studio.Host, Path: "/studio/m/" + id} + link, err := setupsession.StudioURL( + studio.String(), + setupsession.Session{ + ProjectID: userconfig.GenerateProjectID(root), + Endpoint: endpoint, + }, + ) + if err != nil { + return err + } + fmt.Fprintln(cmd.OutOrStdout(), link) + if !opts.noBrowser { + if err := openSetupStudio(ctx, link); err != nil { + return fmt.Errorf( + "could not launch a browser; open the printed Studio URL: %w", + err, + ) + } + } + if started == nil { + return nil // Reused agent; its existing owner controls its lifetime. + } + fmt.Fprintln(cmd.ErrOrStderr(), "Press Ctrl-C to stop the preview agent.") + select { + case <-ctx.Done(): + return parent.Err() // Ctrl-C/TERM is an orderly shutdown; preserve caller cancellation. + case <-started.done: + if started.err != nil { + return fmt.Errorf( + "preview agent exited: %w; inspect %s", + started.err, + setupAgentLogPath(), + ) + } + return nil + } +} + +func prepareModuleConsumer( + cmd *cobra.Command, + root, id, path, framework string, +) (string, error) { + if err := os.MkdirAll(filepath.Dir(root), 0o700); err != nil { + return "", err + } + parent, err := filepath.EvalSymlinks(filepath.Dir(root)) + if err != nil { + return "", err + } + root = filepath.Join(parent, filepath.Base(root)) + if rel, err := filepath.Rel(path, root); err != nil || filepath.IsLocal(rel) { + return "", fmt.Errorf("scratch consumer cannot be inside module checkout %s", path) + } + // Follows keep the consumer on the framework's actual pins. The path + // input makes the initial locked nix develop work without an override; + // userconfig supplies the live override on subsequent agent evaluations. + ref, err := nix.Serialize(framework) + if err != nil { + return "", err + } + input, err := nix.Serialize(modulePathRef(path)) + if err != nil { + return "", err + } + flake := fmt.Sprintf(`{ + description = "Stackpanel module development consumer"; + inputs = { + stackpanel.url = %s; + nixpkgs.follows = "stackpanel/nixpkgs"; + flake-parts.follows = "stackpanel/flake-parts"; + "%s".url = %s; + }; + outputs = { self, stackpanel, ... }@inputs: + assert inputs."%s" ? stackpanelModules.default; + stackpanel.lib.mkFlake { inherit inputs self; }; +} +`, ref, id, input, id) + if err := os.Mkdir(root, 0o700); err == nil { + if err := initModuleConsumer( + cmd.Context(), + root, + id, + flake, + cmd.ErrOrStderr(), + ); err != nil { + _ = os.RemoveAll( + root, + ) // Created exclusively above; never remove a reused project. + return "", err + } + } else if !errors.Is(err, os.ErrExist) { + return "", err + } else { + // Keep the author's changes to the preview config on the next run. + real, err := filepath.EvalSymlinks(root) + if err != nil || real != root { + return "", fmt.Errorf("unsafe scratch project path: %s", root) + } + top, err := setupGitCommand(cmd.Context(), root, "rev-parse", "--show-toplevel") + if err != nil || strings.TrimSuffix(string(top), "\n") != root { + return "", fmt.Errorf("not a scratch Git repository: %s", root) + } + old, err := os.ReadFile(filepath.Join(root, "flake.nix")) + if err != nil || string(old) != flake { + return "", fmt.Errorf("scratch flake changed; refusing to overwrite %s", root) + } + for _, rel := range []string{"flake.lock", ".stack/config.nix"} { + if err := moduleRegularFile(filepath.Join(root, rel)); err != nil { + return "", fmt.Errorf("incomplete scratch consumer: %w", err) + } + } + if _, err := setupGitCommand( + cmd.Context(), + root, + "ls-files", + "--error-unmatch", + "--", + "flake.nix", + "flake.lock", + ".stack/config.nix", + ); err != nil { + return "", fmt.Errorf("scratch flake inputs are not tracked: %w", err) + } + } + return root, nil +} + +func initModuleConsumer( + ctx context.Context, + root, id, flake string, + out io.Writer, +) error { + if _, err := setupGitCommand(ctx, root, "init", "--quiet"); err != nil { + return err + } + if err := os.Mkdir(filepath.Join(root, ".stack"), 0o700); err != nil { + return err + } + if err := os.WriteFile( + filepath.Join(root, "flake.nix"), + []byte(flake), + 0o644, + ); err != nil { + return err + } + cfg := fmt.Sprintf( + "{\n name = \"%s-dev\";\n enable = true;\n cli.enable = true;\n modules.\"%s\".enable = true;\n}\n", + id, + id, + ) + if err := os.WriteFile( + filepath.Join(root, ".stack", "config.nix"), + []byte(cfg), + 0o644, + ); err != nil { + return err + } + if _, err := setupGitCommand( + ctx, + root, + "add", + "-f", + "--", + "flake.nix", + ".stack/config.nix", + ); err != nil { + return err + } + if err := runSetupProcess(ctx, root, out, "nix", "flake", "lock"); err != nil { + return fmt.Errorf("lock scratch flake: %w", err) + } + _, err := setupGitCommand(ctx, root, "add", "-f", "--", "flake.lock") + return err +} + +func ejectLocalModule(ctx context.Context, project, id, dest string) error { + if !userconfig.ValidModuleID(id) { + return fmt.Errorf("invalid module ID %q", id) + } + project, err := filepath.EvalSymlinks(project) + if err != nil { + return err + } + src := filepath.Join(project, ".stack", "modules", id) + real, err := filepath.EvalSymlinks(src) + if err != nil { + return err + } + if real != src { + return fmt.Errorf("refusing to eject a symlinked module: %s", src) + } + dest, err = filepath.Abs(dest) + if err != nil { + return err + } + parent, err := filepath.EvalSymlinks(filepath.Dir(dest)) + if err != nil { + return fmt.Errorf("destination parent must exist: %w", err) + } + dest = filepath.Join(parent, filepath.Base(dest)) + for _, part := range strings.Split(dest, string(filepath.Separator)) { + if strings.EqualFold(part, ".git") { + return fmt.Errorf("refusing to eject into Git metadata: %s", dest) + } + } + if rel, err := filepath.Rel(src, dest); err != nil || filepath.IsLocal(rel) { + return fmt.Errorf("destination %s is inside the source module", dest) + } + if err := os.Mkdir(dest, 0o755); err != nil { + return fmt.Errorf("destination must be a new directory: %w", err) + } + success := false + defer func() { + if !success { + _ = os.RemoveAll(dest) + } + }() + if _, err := setupGitCommand(ctx, dest, "init", "--quiet"); err != nil { + return err + } + if err := copyModuleSources(ctx, src, dest); err != nil { + return err + } + entry := "default.nix" + if err := moduleRegularFile(filepath.Join(dest, entry)); err != nil { + entry = "module.nix" + if err := moduleRegularFile(filepath.Join(dest, entry)); err != nil { + return fmt.Errorf("module %s needs a regular default.nix or module.nix", id) + } + } + flake := fmt.Sprintf(`{ + description = "Stackpanel module: %s"; + outputs = { self }: { + stackpanelModules.default = import ./%s; + }; +} +`, id, entry) + if err := writeEjectedFile( + filepath.Join(dest, "flake.nix"), + strings.NewReader(flake), + 0o644, + ); err != nil { + return err + } + // The source Git file list has already applied the author's ignores; + // keep deliberately tracked files even if they match a global ignore. + if _, err := setupGitCommand(ctx, dest, "add", "-f", "--", "."); err != nil { + return err + } + success = true + return nil +} + +func copyModuleSources(ctx context.Context, src, dest string) error { + // Respect ignores in the containing project, including private local + // files. For a prototype not yet in Git, use the new (empty) index + // with the source as the work tree so module-local ignores still work. + var opts []string + for dir := src; ; dir = filepath.Dir(dir) { + if _, err := os.Lstat(filepath.Join(dir, ".git")); err == nil { + break + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + if filepath.Dir(dir) == dir { + opts = []string{"--git-dir=" + filepath.Join(dest, ".git"), "--work-tree=" + src} + break + } + } + files, err := setupGitCommand( + ctx, + src, + append( + opts, + "ls-files", + "--cached", + "--others", + "--exclude-standard", + "-z", + "--", + ".", + )...) + if err != nil { + return err + } + source, err := os.OpenRoot(src) + if err != nil { + return err + } + defer source.Close() + parser := treesitter.NewParser() + defer parser.Close() + if err := parser.SetLanguage( + treesitter.NewLanguage(nixgrammar.Language()), + ); err != nil { + return err + } + var deps []ejectedDependency + for _, rel := range setupGitPaths(files) { + if !filepath.IsLocal(rel) || filepath.Clean(rel) != rel { + return fmt.Errorf("cannot eject nested repository or non-local path %q", rel) + } + for _, part := range strings.Split(rel, string(filepath.Separator)) { + if strings.EqualFold(part, ".git") { + return fmt.Errorf("refusing to copy Git metadata %q", rel) + } + } + switch rel { + case "flake.nix", "flake.lock": + return fmt.Errorf( + "module already contains %s; refusing to replace an existing flake", + rel, + ) + } + if err := copyModuleFile(source, rel, dest, parser, &deps); err != nil { + return err + } + } + // Validate against the finished copy, not the checkout: Git ignores, + // deletions, and empty directories affect what will actually be published. + for _, dep := range deps { + target := filepath.Join(dest, dep.target) + info, err := os.Stat(target) + if err == nil && dep.isImport && info.IsDir() { + err = moduleRegularFile(filepath.Join(target, "default.nix")) + } + if err != nil { + return fmt.Errorf( + "%s: required module path %q is missing from the ejected flake: %w", + dep.from, + dep.target, + err, + ) + } + } + return nil +} + +type ejectedDependency struct { + from, target string + isImport bool +} + +func copyModuleFile( + source *os.Root, + rel, dest string, + parser *treesitter.Parser, + deps *[]ejectedDependency, +) error { + info, err := source.Lstat(rel) + if errors.Is(err, os.ErrNotExist) { + return nil // A tracked file deleted from the working tree. + } + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return fmt.Errorf("refusing to copy non-regular module source %s", rel) + } + in, err := source.Open(rel) + if err != nil { + return err + } + defer in.Close() + var r io.Reader = in + if strings.HasSuffix(rel, ".nix") { + data, err := io.ReadAll(in) + if err != nil { + return err + } + if err := checkModuleNixPaths(parser, rel, data, deps); err != nil { + return err + } + r = bytes.NewReader(data) + } + return writeEjectedFile(filepath.Join(dest, rel), r, info.Mode().Perm()) +} + +func writeEjectedFile(path string, r io.Reader, mode os.FileMode) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode) + if err != nil { + return err + } + _, err = io.Copy(out, r) + return errors.Join(err, out.Close()) +} + +// A prototype that imports ../../nix/... isn't standalone. Catch literal +// paths that won't survive extraction, including those in helper modules, +// without interpreting comments or shell strings as dependencies. Computed +// dependencies still need the author's normal consumer evaluation/CI. +func checkModuleNixPaths( + parser *treesitter.Parser, + rel string, + data []byte, + deps *[]ejectedDependency, +) error { + tree := parser.Parse(data, nil) + if tree == nil { + return fmt.Errorf("cannot parse %s", rel) + } + defer tree.Close() + root := tree.RootNode() + if root.HasError() { + return fmt.Errorf("invalid Nix syntax in %s", rel) + } + var visit func(*treesitter.Node) error + visit = func(n *treesitter.Node) error { + switch n.Kind() { + case "hpath_expression", "spath_expression": + return fmt.Errorf( + "%s uses a host-dependent Nix path: %s", + rel, + data[n.StartByte():n.EndByte()], + ) + case "path_expression": + path := string(data[n.StartByte():n.EndByte()]) + prefix, _, dynamic := strings.Cut(path, "${") + target := filepath.Join(filepath.Dir(rel), prefix) + first, _, _ := strings.Cut(target, string(filepath.Separator)) + if filepath.IsAbs(prefix) || !filepath.IsLocal(target) || + strings.EqualFold(first, ".git") { + return fmt.Errorf( + "%s: %s is outside the module; move the dependency into the module before ejecting", + rel, + path, + ) + } + if !dynamic { + callee := nixPathCallee(n, data) + if callee != "builtins.pathExists" { + *deps = append( + *deps, + ejectedDependency{ + from: rel, + target: target, + isImport: callee == "import" || callee == "builtins.import", + }, + ) + } + } + } + for i := uint(0); i < n.NamedChildCount(); i++ { + if err := visit(n.NamedChild(i)); err != nil { + return err + } + } + return nil + } + return visit(root) +} + +func nixPathCallee(path *treesitter.Node, data []byte) string { + parent := path.Parent() + for parent != nil && parent.Kind() == "parenthesized_expression" { + path, parent = parent, parent.Parent() + } + if parent != nil && parent.Kind() == "apply_expression" { + fn, arg := parent.ChildByFieldName("function"), parent.ChildByFieldName("argument") + if fn != nil && arg != nil && arg.StartByte() == path.StartByte() { + return string(data[fn.StartByte():fn.EndByte()]) + } + } + return "" +} diff --git a/apps/stackpanel-go/cmd/cli/module_dev_test.go b/apps/stackpanel-go/cmd/cli/module_dev_test.go new file mode 100644 index 00000000..d5bbb361 --- /dev/null +++ b/apps/stackpanel-go/cmd/cli/module_dev_test.go @@ -0,0 +1,901 @@ +package cmd + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +func authorFile(t *testing.T, path, text string, mode os.FileMode) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(text), mode); err != nil { + t.Fatal(err) + } +} + +func authorRead(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func authorGit(t *testing.T, dir string, args ...string) string { + t.Helper() + b, err := setupGitCommand(t.Context(), dir, args...) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func authorCLI(t *testing.T, args ...string) (string, error) { + t.Helper() + cmd := newModuleCmd() + var out, stderr bytes.Buffer + cmd.SetOut(&out) + cmd.SetErr(&stderr) + cmd.SetArgs(args) + if err := cmd.ExecuteContext(t.Context()); err != nil { + return out.String(), fmt.Errorf("%w\n%s", err, stderr.String()) + } + return out.String(), nil +} + +func TestModuleProjectRootUsesCanonicalDirectory(t *testing.T) { + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + nested := filepath.Join(root, "nested") + authorFile(t, filepath.Join(nested, ".stackpanel", "config.nix"), "{}", 0o644) + t.Chdir(nested) + if got, err := findProjectRoot(); err == nil { + t.Fatalf("unsupported config directory selected a project: %s", got) + } + authorFile(t, filepath.Join(root, ".stack", "config.nix"), "{}", 0o644) + got, err := findProjectRoot() + if err != nil || got != root { + t.Fatalf("findProjectRoot() = %q, %v; want %q", got, err, root) + } +} + +func TestModuleLinkKeepsOtherProjectOverrides(t *testing.T) { + project, old, other, author := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir() + for _, dir := range []string{project, old, other, author} { + authorFile(t, filepath.Join(dir, "flake.nix"), `{ outputs = { self }: {}; }`, 0o644) + } + authorFile( + t, + filepath.Join(project, "flake.nix"), + `{ inputs.demo.url = "path:/demo"; outputs = { self, stackpanel, ... }@inputs: stackpanel.lib.mkFlake { inherit inputs self; }; }`, + 0o644, + ) + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + mgr, err := userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + for id, path := range map[string]string{"demo": old, "other": other} { + if err := mgr.SetLinkedModule( + project, + id, + userconfig.LinkedModule{Path: path}, + ); err != nil { + t.Fatal(err) + } + } + bin, argv := t.TempDir(), filepath.Join(t.TempDir(), "args") + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("AUTHOR_TEST_ARGS", argv) + authorFile(t, filepath.Join(bin, "nix"), `#!/bin/sh +if [ "$1" = eval ]; then + case "$*" in + *--apply*) echo true ;; + *) echo '{"modulesListAll":[{"id":"demo"}]}' ;; + esac + exit 0 +fi +printf '%s\n' "$@" >"$AUTHOR_TEST_ARGS" +echo '{"locks":{"root":"project","nodes":{"project":{"inputs":{"demo":"demo_2","other":"other"}}}}}' +`, 0o755) + if _, err := authorCLI( + t, + "link", + author, + "--id", + "demo", + "--project-root", + project, + ); err != nil { + t.Fatal(err) + } + links, err := userconfig.LoadLinkedModules(project) + if err != nil { + t.Fatal(err) + } + for id, path := range map[string]string{"demo": author, "other": other} { + path, err := filepath.EvalSymlinks(path) + if err != nil || links[id].Path != path { + t.Fatalf("unexpected link for %s: %+v (%v)", id, links[id], err) + } + } + want := []string{ + "flake", + "metadata", + "--json", + "--no-write-lock-file", + "--override-input", + "demo", + modulePathRef(links["demo"].Path), + "--override-input", + "other", + modulePathRef(links["other"].Path), + ".", + } + if got := authorRead(t, argv); got != strings.Join(want, "\n")+"\n" { + t.Fatalf("validation didn't use the resulting input graph:\n%s", got) + } +} + +func TestModuleEjectPublishesIndependentWorkingCopy(t *testing.T) { + for _, entry := range []string{"default.nix", "module.nix"} { + t.Run(entry, func(t *testing.T) { + root := t.TempDir() + authorGit(t, root, "init", "--quiet") + src := filepath.Join(root, ".stack", "modules", "sample") + authorFile( + t, + filepath.Join(src, entry), + `{ ... }: { text = builtins.readFile ./message; }`, + 0o644, + ) + authorFile(t, filepath.Join(src, "message"), "staged version", 0o644) + authorFile(t, filepath.Join(src, "bin", "report"), "#!/bin/sh\necho ok\n", 0o755) + authorFile(t, filepath.Join(root, ".gitignore"), "private-token\n", 0o644) + authorGit(t, root, "add", "-f", "--", ".stack/modules/sample/message") + authorFile(t, filepath.Join(src, "message"), "working copy", 0o644) + authorFile(t, filepath.Join(src, "private-token"), "must not be exported", 0o600) + before := authorGit(t, root, "status", "--porcelain=v1", "--untracked-files=all") + dest := filepath.Join(t.TempDir(), "standalone") + t.Setenv("STACKPANEL_ROOT", t.TempDir()) + if _, err := authorCLI( + t, + "eject", + "--project-root", + root, + "sample", + dest, + ); err != nil { + t.Fatal(err) + } + if got := authorGit( + t, + root, + "status", + "--porcelain=v1", + "--untracked-files=all", + ); got != before { + t.Fatalf("eject modified the source/index: %s -> %s", before, got) + } + if got := authorRead(t, filepath.Join(dest, "message")); got != "working copy" { + t.Fatalf("ejected %q instead of working copy", got) + } + st, err := os.Stat(filepath.Join(dest, "bin", "report")) + if err != nil || st.Mode()&0o111 == 0 { + t.Fatalf("lost executable bit: %v %v", st, err) + } + if _, err := os.Lstat( + filepath.Join(dest, "private-token"), + ); !errors.Is( + err, + os.ErrNotExist, + ) { + t.Fatalf("copied ignored local data: %v", err) + } + if got := authorRead( + t, + filepath.Join(dest, "flake.nix"), + ); !strings.Contains(got, "stackpanelModules.default = import ./"+entry) || + strings.Contains(got, src) { + t.Fatal(got) + } + authorGit( + t, + dest, + "ls-files", + "--error-unmatch", + "--", + "flake.nix", + entry, + "message", + "bin/report", + ) + authorFile(t, filepath.Join(src, "message"), "changed again", 0o644) + if _, err := authorCLI( + t, + "eject", + "--project-root", + root, + "sample", + dest, + ); err == nil || + authorRead(t, filepath.Join(dest, "message")) != "working copy" { + t.Fatal( + "overwrote an existing destination or ejected a reference to the source", + ) + } + }) + } +} + +func TestModuleEjectRejectsUnsafeCopies(t *testing.T) { + root := t.TempDir() + src := filepath.Join(root, ".stack", "modules", "demo") + authorFile(t, filepath.Join(src, "module.nix"), `{ ... }: { }`, 0o644) + outside := filepath.Join(t.TempDir(), "outside") + authorFile(t, outside, "unchanged", 0o644) + if err := os.Symlink(outside, filepath.Join(src, "token")); err != nil { + t.Fatal(err) + } + alias := filepath.Join(t.TempDir(), "alias") + if err := os.Symlink(src, alias); err != nil { + t.Fatal(err) + } + if err := os.Symlink( + filepath.Dir(outside), + filepath.Join(root, ".stack", "modules", "linked"), + ); err != nil { + t.Fatal(err) + } + for _, tc := range []struct{ id, dest string }{ + {"demo", filepath.Join(t.TempDir(), "copy")}, // symlink among regular files + {"demo", filepath.Join(src, "inside")}, + {"demo", filepath.Join(alias, "inside")}, + {"linked", filepath.Join(t.TempDir(), "copy")}, + {"../demo", filepath.Join(t.TempDir(), "copy")}, + } { + if err := ejectLocalModule(t.Context(), root, tc.id, tc.dest); err == nil { + t.Fatalf("allowed unsafe ejection %s -> %s", tc.id, tc.dest) + } + if _, err := os.Lstat(tc.dest); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("left a partial copy at %s", tc.dest) + } + } + if got := authorRead(t, outside); got != "unchanged" { + t.Fatal("modified symlink target") + } +} + +func TestModuleEjectRejectsRepoRelativeDependency(t *testing.T) { + project := t.TempDir() + dir := filepath.Join(project, ".stack", "modules", "sample") + authorFile( + t, + filepath.Join(dir, "module.nix"), + `{ imports = [ ./helpers/ui.nix ]; }`, + 0o644, + ) + authorFile( + t, + filepath.Join(dir, "helpers", "ui.nix"), + `import ../../repo-only.nix`, + 0o644, + ) + dest := filepath.Join(t.TempDir(), "sample") + if err := ejectLocalModule( + t.Context(), + project, + "sample", + dest, + ); err == nil || + !strings.Contains(err.Error(), "repo-only.nix") { + t.Fatalf("expected an error identifying the non-portable dependency, got %v", err) + } + if _, err := os.Stat(dest); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("failed ejection left a partial destination: %v", err) + } +} + +func TestModuleEjectRequiresCopiedSiblingDependencies(t *testing.T) { + for _, state := range []string{"present", "ignored", "absent"} { + t.Run(state, func(t *testing.T) { + project := t.TempDir() + authorGit(t, project, "init", "--quiet") + src := filepath.Join(project, ".stack", "modules", "demo") + authorFile( + t, + filepath.Join(src, "default.nix"), + `import ./helpers/detail.nix`, + 0o644, + ) + authorFile( + t, + filepath.Join(src, "helpers/detail.nix"), + `{ text = builtins.readFile ../assets/message; }`, + 0o644, + ) + if state != "absent" { + authorFile(t, filepath.Join(src, "assets/message"), "hello", 0o644) + } + if state == "ignored" { + // A slash-containing pattern is relative to the .gitignore that + // declares it. Verify Git really excludes this dependency. + authorFile(t, filepath.Join(src, ".gitignore"), "assets/message\n", 0o644) + if got := authorGit( + t, + src, + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "--", + "assets/message", + ); strings.TrimSpace( + got, + ) != "assets/message" { + t.Fatalf("fixture must omit a real ignored dependency; git reported %q", got) + } + } + dest := filepath.Join(t.TempDir(), "demo") + err := ejectLocalModule(t.Context(), project, "demo", dest) + if state != "present" { + if err == nil || !strings.Contains(err.Error(), "assets/message") { + t.Fatalf("expected missing module dependency error, got %v", err) + } + if _, err := os.Stat(dest); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("partial ejection left behind: %v", err) + } + return + } + if err != nil { + t.Fatal(err) + } + authorGit( + t, + dest, + "ls-files", + "--error-unmatch", + "--", + "helpers/detail.nix", + "assets/message", + ) + if got := authorRead( + t, + filepath.Join(dest, "helpers/../assets/message"), + ); got != "hello" { + t.Fatalf("wrong sibling content: %s", got) + } + }) + } +} + +func TestModuleDevOpensSelectedScratchProject(t *testing.T) { + cfg := filepath.Join(t.TempDir(), "user.yaml") + cache, bin := t.TempDir(), t.TempDir() + src := filepath.Join(t.TempDir(), "checkout") + authorFile( + t, + filepath.Join(src, "flake.nix"), + `{ outputs = { self }: { stackpanelModules.default = {}; }; }`, + 0o644, + ) + t.Chdir(src) + t.Setenv("STACKPANEL_USER_CONFIG", cfg) + t.Setenv("STACKPANEL_ROOT", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", cache) + t.Setenv("STACKPANEL_FLAKE", "github:fixture/framework") + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + authorFile(t, filepath.Join(bin, "nix"), `#!/bin/sh +set -eu +test "$*" = 'flake lock' +test ! -e flake.lock +git ls-files --error-unmatch -- flake.nix .stack/config.nix >/dev/null +printf '{}\n' >flake.lock +`, 0o755) + opened := filepath.Join(t.TempDir(), "url") + t.Setenv("AUTHOR_TEST_URL", opened) + for _, launcher := range []string{"open", "xdg-open"} { + authorFile( + t, + filepath.Join(bin, launcher), + "#!/bin/sh\nprintf '%s' \"$1\" >\"$AUTHOR_TEST_URL\"\n", + 0o755, + ) + } + mgr, err := userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + other := t.TempDir() + if _, err := mgr.SetCurrentProject(other); err != nil { + t.Fatal(err) + } + // A live agent can be reused only after it reports the expected root and + // a ready devshell. Discover that root as an independent Studio client would. + agent := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/health" { + http.NotFound(w, r) + return + } + current, err := userconfig.NewManager() + if err != nil { + http.Error(w, err.Error(), 500) + return + } + for _, p := range current.ListProjects() { + if _, ok := p.LinkedModules["demo"]; ok { + _ = json.NewEncoder(w). + Encode(map[string]any{"project_root": p.Path, "status": "ok", "agent_id": "test-agent", "devshell_ready": true, "setup_version": 1}) + return + } + } + http.NotFound(w, r) + }), + ) + defer agent.Close() + agentURL, _ := url.Parse(agent.URL) + if _, err := authorCLI( + t, + "dev", + "--id", + "demo", + "--studio-url", + "https://studio.example", + ); err == nil { + t.Fatal("accepted an arbitrary remote Studio origin") + } + args := []string{ + "dev", + "--id", + "demo", + "--ui-url", + "http://localhost:5174", + "--studio-url", + "http://localhost:3000", + "--agent-port", + agentURL.Port(), + } + out, err := authorCLI(t, args...) + if err != nil { + t.Fatal(err) + } + link, err := url.Parse(strings.TrimSpace(out)) + if err != nil { + t.Fatal(err) + } + if link.Path != "/studio/m/demo" || link.Host != "localhost:3000" || + link.Query().Get("agent") != agent.URL || + authorRead(t, opened) != link.String() { + t.Fatalf("bad browser handoff: %s", link) + } + mgr, err = userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + p := mgr.ResolveProject(link.Query().Get("project")) + if p == nil || p.Path == other || p.Path == src || mgr.CurrentProjectPath() != other { + t.Fatalf("preview was not scoped to the scratch consumer: %+v", p) + } + realSource, err := filepath.EvalSymlinks(src) + if err != nil { + t.Fatal(err) + } + if got := p.LinkedModules["demo"]; got.Path != realSource || + got.UIDevURL != "http://localhost:5174" { + t.Fatalf("incorrect module link: %+v", got) + } + authorGit( + t, + p.Path, + "ls-files", + "--error-unmatch", + "--", + "flake.lock", + "flake.nix", + ".stack/config.nix", + ) + if _, err := os.Stat( + filepath.Join(src, "flake.lock"), + ); !errors.Is( + err, + os.ErrNotExist, + ) { + t.Fatal("preview locked the author project") + } + if again, err := authorCLI( + t, + args...); err != nil || + strings.TrimSpace(again) != link.String() { + t.Fatalf( + "unable to reuse the same consumer without rewriting its lock: %s %v", + again, + err, + ) + } +} + +// Stand-in for the agent below nix develop. This subprocess must also die +// when the preview closes, not just the Nix wrapper that launched it. +func TestModuleDevHealthFixture(t *testing.T) { + addr := os.Getenv("AUTHOR_TEST_SERVE_HEALTH") + if addr == "" { + return + } + root, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + s := &http.Server{ + Addr: addr, + Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w). + Encode(map[string]any{"project_root": root, "status": "ok", "agent_id": "preview", "devshell_ready": true, "setup_version": 1}) + }), + } + time.AfterFunc(20*time.Second, func() { _ = s.Close() }) + if err := s.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + t.Fatal(err) + } +} + +func TestModuleDevCancellationStopsOwnedProcessGroup(t *testing.T) { + bin, src := t.TempDir(), filepath.Join(t.TempDir(), "demo") + authorFile( + t, + filepath.Join(src, "flake.nix"), + `{ outputs = { self }: { stackpanelModules.default = {}; }; }`, + 0o644, + ) + t.Chdir(src) + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + l, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().(*net.TCPAddr) + l.Close() + pids := filepath.Join(t.TempDir(), "pids") + t.Setenv("AUTHOR_TEST_ADDR", addr.String()) + t.Setenv("AUTHOR_TEST_BIN", exe) + t.Setenv("AUTHOR_TEST_PIDS", pids) + authorFile(t, filepath.Join(bin, "nix"), `#!/bin/sh +set -eu +if [ "$1" = flake ]; then echo '{}' >flake.lock; exit; fi +test "$1" = develop +AUTHOR_TEST_SERVE_HEALTH="$AUTHOR_TEST_ADDR" "$AUTHOR_TEST_BIN" -test.run='^TestModuleDevHealthFixture$' & +agent=$! +trap 'wait "$agent" || :; exit 0' TERM +printf '%d %d\n' "$$" "$agent" >"$AUTHOR_TEST_PIDS" +wait "$agent" +`, 0o755) + cmd := newModuleCmd() + cmd.SilenceUsage, cmd.SilenceErrors = true, true + r, w := io.Pipe() + defer r.Close() + cmd.SetOut(w) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + cmd.SetArgs([]string{"dev", "--no-browser", "--agent-port", strconv.Itoa(addr.Port)}) + ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + err := cmd.ExecuteContext(ctx) + _ = w.CloseWithError(err) + done <- err + }() + link, readErr := bufio.NewReader(r).ReadString('\n') + cancel() + err = <-done + if readErr != nil || !strings.Contains(link, "/studio/m/demo?") || + !errors.Is(err, context.Canceled) { + t.Fatalf( + "preview handoff / cancellation: %q %v %v\n%s", + link, + readErr, + err, + stderr.String(), + ) + } + var wrapper, child int + if _, err := fmt.Sscan( + authorRead(t, pids), + &wrapper, + &child, + ); err != nil || wrapper <= 0 || + child <= 0 { + t.Fatalf("bad fixture PIDs: %v", err) + } + for _, pid := range []int{wrapper, child} { + if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) { + t.Fatalf("preview process %d still exists after cancellation: %v", pid, err) + } + } +} + +func TestModuleDevWaitsForStartupOutcome(t *testing.T) { + for _, tc := range []struct{ name, command string }{ + {"child failure", "exit 37"}, + {"cancel while preparing", "exec sleep 30"}, + } { + t.Run(tc.name, func(t *testing.T) { + root, bin := t.TempDir(), t.TempDir() + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "config.yaml")) + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + authorFile( + t, + filepath.Join(bin, "nix"), + "#!/bin/sh\necho $$ > launcher.pid\n"+tc.command+"\n", + 0o755, + ) + l, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().(*net.TCPAddr) + l.Close() + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + _, started, err := ensureLocalAgent( + ctx, + root, + "stack", + "http://"+addr.String(), + "https://stackpanel.dev", + addr.Port, + ) + if started != nil || err == nil { + t.Fatalf("claimed readiness before any health response: %v, %v", started, err) + } + if tc.command == "exit 37" { + if !strings.Contains(err.Error(), "exit status 37") { + t.Fatalf("lost child failure: %v", err) + } + } else if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("did not honor caller context before readiness: %v", err) + } + pid, err := strconv.Atoi( + strings.TrimSpace(authorRead(t, filepath.Join(root, "launcher.pid"))), + ) + if err != nil || pid <= 0 { + t.Fatalf("invalid launcher pid: %d %v", pid, err) + } + if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) { + t.Fatalf("startup did not reap launcher %d: %v", pid, err) + } + }) + } +} + +// Exercise Git filtering, pure evaluation of the ejected module, a live edit +// via the same evaluator flags used by the agent, and returning to the pin. +// No network inputs, external catalog, or pre-existing user config are needed. +func TestModuleEjectLinkUnlinkPureNix(t *testing.T) { + if _, err := exec.LookPath("nix"); err != nil { + t.Skip("requires Nix") + } + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "config.yaml")) + t.Setenv("NIX_CONFIG", "experimental-features = nix-command flakes") + t.Setenv("STACKPANEL_ROOT", t.TempDir()) + project := t.TempDir() + src := filepath.Join(project, ".stack", "modules", "sample") + authorFile( + t, + filepath.Join(src, "default.nix"), + `{ ... }: { text = builtins.readFile ./message; }`, + 0o644, + ) + authorFile(t, filepath.Join(src, "message"), "first", 0o644) + dest := filepath.Join(t.TempDir(), "sample") + if _, err := authorCLI( + t, + "eject", + "sample", + dest, + "--project-root", + project, + ); err != nil { + t.Fatal(err) + } + // Deliberately tiny local framework: consumes exactly the public mkFlake + // argument shape, the module flake output and the consumer config file. + dep, framework := t.TempDir(), t.TempDir() + authorFile(t, filepath.Join(dep, "flake.nix"), `{ outputs = { self }: {}; }`, 0o644) + authorFile(t, filepath.Join(framework, "flake.nix"), fmt.Sprintf(`{ + inputs.nixpkgs.url = %q; + inputs.flake-parts.follows = "nixpkgs"; + outputs = { self, ... }: { + lib.mkFlake = { self, inputs }: { + # self includes these outputs; force the consumer config only once its + # message is requested, not while constructing the output set itself. + message = assert (import (self + "/.stack/config.nix")).modules.sample.enable; + (inputs.sample.stackpanelModules.default {}).text; + legacyPackages.%q.stackpanelSerializable.modulesListAll = [ { + id = (inputs.sample.stackpanelModules.default {}).id or "sample"; + readme = (inputs.sample.stackpanelModules.default {}).text; + } ]; + }; + }; +}`, modulePathRef(dep), nixeval.CurrentSystem()), 0o644) + cmd := newModuleCmd() + cmd.SetContext(t.Context()) + consumer, err := prepareModuleConsumer( + cmd, + filepath.Join(t.TempDir(), "consumer"), + "sample", + dest, + modulePathRef(framework), + ) + if err != nil { + t.Fatal(err) + } + lock := authorRead(t, filepath.Join(consumer, "flake.lock")) + eval := func() string { + t.Helper() + args, err := nixeval.ProjectFlakeArgs(consumer) + if err != nil { + t.Fatal(err) + } + args = append([]string{"eval", "--raw", ".#message"}, args...) + c := exec.CommandContext(t.Context(), "nix", args...) + c.Dir = consumer + var stderr bytes.Buffer + c.Stderr = &stderr + out, err := c.Output() + if err != nil { + t.Fatalf("pure Nix evaluation failed: %v\n%s", err, stderr.String()) + } + return string(out) + } + if got := eval(); got != "first" { + t.Fatalf("scratch consumer evaluated %q", got) + } + // Override with a different checkout; leave the original pinned input + // alone. Relative path and HMR state must stay scoped to this project. + author := filepath.Join(t.TempDir(), "sample") + if _, err := authorCLI( + t, + "eject", + "sample", + author, + "--project-root", + project, + ); err != nil { + t.Fatal(err) + } + t.Chdir(filepath.Dir(author)) + if _, err := authorCLI( + t, + "link", + "sample", + "--project-root", + consumer, + "--ui-url", + "https://not-local.example/ui", + ); err == nil { + t.Fatal("accepted a non-local UI dev server") + } + if _, err := authorCLI( + t, + "link", + "sample", + "--id", + "undeclared", + "--project-root", + consumer, + ); err == nil { + t.Fatal("linked an input absent from the consumer") + } + if _, err := authorCLI( + t, + "link", + "sample", + "--project-root", + consumer, + "--ui-url", + "http://localhost:5174", + ); err != nil { + t.Fatal(err) + } + authorFile(t, filepath.Join(author, "message"), "edited", 0o644) + if got := eval(); got != "edited" { + t.Fatalf("live override evaluated %q", got) + } + // An input and even a placeholder module ID in consumer settings are + // insufficient: the author checkout must supply the expected module. + bogus := t.TempDir() + authorFile( + t, + filepath.Join(bogus, "flake.nix"), + `{ outputs = _: { unrelated = true; }; }`, + 0o644, + ) + configBefore := authorRead(t, userconfig.GetConfigPath()) + if _, err := authorCLI( + t, + "link", + bogus, + "--id", + "sample", + "--project-root", + consumer, + ); err == nil { + t.Fatal("linked a non-module over the working input") + } + if got := authorRead(t, userconfig.GetConfigPath()); got != configBefore { + t.Fatal("invalid candidate changed the active link") + } + if got := authorRead(t, filepath.Join(consumer, "flake.lock")); got != lock { + t.Fatal("prospective validation wrote the lockfile") + } + authorFile( + t, + filepath.Join(bogus, "flake.nix"), + `{ outputs = _: { stackpanelModules.default = _: { text = "ok"; id = "other"; }; }; }`, + 0o644, + ) + if _, err := authorCLI( + t, + "link", + bogus, + "--id", + "sample", + "--project-root", + consumer, + ); err == nil { + t.Fatal("linked an export that does not register the requested module") + } + if got := authorRead(t, userconfig.GetConfigPath()); got != configBefore { + t.Fatal("wrong module ID changed the active link") + } + if _, err := authorCLI(t, "unlink", "sample", "--project-root", project); err == nil { + t.Fatal("unlinked from another project") + } + if _, err := authorCLI( + t, + "unlink", + "sample", + "--project-root", + consumer, + ); err != nil { + t.Fatal(err) + } + if got := eval(); got != "first" { + t.Fatalf("unlink failed to restore locked input: %q", got) + } + if got := authorRead(t, filepath.Join(consumer, "flake.lock")); got != lock { + t.Fatal("link, evaluation or unlink modified the consumer lockfile") + } +} diff --git a/apps/stackpanel-go/cmd/cli/module_local_test.go b/apps/stackpanel-go/cmd/cli/module_local_test.go new file mode 100644 index 00000000..209d7cc0 --- /dev/null +++ b/apps/stackpanel-go/cmd/cli/module_local_test.go @@ -0,0 +1,63 @@ +package cmd + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" +) + +// Run the real Cobra tree, local service, and pure Nix evaluator against a +// self-contained consumer. No agent process, default project, or pairing token. +func TestModuleInfoWithoutAgent(t *testing.T) { + if _, err := exec.LookPath("nix"); err != nil { + t.Skip("requires Nix") + } + root := t.TempDir() + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "config.yaml")) + t.Setenv("STACKPANEL_ROOT", t.TempDir()) // another project's shell + t.Setenv("NIX_CONFIG", "experimental-features = nix-command flakes") + flake := fmt.Sprintf(`{ + outputs = { self }: { + legacyPackages.%q.stackpanelSerializable = { + modulesListAll = [{ id = "db"; enabled = true; + enablePath = "modules.db.enable"; configPath = "modules.db.settings"; + meta = { name = "Database"; category = "services"; }; + settings.token = "private-value"; + actions.migrate = { label = "Migrate schema"; outputMode = "stream"; }; + }]; + moduleOutputs.db.files = [{ path = "schema.sql"; type = "text"; }]; + }; + }; +}`, nixeval.CurrentSystem()) + if err := os.WriteFile( + filepath.Join(root, "flake.nix"), + []byte(flake), + 0o644, + ); err != nil { + t.Fatal(err) + } + subdir := filepath.Join(root, "apps") + if err := os.Mkdir(subdir, 0o755); err != nil { + t.Fatal(err) + } + t.Chdir(subdir) + cmd := newModuleCmd() + var out bytes.Buffer + cmd.SetOut(&out) + cmd.SetErr(&out) + cmd.SetArgs([]string{"info", "db"}) + if err := cmd.ExecuteContext(t.Context()); err != nil { + t.Fatal(err) + } + got := out.String() + if !strings.Contains(got, "schema.sql") || !strings.Contains(got, "Migrate schema") || + strings.Contains(got, "private-value") { + t.Errorf("unexpected module info: %q", got) + } +} diff --git a/apps/stackpanel-go/cmd/cli/module_test.go b/apps/stackpanel-go/cmd/cli/module_test.go new file mode 100644 index 00000000..165643a6 --- /dev/null +++ b/apps/stackpanel-go/cmd/cli/module_test.go @@ -0,0 +1,465 @@ +package cmd + +import ( + "bytes" + "context" + "errors" + "slices" + "strings" + "testing" + + "connectrpc.com/connect" + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1/agentv1connect" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/structpb" +) + +type moduleFixture struct { + agentv1connect.UnimplementedModuleServiceHandler + calls []string + schema *structpb.Struct + params *structpb.Struct + exitCode int32 + reconcileErr error + offers []*agentv1.ModuleAdoptionOffer + reviewed, committed []*agentv1.ModuleAdoptionAnswer +} + +func (f *moduleFixture) invoke( + t *testing.T, + stdin string, + args ...string, +) (string, string, error) { + t.Helper() + root := t.TempDir() + cli := moduleCLI{ + open: func(ctx context.Context, project string) (context.Context, moduleAPI, error) { + if project != root { + t.Fatalf("selected %q instead of %q", project, root) + } + return ctx, f, nil + }, + reconcile: func(context.Context, string) error { + f.calls = append(f.calls, "reconcile") + return f.reconcileErr + }, + } + cmd := cli.command() + var out, stderr bytes.Buffer + cmd.SilenceErrors, cmd.SilenceUsage = true, true + cmd.SetArgs(append([]string{"--project-root", root}, args...)) + cmd.SetIn(strings.NewReader(stdin)) + cmd.SetOut(&out) + cmd.SetErr(&stderr) + err := cmd.ExecuteContext(t.Context()) + return out.String(), stderr.String(), err +} + +func (f *moduleFixture) InstallModule( + _ context.Context, + req *connect.Request[agentv1.InstallModuleRequest], +) (*connect.Response[agentv1.InstallModuleResponse], error) { + f.calls = append(f.calls, "install:"+req.Msg.ModuleId+"@"+req.Msg.Version) + return connect.NewResponse( + &agentv1.InstallModuleResponse{ + ModuleId: "cache", + Message: "Installed external/cache", + }, + ), nil +} + +func (f *moduleFixture) PreviewModuleEnable( + _ context.Context, + req *connect.Request[agentv1.PreviewModuleEnableRequest], +) (*connect.Response[agentv1.PreviewModuleEnableResponse], error) { + f.calls = append(f.calls, "preview:"+req.Msg.ModuleId) + f.reviewed = req.Msg.Answers + files := []string{"cache.conf"} + if len(f.reviewed) > 0 { + files = append(files, "selected.conf") + } + return connect.NewResponse( + &agentv1.PreviewModuleEnableResponse{ + Preview: &agentv1.ModulePreview{ + Files: &agentv1.ModulePreviewDiff{Added: files}, + Offers: f.offers, + }, + }, + ), nil +} + +func (f *moduleFixture) EnableModule( + _ context.Context, + req *connect.Request[agentv1.EnableModuleRequest], +) (*connect.Response[agentv1.EnableModuleResponse], error) { + f.calls = append(f.calls, "enable:"+req.Msg.ModuleId) + f.committed = req.Msg.Answers + return connect.NewResponse( + &agentv1.EnableModuleResponse{Message: "Enabled cache"}, + ), nil +} + +func (f *moduleFixture) DisableModule( + _ context.Context, + req *connect.Request[agentv1.DisableModuleRequest], +) (*connect.Response[agentv1.DisableModuleResponse], error) { + f.calls = append(f.calls, "disable:"+req.Msg.ModuleId) + return connect.NewResponse( + &agentv1.DisableModuleResponse{Message: "Disabled cache"}, + ), nil +} + +func (f *moduleFixture) UninstallModule( + _ context.Context, + req *connect.Request[agentv1.UninstallModuleRequest], +) (*connect.Response[agentv1.UninstallModuleResponse], error) { + f.calls = append(f.calls, "uninstall:"+req.Msg.ModuleId) + return connect.NewResponse( + &agentv1.UninstallModuleResponse{Message: "Uninstalled cache"}, + ), nil +} + +func (f *moduleFixture) ListRegistryModules( + _ context.Context, + req *connect.Request[agentv1.ListRegistryModulesRequest], +) (*connect.Response[agentv1.ListRegistryModulesResponse], error) { + f.calls = append( + f.calls, + strings.Join([]string{"search", req.Msg.Query, req.Msg.Category, req.Msg.Tag}, ":"), + ) + return connect.NewResponse( + &agentv1.ListRegistryModulesResponse{Modules: []*agentv1.RegistryModule{ + { + Id: "uninstalled", + }, + { + Id: "external/cache", + Installed: true, + LatestVersion: "1.2.0", + Category: "services", + }, + }}, + ), nil +} + +func (f *moduleFixture) UpdateModule( + _ context.Context, + req *connect.Request[agentv1.UpdateModuleRequest], +) (*connect.Response[agentv1.UpdateModuleResponse], error) { + f.calls = append(f.calls, "update:"+req.Msg.ModuleId+"@"+req.Msg.Version) + return connect.NewResponse( + &agentv1.UpdateModuleResponse{Message: "Updated cache"}, + ), nil +} + +func (f *moduleFixture) ListModules( + context.Context, + *connect.Request[agentv1.ListModulesRequest], +) (*connect.Response[agentv1.ListModulesResponse], error) { + return connect.NewResponse( + &agentv1.ListModulesResponse{ + Modules: []*agentv1.Module{{Id: "cache", Enabled: true}, {Id: "lint"}}, + }, + ), nil +} + +func (f *moduleFixture) GetModule( + context.Context, + *connect.Request[agentv1.GetModuleRequest], +) (*connect.Response[agentv1.GetModuleResponse], error) { + settings := &structpb.Struct{ + Fields: map[string]*structpb.Value{ + "token": structpb.NewStringValue("private-setting"), + }, + } + return connect.NewResponse(&agentv1.GetModuleResponse{Module: &agentv1.Module{ + Id: "cache", + Enabled: true, + Settings: settings, + Actions: map[string]*agentv1.ModuleAction{ + "flush": {ArgsSchema: f.schema, Confirm: proto.String("Flush the cache?")}, + }, + }}), nil +} + +func (f *moduleFixture) GetModuleOutputs( + context.Context, + *connect.Request[agentv1.GetModuleOutputsRequest], +) (*connect.Response[agentv1.GetModuleOutputsResponse], error) { + return connect.NewResponse( + &agentv1.GetModuleOutputsResponse{ + Outputs: &agentv1.ModuleOutputs{ + ModuleId: "cache", + Services: []*agentv1.ModuleOutputService{{Name: "cache.service"}}, + }, + }, + ), nil +} + +func (f *moduleFixture) ExecuteAction( + _ context.Context, + req *agentv1.RunModuleActionRequest, + send func(*agentv1.RunModuleActionResponse) error, +) error { + f.params = req.Args + for _, ev := range []*agentv1.RunModuleActionResponse{ + {Event: &agentv1.RunModuleActionResponse_Stdout{Stdout: "done\n"}}, + {Event: &agentv1.RunModuleActionResponse_Stderr{Stderr: "progress\n"}}, + {Event: &agentv1.RunModuleActionResponse_ExitCode{ExitCode: f.exitCode}}, + } { + if err := send(ev); err != nil { + return err + } + } + return nil +} + +func TestModuleInstallAdoption(t *testing.T) { + for _, tc := range []struct { + name, stdin string + yes, adopted, wantErr bool + }{ + {"accept", "yes\n", false, true, false}, + {"explicit flag", "", true, true, false}, + {"decline", "n\n", false, false, false}, + {"closed stdin", "", false, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &moduleFixture{} + args := []string{"install", "external/cache@1.2.0"} + if tc.yes { + args = append(args, "--yes") + } + out, _, err := f.invoke(t, tc.stdin, args...) + if (err != nil) != tc.wantErr || !strings.Contains(out, "cache.conf") { + t.Fatalf("out=%q err=%v", out, err) + } + want := []string{"install:external/cache@1.2.0", "preview:cache"} + if tc.adopted { + want = append(want, "enable:cache", "reconcile") + } + if !slices.Equal(f.calls, want) { + t.Fatalf("operations %v, want %v", f.calls, want) + } + }) + } +} + +func TestModuleMutationCommands(t *testing.T) { + for _, tc := range []struct{ args, calls []string }{ + {[]string{"enable", "cache", "--yes"}, []string{"preview:cache", "enable:cache", "reconcile"}}, + {[]string{"disable", "cache"}, []string{"disable:cache", "reconcile"}}, + {[]string{"uninstall", "external/cache"}, []string{"uninstall:external/cache", "reconcile"}}, + {[]string{"update", "external/cache@2"}, []string{"update:external/cache@2", "reconcile"}}, + {[]string{"update", "--all"}, []string{"search:::", "update:external/cache@", "reconcile"}}, + } { + f := &moduleFixture{} + _, _, err := f.invoke(t, "", tc.args...) + if err != nil || !slices.Equal(f.calls, tc.calls) { + t.Errorf("%v: operations %v err=%v", tc.args, f.calls, err) + } + } + f := &moduleFixture{reconcileErr: errors.New("writer failed")} + if _, _, err := f.invoke( + t, + "", + "enable", + "cache", + "-y", + ); !errors.Is( + err, + f.reconcileErr, + ) { + t.Fatalf("lost reconciliation failure: %v", err) + } +} + +func TestModuleDiscoveryCLI(t *testing.T) { + f := &moduleFixture{} + out, _, err := f.invoke( + t, + "", + "search", + "redis", + "--category", + "services", + "--tag", + "kv", + ) + if err != nil || !slices.Equal(f.calls, []string{"search:redis:services:kv"}) || + !strings.Contains(out, "external/cache") { + t.Fatalf("search: %q %v %v", out, f.calls, err) + } + for _, all := range []bool{true, false} { + args := []string{"list"} + if all { + args = append(args, "--all") + } + out, _, err := f.invoke(t, "", args...) + if err != nil || !strings.Contains(out, "cache") || + strings.Contains(out, "lint") != all { + t.Errorf("%v: %q %v", args, out, err) + } + } + out, _, err = f.invoke(t, "", "info", "cache") + if err != nil || !strings.Contains(out, "flush") || + !strings.Contains(out, "cache.service") || + strings.Contains(out, "private-setting") { + t.Errorf("info: %q %v", out, err) + } +} + +func TestModuleActionCLI(t *testing.T) { + schema, err := structpb.NewStruct(map[string]any{"properties": map[string]any{ + "filter": map[string]any{ + "type": "string", + }, + "force": map[string]any{"type": "boolean"}, + }}) + if err != nil { + t.Fatal(err) + } + for _, argv := range [][]string{{"--", "--filter", "false", "--force"}, {"--json", `{"filter":"false","force":true}`}} { + f := &moduleFixture{schema: schema} + out, stderr, err := f.invoke( + t, + "yes\n", + append([]string{"run", "cache", "flush"}, argv...)...) + if err != nil || out != "done\n" || !strings.Contains(stderr, "progress\n") || + f.params.GetFields()["filter"].GetStringValue() != "false" || + !f.params.GetFields()["force"].GetBoolValue() { + t.Fatalf( + "%v: stdout=%q stderr=%q args=%v err=%v", + argv, + out, + stderr, + f.params, + err, + ) + } + } + f := &moduleFixture{exitCode: 7} + if _, _, err := f.invoke( + t, + "no\n", + "run", + "cache", + "flush", + ); err == nil || + f.params != nil { + t.Fatal("action ran without confirmation") + } + if _, _, err := f.invoke( + t, + "", + "run", + "cache", + "flush", + "--yes", + ); err == nil || + !strings.Contains(err.Error(), "status 7") { + t.Fatalf("lost exit status: %v", err) + } + for _, args := range [][]string{{"--json", "[]"}, {"--json", `{"x":1}`, "--", "--x=2"}, {"--", "--x", "--x"}} { + if _, _, err := f.invoke( + t, + "", + append([]string{"run", "cache", "flush", "--yes"}, args...)...); err == nil { + t.Errorf("accepted invalid arguments: %v", args) + } + } +} + +func TestModuleOptionalAnswersRequireFinalApproval(t *testing.T) { + choices := []*agentv1.ModuleAdoptionChoice{ + {Label: "Alpha", Value: "a"}, + {Label: "Beta", Value: "b"}, + } + offers := []*agentv1.ModuleAdoptionOffer{ + { + Id: "configure", + Module: "cache", + Revision: "2", + Type: "bool", + Default: structpb.NewBoolValue(true), + }, + { + Id: "engine", + Module: "dependency", + Revision: "4", + Type: "select", + Choices: choices, + Default: structpb.NewStringValue("a"), + }, + { + Id: "features", + Module: "cache", + Revision: "1", + Type: "multiselect", + Choices: choices, + }, + } + for _, tc := range []struct { + name string + flags []string + stdin string + accepted, configured bool + engine string + }{ + {"interactive", nil, "yes\nb\na,b\ny\n", true, true, "b"}, + {"explicit", []string{"--yes", "--without", "configure", "--with", "engine", "--addon", "features=a,b"}, "", true, false, "a"}, + {"defaults", []string{"--yes", "--adopt-defaults", "--with", "features"}, "", true, true, "a"}, + {"cancel reviewed plan", nil, "yes\nb\na,b\nn\n", false, true, "b"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &moduleFixture{offers: offers} + out, _, err := f.invoke( + t, + tc.stdin, + append([]string{"install", "external/cache"}, tc.flags...)...) + if err != nil || !strings.Contains(out, "selected.conf") || len(f.reviewed) != 3 { + t.Fatalf("out=%s, answers=%v, err=%v", out, f.reviewed, err) + } + if a := f.reviewed[0]; a.Id != "configure" || a.Revision != "2" || + a.Answer.GetBoolValue() != tc.configured { + t.Fatal(a) + } + if a := f.reviewed[1]; a.Id != "engine" || a.Revision != "4" || + a.Answer.GetStringValue() != tc.engine { + t.Fatal(a) + } + if a := f.reviewed[2]; a.Id != "features" || a.Revision != "1" || + len(a.Answer.GetListValue().Values) != 2 { + t.Fatal(a) + } + calls := []string{"install:external/cache@", "preview:cache", "preview:cache"} + if tc.accepted { + calls = append(calls, "enable:cache", "reconcile") + if !slices.EqualFunc( + f.reviewed, + f.committed, + func(a, b *agentv1.ModuleAdoptionAnswer) bool { return proto.Equal(a, b) }, + ) { + t.Fatal("commit does not match reviewed answers") + } + } else if len(f.committed) != 0 { + t.Fatal("cancelled answers were committed") + } + if !slices.Equal(f.calls, calls) { + t.Fatalf("operations: %v", f.calls) + } + }) + } + f := &moduleFixture{offers: offers} + if _, _, err := f.invoke( + t, + "", + "enable", + "cache", + "--yes", + ); err != nil || len(f.committed) != 0 || + !slices.Equal(f.calls, []string{"preview:cache", "enable:cache", "reconcile"}) { + t.Fatalf("--yes alone must enable only: %v, %v", f.calls, err) + } +} diff --git a/apps/stackpanel-go/cmd/cli/project.go b/apps/stackpanel-go/cmd/cli/project.go index 41af4867..64bbfe30 100644 --- a/apps/stackpanel-go/cmd/cli/project.go +++ b/apps/stackpanel-go/cmd/cli/project.go @@ -1,5 +1,5 @@ // project.go manages the global project registry stored in -// ~/.config/stackpanel/stackpanel.yaml. +// ~/.config/stackpanel/config.yaml. // // The agent serves multiple projects and needs a way to route API requests. // Each project gets a deterministic ID (hash of its path) that v1 API clients @@ -28,7 +28,7 @@ var projectCmd = &cobra.Command{ Short: "Manage Stackpanel projects", Long: `Manage Stackpanel projects across your system. -Projects are stored in ~/.config/stackpanel/stackpanel.yaml and can be +Projects are stored in ~/.config/stackpanel/config.yaml and can be accessed from any directory. Each project has a unique ID; v1 API requests select their project by sending it in the X-Stackpanel-Project header. @@ -201,7 +201,9 @@ With an argument, shows information about the specified project (by ID, name, or // Usage hint fmt.Println() - fmt.Println(color.New(color.Faint).Sprint("Select this project in v1 API requests:")) + fmt.Println( + color.New(color.Faint).Sprint("Select this project in v1 API requests:"), + ) fmt.Printf( " %s\n", color.New(color.Faint).Sprintf("curl -H 'X-Stackpanel-Project: %s' ...", id), diff --git a/apps/stackpanel-go/cmd/cli/root.go b/apps/stackpanel-go/cmd/cli/root.go index 11b8bda3..13e4bea9 100644 --- a/apps/stackpanel-go/cmd/cli/root.go +++ b/apps/stackpanel-go/cmd/cli/root.go @@ -88,6 +88,7 @@ func init() { rootCmd.AddCommand(agentCmd) rootCmd.AddCommand(usersCmd) rootCmd.AddCommand(deployCmd) + rootCmd.AddCommand(newModuleCmd()) rootCmd.AddCommand(provisionCmd) rootCmd.AddCommand(direnvCmd) diff --git a/apps/stackpanel-go/cmd/cli/setup.go b/apps/stackpanel-go/cmd/cli/setup.go index 6ad555ae..89cf3622 100644 --- a/apps/stackpanel-go/cmd/cli/setup.go +++ b/apps/stackpanel-go/cmd/cli/setup.go @@ -102,15 +102,60 @@ Examples: func init() { f := setupCmd.Flags() - f.StringVar(&setupOpts.experimentalAgent, "experimental-agent", "", "Repository onboarding backend (auto, codex, claude, pi)") - f.StringVar(&setupOpts.agentModel, "agent-model", "", "Pi API model: openai/ or anthropic/ (requires an API key)") - f.IntVar(&setupOpts.agentPort, "agent-port", 0, "Local agent port (defaults to agent configuration)") - f.StringVar(&setupOpts.newDir, "new", "", "Create a new repository in an absent or empty directory (requires --experimental-agent)") - f.StringVar(&setupOpts.studioURL, "studio-url", "", "Studio URL to open after experimental setup") - f.BoolVar(&setupOpts.noBrowser, "no-browser", false, "Verify runtime without opening Studio; browser remains unverified") - f.BoolVar(&setupOpts.noRuntime, "no-runtime", false, "Verify repository only, without starting local runtime or Studio") - f.StringVar(&setupOpts.agentLog, "agent-log", "", "Write raw coding-agent output to a private debug log") - f.BoolVar(&setupOpts.restart, "restart", false, "Start a new agent onboarding plan; with --tmp create a fresh repository (keeps existing files)") + f.StringVar( + &setupOpts.experimentalAgent, + "experimental-agent", + "", + "Repository onboarding backend (auto, codex, claude, pi)", + ) + f.StringVar( + &setupOpts.agentModel, + "agent-model", + "", + "Pi API model: openai/ or anthropic/ (requires an API key)", + ) + f.IntVar( + &setupOpts.agentPort, + "agent-port", + 0, + "Local agent port (defaults to agent configuration)", + ) + f.StringVar( + &setupOpts.newDir, + "new", + "", + "Create a new repository in an absent or empty directory (requires --experimental-agent)", + ) + f.StringVar( + &setupOpts.studioURL, + "studio-url", + "", + "Studio URL to open after experimental setup", + ) + f.BoolVar( + &setupOpts.noBrowser, + "no-browser", + false, + "Verify runtime without opening Studio; browser remains unverified", + ) + f.BoolVar( + &setupOpts.noRuntime, + "no-runtime", + false, + "Verify repository only, without starting local runtime or Studio", + ) + f.StringVar( + &setupOpts.agentLog, + "agent-log", + "", + "Write raw coding-agent output to a private debug log", + ) + f.BoolVar( + &setupOpts.restart, + "restart", + false, + "Start a new agent onboarding plan; with --tmp create a fresh repository (keeps existing files)", + ) f.BoolVarP( &setupOpts.yes, "yes", @@ -206,18 +251,26 @@ func runSetupWith(cmd *cobra.Command, opts setupFlags) error { return errors.New("--agent-model requires --experimental-agent=pi") } if opts.restart && (opts.experimentalAgent == "" || opts.json || opts.dryRun) { - return errors.New("--restart requires --experimental-agent and cannot be combined with --json or --dry-run") + return errors.New( + "--restart requires --experimental-agent and cannot be combined with --json or --dry-run", + ) } if opts.agentPort < 0 || opts.agentPort > 65535 { return errors.New("--agent-port must be between 1 and 65535, or 0 for the default") } if opts.studioURL != "" { - if _, err := setupsession.StudioURL(opts.studioURL, setupsession.Session{}); err != nil { + if _, err := setupsession.StudioURL( + opts.studioURL, + setupsession.Session{}, + ); err != nil { return err } } - if opts.newDir != "" && (opts.experimentalAgent == "" || opts.tmp || opts.json || opts.dryRun) { - return errors.New("--new requires --experimental-agent and cannot be combined with --tmp, --json or --dry-run") + if opts.newDir != "" && + (opts.experimentalAgent == "" || opts.tmp || opts.json || opts.dryRun) { + return errors.New( + "--new requires --experimental-agent and cannot be combined with --tmp, --json or --dry-run", + ) } if opts.experimentalAgent != "" && !opts.json && !opts.dryRun { return runAgentSetup(cmd, opts) @@ -380,11 +433,7 @@ func runSetupWith(cmd *cobra.Command, opts setupFlags) error { } if !ok { // The offers were shown; remember that without applying anything. - if err := recordDecisions( - targetDir, - addonsFor(addonsRC, ctx), - decisions, - ); err != nil { + if err := recordDecisions(targetDir, decisions); err != nil { return err } output.Warning("Aborted: nothing applied (offers shown were recorded)") @@ -427,11 +476,7 @@ func runSetupWith(cmd *cobra.Command, opts setupFlags) error { } } - if err := recordDecisions( - targetDir, - addonsFor(addonsRC, ctx), - decisions, - ); err != nil { + if err := recordDecisions(targetDir, decisions); err != nil { return err } @@ -489,30 +534,13 @@ func decideOffers( return decisions, mutations, nil } -func addonsFor( - rc *reconcile.AddonsReconciler, - ctx *reconcile.Context, -) []nixeval.AddonSpec { - if rc.Addons != nil { - return rc.Addons - } - if ctx.Config != nil { - return ctx.Config.Addons - } - return nil -} - // recordDecisions writes the shown offers into the ledger. It records what was // shown, not what the user wants: declining writes no config at all. -func recordDecisions( - projectRoot string, - addons []nixeval.AddonSpec, - decisions []offerDecision, -) error { +func recordDecisions(projectRoot string, decisions []offerDecision) error { if len(decisions) == 0 { return nil } - ledger, err := reconcile.LoadLedger(projectRoot, reconcile.RevisionsOf(addons)) + ledger, err := reconcile.LoadLedger(projectRoot) if err != nil { return err } @@ -566,25 +594,28 @@ func reconcileAfterMutation(ctx *reconcile.Context, spec *reconcile.Speculation) manifest = o } } - filesRC := &reconcile.FilesReconciler{} - if _, err := os.Stat(filepath.Join(writer, "bin", "write-files")); err == nil { - res, err := runWriteFilesAt(ctx, filepath.Join(writer, "bin", "write-files")) - if err != nil { - return err - } - for _, c := range res.Applied { - output.Dimmed(fmt.Sprintf(" %s %s %s", filesRC.ID(), c.Kind, c.Path)) - } + if !filepath.IsAbs(writer) || !filepath.IsAbs(manifest) { + return errors.New( + "speculation did not return paths to the realized writer and preflight manifest", + ) } - if _, err := os.Stat(manifest); err == nil { - fileopsRC := &reconcile.FileopsReconciler{ManifestPath: manifest} - res, err := fileopsRC.Apply(ctx) - if err != nil { - return err - } - for _, c := range res.Applied { - output.Dimmed(fmt.Sprintf(" %s %s %s", fileopsRC.ID(), c.Kind, c.Path)) - } + if _, err := os.Stat(manifest); err != nil { + return fmt.Errorf("missing realized preflight manifest: %w", err) + } + files, err := runWriteFilesAt(ctx, filepath.Join(writer, "bin", "write-files")) + if err != nil { + return err + } + for _, c := range files.Applied { + output.Dimmed(fmt.Sprintf(" files %s %s", c.Kind, c.Path)) + } + fileopsRC := &reconcile.FileopsReconciler{ManifestPath: manifest} + res, err := fileopsRC.Apply(ctx) + if err != nil { + return err + } + for _, c := range res.Applied { + output.Dimmed(fmt.Sprintf(" %s %s %s", fileopsRC.ID(), c.Kind, c.Path)) } return nil } @@ -723,7 +754,7 @@ func createTmpInitTarget(ctx context.Context) (string, error) { } // findProjectRoot walks up the directory tree to find a project root -// (directory containing flake.nix or .stackpanel). +// (directory containing flake.nix or .stack/). func findProjectRoot() (string, error) { dir, err := os.Getwd() if err != nil { @@ -733,13 +764,13 @@ func findProjectRoot() (string, error) { if _, err := os.Stat(filepath.Join(dir, "flake.nix")); err == nil { return dir, nil } - if _, err := os.Stat(filepath.Join(dir, ".stackpanel")); err == nil { + if info, err := os.Stat(filepath.Join(dir, nixdata.ConfigDirName)); err == nil && info.IsDir() { return dir, nil } parent := filepath.Dir(dir) if parent == dir { return "", fmt.Errorf( - "no project root found (looking for flake.nix or .stackpanel)", + "no project root found (looking for flake.nix or .stack/)", ) } dir = parent diff --git a/apps/stackpanel-go/cmd/cli/setup_agent_constraints.go b/apps/stackpanel-go/cmd/cli/setup_agent_constraints.go index 2346d0e6..c24576b5 100644 --- a/apps/stackpanel-go/cmd/cli/setup_agent_constraints.go +++ b/apps/stackpanel-go/cmd/cli/setup_agent_constraints.go @@ -7,12 +7,17 @@ import ( "strings" "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" ) // setupAgentExpectations freezes explicit CLI choices independently of the // agent's interpretation. Unrequested addons do not contribute their defaults. -func setupAgentExpectations(plan reconcile.Expectations, opts setupFlags, addons []nixeval.AddonSpec) (reconcile.Expectations, error) { +func setupAgentExpectations( + plan reconcile.Expectations, + opts setupFlags, + addons []nixeval.AddonSpec, +) (reconcile.Expectations, error) { byID := make(map[string]nixeval.AddonSpec, len(addons)) for _, addon := range addons { byID[strings.ToLower(addon.ID)] = addon @@ -48,7 +53,11 @@ func setupAgentExpectations(plan reconcile.Expectations, opts setupFlags, addons // Copy the slice before replacing assertions; the caller may retain the // original plan for display or diagnostics. plan.Config = slices.Clone(plan.Config) - inputs := reconcile.AnswerInputs{With: opts.with, Without: opts.without, Values: opts.addonValues} + inputs := reconcile.AnswerInputs{ + With: opts.with, + Without: opts.without, + Values: opts.addonValues, + } for _, addon := range addons { if !requested[strings.ToLower(addon.ID)] { continue @@ -66,13 +75,17 @@ func setupAgentExpectations(plan reconcile.Expectations, opts setupFlags, addons disabled = append(disabled, setupAddonDisableSwitches(addon.Config)...) } for _, choice := range addon.Question.Choices { - selected := active && (answer.Select == choice.Value || slices.Contains(answer.Multi, choice.Value)) + selected := active && + (answer.Select == choice.Value || slices.Contains(answer.Multi, choice.Value)) if !selected { disabled = append(disabled, setupAddonDisableSwitches(choice.Config)...) } } if !active && len(disabled) == 0 { - return plan, fmt.Errorf("cannot verify declining addon %q: metadata has no enable switch to disable", addon.ID) + return plan, fmt.Errorf( + "cannot verify declining addon %q: metadata has no enable switch to disable", + addon.ID, + ) } // Selected values win when a choice shares an enable switch with other // choices, matching Materialize's base-then-choice assignment order. @@ -85,11 +98,17 @@ func setupAgentExpectations(plan reconcile.Expectations, opts setupFlags, addons return plan, fmt.Errorf("addon %q configuration: %w", addon.ID, err) } plan.Config = replaceSetupAssertion(plan.Config, reconcile.ConfigAssertion{ - Path: strings.Split(mutation.Path, "."), Equals: value, + Path: nixdata.SplitConfigPath(mutation.Path), Equals: value, }) } } - plan.Config = replaceSetupAssertion(plan.Config, reconcile.ConfigAssertion{Path: []string{"enable"}, Equals: json.RawMessage("true")}) + plan.Config = replaceSetupAssertion( + plan.Config, + reconcile.ConfigAssertion{ + Path: []string{"enable"}, + Equals: json.RawMessage("true"), + }, + ) return plan, reconcile.ValidateExpectations(plan) } @@ -102,7 +121,10 @@ func validateSetupAddonValue(addon nixeval.AddonSpec, raw string) error { return fmt.Errorf("addon %q requires a boolean value, got %q", addon.ID, raw) } } - return validateSetupAddonAnswer(addon, reconcile.ParseAnswer(addon.Question.Type, raw)) + return validateSetupAddonAnswer( + addon, + reconcile.ParseAnswer(addon.Question.Type, raw), + ) } func validateSetupAddonAnswer(addon nixeval.AddonSpec, answer reconcile.Answer) error { @@ -117,7 +139,11 @@ func validateSetupAddonAnswer(addon nixeval.AddonSpec, answer reconcile.Answer) case "multiselect": selected = answer.Multi default: - return fmt.Errorf("addon %q has unsupported question type %q", addon.ID, addon.Question.Type) + return fmt.Errorf( + "addon %q has unsupported question type %q", + addon.ID, + addon.Question.Type, + ) } for _, value := range selected { if _, ok := reconcile.FindChoice(addon.Question, value); !ok { @@ -132,7 +158,8 @@ func validateSetupAddonAnswer(addon nixeval.AddonSpec, answer reconcile.Answer) func setupAddonDisableSwitches(config map[string]any) []reconcile.Mutation { var switches []reconcile.Mutation for _, mutation := range reconcile.FlattenConfig("", config) { - if mutation.Value == true && (mutation.Path == "enable" || strings.HasSuffix(mutation.Path, ".enable")) { + parts := nixdata.SplitConfigPath(mutation.Path) + if mutation.Value == true && len(parts) != 0 && parts[len(parts)-1] == "enable" { switches = append(switches, reconcile.Mutation{Path: mutation.Path, Value: false}) } } @@ -142,7 +169,10 @@ func setupAddonDisableSwitches(config map[string]any) []reconcile.Mutation { // A CLI assertion also replaces enclosing agent assertions. For example, an // agent's equality assertion for the whole modules attrset must not contradict // an explicit --without that fixes one nested module's enable value. -func replaceSetupAssertion(assertions []reconcile.ConfigAssertion, replacement reconcile.ConfigAssertion) []reconcile.ConfigAssertion { +func replaceSetupAssertion( + assertions []reconcile.ConfigAssertion, + replacement reconcile.ConfigAssertion, +) []reconcile.ConfigAssertion { out := assertions[:0] for _, assertion := range assertions { n := min(len(assertion.Path), len(replacement.Path)) diff --git a/apps/stackpanel-go/cmd/cli/setup_agent_context_test.go b/apps/stackpanel-go/cmd/cli/setup_agent_context_test.go index 7fd47e9f..aa8c4a45 100644 --- a/apps/stackpanel-go/cmd/cli/setup_agent_context_test.go +++ b/apps/stackpanel-go/cmd/cli/setup_agent_context_test.go @@ -38,11 +38,15 @@ printf '%s\n' '[{"name":"apps..tooling.dev.package","type":"package","desc t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) t.Setenv("STACKPANEL_ROOT", "/wrong-caller") request := setupagent.SetupRequest{ - Root: t.TempDir(), InspectionRef: "git+file:///framework?rev=pinned&dir=${literal}", - FlakeRef: "git+file:///framework?rev=pinned&dir=${literal}", Template: "minimal", Mode: "new", - Context: `{"templateFiles":{".stack/config.nix":"original template"},"addons":[],"futureField":{"keep":true}}`, - Answers: []setupagent.Answer{{ID: "language", Values: []string{"Bun"}}}, - Resuming: true, PreviousError: "apps.web.dev does not exist", + Root: t.TempDir(), + InspectionRef: "git+file:///framework?rev=pinned&dir=${literal}", + FlakeRef: "git+file:///framework?rev=pinned&dir=${literal}", + Template: "minimal", + Mode: "new", + Context: `{"templateFiles":{".stack/config.nix":"original template"},"addons":[],"futureField":{"keep":true}}`, + Answers: []setupagent.Answer{{ID: "language", Values: []string{"Bun"}}}, + Resuming: true, + PreviousError: "apps.web.dev does not exist", } before := request if err := ensureSetupOptionContext(context.Background(), &request); err != nil { @@ -57,7 +61,11 @@ printf '%s\n' '[{"name":"apps..tooling.dev.package","type":"package","desc } } var schema setupOptionSchema - if err := json.Unmarshal(brief["optionSchema"], &schema); err != nil || schema.FlakeRef != request.InspectionRef || len(schema.Options) != 1 { + if err := json.Unmarshal( + brief["optionSchema"], + &schema, + ); err != nil || schema.FlakeRef != request.InspectionRef || + len(schema.Options) != 1 { t.Fatalf("missing pinned schema: %+v %v", schema, err) } before.Context = request.Context @@ -87,14 +95,23 @@ printf '%s\n' '[{"name":"apps..tooling.dev.package","type":"package","desc func TestInstalledSetupSchemaRepair(t *testing.T) { ref := os.Getenv("STACKPANEL_TEST_FRAMEWORK") if os.Getenv("STACKPANEL_TEST_INSTALLED_AGENTS") != "1" || ref == "" { - t.Skip("set STACKPANEL_TEST_INSTALLED_AGENTS=1 and STACKPANEL_TEST_FRAMEWORK for real repair test") + t.Skip( + "set STACKPANEL_TEST_INSTALLED_AGENTS=1 and STACKPANEL_TEST_FRAMEWORK for real repair test", + ) } binary, err := exec.LookPath("codex") if err != nil { t.Fatal(err) } root := t.TempDir() - request := setupagent.SetupRequest{Root: root, InspectionRef: ref, FlakeRef: ref, Context: `{}`, Mode: "existing", Resuming: true} + request := setupagent.SetupRequest{ + Root: root, + InspectionRef: ref, + FlakeRef: ref, + Context: `{}`, + Mode: "existing", + Resuming: true, + } if err := ensureSetupOptionContext(context.Background(), &request); err != nil { t.Fatal(err) } @@ -112,10 +129,12 @@ func TestInstalledSetupSchemaRepair(t *testing.T) { inputs.stackpanel.url = %s; outputs = { self, stackpanel }: let pkgs = import stackpanel.inputs.nixpkgs { system = "x86_64-linux"; }; - evaluated = pkgs.lib.evalModules { modules = [ + lib = pkgs.lib // { stackpanel = stackpanel.lib; }; + evaluated = lib.evalModules { specialArgs = { + inherit pkgs lib self; inputs = { inherit stackpanel self; }; localFlake = stackpanel; isGlobalEval = false; + }; modules = [ (stackpanel.outPath + "/nix/stackpanel") - { _module.args = { inherit pkgs; inputs = {}; }; - stackpanel = import ./.stack/config.nix { inherit pkgs; }; } + { stackpanel = import ./.stack/config.nix { inherit pkgs lib; }; } ]; }; app = evaluated.config.stackpanel.apps.web; in { repaired = app.path == "." && app.type == "bun" && ( @@ -138,31 +157,77 @@ func TestInstalledSetupSchemaRepair(t *testing.T) { run("git", "init") run("git", "add", "flake.nix", ".stack/config.nix") run("nix", "flake", "lock") - broken := exec.Command("nix", "eval", "--json", "--no-update-lock-file", "--no-write-lock-file", ".#repaired") + broken := exec.Command( + "nix", + "eval", + "--json", + "--no-update-lock-file", + "--no-write-lock-file", + ".#repaired", + ) broken.Dir, broken.Env = root, freshSetupEnvironment(os.Environ()) - if output, err := broken.CombinedOutput(); err == nil || !strings.Contains(string(output), "stackpanel.apps.web.dev") { - t.Fatalf("fixture must reproduce the unknown-option error before invoking Codex: %s %v", output, err) + if output, err := broken.CombinedOutput(); err == nil || + !strings.Contains(string(output), "stackpanel.apps.web.dev") { + t.Fatalf( + "fixture must reproduce the unknown-option error before invoking Codex: %s %v", + output, + err, + ) } exists := true - plan := &setupagent.Plan{Summary: "Repair only .stack/config.nix using the supplied option schema. Keep web at path . with type bun and development command bun --hot src/server.ts. Do not edit flake.nix or create other files.", Expectations: reconcile.Expectations{Version: 1, Config: []reconcile.ConfigAssertion{{Path: []string{"apps", "web"}, Exists: &exists}}}} - _, err = setupagent.Run(context.Background(), setupagent.Agent{ID: "codex", Path: binary}, setupagent.RunRequest{ - Dir: root, Prompt: setupagent.BuildPrompt(request, setupagent.Repair, plan, "The option stackpanel.apps.web.dev does not exist."), - Timeout: 2 * time.Minute, Env: freshSetupEnvironment(os.Environ()), - }) + plan := &setupagent.Plan{ + Summary: "Repair only .stack/config.nix using the supplied option schema. Keep web at path . with type bun and development command bun --hot src/server.ts. Do not edit flake.nix or create other files.", + Expectations: reconcile.Expectations{ + Version: 1, + Config: []reconcile.ConfigAssertion{ + {Path: []string{"apps", "web"}, Exists: &exists}, + }, + }, + } + _, err = setupagent.Run( + context.Background(), + setupagent.Agent{ID: "codex", Path: binary}, + setupagent.RunRequest{ + Dir: root, + Prompt: setupagent.BuildPrompt( + request, + setupagent.Repair, + plan, + "The option stackpanel.apps.web.dev does not exist.", + ), + Timeout: 2 * time.Minute, + Env: freshSetupEnvironment(os.Environ()), + }, + ) if err != nil { t.Fatal(err) } - if got, err := os.ReadFile(filepath.Join(root, "flake.nix")); err != nil || string(got) != flake { + if got, err := os.ReadFile( + filepath.Join(root, "flake.nix"), + ); err != nil || + string(got) != flake { t.Fatal("agent changed the verifier flake") } // Keep stdout separate from Nix's dirty-tree warnings. - command := exec.Command("nix", "eval", "--json", "--no-update-lock-file", "--no-write-lock-file", ".#repaired") + command := exec.Command( + "nix", + "eval", + "--json", + "--no-update-lock-file", + "--no-write-lock-file", + ".#repaired", + ) command.Dir, command.Env = root, freshSetupEnvironment(os.Environ()) var stderr strings.Builder command.Stderr = &stderr output, err := command.Output() if err != nil || strings.TrimSpace(string(output)) != "true" { - t.Fatalf("repaired config did not evaluate to the accepted command: %s %v\n%s", output, err, stderr.String()) + t.Fatalf( + "repaired config did not evaluate to the accepted command: %s %v\n%s", + output, + err, + stderr.String(), + ) } } @@ -171,7 +236,11 @@ func TestSetupOptionContextFromPinnedFramework(t *testing.T) { if ref == "" { t.Skip("set STACKPANEL_TEST_FRAMEWORK to test real pure Nix introspection") } - request := setupagent.SetupRequest{Root: t.TempDir(), InspectionRef: ref, Context: `{}`} + request := setupagent.SetupRequest{ + Root: t.TempDir(), + InspectionRef: ref, + Context: `{}`, + } if err := ensureSetupOptionContext(context.Background(), &request); err != nil { t.Fatal(err) } @@ -193,9 +262,19 @@ func TestSetupOptionContextFromPinnedFramework(t *testing.T) { if options["apps..dev.command"] != "" { t.Error("invented app command option") } - prompt := setupagent.BuildPrompt(request, setupagent.Repair, nil, "apps.web.dev does not exist") + prompt := setupagent.BuildPrompt( + request, + setupagent.Repair, + nil, + "apps.web.dev does not exist", + ) if !strings.Contains(prompt, ".tooling.dev.package") { t.Error("repair did not receive schema") } - t.Logf("supplied %d options (%d bytes) from %s", len(options), len(request.Context), ref) + t.Logf( + "supplied %d options (%d bytes) from %s", + len(options), + len(request.Context), + ref, + ) } diff --git a/apps/stackpanel-go/cmd/cli/setup_agent_runtime.go b/apps/stackpanel-go/cmd/cli/setup_agent_runtime.go index 8148b5dc..2f0ca7d1 100644 --- a/apps/stackpanel-go/cmd/cli/setup_agent_runtime.go +++ b/apps/stackpanel-go/cmd/cli/setup_agent_runtime.go @@ -21,11 +21,20 @@ import ( "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" "github.com/darkmatter/stackpanel/stackpanel-go/internal/setupsession" "github.com/darkmatter/stackpanel/stackpanel-go/internal/tui" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/services" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" ) -func runSetupRuntime(ctx context.Context, root, executable string, selected []string, opts setupFlags, ui *tui.SetupUI, debug io.Writer, state *setupManifest) (string, error) { +func runSetupRuntime( + ctx context.Context, + root, executable string, + selected []string, + opts setupFlags, + ui *tui.SetupUI, + debug io.Writer, + state *setupManifest, +) (string, error) { base := opts.studioURL if base == "" { base = setupsession.DefaultStudioURL @@ -49,7 +58,14 @@ func runSetupRuntime(ctx context.Context, root, executable string, selected []st port = config.DefaultConfig().Port } endpoint := "http://" + net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) - health, err := ensureSetupAgent(ctx, root, executable, endpoint, origin, port) + // Setup intentionally leaves its agent running after the browser handoff. + startCtx, cancelStart := context.WithTimeoutCause( + ctx, + 2*time.Minute, + fmt.Errorf("local agent did not start; inspect %s", setupAgentLogPath()), + ) + health, _, err := ensureLocalAgent(startCtx, root, executable, endpoint, origin, port) + cancelStart() if err != nil { return "", err } @@ -57,7 +73,18 @@ func runSetupRuntime(ctx context.Context, root, executable string, selected []st if err := startSetupServices(ctx, root, executable, selected, debug); err != nil { return "", err } - session, err := resumeSetupStudioSession(state, setupsession.Session{Root: root, ProjectID: project.ID, AgentID: health.AgentID, Endpoint: endpoint, Origin: origin, RequireBrowser: !opts.noBrowser, Services: selected}) + session, err := resumeSetupStudioSession( + state, + setupsession.Session{ + Root: root, + ProjectID: project.ID, + AgentID: health.AgentID, + Endpoint: endpoint, + Origin: origin, + RequireBrowser: !opts.noBrowser, + Services: selected, + }, + ) if err != nil { return "", err } @@ -71,7 +98,11 @@ func runSetupRuntime(ctx context.Context, root, executable string, selected []st ui.Progress("Could not launch a browser. Open this link manually:\n" + link) } if err := waitForSetupStudio(ctx, session.ID); err != nil { - return "", fmt.Errorf("%w; open Studio, pair, and retry setup (agent log: %s)", err, setupAgentLogPath()) + return "", fmt.Errorf( + "%w; open Studio, pair, and retry setup (agent log: %s)", + err, + setupAgentLogPath(), + ) } } ui.Progress("Verifying runtime with stack doctor…") @@ -81,7 +112,13 @@ func runSetupRuntime(ctx context.Context, root, executable string, selected []st if err != nil { if report != nil { var rendered bytes.Buffer - report.Render(&rendered, reconcile.RenderOptions{Title: "stack doctor · runtime verification", Verbose: true}) + report.Render( + &rendered, + reconcile.RenderOptions{ + Title: "stack doctor · runtime verification", + Verbose: true, + }, + ) return "", fmt.Errorf("%w\n%s", err, rendered.String()) } return "", err @@ -103,11 +140,17 @@ func runSetupRuntime(ctx context.Context, root, executable string, selected []st // Reuse a live browser handoff after interruption, but never stale readiness // evidence or a receipt bound to a different agent, origin, or runtime scope. -func resumeSetupStudioSession(state *setupManifest, want setupsession.Session) (setupsession.Session, error) { +func resumeSetupStudioSession( + state *setupManifest, + want setupsession.Session, +) (setupsession.Session, error) { if state.StudioSession != "" { - if old, err := setupsession.Load(state.StudioSession); err == nil && old.Root == want.Root && + if old, err := setupsession.Load( + state.StudioSession, + ); err == nil && old.Root == want.Root && old.ProjectID == want.ProjectID && old.AgentID == want.AgentID && old.Endpoint == want.Endpoint && - old.Origin == want.Origin && old.RequireBrowser == want.RequireBrowser && slices.Equal(old.Services, want.Services) { + old.Origin == want.Origin && old.RequireBrowser == want.RequireBrowser && + slices.Equal(old.Services, want.Services) { return old, nil } } @@ -123,78 +166,155 @@ func setupAgentLogPath() string { return filepath.Join(filepath.Dir(userconfig.GetConfigPath()), "agent.log") } -func ensureSetupAgent(ctx context.Context, root, executable, endpoint, origin string, port int) (setupsession.Health, error) { +// Only created after starting our own session leader; never derive a PID or +// process group from a reused agent's health endpoint or listening port. +type startedLocalAgent struct { + pgid int + done chan struct{} + err error // written by the sole waiter before closing done +} + +func (p *startedLocalAgent) stop() { + if err := syscall.Kill(-p.pgid, syscall.SIGTERM); err == nil { + select { + case <-p.done: + case <-time.After(3 * time.Second): + } + // A wrapper can exit before its descendants, or ignore SIGTERM. + _ = syscall.Kill(-p.pgid, syscall.SIGKILL) + } + <-p.done // reap nix develop before allowing the foreground CLI to exit +} + +func ensureLocalAgent( + ctx context.Context, + root, executable, endpoint, origin string, + port int, +) (setupsession.Health, *startedLocalAgent, error) { client := &http.Client{Timeout: time.Second} - if health, err := setupsession.ReadHealth(client, endpoint); err == nil { + validate := func(health setupsession.Health) error { if filepath.Clean(health.ProjectRoot) != filepath.Clean(root) { - return health, fmt.Errorf("running agent serves %s; use --agent-port for a separate agent or restart it for %s", health.ProjectRoot, root) + return fmt.Errorf( + "running agent serves %s; use --agent-port for a separate agent or restart it for %s", + health.ProjectRoot, + root, + ) } if !health.DevshellReady { - return health, fmt.Errorf("running agent has no devshell environment; restart it from this repository devshell") + return fmt.Errorf( + "running agent has no devshell environment; restart it from this repository devshell", + ) } if health.SetupVersion < 1 { - return health, fmt.Errorf("running agent needs updating; restart it with %s agent --project-root %s", executable, root) + return fmt.Errorf( + "running agent needs updating; restart it with %s agent --project-root %s", + executable, + root, + ) } - return health, nil + return nil + } + if health, err := setupsession.ReadHealth(client, endpoint); err == nil { + return health, nil, validate(health) } // Never start a second process over an occupied endpoint. u, _ := url.Parse(endpoint) if conn, err := net.DialTimeout("tcp", u.Host, time.Second); err == nil { conn.Close() - return setupsession.Health{}, fmt.Errorf("%s is occupied but is not a healthy Stackpanel agent", endpoint) + return setupsession.Health{}, nil, fmt.Errorf( + "%s is occupied but is not a healthy Stackpanel agent", + endpoint, + ) } path := setupAgentLogPath() if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { - return setupsession.Health{}, err + return setupsession.Health{}, nil, err } log, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { - return setupsession.Health{}, err + return setupsession.Health{}, nil, err } defer log.Close() - cmd := services.NewBackgroundProcess("nix", "develop", ".", "--no-update-lock-file", "--no-write-lock-file", "--command", executable, "agent", "--project-root", root, "--port", strconv.Itoa(port), "--host", origin) + flags, err := nixeval.SetupFlakeArgs(root) + if err != nil { + return setupsession.Health{}, nil, err + } + args := append([]string{"develop", "."}, flags...) + args = append( + args, + "--command", + executable, + "agent", + "--project-root", + root, + "--port", + strconv.Itoa(port), + "--host", + origin, + ) + cmd := services.NewBackgroundProcess("nix", args...) cmd.Dir = root cmd.Env = freshSetupEnvironment(os.Environ()) cmd.Stdout, cmd.Stderr = log, log cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} if err := cmd.Start(); err != nil { - return setupsession.Health{}, err + return setupsession.Health{}, nil, err } - done := make(chan error, 1) - go func() { done <- cmd.Wait() }() + process := &startedLocalAgent{pgid: cmd.Process.Pid, done: make(chan struct{})} + go func() { + process.err = cmd.Wait() + close(process.done) + }() ready := false defer func() { if !ready { - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + process.stop() } }() ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() - timeout := time.NewTimer(2 * time.Minute) - defer timeout.Stop() for { select { case <-ctx.Done(): - return setupsession.Health{}, ctx.Err() - case err := <-done: - return setupsession.Health{}, fmt.Errorf("local agent exited (%v); inspect %s", err, path) - case <-timeout.C: - return setupsession.Health{}, fmt.Errorf("local agent did not start; inspect %s", path) + return setupsession.Health{}, nil, context.Cause(ctx) + case <-process.done: + return setupsession.Health{}, nil, fmt.Errorf( + "local agent exited (%v); inspect %s", + process.err, + path, + ) case <-ticker.C: - if health, err := setupsession.ReadHealth(client, endpoint); err == nil && health.SetupVersion >= 1 && health.DevshellReady && filepath.Clean(health.ProjectRoot) == filepath.Clean(root) { + if health, err := setupsession.ReadHealth(client, endpoint); err == nil { + if err := validate(health); err != nil { + return health, nil, err + } ready = true - return health, nil + return health, process, nil } } } } -func startSetupServices(ctx context.Context, root, executable string, selected []string, out io.Writer) error { +func startSetupServices( + ctx context.Context, + root, executable string, + selected []string, + out io.Writer, +) error { for _, name := range selected { if services.Get(name) == nil { return fmt.Errorf("unsupported local service %q", name) } - if err := runSetupShell(ctx, root, out, executable, "services", "start", name, "--no-tui"); err != nil { + if err := runSetupShell( + ctx, + root, + out, + executable, + "services", + "start", + name, + "--no-tui", + ); err != nil { return err } } @@ -210,6 +330,7 @@ func openSetupStudio(ctx context.Context, link string) error { defer cancel() return exec.CommandContext(runCtx, launcher, link).Run() } + func waitForSetupStudio(ctx context.Context, id string) error { ticker := time.NewTicker(time.Second) defer ticker.Stop() @@ -218,7 +339,8 @@ func waitForSetupStudio(ctx context.Context, id string) error { if err != nil { return err } - if !s.ReadyAt.IsZero() && s.Connection != "" && time.Since(s.ConnectedAt) < 15*time.Second { + if !s.ReadyAt.IsZero() && s.Connection != "" && + time.Since(s.ConnectedAt) < 15*time.Second { return nil } select { diff --git a/apps/stackpanel-go/cmd/cli/setup_agent_state.go b/apps/stackpanel-go/cmd/cli/setup_agent_state.go index f4d806d4..2ee87861 100644 --- a/apps/stackpanel-go/cmd/cli/setup_agent_state.go +++ b/apps/stackpanel-go/cmd/cli/setup_agent_state.go @@ -165,7 +165,7 @@ func (s *setupManifest) restoreGit(g *setupGitGuard) { func isEditableStackpanelConfig(rel string) bool { switch filepath.ToSlash(filepath.Clean(rel)) { - case ".stack/config.nix", ".stack/data.nix", ".stack/reconcile.json", ".stack/addons.json": + case ".stack/config.nix", ".stack/data.nix", ".stack/reconcile.json": return true default: return false diff --git a/apps/stackpanel-go/cmd/cli/setup_agent_state_test.go b/apps/stackpanel-go/cmd/cli/setup_agent_state_test.go index 85f59f40..8a477d31 100644 --- a/apps/stackpanel-go/cmd/cli/setup_agent_state_test.go +++ b/apps/stackpanel-go/cmd/cli/setup_agent_state_test.go @@ -354,6 +354,7 @@ func TestAllowStackpanelConfigUnprotectsPreexistingScaffoldConfig(t *testing.T) writeSetupGitFile(t, root, ".stack/config.nix", "# starter template\n{\n ide.vscode.enable = true;\n}\n") writeSetupGitFile(t, root, ".stack/data.nix", "{}\n") writeSetupGitFile(t, root, ".stack/reconcile.json", "{\"version\":1}\n") + writeSetupGitFile(t, root, ".stack/addons.json", "{\"addons\":{}}\n") g, err := captureSetupGit(ctx, root) if err != nil { @@ -366,8 +367,10 @@ func TestAllowStackpanelConfigUnprotectsPreexistingScaffoldConfig(t *testing.T) t.Fatalf("expected %s to be editable during agent setup, but it remained protected", p) } } - if _, protected := g.protected["unstaged.txt"]; !protected { - t.Fatal("unrelated user file unstaged.txt must remain protected") + for _, p := range []string{"unstaged.txt", ".stack/addons.json"} { + if _, protected := g.protected[p]; !protected { + t.Fatalf("unrelated user file %s must remain protected", p) + } } // Agent edits .stack/config.nix and AddNixInputs exposes it to Git-backed Nix eval. diff --git a/apps/stackpanel-go/cmd/cli/setup_agent_test.go b/apps/stackpanel-go/cmd/cli/setup_agent_test.go index acdf85c7..50cc6b58 100644 --- a/apps/stackpanel-go/cmd/cli/setup_agent_test.go +++ b/apps/stackpanel-go/cmd/cli/setup_agent_test.go @@ -19,10 +19,20 @@ import ( func TestFreshSetupEnvironment(t *testing.T) { env := freshSetupEnvironment([]string{ - "PATH=/test/bin", "HOME=/test/home", "NIX_CONFIG=keep", "PROVIDER_TOKEN=test", - "STACKPANEL_ROOT=/wrong", "STACKPANEL_CONFIG_JSON=/stale", "STACKPANEL_STATE_DIR=/wrong", - "__STACKPANEL_HOOK_RAN=1", "__STACKPANEL_CLEAN_ENV=1", "DIRENV_DIR=/wrong", "IN_NIX_SHELL=impure", - "STACKPANEL_USER_CONFIG=/custom/config.json", "PWD=/wrong", "OLDPWD=/wrong", + "PATH=/test/bin", + "HOME=/test/home", + "NIX_CONFIG=keep", + "PROVIDER_TOKEN=test", + "STACKPANEL_ROOT=/wrong", + "STACKPANEL_CONFIG_JSON=/stale", + "STACKPANEL_STATE_DIR=/wrong", + "__STACKPANEL_HOOK_RAN=1", + "__STACKPANEL_CLEAN_ENV=1", + "DIRENV_DIR=/wrong", + "IN_NIX_SHELL=impure", + "STACKPANEL_USER_CONFIG=/custom/config.json", + "PWD=/wrong", + "OLDPWD=/wrong", }) got := strings.Join(env, "\n") want := "PATH=/test/bin\nHOME=/test/home\nNIX_CONFIG=keep\nPROVIDER_TOKEN=test\nSTACKPANEL_USER_CONFIG=/custom/config.json" @@ -55,7 +65,10 @@ func TestRetainSetupChecksPreventsRemovalDuringRepair(t *testing.T) { }} retainSetupChecks(&expected, report) retainSetupChecks(&expected, report) - if got := strings.Join(expected.RequiredChecks, ","); got != "declared,failed,skipped" { + if got := strings.Join( + expected.RequiredChecks, + ",", + ); got != "declared,failed,skipped" { t.Fatalf("repair contract lost checks or added duplicates: %s", got) } } @@ -67,7 +80,8 @@ func TestPrepareSetupRequestRejectsDirtyLocalFramework(t *testing.T) { if [ "$1" = flake ]; then printf '%s\n' '{"url":"git+file:///local/framework","path":"/nix/store/fixture-source","locked":{}}' else - case "$3" in + test "$3" = --no-write-lock-file || exit 1 + case "$4" in /nix/store/fixture-source#lib.initTemplates.default) printf '%s\n' '{"flake.nix":"template"}' ;; /nix/store/fixture-source#lib.initAddons) printf '%s\n' '{}' ;; *) echo "unexpected inspection reference" >&2; exit 1 ;; @@ -78,9 +92,17 @@ fi t.Fatal(err) } t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) - _, err := prepareSetupRequest(context.Background(), root, setupFlags{flake: "git+file:///local/framework"}) - if err == nil || !strings.Contains(err.Error(), "local framework checkout has uncommitted changes") { - t.Fatalf("dirty local input must not reach the agent as a directory reference: %v", err) + _, err := prepareSetupRequest( + context.Background(), + root, + setupFlags{flake: "git+file:///local/framework"}, + ) + if err == nil || + !strings.Contains(err.Error(), "local framework checkout has uncommitted changes") { + t.Fatalf( + "dirty local input must not reach the agent as a directory reference: %v", + err, + ) } } @@ -90,7 +112,8 @@ func TestPrepareSetupRequestAllowsCommittedLocalFramework(t *testing.T) { if [ "$1" = flake ]; then printf '%s\n' '{"url":"git+file:///local/framework?rev=committed","locked":{"rev":"committed"}}' else - case "$3" in + test "$3" = --no-write-lock-file || exit 1 + case "$4" in *'#lib.initTemplates.default') printf '%s\n' '{"flake.nix":"template"}' ;; *'#lib.initAddons') printf '%s\n' '{}' ;; *) exit 1 ;; @@ -101,7 +124,11 @@ fi t.Fatal(err) } t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) - request, err := prepareSetupRequest(context.Background(), t.TempDir(), setupFlags{flake: "git+file:///local/framework"}) + request, err := prepareSetupRequest( + context.Background(), + t.TempDir(), + setupFlags{flake: "git+file:///local/framework"}, + ) if err != nil || request.FlakeRef != "git+file:///local/framework?rev=committed" { t.Fatalf("committed local source was not retained: %+v %v", request, err) } @@ -110,7 +137,13 @@ fi func TestRunFreshDoctorIsolatesShellOutputAndPaths(t *testing.T) { root, executable := setupShellFixture(t) var output bytes.Buffer - report, err := runFreshDoctor(context.Background(), root, executable, "/expectations with spaces.json", &output) + report, err := runFreshDoctor( + context.Background(), + root, + executable, + "/expectations with spaces.json", + &output, + ) if err != nil { t.Fatal(err) } @@ -142,7 +175,13 @@ func TestRunFreshDoctorRejectsFalseSuccess(t *testing.T) { t.Fatal(err) } t.Setenv("TEST_DOCTOR_JSON", string(data)) - if _, err := runFreshDoctor(context.Background(), root, executable, "/expectations.json", io.Discard); err == nil { + if _, err := runFreshDoctor( + context.Background(), + root, + executable, + "/expectations.json", + io.Discard, + ); err == nil { t.Fatal("accepted incomplete report from a zero-exit process") } }) @@ -154,7 +193,13 @@ func TestFreshReconciliationRequiresLock(t *testing.T) { if err := os.Remove(filepath.Join(root, "flake.lock")); err != nil { t.Fatal(err) } - if err := runFreshReconciliation(context.Background(), root, executable, io.Discard); err == nil || !strings.Contains(err.Error(), "flake.lock") { + if err := runFreshReconciliation( + context.Background(), + root, + executable, + io.Discard, + ); err == nil || + !strings.Contains(err.Error(), "flake.lock") { t.Fatalf("expected missing-lock error, got %v", err) } } @@ -174,7 +219,17 @@ func TestSetupPrepareRunsPlannedCommandInsideRepository(t *testing.T) { if err := os.MkdirAll(app, 0o755); err != nil { t.Fatal(err) } - step := setupagent.PrepareCommand{ID: "deps", Dir: "apps/web app", Argv: []string{"sh", "-c", `pwd > lock; printf '%s' "$1" >> lock`, "deps", "a $b 'c'"}} + step := setupagent.PrepareCommand{ + ID: "deps", + Dir: "apps/web app", + Argv: []string{ + "sh", + "-c", + `pwd > lock; printf '%s' "$1" >> lock`, + "deps", + "a $b 'c'", + }, + } if err := runSetupPrepare(context.Background(), root, step, io.Discard); err != nil { t.Fatal(err) } @@ -182,18 +237,34 @@ func TestSetupPrepareRunsPlannedCommandInsideRepository(t *testing.T) { if err != nil { t.Fatal(err) } - if data, _ := os.ReadFile(filepath.Join(app, "lock")); string(data) != resolved+"\na $b 'c'" { + if data, _ := os.ReadFile( + filepath.Join(app, "lock"), + ); string( + data, + ) != resolved+"\na $b 'c'" { t.Fatalf("command did not run unchanged in its directory: %q", data) } step.Argv = []string{"sh", "-c", "echo registry unreachable >&2; exit 3"} - if err := runSetupPrepare(context.Background(), root, step, io.Discard); err == nil || !strings.Contains(err.Error(), "registry unreachable") { + if err := runSetupPrepare( + context.Background(), + root, + step, + io.Discard, + ); err == nil || + !strings.Contains(err.Error(), "registry unreachable") { t.Fatalf("repair needs the command's own diagnostic: %v", err) } if err := os.Symlink(t.TempDir(), filepath.Join(root, "outside")); err != nil { t.Fatal(err) } step.Dir, step.Argv = "outside", []string{"sh", "-c", "touch ran"} - if err := runSetupPrepare(context.Background(), root, step, io.Discard); err == nil || !strings.Contains(err.Error(), "escapes repository") { + if err := runSetupPrepare( + context.Background(), + root, + step, + io.Discard, + ); err == nil || + !strings.Contains(err.Error(), "escapes repository") { t.Fatalf("command ran through a symlink out of the repository: %v", err) } } @@ -219,7 +290,11 @@ case "$5" in "$PWD"/*) echo 'output is inside the repository' >&2; exit 1 ;; esa test -z "${STACKPANEL_ROOT:-}" || exit 1 printf '%s\n' "$TEST_LOCK_CONTENT" > "$5" ` - if err := os.WriteFile(filepath.Join(bin, "nix"), []byte(script), 0o755); err != nil { + if err := os.WriteFile( + filepath.Join(bin, "nix"), + []byte(script), + 0o755, + ); err != nil { t.Fatal(err) } t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) @@ -265,7 +340,12 @@ func TestSetupLockWithRealNix(t *testing.T) { // No network or registry needed: exercise the actual daemon and Git-backed // flake machinery with a relative local input. writeSetupGitFile(t, root, "dependency/flake.nix", "{ outputs = _: {}; }\n") - writeSetupGitFile(t, root, "flake.nix", "{ inputs.test.url = \"path:./dependency\"; outputs = _: {}; }\n") + writeSetupGitFile( + t, + root, + "flake.nix", + "{ inputs.test.url = \"path:./dependency\"; outputs = _: {}; }\n", + ) if err := guard.AddNixInputs(ctx); err != nil { t.Fatal(err) } @@ -301,7 +381,11 @@ func TestExperimentalSetupRejectsPartialVerification(t *testing.T) { } { cmd := &cobra.Command{} cmd.SetContext(context.Background()) - if err := runSetupWith(cmd, opts); err == nil || !strings.Contains(err.Error(), "cannot be combined") { + if err := runSetupWith( + cmd, + opts, + ); err == nil || + !strings.Contains(err.Error(), "cannot be combined") { t.Fatalf("unexpected error: %v", err) } } @@ -312,7 +396,10 @@ func TestExperimentalSetupDryRunDoesNotStartAgent(t *testing.T) { cmd.SetContext(context.Background()) // Ordinary setup rejects this combination before evaluating or writing. // The agent branch would instead try to discover this nonexistent agent. - err := runSetupWith(cmd, setupFlags{experimentalAgent: "not-an-agent", tmp: true, dryRun: true}) + err := runSetupWith( + cmd, + setupFlags{experimentalAgent: "not-an-agent", tmp: true, dryRun: true}, + ) if err == nil || !strings.Contains(err.Error(), "--tmp cannot be combined") { t.Fatalf("dry-run did not follow the read-only path: %v", err) } @@ -322,15 +409,21 @@ func TestSetupLogTailBounded(t *testing.T) { var tail setupLogTail _, _ = tail.Write(bytes.Repeat([]byte("a"), 64*1024)) _, _ = tail.Write([]byte("last diagnostic")) - if len(tail.data) != 32*1024 || !bytes.HasSuffix(tail.data, []byte("last diagnostic")) { + if len(tail.data) != 32*1024 || + !bytes.HasSuffix(tail.data, []byte("last diagnostic")) { t.Fatalf("invalid diagnostic tail: %d bytes", len(tail.data)) } } func completeSetupReport() reconcile.Report { - r := reconcile.Report{Reconcilers: []string{"codegen", "files", "fileops", "checks", "verification"}} + r := reconcile.Report{ + Reconcilers: []string{"codegen", "files", "fileops", "checks", "verification"}, + } for _, id := range r.Reconcilers { - r.Coverage = append(r.Coverage, reconcile.Coverage{Reconciler: id, Status: "complete"}) + r.Coverage = append( + r.Coverage, + reconcile.Coverage{Reconciler: id, Status: "complete"}, + ) } return r } @@ -342,7 +435,11 @@ func setupShellFixture(t *testing.T) (string, string) { if err := os.Mkdir(root, 0o755); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(root, "flake.lock"), []byte("{}"), 0o644); err != nil { + if err := os.WriteFile( + filepath.Join(root, "flake.lock"), + []byte("{}"), + 0o644, + ); err != nil { t.Fatal(err) } write := func(path, contents string) { diff --git a/apps/stackpanel-go/cmd/cli/template_configs/default.nix b/apps/stackpanel-go/cmd/cli/template_configs/default.nix index ace2fe4f..431cb7fe 100644 --- a/apps/stackpanel-go/cmd/cli/template_configs/default.nix +++ b/apps/stackpanel-go/cmd/cli/template_configs/default.nix @@ -283,10 +283,7 @@ # ---------------------------------------------------------------------------- # Git hooks configuration fragment (consumed by git-hooks.nix). git-hooks = { - pre-commit = { - enable = true; - stages = [ "pre-commit" ]; - }; + enable = true; }; # ---------------------------------------------------------------------------- @@ -410,15 +407,29 @@ # Name of your project. May be used for naming things and diplay purposes. name = "acme-storefront"; + # ---------------------------------------------------------------------------- + # Prelude (shell DX — MOTD, menu/x, docs) + # ---------------------------------------------------------------------------- + # Enabled by default via stackpanel.prelude.enable. Arrives transitively; + # no prelude flake input needed. enable = false skips packages + shell banner. + # Tagline/subtitle belong here (framework defaults are "${name} devshell"): + # prelude = { + # enable = true; + # # tagline = "My product"; + # # subtitle = "ready to build"; + # # theme = "minted"; + # # menu.enable = true; + # # docs.enable = true; + # # prompt.enable = false; # keep off until Starship theme bridge + # # settings = { }; # passthrough into prelude.* + # }; + # ---------------------------------------------------------------------------- # Panels # ---------------------------------------------------------------------------- - # UI panels for core Stackpanel modules. Panels are UI components that display - # information about a module's state, configuration, or managed resources. - # Unlike extension panels, these belong to built-in modules like Go, Caddy, - # Healthchecks, etc. Example: stackpanel.panels.go-status = { module = "go"; - # title = "Go Environment"; type = "PANEL_TYPE_STATUS"; order = 10; fields = [ - # { name = "metrics"; type = "FIELD_TYPE_STRING"; value = "..."; } ]; }; + # A panel belongs to its module and uses the same renderer whether the module + # is bundled, project-local, or a flake input. Example: + # panels.go-status = { module = "go"; title = "Go"; type = "PANEL_TYPE_STATUS"; }; panels = { }; # ---------------------------------------------------------------------------- @@ -705,13 +716,6 @@ ]; enabled = [ "postgres" ]; }; - languages = { - available = [ - "go" - "javascript" - ]; - enabled = [ "go" ]; - }; }; # Name of the state file written to the state directory. diff --git a/apps/stackpanel-go/cmd/cli/template_configs/minimal.nix b/apps/stackpanel-go/cmd/cli/template_configs/minimal.nix index 8cd0aa73..eb9c13ed 100644 --- a/apps/stackpanel-go/cmd/cli/template_configs/minimal.nix +++ b/apps/stackpanel-go/cmd/cli/template_configs/minimal.nix @@ -147,10 +147,7 @@ }; git-hooks = { - pre-commit = { - enable = true; - stages = [ "pre-commit" ]; - }; + enable = true; }; gitignore = { @@ -366,13 +363,6 @@ ]; enabled = [ "postgres" ]; }; - languages = { - available = [ - "go" - "javascript" - ]; - enabled = [ "go" ]; - }; }; file = "stackpanel-dev.json"; }; diff --git a/apps/stackpanel-go/go.mod b/apps/stackpanel-go/go.mod index 8b9351dd..c757cd22 100644 --- a/apps/stackpanel-go/go.mod +++ b/apps/stackpanel-go/go.mod @@ -21,12 +21,15 @@ require ( github.com/muesli/termenv v0.16.0 github.com/pelletier/go-toml/v2 v2.2.4 github.com/rs/zerolog v1.34.0 + github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 github.com/sky-valley/pi v0.85.21 github.com/spf13/cobra v1.9.1 github.com/spf13/pflag v1.0.7 github.com/stretchr/testify v1.11.1 github.com/tree-sitter/go-tree-sitter v0.25.0 github.com/yuin/goldmark v1.7.13 + golang.org/x/sys v0.43.0 + golang.org/x/text v0.37.0 google.golang.org/protobuf v1.36.9 gopkg.in/yaml.v3 v3.0.1 mvdan.cc/gofumpt v0.9.2 @@ -183,7 +186,6 @@ require ( github.com/ryancurrah/gomodguard v1.3.5 // indirect github.com/ryanrolds/sqlclosecheck v0.5.1 // indirect github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect - github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 // indirect github.com/sashamelentyev/interfacebloat v1.1.0 // indirect github.com/sashamelentyev/usestdlibvars v1.28.0 // indirect github.com/securego/gosec/v2 v2.22.2 // indirect @@ -228,9 +230,7 @@ require ( golang.org/x/mod v0.35.0 // indirect golang.org/x/net v0.53.0 // indirect golang.org/x/sync v0.20.0 // indirect - golang.org/x/sys v0.43.0 // indirect golang.org/x/term v0.42.0 // indirect - golang.org/x/text v0.37.0 // indirect golang.org/x/tools v0.44.0 // indirect golang.org/x/tools/go/expect v0.1.1-deprecated // indirect golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated // indirect diff --git a/apps/stackpanel-go/internal/agent/README.md b/apps/stackpanel-go/internal/agent/README.md index 5557cc54..0afac54c 100644 --- a/apps/stackpanel-go/internal/agent/README.md +++ b/apps/stackpanel-go/internal/agent/README.md @@ -138,7 +138,7 @@ This is the HTTP layer. Files are grouped by domain below. |------|---------| | `cors_auth.go` | `withCORS()`, `withLogging()`, `requireAuth()` middleware. Origin allow-list logic, token extraction from `Authorization` header. | | `jwt.go` | `JWTManager` — generates and validates agent JWT tokens. Tokens are created during pairing and last 30 days. | -| `pair.go` | `GET /pair` — serves the browser pairing page. The page receives a one-time token via `postMessage` so the web UI can authenticate future requests. | +| `pair.go`, `pair_return.go` | `POST /pair` — Studio submits a form into a fresh popup. The agent checks the browser's `Origin` and displays it for approval. Studio accepts `postMessage` only from that popup at the selected agent origin and with the current nonce. A loopback popup without an opener returns a short-lived, one-use code; Studio redeems it at `POST /pair/redeem` using a private verifier from that tab. Neither the JWT nor the verifier is placed in a URL. CLI launch links carry routing metadata, not credentials. | ### Nix Data (HTTP Handlers) @@ -235,7 +235,7 @@ Three backends, dispatched based on the project's `variables.backend` setting. |------|---------| | `api_handlers.go` | `handleValidateToken` and small one-off REST handlers. | | `helpers.go` | `writeJSON()`, `writeAPI()`, `writeAPIError()`, `readJSON()`, random string generation, YAML helpers. | -| `modules.go` | Module types (`Module`, `ModuleMeta`, etc.), module config file I/O, and REST handlers for `/api/modules`. | +| `connect_v1_modules.go`, `modules.go` | Project-scoped ModuleService CRUD, attributed outputs, and read-only enable previews. Writes patch the project's Nix config directly. | --- @@ -248,8 +248,11 @@ withCORS → requireAuth → requireProject → handler ``` - **Public** (no auth): `/health`, `/status`, `/pair`, `/api/project/current`, `/api/project/list` -- **Auth only** (no project needed): `/api/auth/validate`, `/api/security/*`, `/api/nixpkgs/*`, `/api/registry` +- **Auth only** (no project needed): `/api/auth/validate`, `/api/security/*`, `/api/nixpkgs/*` - **Auth + project**: everything else (`/api/nix/*`, `/api/secrets/*`, `/api/files/*`, etc.) +- Registry browsing and installation use the authenticated, project-scoped Connect v1 `ModuleService`. Install locks the selected release and leaves it disabled for preview, even when its upstream default is enabled. Unlink a local development override with `stack module unlink ` before uninstalling. +- `PreviewModuleEnable` and `EnableModule` accept the same optional adoption answers (offer ID, revision, and typed value). Preview never writes. Enable validates against fresh declarations and saves decisions in the project reconcile ledger only after the declared config edits evaluate successfully. Omitted answers remain pending. +- For a custom app panel, `UpdateModuleConfig` takes its app and module namespace from the host's verified UI grant. Only that panel's projected settings are writable; the request cannot choose an app or an absolute config path. --- diff --git a/apps/stackpanel-go/internal/agent/project/project.go b/apps/stackpanel-go/internal/agent/project/project.go index d290e8ec..6a405436 100644 --- a/apps/stackpanel-go/internal/agent/project/project.go +++ b/apps/stackpanel-go/internal/agent/project/project.go @@ -1,7 +1,7 @@ // Package project manages Stackpanel project discovery, validation, and lifecycle. // A valid project requires a .git directory and either .stack/config.nix or a // flake.nix that references stackpanel. Projects are persisted in the user config -// (~/.config/stackpanel/stackpanel.yaml) so they survive agent restarts. +// (~/.config/stackpanel/config.yaml) so they survive agent restarts. // // Validation uses a multi-strategy approach: it first tries Nix evaluation // (most accurate), then flake metadata inspection, and finally falls back to @@ -18,11 +18,12 @@ import ( "os" "os/exec" "path/filepath" - "runtime" + "regexp" "strings" "sync" "time" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" "github.com/rs/zerolog/log" ) @@ -114,7 +115,7 @@ func (m *Manager) UserConfigManager() *userconfig.Manager { // NewManager creates a new project manager. // The dataDir parameter is kept for backward compatibility but is no longer used. -// Projects are now stored in ~/.config/stackpanel/stackpanel.yaml +// Projects are now stored in ~/.config/stackpanel/config.yaml func NewManager(dataDir string) (*Manager, error) { ucm, err := userconfig.NewManager() if err != nil { @@ -527,8 +528,11 @@ func checkFlakeForStackpanelOutputWithTimeout( ) (bool, []string) { var warnings []string - // Detect current system - system := detectNixSystem() + system := nixeval.CurrentSystem() + flags, err := nixeval.ProjectFlakeArgs(projectDir) + if err != nil { + return false, []string{err.Error()} + } // Paths to check for stackpanelConfig (in order of likelihood) // We check .name attribute to verify it's a real config, not just an empty attrset @@ -553,7 +557,8 @@ func checkFlakeForStackpanelOutputWithTimeout( } // Try to evaluate this path - cmd := exec.CommandContext(ctx, "nix", "eval", "--json", path, "--no-eval-cache") + args := append([]string{"eval", "--json", path, "--no-eval-cache"}, flags...) + cmd := exec.CommandContext(ctx, "nix", args...) cmd.Dir = projectDir var stdout, stderr bytes.Buffer @@ -585,74 +590,6 @@ func checkFlakeForStackpanelOutputWithTimeout( return false, warnings } -// detectNixSystem returns the Nix system identifier (e.g., "aarch64-darwin"). -// Tries `nix eval builtins.currentSystem` first for accuracy, then falls back -// to Go's runtime.GOARCH/GOOS mapping. The fallback is needed when the agent -// runs outside a Nix environment (e.g., during initial project discovery). -func detectNixSystem() string { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - cmd := exec.CommandContext( - ctx, - "nix", - "eval", - "--impure", - "--raw", - "--expr", - "builtins.currentSystem", - ) - var stdout bytes.Buffer - cmd.Stdout = &stdout - - if err := cmd.Run(); err == nil { - system := strings.TrimSpace(stdout.String()) - if system != "" { - return system - } - } - - // Fall back to runtime detection - arch := "x86_64" - os := "linux" - - // Detect architecture - switch a := strings.ToLower(getArch()); a { - case "arm64", "aarch64": - arch = "aarch64" - case "amd64", "x86_64": - arch = "x86_64" - } - - // Detect OS - switch o := strings.ToLower(getOS()); o { - case "darwin", "macos": - os = "darwin" - case "linux": - os = "linux" - } - - return fmt.Sprintf("%s-%s", arch, os) -} - -// getArch returns the current architecture from Go runtime -func getArch() string { - // Use build-time constant - switch arch := runtime.GOARCH; arch { - case "arm64": - return "aarch64" - case "amd64": - return "x86_64" - default: - return arch - } -} - -// getOS returns the current OS from Go runtime -func getOS() string { - return runtime.GOOS -} - // flakeMetadata represents the relevant parts of `nix flake metadata --json` output type flakeMetadata struct { Locks struct { @@ -678,7 +615,12 @@ func checkFlakeMetadataForStackpanelWithTimeout( ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() - cmd := exec.CommandContext(ctx, "nix", "flake", "metadata", "--json", ".") + flags, err := nixeval.ProjectFlakeArgs(projectDir) + if err != nil { + return false, []string{err.Error()} + } + args := append([]string{"flake", "metadata", "--json", "."}, flags...) + cmd := exec.CommandContext(ctx, "nix", args...) cmd.Dir = projectDir var stdout, stderr bytes.Buffer @@ -745,6 +687,10 @@ func checkFlakeMetadataForStackpanelWithTimeout( return false, warnings } +// A flake can reference the framework by input name, URL or exported option. +// A similarly named dot-directory is not evidence of a Stackpanel flake. +var stackpanelFlakeRef = regexp.MustCompile(`(?i)(^|[^[:alnum:]_.-]|[[:alnum:]_]\.)stackpanel\b|\bstackpanel(Config|Modules|Serializable|Options)\b`) + // checkFlakeTextForStackpanel does a text-based search for stackpanel references // This is a fallback when nix flake metadata isn't available func checkFlakeTextForStackpanel(flakePath string) (bool, []string) { @@ -760,24 +706,10 @@ func checkFlakeTextForStackpanel(flakePath string) (bool, []string) { scanner := bufio.NewScanner(file) lineCount := 0 - // Patterns that indicate stackpanel usage - stackpanelPatterns := []string{ - "stackpanel", - "Stackpanel", - "STACKPANEL", - ".stack", - "stackpanelConfig", - "stackpanelModules", - } - for scanner.Scan() { lineCount++ - line := scanner.Text() - - for _, pattern := range stackpanelPatterns { - if strings.Contains(line, pattern) { - return true, warnings - } + if stackpanelFlakeRef.Match(scanner.Bytes()) { + return true, warnings } // Don't scan entire huge files diff --git a/apps/stackpanel-go/internal/agent/project/project_test.go b/apps/stackpanel-go/internal/agent/project/project_test.go new file mode 100644 index 00000000..d18db4eb --- /dev/null +++ b/apps/stackpanel-go/internal/agent/project/project_test.go @@ -0,0 +1,37 @@ +package project + +import ( + "os" + "path/filepath" + "testing" +) + +func TestFlakeOnlyProjectRecognition(t *testing.T) { + root := t.TempDir() + for _, folder := range []string{".stack-unknown", ".stackpanel"} { + if err := os.Mkdir(filepath.Join(root, folder), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, folder, "config.nix"), []byte("{}"), 0o644); err != nil { + t.Fatal(err) + } + } + for _, tc := range []struct { + flake string + want bool + }{ + {`{ outputs = { self }: import ./.stack-unknown/config.nix; }`, false}, + {`{ outputs = { self }: import ./.stackpanel/config.nix; }`, false}, + {`{ inputs.stackpanel.url = "path:../framework"; outputs = _: {}; }`, true}, + {`{ outputs = inputs: inputs.stackpanel.lib.mkFlake { inherit inputs; }; }`, true}, + {`{ outputs = { self }: { stackpanelConfig.name = "example"; }; }`, true}, + } { + file := filepath.Join(root, "flake.nix") + if err := os.WriteFile(file, []byte(tc.flake), 0o644); err != nil { + t.Fatal(err) + } + if got, _ := checkFlakeForStackpanelWithOptions(file, ValidationOptions{SkipNixEval: true}); got != tc.want { + t.Errorf("recognized %s: got %v, want %v", tc.flake, got, tc.want) + } + } +} diff --git a/apps/stackpanel-go/internal/agent/server/connect_entities_gen.go b/apps/stackpanel-go/internal/agent/server/connect_entities_gen.go index 66e177fc..4d4e52c0 100644 --- a/apps/stackpanel-go/internal/agent/server/connect_entities_gen.go +++ b/apps/stackpanel-go/internal/agent/server/connect_entities_gen.go @@ -12,42 +12,18 @@ import ( "google.golang.org/protobuf/encoding/protojson" ) -// GetVariables retrieves the variables entity from Nix data. -// Generated from proto - do not edit manually. -func (s *AgentServiceServer) GetVariables( - ctx context.Context, - req *connect.Request[gopb.GetVariablesRequest], -) (*connect.Response[gopb.Variables], error) { - data, err := s.server.readNixEntityJSON("variables") - if err != nil { - return nil, connect.NewError(connect.CodeInternal, err) - } - - var result gopb.Variables - if len(data) > 0 { - if err := protojson.Unmarshal(data, &result); err != nil { - // Fall back to standard JSON if protojson fails - if err := json.Unmarshal(data, &result); err != nil { - return nil, connect.NewError(connect.CodeInternal, err) - } - } - } - - return connect.NewResponse(&result), nil -} - -// GetModuleOutputs retrieves the moduleoutputs entity from Nix data. +// GetApps retrieves the apps entity from Nix data. // Generated from proto - do not edit manually. -func (s *AgentServiceServer) GetModuleOutputs( +func (s *AgentServiceServer) GetApps( ctx context.Context, - req *connect.Request[gopb.GetModuleOutputsRequest], -) (*connect.Response[gopb.ModuleOutputs], error) { - data, err := s.server.readNixEntityJSON("moduleoutputs") + req *connect.Request[gopb.GetAppsRequest], +) (*connect.Response[gopb.Apps], error) { + data, err := s.readProjectEntityJSON(ctx, req.Header(), "apps") if err != nil { - return nil, connect.NewError(connect.CodeInternal, err) + return nil, err } - var result gopb.ModuleOutputs + var result gopb.Apps if len(data) > 0 { if err := protojson.Unmarshal(data, &result); err != nil { // Fall back to standard JSON if protojson fails @@ -66,9 +42,9 @@ func (s *AgentServiceServer) GetSecrets( ctx context.Context, req *connect.Request[gopb.GetSecretsRequest], ) (*connect.Response[gopb.Secrets], error) { - data, err := s.server.readNixEntityJSON("secrets") + data, err := s.readProjectEntityJSON(ctx, req.Header(), "secrets") if err != nil { - return nil, connect.NewError(connect.CodeInternal, err) + return nil, err } var result gopb.Secrets @@ -90,9 +66,9 @@ func (s *AgentServiceServer) GetUsers( ctx context.Context, req *connect.Request[gopb.GetUsersRequest], ) (*connect.Response[gopb.Users], error) { - data, err := s.server.readNixEntityJSON("users") + data, err := s.readProjectEntityJSON(ctx, req.Header(), "users") if err != nil { - return nil, connect.NewError(connect.CodeInternal, err) + return nil, err } var result gopb.Users @@ -108,18 +84,18 @@ func (s *AgentServiceServer) GetUsers( return connect.NewResponse(&result), nil } -// GetApps retrieves the apps entity from Nix data. +// GetVariables retrieves the variables entity from Nix data. // Generated from proto - do not edit manually. -func (s *AgentServiceServer) GetApps( +func (s *AgentServiceServer) GetVariables( ctx context.Context, - req *connect.Request[gopb.GetAppsRequest], -) (*connect.Response[gopb.Apps], error) { - data, err := s.server.readNixEntityJSON("apps") + req *connect.Request[gopb.GetVariablesRequest], +) (*connect.Response[gopb.Variables], error) { + data, err := s.readProjectEntityJSON(ctx, req.Header(), "variables") if err != nil { - return nil, connect.NewError(connect.CodeInternal, err) + return nil, err } - var result gopb.Apps + var result gopb.Variables if len(data) > 0 { if err := protojson.Unmarshal(data, &result); err != nil { // Fall back to standard JSON if protojson fails diff --git a/apps/stackpanel-go/internal/agent/server/connect_handlers.go b/apps/stackpanel-go/internal/agent/server/connect_handlers.go index f042efe8..3dfeaa02 100644 --- a/apps/stackpanel-go/internal/agent/server/connect_handlers.go +++ b/apps/stackpanel-go/internal/agent/server/connect_handlers.go @@ -13,6 +13,7 @@ import ( "connectrpc.com/connect" gopb "github.com/darkmatter/stackpanel/packages/proto/gen/gopb" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" ) // ============================================================================= @@ -152,57 +153,73 @@ func (s *AgentServiceServer) GetNixConfig( ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() - forceRefresh := req.Msg.Refresh - - // Try FlakeWatcher first (preferred - has file watching and smart caching) - if s.server.flakeWatcher != nil { - if forceRefresh { - s.server.flakeWatcher.InvalidateAll() - } - - config, err := s.server.flakeWatcher.GetConfig(ctx) - if err == nil { - updated, cached := s.server.flakeWatcher.ConfigStatus() - - // Convert config to JSON string - configJSON, err := json.Marshal(config) - if err != nil { - return nil, connect.NewError( - connect.CodeInternal, - fmt.Errorf("failed to marshal config: %w", err), - ) - } - - return connect.NewResponse(&gopb.NixConfigResponse{ - ConfigJson: string(configJSON), - LastUpdated: updated.Format(time.RFC3339), - Cached: cached, - Source: "flake_watcher", - }), nil - } + rt, err := s.server.requestRuntime(req.Header()) + if err != nil { + return nil, err } - - // Fallback to legacy evaluation - config, err := s.server.evaluateConfig() + if req.Msg.Refresh && rt.flake != nil { + rt.flake.InvalidateAll() + } + config, updated, cached, err := authenticatedProjectConfig(ctx, rt) if err != nil { - return nil, connect.NewError( - connect.CodeInternal, - fmt.Errorf("failed to evaluate config: %w", err), - ) + return nil, err } - - configJSON, err := json.Marshal(config) + configJSON, err := json.Marshal(configWithUIReviews(rt.root, moduleStoreRoot, config, s.server.config.Port)) if err != nil { - return nil, connect.NewError( - connect.CodeInternal, - fmt.Errorf("failed to marshal config: %w", err), - ) + return nil, connect.NewError(connect.CodeInternal, err) + } + source := "fresh_eval" + if rt.flake != nil { + source = "flake_watcher" } return connect.NewResponse(&gopb.NixConfigResponse{ ConfigJson: string(configJSON), - LastUpdated: time.Now().Format(time.RFC3339), - Cached: false, - Source: "fresh_eval", + LastUpdated: updated.Format(time.RFC3339), + Cached: cached, + Source: source, }), nil } + +// Authenticated editors need the full project config (including variable +// values); module metadata and frames must use loadModuleState instead. +func authenticatedProjectConfig( + ctx context.Context, + rt *projectRuntime, +) (map[string]any, time.Time, bool, error) { + if rt == nil || rt.root == "" { + return nil, time.Time{}, false, invalidModuleState("no project selected") + } + if rt.flake != nil { + data, err := rt.flake.GetConfig(ctx) + updated, cached := rt.flake.ConfigStatus() + if err != nil { + return nil, time.Time{}, false, projectConfigEvalError(ctx, err) + } + return data, updated, cached, nil + } + raw, err := nixeval.EvalOnce(ctx, nixeval.EvalOnceParams{ + ProjectRoot: rt.root, + Expression: nixeval.ProjectAttr("stackpanelConfig"), + Timeout: 30 * time.Second, + }) + if err != nil { + return nil, time.Time{}, false, projectConfigEvalError(ctx, err) + } + var data map[string]any + if err := json.Unmarshal(raw, &data); err != nil || data == nil { + return nil, time.Time{}, false, invalidModuleState( + "invalid evaluated project config", + ) + } + return data, time.Now(), false, nil +} + +func projectConfigEvalError(ctx context.Context, err error) error { + if ctx.Err() != nil { + return moduleEvalError(ctx, err) + } + return invalidModuleState( + "could not evaluate the selected project's stackpanelConfig", + ) +} diff --git a/apps/stackpanel-go/internal/agent/server/connect_patch.go b/apps/stackpanel-go/internal/agent/server/connect_patch.go index 3969c9e1..74cbdd5c 100644 --- a/apps/stackpanel-go/internal/agent/server/connect_patch.go +++ b/apps/stackpanel-go/internal/agent/server/connect_patch.go @@ -16,7 +16,9 @@ import ( "connectrpc.com/connect" gopb "github.com/darkmatter/stackpanel/packages/proto/gen/gopb" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/flakeedit" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" "github.com/rs/zerolog/log" ) @@ -52,10 +54,10 @@ func (s *AgentServiceServer) PatchNixData( fmt.Errorf("entity is required"), ) } - if err := validateEntityName(entity); err != nil { + if err := validateDataEntity(entity); err != nil { return nil, connect.NewError(connect.CodeInvalidArgument, err) } - if isExternalEntity(entity) { + if nixdata.IsExternalEntity(entity) { return nil, connect.NewError( connect.CodePermissionDenied, fmt.Errorf("external entities are read-only"), @@ -81,13 +83,16 @@ func (s *AgentServiceServer) PatchNixData( ) } - srv := s.server + rt, err := s.server.requestRuntime(req.Header()) + if err != nil { + return nil, err + } // All patches now go to config.nix // For entity="config" with "stackpanel." prefix, strip the prefix // For other entities, prepend the entity name to the path if entity == "config" && strings.HasPrefix(path, "stackpanel.") { - return s.patchConsolidatedConfig(srv, path, parsedValue) + return s.patchConsolidatedConfig(ctx, rt, path, parsedValue) } // For entity-based patches (e.g., entity="apps", key="web", path="container.enable") @@ -101,27 +106,45 @@ func (s *AgentServiceServer) PatchNixData( } else { fullPath = entity + "." + path } - return s.patchConsolidatedConfig(srv, "stackpanel."+fullPath, parsedValue) + return s.patchConsolidatedConfig(ctx, rt, "stackpanel."+fullPath, parsedValue) } // patchConsolidatedConfig handles patches to the consolidated config.nix file. // Path format: "stackpanel.deployment.fly.organization" -> writes to config.nix at deployment.fly.organization func (s *AgentServiceServer) patchConsolidatedConfig( - srv *Server, + ctx context.Context, + rt *projectRuntime, fullPath string, value any, ) (*connect.Response[gopb.PatchNixDataResponse], error) { - // Strip "stackpanel." prefix to get the path within config.nix - configPath := parseConfigPath(fullPath) + rt.moduleMu.Lock() + defer rt.moduleMu.Unlock() + var response *connect.Response[gopb.PatchNixDataResponse] + err := flakeedit.WithModuleProject(ctx, rt.root, func(scoped context.Context) error { + var err error + response, err = s.applyConsolidatedConfig(scoped, rt, fullPath, value) + return err + }) + if err != nil && connect.CodeOf(err) == connect.CodeUnknown { + if ctx.Err() != nil { + return nil, projectConfigEvalError(ctx, err) + } + return nil, invalidModuleState("could not lock project config") + } + return response, err +} - log.Info(). - Str("fullPath", fullPath). - Str("configPath", configPath). - Interface("value", value). - Msg("PatchNixData: patching consolidated config.nix") +func (s *AgentServiceServer) applyConsolidatedConfig( + ctx context.Context, + rt *projectRuntime, + fullPath string, + value any, +) (*connect.Response[gopb.PatchNixDataResponse], error) { + // Strip "stackpanel." prefix to get the path within config.nix + configPath := nixdata.ParseConfigPath(fullPath) // Patch the consolidated config file - if err := srv.patchConsolidatedData(configPath, value); err != nil { + if err := rt.store.PatchConsolidatedData(configPath, value); err != nil { log.Error().Err(err).Msg("PatchNixData: failed to patch consolidated config") return nil, connect.NewError( connect.CodeInternal, @@ -129,21 +152,15 @@ func (s *AgentServiceServer) patchConsolidatedConfig( ) } - // Read back the updated data for cache invalidation - updatedData, err := srv.readConsolidatedData() - if err != nil { - log.Warn().Err(err).Msg("PatchNixData: failed to read back updated config") - } - // Invalidate FlakeWatcher cache so next GetNixConfig returns fresh data - if srv.flakeWatcher != nil { - srv.flakeWatcher.InvalidateConfig() - log.Debug().Msg("PatchNixData: invalidated FlakeWatcher config cache") + if rt.flake != nil { + rt.flake.InvalidateAll() } // Emit config.changed SSE event - srv.broadcastSSE(SSEEvent{ - Event: "config.changed", + s.server.broadcastSSE(SSEEvent{ + Event: "config.changed", + ProjectRoot: rt.root, Data: map[string]any{ "entity": "config", "path": fullPath, @@ -153,13 +170,19 @@ func (s *AgentServiceServer) patchConsolidatedConfig( log.Info(). Str("path", fullPath). - Str("file", srv.nixDataFilePath()). + Str("file", rt.store.Paths().ConfigFilePath()). Msg("PatchNixData: successfully patched consolidated config.nix") - // Return updated data as JSON - var updatedJSON []byte - if updatedData != nil { - updatedJSON, _ = json.Marshal(updatedData) + // The response contains the raw configured values as before, evaluated + // through the selected pure flake (not an import of a host path). + updatedJSON, err := nixeval.EvalOnce(ctx, nixeval.EvalOnceParams{ + ProjectRoot: rt.root, + Expression: ".#legacyPackages." + nixeval.CurrentSystem() + ".stackpanelRawConfig", + }) + if err != nil { + return nil, invalidModuleState( + "config saved, but the selected project's stackpanelRawConfig could not be evaluated", + ) } return connect.NewResponse(&gopb.PatchNixDataResponse{ diff --git a/apps/stackpanel-go/internal/agent/server/connect_service.go b/apps/stackpanel-go/internal/agent/server/connect_service.go index 248e538e..b8fd70a5 100644 --- a/apps/stackpanel-go/internal/agent/server/connect_service.go +++ b/apps/stackpanel-go/internal/agent/server/connect_service.go @@ -60,12 +60,6 @@ func (s *AgentServiceServer) GetProject( }), nil } -// ============================================================================= -// Config Entity Reads - generated in connect_entities_gen.go -// ============================================================================= -// GetSecrets, GetUsers, GetApps, GetVariables, and GetModuleOutputs are -// generated from agent.proto by protoc-gen-connect-handlers. - // ============================================================================= // Command Execution // ============================================================================= diff --git a/apps/stackpanel-go/internal/agent/server/connect_v1.go b/apps/stackpanel-go/internal/agent/server/connect_v1.go index a5c24646..ba77275f 100644 --- a/apps/stackpanel-go/internal/agent/server/connect_v1.go +++ b/apps/stackpanel-go/internal/agent/server/connect_v1.go @@ -25,6 +25,7 @@ func (s *Server) mountV1(mux *http.ServeMux) { validToken: s.isValidToken, projects: project.NewConnectHandler(s.projectMgr), shell: newShellService(), + modules: &moduleService{s: s}, scope: projectInterceptor{resolve: s.resolveProjectRoot, runtimes: s.runtimes}, }) for _, r := range routes { @@ -46,6 +47,7 @@ type v1Deps struct { validToken func(token string) bool projects agentv1connect.ProjectServiceHandler shell agentv1connect.ShellServiceHandler + modules agentv1connect.ModuleServiceHandler // scope resolves the request's project for project-scoped services. scope connect.Interceptor } @@ -64,13 +66,14 @@ func newV1Routes(d v1Deps) []v1Route { scoped := connect.WithHandlerOptions(opts, connect.WithInterceptors(d.scope)) info := &agentInfoService{version: d.version} - routes := make([]v1Route, 0, 3) + routes := make([]v1Route, 0, 4) add := func(path string, handler http.Handler) { routes = append(routes, v1Route{path: path, handler: handler}) } add(agentv1connect.NewAgentServiceHandler(info, opts)) add(agentv1connect.NewProjectServiceHandler(d.projects, opts)) add(agentv1connect.NewShellServiceHandler(d.shell, scoped)) + add(agentv1connect.NewModuleServiceHandler(d.modules, scoped)) info.procedures = procedurePaths(routes) return routes @@ -131,11 +134,15 @@ func (a authInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc { } } -func (a authInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc { +func (a authInterceptor) WrapStreamingClient( + next connect.StreamingClientFunc, +) connect.StreamingClientFunc { return next } -func (a authInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc { +func (a authInterceptor) WrapStreamingHandler( + next connect.StreamingHandlerFunc, +) connect.StreamingHandlerFunc { return func(ctx context.Context, conn connect.StreamingHandlerConn) error { if err := a.check(conn.Spec().Procedure, conn.RequestHeader()); err != nil { return err @@ -162,6 +169,9 @@ func (a authInterceptor) check(procedure string, header http.Header) error { // recoverRPC reports a handler panic to the caller as Internal and logs it // with the procedure, instead of dropping the connection. func recoverRPC(_ context.Context, spec connect.Spec, _ http.Header, p any) error { - log.Error().Str("procedure", spec.Procedure).Interface("panic", p).Msg("v1 handler panicked") + log.Error(). + Str("procedure", spec.Procedure). + Interface("panic", p). + Msg("v1 handler panicked") return connect.NewError(connect.CodeInternal, errors.New("internal error")) } diff --git a/apps/stackpanel-go/internal/agent/server/connect_v1_modules.go b/apps/stackpanel-go/internal/agent/server/connect_v1_modules.go new file mode 100644 index 00000000..16fffa12 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/connect_v1_modules.go @@ -0,0 +1,335 @@ +package server + +import ( + "context" + "errors" + "net/http" + "reflect" + "slices" + + "connectrpc.com/connect" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/flakeedit" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +type moduleService struct{ s *Server } + +func moduleInfo( + data map[string]any, + links map[string]userconfig.LinkedModule, +) (*agentv1.Module, error) { + var mod agentv1.Module + if err := decodeModuleProjection(data, &mod); err != nil { + return nil, err + } + if mod.Id == "" { + return nil, invalidModuleState("module metadata missing id") + } + if readme, ok := data["readme"].(string); ok { + mod.ReadmeContent = &readme + } + // Linking and dev origins are machine-local authority; never honor these + // claims from Nix (including protobuf's alternate snake_case spelling). + link, linked := links[mod.Id] + mod.Linked, mod.UiDevUrl = linked, nil + if linked && link.UIDevURL != "" { + mod.UiDevUrl = &link.UIDevURL + } + return &mod, nil +} + +func (s *moduleService) ListModules( + ctx context.Context, + _ *connect.Request[agentv1.ListModulesRequest], +) (*connect.Response[agentv1.ListModulesResponse], error) { + rt := runtimeFor(ctx) + state, err := loadModuleState(ctx, rt) + if err != nil { + return nil, err + } + list, err := evaluatedModules(state) + if err != nil { + return nil, err + } + links := userconfig.LinkedModules(rt.root) + resp := &agentv1.ListModulesResponse{Modules: make([]*agentv1.Module, 0, len(list))} + for _, item := range list { + data, _ := item.(map[string]any) + mod, err := moduleInfo(data, links) + if err != nil { + return nil, err + } + resp.Modules = append(resp.Modules, mod) + } + return connect.NewResponse(resp), nil +} + +func (s *moduleService) GetModule( + ctx context.Context, + req *connect.Request[agentv1.GetModuleRequest], +) (*connect.Response[agentv1.GetModuleResponse], error) { + rt := runtimeFor(ctx) + state, err := loadModuleState(ctx, rt) + if err != nil { + return nil, err + } + data, err := findModule(state, req.Msg.GetModuleId()) + if err != nil { + return nil, err + } + mod, err := moduleInfo(data, userconfig.LinkedModules(rt.root)) + if err != nil { + return nil, err + } + return connect.NewResponse(&agentv1.GetModuleResponse{Module: mod}), nil +} + +func (s *moduleService) GetModuleOutputs( + ctx context.Context, + req *connect.Request[agentv1.GetModuleOutputsRequest], +) (*connect.Response[agentv1.GetModuleOutputsResponse], error) { + out, err := moduleOutputData(ctx, runtimeFor(ctx), req.Msg.GetModuleId()) + if err != nil { + return nil, err + } + var result agentv1.ModuleOutputs + if err := decodeModuleProjection(out, &result); err != nil { + return nil, err + } + return connect.NewResponse(&agentv1.GetModuleOutputsResponse{Outputs: &result}), nil +} + +func (s *moduleService) EnableModule( + ctx context.Context, + req *connect.Request[agentv1.EnableModuleRequest], +) (*connect.Response[agentv1.EnableModuleResponse], error) { + var err error + if answers := req.Msg.GetAnswers(); len(answers) != 0 { + rt := runtimeFor(ctx) + err = withModuleConfigLock(ctx, rt, func(ctx context.Context) error { + plan, err := prepareModuleAdoption(ctx, rt, req.Msg.GetModuleId(), answers) + if err != nil { + return err + } + return plan.commit(ctx, rt, req.Msg.GetModuleId()) + }) + } else { + err = s.patchModuleOption( + ctx, + req.Header(), + req.Msg.GetModuleId(), + "enablePath", + true, + ) + } + if err != nil { + return nil, err + } + return connect.NewResponse( + &agentv1.EnableModuleResponse{Message: "Module enabled in project config."}, + ), nil +} + +func (s *moduleService) DisableModule( + ctx context.Context, + req *connect.Request[agentv1.DisableModuleRequest], +) (*connect.Response[agentv1.DisableModuleResponse], error) { + if err := s.patchModuleOption( + ctx, + req.Header(), + req.Msg.GetModuleId(), + "enablePath", + false, + ); err != nil { + return nil, err + } + return connect.NewResponse( + &agentv1.DisableModuleResponse{Message: "Module disabled in project config."}, + ), nil +} + +func (s *moduleService) UpdateModuleConfig( + ctx context.Context, + req *connect.Request[agentv1.UpdateModuleConfigRequest], +) (*connect.Response[agentv1.UpdateModuleConfigResponse], error) { + if req.Msg.Settings == nil { + return nil, connect.NewError( + connect.CodeInvalidArgument, + errors.New("settings must be an object"), + ) + } + if err := s.patchModuleOption( + ctx, + req.Header(), + req.Msg.GetModuleId(), + "configPath", + req.Msg.Settings.AsMap(), + ); err != nil { + return nil, err + } + return connect.NewResponse( + &agentv1.UpdateModuleConfigResponse{ + Message: "Module settings saved in project config.", + }, + ), nil +} + +func (s *moduleService) patchModuleOption( + ctx context.Context, + header http.Header, + id, field string, + value any, +) error { + rt := runtimeFor(ctx) + return withModuleConfigLock(ctx, rt, func(ctx context.Context) error { + return s.applyModuleOption(ctx, rt, header, id, field, value) + }) +} + +func withModuleConfigLock( + ctx context.Context, + rt *projectRuntime, + fn func(context.Context) error, +) error { + if rt == nil || rt.store == nil { + return invalidModuleState("no project config store") + } + rt.moduleMu.Lock() + defer rt.moduleMu.Unlock() + err := flakeedit.WithModuleProject(ctx, rt.root, fn) + if err != nil && connect.CodeOf(err) == connect.CodeUnknown { + if ctx.Err() != nil { + return moduleEvalError(ctx, ctx.Err()) + } + return invalidModuleState("could not lock project config for module edit") + } + return err +} + +func (s *moduleService) applyModuleOption( + ctx context.Context, + rt *projectRuntime, + header http.Header, + id, field string, + value any, +) error { + state, err := loadModuleState(ctx, rt) + if err != nil { + return err + } + var appPath []string + if field == "configPath" { + var public map[string]any + appPath, public, err = s.s.moduleUIConfigPatchScope(header, rt, state, id) + if err != nil { + return err + } + if appPath != nil && !appPatchIsProjected(public, value) { + return uiGrantDenied() + } + } + module, err := findModule(state, id) + if err != nil { + return err + } + path := appPath + if path == nil { + path, err = moduleOptionPath(module, field) + if err != nil { + return err + } + } + if err := ctx.Err(); err != nil { + return moduleEvalError(ctx, err) + } + check := func() error { + state, err := loadModuleState(ctx, rt) + if err != nil { + return err + } + if ctx.Err() != nil { + return moduleEvalError(ctx, ctx.Err()) + } + if appPath != nil { + // Revalidate the original panel's authority, not just the write + // location. A patch can disable an app or revoke its own grant. + verified, public, err := s.s.moduleUIConfigPatchScope(header, rt, state, id) + if err != nil { + return err + } + if !slices.Equal(verified, appPath) { + return uiGrantDenied() + } + if !moduleSettingsMatch(public, value) { + return invalidModuleState("app settings did not apply to the selected panel") + } + if ctx.Err() != nil { + return moduleEvalError(ctx, ctx.Err()) + } + return nil + } + updated, err := findModule(state, id) + if err != nil { + return err + } + if field == "enablePath" && updated["enabled"] == value { + return nil + } + if field == "configPath" && moduleSettingsMatch(updated["settings"], value) { + return nil + } + return invalidModuleState( + "project flake did not apply the module option; verify the option is declared and the config file is tracked", + ) + } + if err := rt.store.PatchModuleDataChecked(path, value, check); err != nil { + var rpcErr *connect.Error + if errors.As(err, &rpcErr) { + return rpcErr + } + if errors.Is(err, nixdata.ErrInvalidModuleData) { + return connect.NewError(connect.CodeInvalidArgument, nixdata.ErrInvalidModuleData) + } + return invalidModuleState("could not patch the declared option in project config") + } + if rt.flake != nil { + rt.flake.InvalidateAll() + } + return nil +} + +// Object patches merge literal keys. An object projection may omit private +// siblings: never allow their replacement through a scalar or an ancestor. +func appPatchIsProjected(public any, patch any) bool { + fields, object := public.(map[string]any) + updates, merge := patch.(map[string]any) + if object != merge { + return false + } + for key, value := range updates { + v, ok := fields[key] + if !ok || !appPatchIsProjected(v, value) { + return false + } + } + return true +} + +// A patch only constrains the leaves supplied by the caller. Defaults and +// unrelated evaluated settings need not be written back to disk. +func moduleSettingsMatch(actual, patch any) bool { + if fields, ok := patch.(map[string]any); ok { + data, _ := actual.(map[string]any) + for key, value := range fields { + v, present := data[key] + if !present || !moduleSettingsMatch(v, value) { + return false + } + } + return true + } + return reflect.DeepEqual(actual, patch) +} diff --git a/apps/stackpanel-go/internal/agent/server/connect_v1_modules_test.go b/apps/stackpanel-go/internal/agent/server/connect_v1_modules_test.go new file mode 100644 index 00000000..e6a8cce5 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/connect_v1_modules_test.go @@ -0,0 +1,977 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io/fs" + "maps" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "connectrpc.com/connect" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/structpb" + + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb" + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/gopbconnect" + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1/agentv1connect" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/config" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/project" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +// No nixpkgs, lockfile, shell profile, network inputs or derivations. Both +// consumers expose the real flake function/data boundary used by ModuleService. +const moduleTestFlake = `{ + outputs = { self }: let + tree = builtins.pathExists ./.stack/config/modules.nix; + cfg = if tree then { modules = import ./.stack/config/modules.nix; } else import ./.stack/config.nix; + enabled = if tree then cfg.modules.demo.enable else cfg.custom.active; + settings = if tree then cfg.modules.demo.settings else cfg.custom.prefs; + expected = if tree then [ "modules" "demo" "enable" ] else [ "custom" "active" ]; + mod = { id = "demo"; inherit enabled settings; readme = "Read me"; + linked = true; uiDevUrl = "https://untrusted.invalid"; + enablePath = if tree then "modules.demo.enable" else "custom.active"; + configPath = if tree then "modules.demo.settings" else "custom.prefs"; + }; + other = { id = "other"; enabled = true; }; + settingsPatch = attrs: if tree then { modules.demo.settings = attrs; } else { custom.prefs = attrs; }; + choice = value: label: attrs: { inherit value label; config = settingsPatch attrs; }; + offers = [ + { id = "adopt"; module = "demo"; revision = if settings.revBumped or false then 2 else 1; + question = { type = "bool"; label = "Import existing config?"; description = "Import legacy settings."; + order = 1; default = true; choices = []; }; config = settingsPatch { imported = "PRIVATE"; }; } + { id = "layout"; module = "demo"; revision = 3; config = {}; + question = { type = "select"; label = "Which layout?"; description = null; order = 2; default = "compact"; choices = [ + (choice "compact" "Compact" { layout = "compact"; }) (choice "wide" "Wide" { layout = "wide"; }) + (choice "broken" "Incompatible" { layout = "broken"; reject = true; }) + ]; }; } + { id = "tools"; module = "demo"; revision = 4; config = {}; + question = { type = "multiselect"; label = "Which tools?"; description = null; order = 3; default = ["bench"]; choices = [ + (choice "docs" "Documentation" { docs = true; }) (choice "lint" "Linting" { lint = true; }) + (choice "bench" "Benchmarks" { bench = true; }) + ]; }; } + ]; + adoptionFiles = prefs: + (if prefs ? imported then [{ path = "imported.json"; }] else []) + ++ (if prefs ? layout then [{ path = "layout-" + prefs.layout + ".json"; }] else []) + ++ map (name: { path = name + ".json"; }) (builtins.filter (name: prefs.${name} or false) ["docs" "lint" "bench"]); + outputs = { files = [{ path = "demo.json"; content = "PRIVATE"; }] ++ adoptionFiles settings; + services = [{ name = "demo-http"; proxy = { enable = true; port = 12080; }; }]; + scripts = []; packages = []; tasks = []; healthchecks = []; }; + in { legacyPackages.fixture = { + stackpanelRawConfig = cfg; + stackpanelSerializable = assert !(settings.reject or false); { + modulesListAll = [mod other]; moduleOutputs.demo = outputs; + secrets = { token = "PRIVATE"; }; + }; + stackpanelSpeculate = {enablePath ? null, adoption ? {}, ...}: let + active = if enablePath == null then enabled else assert enablePath == expected; true; + prefs = settings // (if tree then adoption.modules.demo.settings or {} else adoption.custom.prefs or {}); + in { files = [{path="shared"; content=if active then "PRIVATE" else "old";}] + ++ (if active then [{path="demo.json";}] ++ adoptionFiles prefs else [{path="old";}]); + packageFingerprints = { shared = if active then "2" else "1"; } // (if active then { demo-pkg = "1"; } else {}); + serviceFingerprints = if active then { demo-http = "new"; } else { legacy-http = "old"; }; + addons = if active then offers else []; + }; + }; }; +}` + +func moduleFixtureFile(t *testing.T, root, name, data string) { + t.Helper() + path := filepath.Join(root, name) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(data), 0o644); err != nil { + t.Fatal(err) + } +} + +func moduleFixtureSnapshot(t *testing.T, root string) map[string]string { + t.Helper() + files := map[string]string{} + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + b, err := os.ReadFile(path) + files[path] = string(b) + return err + }) + if err != nil { + t.Fatal(err) + } + return files +} + +func moduleFixtureRequest[T any](project string, msg *T) *connect.Request[T] { + r := connect.NewRequest(msg) + r.Header().Set("Authorization", "Bearer paired") + r.Header().Set(projectHeader, project) + return r +} + +func moduleFixtureClient( + t *testing.T, + roots map[string]string, +) (agentv1connect.ModuleServiceClient, *runtimeRegistry) { + t.Helper() + if _, err := exec.LookPath("nix"); err != nil { + t.Skip("integration test requires Nix flakes") + } + t.Setenv("NIX_SYSTEM", "fixture") + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv( + "NIX_CONFIG", + os.Getenv( + "NIX_CONFIG", + )+"\nexperimental-features = nix-command flakes\nsubstituters =\nflake-registry =\n", + ) + for _, root := range roots { + moduleFixtureFile(t, root, "flake.nix", moduleTestFlake) + } + registry, _ := newTestRegistry() + registry.create = func(root string) (*projectRuntime, error) { + return &projectRuntime{root: root, store: nixdata.NewStore(root, nil)}, nil + } + deps := testV1Deps( + func(token string) bool { return token == "paired" }, + agentv1connect.UnimplementedProjectServiceHandler{}, + ) + deps.modules = &moduleService{s: newUITestServer(t)} + deps.scope = projectInterceptor{ + runtimes: registry, + resolve: func(id string) (string, error) { + if root, ok := roots[id]; ok { + return root, nil + } + return "", connect.NewError(connect.CodeNotFound, errors.New("unknown project")) + }, + } + mux := http.NewServeMux() + for _, route := range newV1Routes(deps) { + mux.Handle(route.path, route.handler) + } + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return agentv1connect.NewModuleServiceClient(srv.Client(), srv.URL), registry +} + +func TestModuleRPCProjectPersistenceAndReadOnlyPreview(t *testing.T) { + a, b := t.TempDir(), t.TempDir() + client, registry := moduleFixtureClient(t, map[string]string{"a": a, "b": b}) + moduleFixtureFile(t, a, ".stack/config.nix", `{ + # This comment and expression belong to the user. + untouched = 2 + 3; + custom.active = false; + custom.prefs.marker = "A"; +} +`) + moduleFixtureFile(t, b, ".stack/config/modules.nix", `{ + # Keep these bytes unchanged. + demo.enable = false; + demo.settings.marker = "B"; +} +`) + ctx := t.Context() + if _, err := client.ListModules( + ctx, + connect.NewRequest(&agentv1.ListModulesRequest{}), + ); connect.CodeOf( + err, + ) != connect.CodeUnauthenticated { + t.Fatalf("no auth: %v", err) + } + for _, ids := range [][]string{nil, {""}, {"a", "b"}, {"a,b"}} { + req := connect.NewRequest(&agentv1.EnableModuleRequest{ModuleId: "demo"}) + req.Header().Set("Authorization", "Bearer paired") + for _, id := range ids { + req.Header().Add(projectHeader, id) + } + _, err := client.EnableModule(ctx, req) + require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err)) + } + require.Empty( + t, + registry.runtimes, + "ambiguous writes must be rejected before project startup", + ) + list, err := client.ListModules( + ctx, + moduleFixtureRequest("a", &agentv1.ListModulesRequest{}), + ) + if err != nil { + t.Fatal(err) + } + require.Len(t, list.Msg.Modules, 2) + require.False(t, list.Msg.Modules[0].Enabled) + require.True(t, list.Msg.Modules[1].Enabled) + require.False(t, list.Msg.Modules[0].Linked) + require.Nil(t, list.Msg.Modules[0].UiDevUrl) + if _, err := client.GetModule( + ctx, + moduleFixtureRequest("a", &agentv1.GetModuleRequest{ModuleId: "missing"}), + ); connect.CodeOf( + err, + ) != connect.CodeNotFound { + t.Fatalf("missing: %v", err) + } + if _, err := client.GetModule( + ctx, + moduleFixtureRequest("a", &agentv1.GetModuleRequest{}), + ); connect.CodeOf( + err, + ) != connect.CodeInvalidArgument { + t.Fatalf("empty id: %v", err) + } + outputs, err := client.GetModuleOutputs( + ctx, + moduleFixtureRequest("a", &agentv1.GetModuleOutputsRequest{ModuleId: "demo"}), + ) + if err != nil { + t.Fatal(err) + } + o := outputs.Msg.Outputs + require.Equal(t, "demo", o.ModuleId) + require.Len(t, o.Files, 1) + require.Equal(t, "demo.json", o.Files[0].Path) + require.Len(t, o.Services, 1) + require.True(t, o.Services[0].ProxyEnabled) + require.NotContains(t, o.String(), "PRIVATE") + + original := moduleFixtureSnapshot(t, a) + result, err := client.PreviewModuleEnable( + ctx, + moduleFixtureRequest("a", &agentv1.PreviewModuleEnableRequest{ModuleId: "demo"}), + ) + if err != nil { + t.Fatal(err) + } + p := result.Msg.Preview + require.Equal(t, []string{"old", "shared"}, p.Files.Before) + require.Equal(t, []string{"demo.json", "shared"}, p.Files.After) + require.Equal(t, []string{"shared"}, p.Files.Changed) + require.Equal(t, []string{"old"}, p.Files.Removed) + require.Equal(t, []string{"demo.json"}, p.Files.Added) + require.Equal(t, []string{"demo-pkg"}, p.Packages.Added) + require.Equal(t, []string{"shared"}, p.Packages.Changed) + require.Equal(t, []string{"demo-http"}, p.Services.Added) + require.Equal(t, []string{"legacy-http"}, p.Services.Removed) + require.Len(t, p.Offers, 3) + require.NotContains(t, p.String(), "PRIVATE") + if !maps.Equal(original, moduleFixtureSnapshot(t, a)) { + t.Fatal("preview wrote project files") + } + + get := func(project string) *agentv1.Module { + t.Helper() + res, err := client.GetModule( + ctx, + moduleFixtureRequest(project, &agentv1.GetModuleRequest{ModuleId: "demo"}), + ) + if err != nil { + t.Fatal(err) + } + return res.Msg.Module + } + other := moduleFixtureSnapshot(t, b) + if _, err := client.EnableModule( + ctx, + moduleFixtureRequest("a", &agentv1.EnableModuleRequest{ModuleId: "demo"}), + ); err != nil { + t.Fatal(err) + } + key := `option."${name}"` + val := "line 1\n${not-an-expression} 'test'" + settings, err := structpb.NewStruct( + map[string]any{ + key: val, + "nested": map[string]any{"list": []any{true, 3, "${name}"}}, + }, + ) + if err != nil { + t.Fatal(err) + } + if _, err := client.UpdateModuleConfig( + ctx, + moduleFixtureRequest( + "a", + &agentv1.UpdateModuleConfigRequest{ModuleId: "demo", Settings: settings}, + ), + ); err != nil { + t.Fatal(err) + } + m := get("a") + if !m.Enabled || m.GetReadmeContent() != "Read me" || + m.Settings.AsMap()[key] != val || + m.Settings.AsMap()["marker"] != "A" { + t.Fatalf("config round trip: %v", m) + } + if bmod := get( + "b", + ); bmod.Enabled || bmod.Settings.AsMap()["marker"] != "B" || + !maps.Equal(other, moduleFixtureSnapshot(t, b)) { + t.Fatalf("project b affected: %v", bmod) + } + aFiles := moduleFixtureSnapshot(t, a) + bad, err := structpb.NewStruct(map[string]any{"reject": true}) + require.NoError(t, err) + _, err = client.UpdateModuleConfig( + ctx, + moduleFixtureRequest( + "a", + &agentv1.UpdateModuleConfigRequest{ModuleId: "demo", Settings: bad}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err)) + require.Equal( + t, + aFiles, + moduleFixtureSnapshot(t, a), + "rejected config must restore exact bytes", + ) + if len(original) != len(aFiles) || + !strings.Contains( + aFiles[filepath.Join(a, ".stack/config.nix")], + " # This comment and expression belong to the user.\n untouched = 2 + 3;", + ) { + t.Fatal("config edit rewrote unrelated files or fields") + } + if _, err := client.EnableModule( + ctx, + moduleFixtureRequest("b", &agentv1.EnableModuleRequest{ModuleId: "demo"}), + ); err != nil { + t.Fatal(err) + } + if !get("b").Enabled { + t.Fatal("tree edit not visible to pure eval") + } + if _, err := client.DisableModule( + ctx, + moduleFixtureRequest("a", &agentv1.DisableModuleRequest{ModuleId: "demo"}), + ); err != nil { + t.Fatal(err) + } + if get("a").Enabled || !get("b").Enabled { + t.Fatal("disable crossed project scopes") + } +} + +func TestModuleRPCAdoption(t *testing.T) { + root := t.TempDir() + client, _ := moduleFixtureClient(t, map[string]string{"project": root}) + moduleFixtureFile(t, root, ".stack/config/modules.nix", `{ + # This project predates demo adoption. + demo.enable = false; + demo.settings.marker = "keep"; +} +`) + ctx := t.Context() + preview := func(answers ...*agentv1.ModuleAdoptionAnswer) *agentv1.ModulePreview { + t.Helper() + before := moduleFixtureSnapshot(t, root) + res, err := client.PreviewModuleEnable( + ctx, + moduleFixtureRequest( + "project", + &agentv1.PreviewModuleEnableRequest{ModuleId: "demo", Answers: answers}, + ), + ) + require.NoError(t, err) + require.Equal( + t, + before, + moduleFixtureSnapshot(t, root), + "preview must not edit config or ledger", + ) + require.NotContains(t, res.Msg.Preview.String(), "PRIVATE") + return res.Msg.Preview + } + enable := func(answers ...*agentv1.ModuleAdoptionAnswer) error { + _, err := client.EnableModule( + ctx, + moduleFixtureRequest( + "project", + &agentv1.EnableModuleRequest{ModuleId: "demo", Answers: answers}, + ), + ) + return err + } + disable := func() { + t.Helper() + _, err := client.DisableModule( + ctx, + moduleFixtureRequest("project", &agentv1.DisableModuleRequest{ModuleId: "demo"}), + ) + require.NoError(t, err) + } + get := func() *agentv1.Module { + t.Helper() + res, err := client.GetModule( + ctx, + moduleFixtureRequest("project", &agentv1.GetModuleRequest{ModuleId: "demo"}), + ) + require.NoError(t, err) + return res.Msg.Module + } + seen := func() map[string]reconcile.LedgerEntry { + t.Helper() + data, err := os.ReadFile(filepath.Join(root, ".stack/reconcile.json")) + require.NoError(t, err) + var ledger reconcile.Ledger + require.NoError(t, json.Unmarshal(data, &ledger)) + require.Equal(t, 1, ledger.Version) + return ledger.Seen + } + + // Defaults are suggestions, not decisions: preview shows only enable's output. + initial := preview() + require.Equal(t, []string{"demo.json"}, initial.Files.Added) + require.Len(t, initial.Offers, 3) + offers := map[string]*agentv1.ModuleAdoptionOffer{} + for _, o := range initial.Offers { + offers[o.Id] = o + } + for _, want := range []struct { + id, typ, rev string + def any + choices map[string]string + }{ + {"adopt", "bool", "1", true, map[string]string{}}, + {"layout", "select", "3", "compact", map[string]string{"compact": "Compact", "wide": "Wide", "broken": "Incompatible"}}, + {"tools", "multiselect", "4", []any{"bench"}, map[string]string{"docs": "Documentation", "lint": "Linting", "bench": "Benchmarks"}}, + } { + o := offers[want.id] + require.NotNil(t, o, want.id) + require.Equal(t, want.typ, o.Type, want.id) + require.Equal(t, want.rev, o.Revision, want.id) + require.Equal(t, want.def, o.Default.AsInterface(), want.id) + choices := map[string]string{} + for _, c := range o.Choices { + choices[c.Value] = c.Label + } + require.Equal(t, want.choices, choices, want.id) + } + answer := func(id string, value any) *agentv1.ModuleAdoptionAnswer { + t.Helper() + v, err := structpb.NewValue(value) + require.NoError(t, err) + return &agentv1.ModuleAdoptionAnswer{ + Id: id, + Revision: offers[id].Revision, + Answer: v, + } + } + + // An explicit no is recorded; omitted select/multiselect are still pending. + stale := answer("adopt", true) + require.NoError(t, enable(answer("adopt", false))) + m := get() + require.True(t, m.Enabled) + require.Equal(t, map[string]any{"marker": "keep"}, m.Settings.AsMap()) + declined := seen() + require.Len(t, declined, 1) + require.Equal(t, 1, declined["adopt"].Revision) + require.Equal(t, false, declined["adopt"].Answer) + disable() + pending := preview().Offers + var ids []string + for _, o := range pending { + ids = append(ids, o.Id) + } + require.ElementsMatch(t, []string{"layout", "tools"}, ids) + + // Change the actual evaluated offer revision after the first preview. + bump, err := structpb.NewStruct(map[string]any{"revBumped": true}) + require.NoError(t, err) + _, err = client.UpdateModuleConfig( + ctx, + moduleFixtureRequest( + "project", + &agentv1.UpdateModuleConfigRequest{ModuleId: "demo", Settings: bump}, + ), + ) + require.NoError(t, err) + before := moduleFixtureSnapshot(t, root) + for _, tc := range []struct { + name string + bad *agentv1.ModuleAdoptionAnswer + code connect.Code + }{ + {"stale preview revision", stale, connect.CodeFailedPrecondition}, + {"wrong multiselect type", answer("tools", "lint"), connect.CodeInvalidArgument}, + {"unknown multiselect choice", answer("tools", []any{"docs", "unknown"}), connect.CodeInvalidArgument}, + } { + batch := []*agentv1.ModuleAdoptionAnswer{answer("layout", "wide"), tc.bad} + _, err := client.PreviewModuleEnable( + ctx, + moduleFixtureRequest( + "project", + &agentv1.PreviewModuleEnableRequest{ModuleId: "demo", Answers: batch}, + ), + ) + require.Equal(t, tc.code, connect.CodeOf(err), tc.name) + require.Equal(t, before, moduleFixtureSnapshot(t, root), tc.name) + require.Equal(t, tc.code, connect.CodeOf(enable(batch...)), tc.name) + require.Equal(t, before, moduleFixtureSnapshot(t, root), tc.name) + } + + revised := preview() + require.Equal(t, []string{"demo.json"}, revised.Files.Added) + require.Len(t, revised.Offers, 3) + for _, o := range revised.Offers { + offers[o.Id] = o + } + require.Equal(t, "2", offers["adopt"].Revision) + require.Equal(t, "revised", offers["adopt"].Reason) + adopt, tools := answer("adopt", true), answer("tools", []any{"docs", "lint"}) + + // A declared, type-correct choice can speculate successfully but fail the + // real stackpanelSerializable eval after patching. Restore even ledger bytes. + broken := answer("layout", "broken") + require.Contains(t, preview(adopt, tools, broken).Files.Added, "layout-broken.json") + require.Equal( + t, + connect.CodeFailedPrecondition, + connect.CodeOf(enable(adopt, tools, broken)), + ) + require.Equal( + t, + before, + moduleFixtureSnapshot(t, root), + "post-patch eval failure must restore all files", + ) + + wide := answer("layout", "wide") + chosen := preview(adopt, tools, wide) + require.Equal(t, revised.Files.Before, chosen.Files.Before) + require.Equal( + t, + []string{ + "demo.json", + "docs.json", + "imported.json", + "layout-wide.json", + "lint.json", + }, + chosen.Files.Added, + ) + require.NoError(t, enable(adopt, tools, wide)) + m = get() + require.True(t, m.Enabled) + require.Equal( + t, + map[string]any{ + "marker": "keep", + "revBumped": true, + "imported": "PRIVATE", + "layout": "wide", + "docs": true, + "lint": true, + }, + m.Settings.AsMap(), + ) + outputs, err := client.GetModuleOutputs( + ctx, + moduleFixtureRequest("project", &agentv1.GetModuleOutputsRequest{ModuleId: "demo"}), + ) + require.NoError(t, err) + var files []string + for _, f := range outputs.Msg.Outputs.Files { + files = append(files, f.Path) + } + require.ElementsMatch( + t, + chosen.Files.Added, + files, + "committed outputs must agree with the chosen preview", + ) + records := seen() + require.Len(t, records, 3) + require.Equal(t, 2, records["adopt"].Revision) + require.Equal(t, true, records["adopt"].Answer) + require.Equal(t, 3, records["layout"].Revision) + require.Equal(t, "wide", records["layout"].Answer) + require.Equal(t, 4, records["tools"].Revision) + require.Equal(t, []any{"docs", "lint"}, records["tools"].Answer) + disable() + require.Empty( + t, + preview().Offers, + "disabling and re-enabling must not re-offer a recorded revision", + ) +} + +func TestModuleStateErrorsDoNotExposePrivateEvalDiagnostics(t *testing.T) { + rt := &projectRuntime{ + root: t.TempDir(), + evalModuleState: func(context.Context, string) ([]byte, error) { return nil, errors.New("PRIVATE") }, + } + ctx := context.WithValue(t.Context(), runtimeKey{}, rt) + _, err := (&moduleService{}).GetModule( + ctx, + connect.NewRequest(&agentv1.GetModuleRequest{ModuleId: "demo"}), + ) + if connect.CodeOf(err) != connect.CodeFailedPrecondition || + strings.Contains(err.Error(), "PRIVATE") { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestLegacyRPCScopedFullProjectConfig(t *testing.T) { + if _, err := exec.LookPath("nix"); err != nil { + t.Skip("integration test requires Nix flakes") + } + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv("NIX_SYSTEM", "fixture") + t.Setenv( + "NIX_CONFIG", + os.Getenv( + "NIX_CONFIG", + )+"\nexperimental-features = nix-command flakes\nsubstituters =\nflake-registry =\n", + ) + projects := t.TempDir() + if errors.Is(project.QuickValidate(projects), project.ErrSuspiciousPath) { + home, err := os.UserHomeDir() + require.NoError(t, err) + projects, err = os.MkdirTemp(home, ".stackpanel-v0-test-") + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, os.RemoveAll(projects)) }) + } + mgr, err := project.NewManager(t.TempDir()) + require.NoError(t, err) + ids := map[string]string{} + for _, name := range []string{"a", "b"} { + root := filepath.Join(projects, name) + moduleFixtureFile( + t, + root, + ".stack/config.nix", + fmt.Sprintf(`{ apps.web.name = "%s"; }`, name), + ) + moduleFixtureFile(t, root, "flake.nix", `{ + outputs = { self }: let cfg = import ./.stack/config.nix; in { legacyPackages.fixture = { + stackpanelRawConfig = cfg; + stackpanelConfig = cfg // { variables.backend = "fixture"; variables.scope.value = "full-" + cfg.apps.web.name; }; + }; }; +}`) + registryCommand(t, root, "git", "init", "-q") + registryCommand(t, root, "git", "add", "-f", "flake.nix", ".stack/config.nix") + registryGitCommit(t, root, "test project") + p, err := mgr.UserConfigManager().AddProject(root, name) + require.NoError(t, err) + ids[name] = p.ID + } + s := &Server{ + config: &config.Config{ProjectRoot: filepath.Join(projects, "a")}, + projectMgr: mgr, + } + s.runtimes, _ = newTestRegistry() + s.runtimes.create = func(root string) (*projectRuntime, error) { + return &projectRuntime{root: root, store: nixdata.NewStore(root, nil)}, nil + } + mux := http.NewServeMux() + mux.Handle(gopbconnect.NewAgentServiceHandler(NewAgentServiceServer(s))) + server := httptest.NewServer(mux) + defer server.Close() + v0 := gopbconnect.NewAgentServiceClient(server.Client(), server.URL) + ctx := t.Context() + patch, err := v0.PatchNixData( + ctx, + moduleFixtureRequest(ids["b"], &gopb.PatchNixDataRequest{ + Entity: "apps", Key: "web", Path: "name", ValueType: "string", Value: `"patched"`, + }), + ) + require.NoError(t, err) + require.True(t, patch.Msg.Success) + require.Contains(t, patch.Msg.UpdatedJson, "patched") + for id, expected := range map[string]string{"": "a", ids["b"]: "patched"} { + apps, err := v0.GetApps(ctx, moduleFixtureRequest(id, &gopb.GetAppsRequest{})) + require.NoError(t, err) + require.Equal(t, expected, apps.Msg.GetApps()["web"].GetName()) + vars, err := v0.GetVariables( + ctx, + moduleFixtureRequest(id, &gopb.GetVariablesRequest{}), + ) + require.NoError(t, err) + require.Equal(t, "full-"+expected, vars.Msg.GetVariables()["scope"].GetValue()) + cfg, err := v0.GetNixConfig( + ctx, + moduleFixtureRequest(id, &gopb.GetNixConfigRequest{}), + ) + require.NoError(t, err) + require.Contains(t, cfg.Msg.ConfigJson, "full-"+expected) + } +} + +func TestModuleConfigGrantCheckedAgainstOperativeState(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + root := t.TempDir() + moduleFixtureFile(t, root, ".stack/config.nix", "{ # unchanged\n}\n") + server := newUITestServer(t) + for _, mutation := range []string{"revoke", "retarget"} { + t.Run(mutation, func(t *testing.T) { + state, panel, module := uiTestState() + bundle := panel["uiBundle"].(map[string]any) + bundle["permissions"] = []any{"config:patch"} + module["configPath"] = "custom.settings" + grant, err := server.issueModuleUIGrant( + root, + state, + "demo", + "inspector", + "", + moduleStoreRoot, + userconfig.LinkedModule{}, + ) + require.NoError(t, err) + if mutation == "revoke" { + bundle["permissions"] = []any{} + } else { + module["configPath"] = "other.settings" + } + rt := &projectRuntime{ + root: root, + store: nixdata.NewStore(root, nil), + evalModuleState: func(context.Context, string) ([]byte, error) { return json.Marshal(state) }, + } + settings, err := structpb.NewStruct(map[string]any{"color": "blue"}) + require.NoError(t, err) + req := moduleFixtureRequest( + "selected", + &agentv1.UpdateModuleConfigRequest{ModuleId: "demo", Settings: settings}, + ) + req.Header().Set(moduleUIGrantHeader, grant) + before := moduleFixtureSnapshot(t, root) + _, err = (&moduleService{s: server}).UpdateModuleConfig( + context.WithValue(t.Context(), runtimeKey{}, rt), + req, + ) + require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err)) + require.Equal(t, before, moduleFixtureSnapshot(t, root)) + }) + } +} + +// The request carries neither an app ID nor an option path. Only the host's +// launch grant selects the panel projection and the app's literal namespace. +func TestModuleRPCAppGrantPatchesOnlyProjectedSettings(t *testing.T) { + root, other := t.TempDir(), t.TempDir() + client, _ := moduleFixtureClient(t, map[string]string{"one": root, "two": other}) + const fixture = `{ + outputs = { self }: let + cfg = import ./.stack/config.nix; + projected = app: { + inherit (app.demo) label retries; + "with.dot" = app.demo."with.dot" or "default"; + fixed = "evaluated constant"; + }; + in { legacyPackages.fixture.stackpanelSerializable = { + modulesListAll = [{id="demo"; enabled=true; settings = cfg.modules.demo.settings;}]; + apps = builtins.mapAttrs (_: _: {enable=true;}) cfg.apps; + panelsList = [{id="preview"; module="demo"; enabled=true; type="PANEL_TYPE_CUSTOM"; slot="app:tab"; + apps = builtins.mapAttrs (_: app: {enabled=true; config=builtins.mapAttrs (_: v: toString v) (projected app);}) cfg.apps; + uiBundle = {package=toString (builtins.path {path=./bundle; name="panel";}); entry="index.html"; + permissions = if cfg.apps.web.demo.label == "revoke" then ["config:read"] else ["config:read" "config:patch"]; + appSettings = builtins.mapAttrs (_: projected) cfg.apps; + appSchemas = builtins.mapAttrs (id: _: { + type = "object"; additionalProperties = false; + properties = { + label.type = "string"; fixed.type = "string"; "with.dot".type = "string"; + retries.type = if id == "web" then builtins.readFile ./retry-type else "integer"; + }; + }) cfg.apps; + }; + }]; + }; }; +}` + const config = `{ + modules.demo.settings.label = "global"; + apps.web.demo.label = "web"; + apps.web.demo.retries = 1; + apps.web.demo.hidden = "PRIVATE"; + apps.web.other.label = "unrelated"; # preserve me + apps.api.demo = { label = "api"; retries = 2; }; +} +` + for _, dir := range []string{root, other} { + moduleFixtureFile(t, dir, "flake.nix", fixture) + moduleFixtureFile(t, dir, ".stack/config.nix", config) + moduleFixtureFile(t, dir, "bundle/index.html", "scoped") + moduleFixtureFile(t, dir, "retry-type", "integer") + } + open := func(app, grant string) (*connect.Response[agentv1.OpenModuleUIResponse], error) { + req := moduleFixtureRequest( + "one", + &agentv1.OpenModuleUIRequest{ModuleId: "demo", PanelId: "preview", AppId: app}, + ) + req.Header().Set("Origin", "https://stackpanel.com") + if grant == "" { + state, err := loadModuleState(t.Context(), &projectRuntime{root: root}) + require.NoError(t, err) + req.Msg.ReviewRevision = testReviewRevision(t, root, moduleStoreRoot, state, "demo", "preview") + } + if grant != "" { + req.Header().Set(moduleUIGrantHeader, grant) + } + return client.OpenModuleUI(t.Context(), req) + } + launch, err := open("web", "") + require.NoError(t, err) + grant := launch.Header().Get(moduleUIGrantHeader) + require.NotEmpty(t, grant) + require.Equal(t, "web", launch.Msg.GetSettings().AsMap()["label"]) + require.NotContains(t, launch.Msg.GetSettings().AsMap(), "hidden") + patch := func(project, id, token string, data map[string]any) error { + settings, err := structpb.NewStruct(data) + require.NoError(t, err) + req := moduleFixtureRequest( + project, + &agentv1.UpdateModuleConfigRequest{ModuleId: id, Settings: settings}, + ) + req.Header().Set(moduleUIGrantHeader, token) + _, err = client.UpdateModuleConfig(t.Context(), req) + return err + } + beforeOther := moduleFixtureSnapshot(t, other) + value := "${literal}" + require.NoError( + t, + patch( + "one", + "demo", + grant, + map[string]any{"label": "edited", "retries": 3, "with.dot": value}, + ), + ) + fresh, err := open("web", grant) + require.NoError(t, err) + require.Equal( + t, + map[string]any{ + "label": "edited", + "retries": float64(3), + "with.dot": value, + "fixed": "evaluated constant", + }, + fresh.Msg.GetSettings().AsMap(), + ) + second, err := open("api", "") + require.NoError(t, err) + require.Equal(t, "api", second.Msg.GetSettings().AsMap()["label"]) + _, err = open("api", grant) + require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err)) + boundRead := moduleFixtureRequest("one", &agentv1.GetModuleRequest{ModuleId: "demo"}) + boundRead.Header().Set(moduleUIGrantHeader, grant) + _, err = client.GetModule(t.Context(), boundRead) + require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err)) + global, err := client.GetModule( + t.Context(), + moduleFixtureRequest("one", &agentv1.GetModuleRequest{ModuleId: "demo"}), + ) + require.NoError(t, err) + require.Equal(t, "global", global.Msg.Module.Settings.AsMap()["label"]) + before := moduleFixtureSnapshot(t, root) + require.Contains( + t, + before[filepath.Join(root, ".stack/config.nix")], + `apps.web.other.label = "unrelated"; # preserve me`, + ) + for _, tc := range []struct { + project, id, token, key, value string + code connect.Code + }{ + {"one", "demo", grant, "hidden", "overwrite", connect.CodePermissionDenied}, + {"one", "demo", grant, "apps.api.demo.label", "overwrite", connect.CodePermissionDenied}, + {"one", "demo", grant, "fixed", "ignored", connect.CodeFailedPrecondition}, + {"one", "demo", grant, "label", "revoke", connect.CodePermissionDenied}, + {"one", "other", grant, "label", "wrong-module", connect.CodePermissionDenied}, + {"two", "demo", grant, "label", "wrong-project", connect.CodePermissionDenied}, + {"one", "demo", "", "label", "empty-grant", connect.CodePermissionDenied}, + } { + err := patch(tc.project, tc.id, tc.token, map[string]any{tc.key: tc.value}) + require.Equal(t, tc.code, connect.CodeOf(err), "%s=%s", tc.key, tc.value) + require.Equal(t, before, moduleFixtureSnapshot(t, root)) + require.Equal(t, beforeOther, moduleFixtureSnapshot(t, other)) + } + // Both schemas accept the existing value 3. Only the selected app's + // declared type changed: rejecting the old grant must precede any write. + moduleFixtureFile(t, root, "retry-type", "number") + afterSchemaChange := moduleFixtureSnapshot(t, root) + err = patch("one", "demo", grant, map[string]any{"label": "stale"}) + require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err)) + require.Equal(t, afterSchemaChange, moduleFixtureSnapshot(t, root)) + reopened, err := open("web", "") + require.NoError(t, err) + require.NoError( + t, + patch( + "one", + "demo", + reopened.Header().Get(moduleUIGrantHeader), + map[string]any{"label": "fresh"}, + ), + ) +} + +func TestModuleActivationCannotEditProtectedSettings(t *testing.T) { + if _, err := exec.LookPath("nix"); err != nil { + t.Skip("requires Nix flakes") + } + root := t.TempDir() + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "config.yaml")) + t.Setenv("NIX_SYSTEM", "fixture") + moduleFixtureFile(t, root, "flake.nix", `{ outputs = { self }: { + legacyPackages.fixture.stackpanelSerializable.modulesListAll = map (id: { + inherit id; enablePath = "secrets.enable"; configPath = "secrets"; + enabled = (import ./.stack/config.nix).secrets.enable; + }) [ "secrets" "unrelated" ]; +}; }`) + moduleFixtureFile( + t, + root, + ".stack/config.nix", + `{ secrets = { enable = true; marker = "untouched"; }; }`, + ) + ctx, modules, err := NewLocalModules(t.Context(), root) + require.NoError(t, err) + before := moduleFixtureSnapshot(t, root) + _, err = modules.DisableModule( + ctx, + connect.NewRequest(&agentv1.DisableModuleRequest{ModuleId: "unrelated"}), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err)) + settings, err := structpb.NewStruct(map[string]any{"marker": "changed"}) + require.NoError(t, err) + _, err = modules.UpdateModuleConfig( + ctx, + connect.NewRequest( + &agentv1.UpdateModuleConfigRequest{ModuleId: "secrets", Settings: settings}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err)) + require.Equal(t, before, moduleFixtureSnapshot(t, root)) + _, err = modules.DisableModule( + ctx, + connect.NewRequest(&agentv1.DisableModuleRequest{ModuleId: "secrets"}), + ) + require.NoError(t, err) + module, err := modules.GetModule( + ctx, + connect.NewRequest(&agentv1.GetModuleRequest{ModuleId: "secrets"}), + ) + require.NoError(t, err) + require.False(t, module.Msg.Module.Enabled) +} diff --git a/apps/stackpanel-go/internal/agent/server/connect_v1_project.go b/apps/stackpanel-go/internal/agent/server/connect_v1_project.go index 7f596a36..ddb73fe3 100644 --- a/apps/stackpanel-go/internal/agent/server/connect_v1_project.go +++ b/apps/stackpanel-go/internal/agent/server/connect_v1_project.go @@ -9,6 +9,7 @@ import ( "connectrpc.com/connect" + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1/agentv1connect" "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/project" ) @@ -37,7 +38,7 @@ type projectInterceptor struct { func (p projectInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc { return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) { - ctx, err := p.attach(ctx, req.Header()) + ctx, err := p.attach(ctx, req.Spec().Procedure, req.Header()) if err != nil { return nil, err } @@ -45,13 +46,17 @@ func (p projectInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc } } -func (p projectInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc { +func (p projectInterceptor) WrapStreamingClient( + next connect.StreamingClientFunc, +) connect.StreamingClientFunc { return next } -func (p projectInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc { +func (p projectInterceptor) WrapStreamingHandler( + next connect.StreamingHandlerFunc, +) connect.StreamingHandlerFunc { return func(ctx context.Context, conn connect.StreamingHandlerConn) error { - ctx, err := p.attach(ctx, conn.RequestHeader()) + ctx, err := p.attach(ctx, conn.Spec().Procedure, conn.RequestHeader()) if err != nil { return err } @@ -59,16 +64,75 @@ func (p projectInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFu } } -func (p projectInterceptor) attach(ctx context.Context, header http.Header) (context.Context, error) { +func (p projectInterceptor) attach( + ctx context.Context, + procedure string, + header http.Header, +) (context.Context, error) { + if strings.HasPrefix(procedure, "/"+agentv1connect.ModuleServiceName+"/") { + if _, bound := header[http.CanonicalHeaderKey(moduleUIGrantHeader)]; bound { + switch procedure { + case agentv1connect.ModuleServiceUpdateModuleConfigProcedure, + agentv1connect.ModuleServiceRunModuleActionProcedure, + agentv1connect.ModuleServiceOpenModuleUIProcedure: + // These methods revalidate the grant against the evaluated project. + default: + return nil, connect.NewError( + connect.CodePermissionDenied, + errors.New("UI grant does not authorize this operation"), + ) + } + } + readOnly := false + switch procedure { + case agentv1connect.ModuleServiceListModulesProcedure, + agentv1connect.ModuleServiceGetModuleProcedure, + agentv1connect.ModuleServiceGetModuleOutputsProcedure, + agentv1connect.ModuleServicePreviewModuleEnableProcedure, + agentv1connect.ModuleServiceListRegistryModulesProcedure, + agentv1connect.ModuleServiceGetRegistryModuleProcedure: + readOnly = true + } + values := header.Values(projectHeader) + if !readOnly || len(values) > 0 { + if len(values) != 1 || strings.TrimSpace(values[0]) == "" || + strings.Contains(values[0], ",") { + return nil, connect.NewError( + connect.CodeInvalidArgument, + errors.New("send exactly one nonempty "+projectHeader), + ) + } + } + } + rt, err := p.requestRuntime(header) + if err != nil { + return nil, err + } + return context.WithValue(ctx, runtimeKey{}, rt), nil +} + +// Panel reads, inline edits, and module RPCs must agree on the selected project. +func (s *Server) requestRuntime(header http.Header) (*projectRuntime, error) { + return (projectInterceptor{resolve: s.resolveProjectRoot, runtimes: s.runtimes}).requestRuntime( + header, + ) +} + +func (p projectInterceptor) requestRuntime( + header http.Header, +) (*projectRuntime, error) { root, err := p.resolve(strings.TrimSpace(header.Get(projectHeader))) if err != nil { return nil, err } rt, err := p.runtimes.get(root) if err != nil { - return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("start project runtime: %w", err)) + return nil, connect.NewError( + connect.CodeInternal, + fmt.Errorf("start project runtime: %w", err), + ) } - return context.WithValue(ctx, runtimeKey{}, rt), nil + return rt, nil } // resolveProjectRoot maps a request's project ID to a project root. Without @@ -81,7 +145,10 @@ func (s *Server) resolveProjectRoot(projectID string) (string, error) { if projectID != "" { p := registry.GetProjectByID(projectID) if p == nil { - return "", connect.NewError(connect.CodeNotFound, fmt.Errorf("unknown project %q", projectID)) + return "", connect.NewError( + connect.CodeNotFound, + fmt.Errorf("unknown project %q", projectID), + ) } if err := project.QuickValidate(p.Path); err != nil { return "", connect.NewError(connect.CodeFailedPrecondition, diff --git a/apps/stackpanel-go/internal/agent/server/connect_v1_test.go b/apps/stackpanel-go/internal/agent/server/connect_v1_test.go index d57754fb..044b85ca 100644 --- a/apps/stackpanel-go/internal/agent/server/connect_v1_test.go +++ b/apps/stackpanel-go/internal/agent/server/connect_v1_test.go @@ -36,7 +36,10 @@ func TestGetAgentInfoIsPublicAndListsServedProcedures(t *testing.T) { srv := newV1TestServer(t) client := agentv1connect.NewAgentServiceClient(srv.Client(), srv.URL) - res, err := client.GetAgentInfo(context.Background(), connect.NewRequest(&agentv1.GetAgentInfoRequest{})) + res, err := client.GetAgentInfo( + context.Background(), + connect.NewRequest(&agentv1.GetAgentInfoRequest{}), + ) if err != nil { t.Fatalf("GetAgentInfo without a token: %v", err) } @@ -49,6 +52,7 @@ func TestGetAgentInfoIsPublicAndListsServedProcedures(t *testing.T) { agentv1connect.ProjectServiceAddProjectProcedure, agentv1connect.ProjectServiceRemoveProjectProcedure, agentv1connect.ProjectServiceSetDefaultProjectProcedure, + agentv1connect.ModuleServiceGetModuleProcedure, } { if !slices.Contains(res.Msg.GetProcedures(), want) { t.Errorf("procedures missing %s; got %v", want, res.Msg.GetProcedures()) @@ -119,7 +123,9 @@ func TestV1RejectsOversizedRequestsBeforeAuth(t *testing.T) { var wireBytes atomic.Int64 projects := &recordingProjects{} mux := http.NewServeMux() - routes := newV1Routes(testV1Deps(func(string) bool { authRan.Store(true); return false }, projects)) + routes := newV1Routes( + testV1Deps(func(string) bool { authRan.Store(true); return false }, projects), + ) for _, r := range routes { mux.Handle(r.path, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { req.Body = countingBody{req.Body, &wireBytes} @@ -138,22 +144,37 @@ func TestV1RejectsOversizedRequestsBeforeAuth(t *testing.T) { maxWireBytes int64 }{ {"uncompressed", nil, 0}, - {"gzip inflates past the limit", []connect.ClientOption{connect.WithSendGzip()}, 64 << 10}, + { + "gzip inflates past the limit", + []connect.ClientOption{connect.WithSendGzip()}, + 64 << 10, + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { wireBytes.Store(0) - client := agentv1connect.NewProjectServiceClient(srv.Client(), srv.URL, tc.opts...) + client := agentv1connect.NewProjectServiceClient( + srv.Client(), + srv.URL, + tc.opts...) // An invalid token: if auth ran first, the call would fail with // Unauthenticated instead. req := connect.NewRequest(&agentv1.AddProjectRequest{Path: path}) req.Header().Set("Authorization", "Bearer bad") _, err := client.AddProject(context.Background(), req) if got := connect.CodeOf(err); got != connect.CodeResourceExhausted { - t.Fatalf("code = %v, want %v (err: %v)", got, connect.CodeResourceExhausted, err) + t.Fatalf( + "code = %v, want %v (err: %v)", + got, + connect.CodeResourceExhausted, + err, + ) } if tc.maxWireBytes > 0 && wireBytes.Load() > tc.maxWireBytes { - t.Errorf("sent %d bytes; the gzip case must fail on the inflated size", wireBytes.Load()) + t.Errorf( + "sent %d bytes; the gzip case must fail on the inflated size", + wireBytes.Load(), + ) } }) } @@ -167,13 +188,17 @@ func TestV1RejectsOversizedRequestsBeforeAuth(t *testing.T) { // testV1Deps wires the v1 routes with the given token check and project // service; project-scoped services resolve every request to /p/test. -func testV1Deps(validToken func(string) bool, projects agentv1connect.ProjectServiceHandler) v1Deps { +func testV1Deps( + validToken func(string) bool, + projects agentv1connect.ProjectServiceHandler, +) v1Deps { registry, _ := newTestRegistry() return v1Deps{ version: "1.2.3", validToken: validToken, projects: projects, shell: agentv1connect.UnimplementedShellServiceHandler{}, + modules: agentv1connect.UnimplementedModuleServiceHandler{}, scope: projectInterceptor{ resolve: func(string) (string, error) { return "/p/test", nil }, runtimes: registry, diff --git a/apps/stackpanel-go/internal/agent/server/cors_auth.go b/apps/stackpanel-go/internal/agent/server/cors_auth.go index 9cdfd7c8..8d8e3b71 100644 --- a/apps/stackpanel-go/internal/agent/server/cors_auth.go +++ b/apps/stackpanel-go/internal/agent/server/cors_auth.go @@ -28,10 +28,15 @@ func (s *Server) withLogging(next http.HandlerFunc) http.HandlerFunc { } duration := time.Since(start) + path := r.URL.Path + if strings.HasPrefix(path, "/api/v1/modules/") { + // Asset paths carry read-only bearer tickets; proxy paths are service data. + path = "/api/v1/modules/[redacted]" + } log.Debug(). Str("method", r.Method). - Str("path", r.URL.Path). + Str("path", path). Int("status", wrapped.statusCode). Dur("duration", duration). Str("origin", r.Header.Get("Origin")). @@ -80,12 +85,12 @@ func (s *Server) withCORS(next http.HandlerFunc) http.HandlerFunc { w.Header().Set("Vary", "Origin") // Include Connect-RPC headers: connect-protocol-version, connect-timeout-ms w.Header(). - Set("Access-Control-Allow-Headers", "content-type, authorization, x-stackpanel-token, x-stackpanel-project, connect-protocol-version, connect-timeout-ms") + Set("Access-Control-Allow-Headers", "content-type, authorization, x-stackpanel-token, x-stackpanel-project, x-stackpanel-ui-grant, connect-protocol-version, connect-timeout-ms") w.Header(). Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") // Expose Connect-RPC headers in responses w.Header(). - Set("Access-Control-Expose-Headers", "connect-protocol-version, grpc-status, grpc-message") + Set("Access-Control-Expose-Headers", "connect-protocol-version, grpc-status, grpc-message, x-stackpanel-ui-grant, x-stackpanel-ui-expires-at") // Private Network Access (PNA) preflight support (Chrome) w.Header().Set("Access-Control-Allow-Private-Network", "true") } diff --git a/apps/stackpanel-go/internal/agent/server/flake_watcher.go b/apps/stackpanel-go/internal/agent/server/flake_watcher.go index b5a63bfa..0fc12dea 100644 --- a/apps/stackpanel-go/internal/agent/server/flake_watcher.go +++ b/apps/stackpanel-go/internal/agent/server/flake_watcher.go @@ -3,502 +3,659 @@ package server import ( "context" "encoding/json" + "errors" + "io/fs" + "maps" "os" "path/filepath" + "reflect" + "strings" "sync" "time" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" "github.com/fsnotify/fsnotify" "github.com/rs/zerolog/log" ) -// FlakeWatcher monitors .nix files for changes and re-evaluates flake outputs -// (.#stackpanelConfig and .#stackpanelPackages) in the background. Results are -// cached and served to API handlers; changes trigger SSE events so the web UI -// can refresh without polling. -// -// This is the "expensive" watcher — it runs `nix eval` which can take seconds. -// Compare with watchConfigFiles() which just broadcasts file-change notifications. +type flakeEvaluator interface { + Eval(context.Context) ([]byte, error) + Invalidate() +} + +// FlakeWatcher caches flake outputs for one project. A separate worker runs +// Nix so even cold evaluations don't block fsnotify or lose newly created dirs. type FlakeWatcher struct { projectRoot string watcher *fsnotify.Watcher server *Server + shell *ShellManager + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup - configEvaluator *nixeval.Evaluator - packagesEvaluator *nixeval.Evaluator + configEvaluator flakeEvaluator + packagesEvaluator flakeEvaluator + configEvalMu sync.Mutex + packagesEvalMu sync.Mutex mu sync.RWMutex cachedConfig map[string]any cachedPackages []nixeval.InstalledPackage configUpdated time.Time pkgsUpdated time.Time - - stopCh chan struct{} + links map[string]userconfig.LinkedModule // replaced, never mutated + linkVersion uint64 + linkErr error + diagnostics ModuleDevDiagnostics } -// FlakeWatcherConfig configures the FlakeWatcher type FlakeWatcherConfig struct { ProjectRoot string Server *Server + Shell *ShellManager } -// NewFlakeWatcher creates a new FlakeWatcher for monitoring flake outputs func NewFlakeWatcher(cfg FlakeWatcherConfig) (*FlakeWatcher, error) { - watcher, err := fsnotify.NewWatcher() + if cfg.ProjectRoot == "" { + return nil, errors.New("flake watcher requires a project root") + } + root, err := filepath.Abs(cfg.ProjectRoot) if err != nil { return nil, err } - - // Config evaluator tries multiple flake attr paths in order: - // 1. devShell passthru (how user projects expose config) - // 2. Direct flake output (how the stackpanel repo itself exposes config) - // stackpanelFullConfig is intentionally excluded — it contains functions and - // other non-serializable Nix values that break JSON output. - configEval, err := nixeval.New( - cfg.ProjectRoot, - nixeval.WithFlakeAttrFallbacks([]string{ - ".#devShells." + getCurrentSystem() + ".default.passthru.stackpanelSerializable", - ".#devShells." + getCurrentSystem() + ".default.passthru.stackpanelConfig", - ".#stackpanelConfig", - }), - nixeval.WithTimeout(30*time.Second), - nixeval.WithCacheTTL(10*time.Second), - ) + // The editor reads full configuration; module RPCs use a restricted output. + configEval, err := nixeval.New(root, "stackpanelConfig", nixeval.WithTimeout(30*time.Second)) if err != nil { - watcher.Close() return nil, err } - - // Packages evaluator uses the same fallback pattern as config. - packagesEval, err := nixeval.New( - cfg.ProjectRoot, - nixeval.WithFlakeAttrFallbacks([]string{ - ".#devShells." + getCurrentSystem() + ".default.passthru.stackpanelPackages", - ".#stackpanelPackages", - }), - nixeval.WithTimeout(30*time.Second), - nixeval.WithCacheTTL(10*time.Second), - ) + packagesEval, err := nixeval.New(root, "stackpanelPackages", nixeval.WithTimeout(30*time.Second)) if err != nil { - watcher.Close() return nil, err } - - fw := &FlakeWatcher{ - projectRoot: cfg.ProjectRoot, + watcher, err := fsnotify.NewWatcher() + if err != nil { + return nil, err + } + ctx, cancel := context.WithCancel(context.Background()) + return &FlakeWatcher{ + projectRoot: root, watcher: watcher, server: cfg.Server, + shell: cfg.Shell, + ctx: ctx, + cancel: cancel, configEvaluator: configEval, packagesEvaluator: packagesEval, - stopCh: make(chan struct{}), - } - - return fw, nil + diagnostics: ModuleDevDiagnostics{ + ProjectID: userconfig.GenerateProjectID( + root, + ), + LinkedModules: map[string]LinkedModuleStatus{}, + }, + }, nil } -// Start begins watching for file changes and evaluating flake outputs func (fw *FlakeWatcher) Start() error { - // Watch paths that affect flake evaluation - watchPaths := []string{ - filepath.Join(fw.projectRoot, "flake.nix"), - filepath.Join(fw.projectRoot, "flake.lock"), - filepath.Join(fw.projectRoot, ".stack"), - filepath.Join(fw.projectRoot, ".stackpanel"), - filepath.Join(fw.projectRoot, "nix"), - } - - for _, path := range watchPaths { - if err := fw.addWatchRecursive(path); err != nil { - log.Debug().Err(err).Str("path", path).Msg("Failed to watch path (may not exist)") + configPath, err := filepath.Abs(userconfig.GetConfigPath()) + if err != nil { + _ = fw.Stop() + return err + } + paths := flakeWatchPaths{ + watcher: fw.watcher, + project: fw.projectRoot, + config: configPath, + dirs: make(map[string]bool), + } + // Arm the config parent before reading links: a link/unlink during startup + // must either be seen by LoadLinkedModules or queued as an event. + paths.watchParent(configPath, paths.dirs) + links, _ := fw.reloadLinks() + paths.reconcile(links) + jobs := make(chan flakeChange) + fw.wg.Go(func() { fw.watchLoop(&paths, jobs) }) + fw.wg.Go(func() { + fw.refresh(flakeChange{packages: true}) // initial eval also publishes diagnostics + for change := range jobs { + fw.refresh(change) } + }) + return nil +} + +func (fw *FlakeWatcher) Stop() error { + fw.cancel() + err := fw.watcher.Close() + fw.wg.Wait() + return err +} + +// DevDiagnostics does not depend on the evaluated config: the toolbar still +// sees which inputs are linked and why evaluation failed with a broken flake. +func (fw *FlakeWatcher) DevDiagnostics() ModuleDevDiagnostics { + fw.mu.RLock() + defer fw.mu.RUnlock() + snapshot := fw.diagnostics + snapshot.LinkedModules = maps.Clone(snapshot.LinkedModules) + if snapshot.DurationMs != nil { + d := *snapshot.DurationMs + snapshot.DurationMs = &d } + return snapshot +} - // Do initial evaluation - go fw.initialEvaluation() +const invalidLinksSummary = "Invalid project link configuration." - // Start the watch loop - go fw.watchLoop() +var ( + errInvalidLinks = errors.New(invalidLinksSummary) + errLinksChanged = errors.New("project links changed during evaluation") +) - log.Info().Str("projectRoot", fw.projectRoot).Msg("FlakeWatcher started") - return nil +func (fw *FlakeWatcher) reloadLinks() (map[string]userconfig.LinkedModule, bool) { + links, err := userconfig.LoadLinkedModules(fw.projectRoot) + if err != nil { + log.Warn().Msg("Failed to read project links") + // Validation errors may quote arbitrary YAML, including values from + // other projects. Do not forward them or retain stale HMR authority. + links, err = nil, errInvalidLinks + } + fw.mu.Lock() + defer fw.mu.Unlock() + if fw.linkErr == err && maps.Equal(fw.links, links) { + return links, false + } + fw.links, fw.linkErr = links, err + fw.linkVersion++ + fw.cachedConfig, fw.cachedPackages = nil, nil + status := make(map[string]LinkedModuleStatus, len(links)) + for id, link := range links { + // Only the validated origin is display metadata. OpenModuleUI reads + // the full author-specified target separately, from machine config. + origin, _ := normalizeOrigin(link.UIDevURL) + status[id] = LinkedModuleStatus{UIDevURL: origin} + } + fw.diagnostics = ModuleDevDiagnostics{ + ProjectID: fw.diagnostics.ProjectID, + LinkedModules: status, + } + fw.diagnostics.Error = devEvalSummary(err) + fw.publish(moduleDevDiagnosticsEvent, fw.diagnostics) + return links, true } -// Stop stops the FlakeWatcher -func (fw *FlakeWatcher) Stop() error { - close(fw.stopCh) - if fw.watcher != nil { - return fw.watcher.Close() +func (fw *FlakeWatcher) publish(event string, data any) { + if fw.server != nil && fw.ctx.Err() == nil { + fw.server.broadcastSSE( + SSEEvent{ProjectRoot: fw.projectRoot, Event: event, Data: data}, + ) } - return nil } -// GetConfig returns the cached config or evaluates if not cached +// Always invalidate the evaluator's own TTL cache on a real evaluation. A +// README save within a few ms of the last eval still needs fresh Nix output. +func evalFlakeJSON(ctx context.Context, ev flakeEvaluator, dest any) error { + ev.Invalidate() + b, err := ev.Eval(ctx) + if err != nil { + return err + } + return json.Unmarshal(b, dest) +} + func (fw *FlakeWatcher) GetConfig(ctx context.Context) (map[string]any, error) { fw.mu.RLock() - if fw.cachedConfig != nil { - config := fw.cachedConfig - fw.mu.RUnlock() - return config, nil - } + cached := fw.cachedConfig fw.mu.RUnlock() - - return fw.evaluateConfig(ctx) + if cached != nil { + return cached, nil + } + return fw.evaluateConfig(ctx, false) } -// GetPackages returns the cached packages or evaluates if not cached -func (fw *FlakeWatcher) GetPackages( +func (fw *FlakeWatcher) evaluateConfig( ctx context.Context, -) ([]nixeval.InstalledPackage, error) { + force bool, +) (map[string]any, error) { + fw.configEvalMu.Lock() + defer fw.configEvalMu.Unlock() fw.mu.RLock() - if fw.cachedPackages != nil { - packages := fw.cachedPackages - fw.mu.RUnlock() - return packages, nil - } + cached, version, err := fw.cachedConfig, fw.linkVersion, fw.linkErr fw.mu.RUnlock() - - return fw.evaluatePackages(ctx) -} - -// initialEvaluation runs on startup in a goroutine. The generous 5-minute timeout -// accounts for cold Nix caches that may need to download substitutes. -func (fw *FlakeWatcher) initialEvaluation() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) - defer cancel() - - // Evaluate config first (usually faster) - if _, err := fw.evaluateConfig(ctx); err != nil { - log.Warn().Err(err).Msg("Initial config evaluation failed") - } else { - log.Debug().Msg("Initial config evaluation succeeded") + if !force && cached != nil { + return cached, nil } - - // Then evaluate packages - if _, err := fw.evaluatePackages(ctx); err != nil { - log.Warn().Err(err).Msg("Initial packages evaluation failed") + start := time.Now() + var config map[string]any + if err == nil { + err = evalFlakeJSON(ctx, fw.configEvaluator, &config) + if err == nil && config == nil { + err = errors.New("expected evaluated flake config to be an object, got null") + } + } + end := time.Now() + duration := end.Sub(start).Milliseconds() + msg := devEvalSummary(err) + fw.mu.Lock() + defer fw.mu.Unlock() + if fw.linkVersion != version { + // An unlink or relink supersedes even an in-flight initial evaluation. + return nil, errLinksChanged + } + if errors.Is(ctx.Err(), context.Canceled) { + return nil, ctx.Err() + } + fw.diagnostics.EvaluatedAt = end.UTC().Format(time.RFC3339Nano) + fw.diagnostics.DurationMs, fw.diagnostics.Error = &duration, msg + if err == nil { + fw.cachedConfig, fw.configUpdated = config, end } else { - log.Debug().Msg("Initial packages evaluation succeeded") + fw.cachedConfig, config = nil, nil } + fw.publish(moduleDevDiagnosticsEvent, fw.diagnostics) + return config, err } -// evaluateConfig evaluates .#stackpanelConfig and caches the result -func (fw *FlakeWatcher) evaluateConfig(ctx context.Context) (map[string]any, error) { - result, err := fw.configEvaluator.Eval(ctx) - if err != nil { - return nil, err +// Return only fixed public messages. Nix can quote an entire expression, +// environment value, or arbitrary author-supplied throw string in stderr; +// redacting paths or truncating source lines cannot make that safe for SSE. +func devEvalSummary(err error) string { + switch { + case err == nil: + return "" + case errors.Is(err, errInvalidLinks): + return invalidLinksSummary + case errors.Is(err, context.DeadlineExceeded): + return "Nix evaluation timed out." + } + text := err.Error() + switch { + case strings.Contains(text, "timed out"), + strings.Contains(text, "context deadline exceeded"): + return "Nix evaluation timed out." + case strings.Contains(text, "syntax error"): + return "Nix syntax error." + case strings.Contains(text, "infinite recursion"): + return "Nix evaluation encountered infinite recursion." + case strings.Contains(text, "type error"), + strings.Contains(text, "not of type"), + strings.Contains(text, "cannot coerce"): + return "Nix type error." + default: + return "Nix evaluation failed." } +} - var config map[string]any - if err := json.Unmarshal(result, &config); err != nil { - return nil, err +func (fw *FlakeWatcher) GetPackages( + ctx context.Context, +) ([]nixeval.InstalledPackage, error) { + fw.mu.RLock() + cached := fw.cachedPackages + fw.mu.RUnlock() + if cached != nil { + return cached, nil } - - fw.mu.Lock() - fw.cachedConfig = config - fw.configUpdated = time.Now() - fw.mu.Unlock() - - return config, nil + return fw.evaluatePackages(ctx, false) } -// evaluatePackages evaluates .#stackpanelPackages and caches the result func (fw *FlakeWatcher) evaluatePackages( ctx context.Context, + force bool, ) ([]nixeval.InstalledPackage, error) { - result, err := fw.packagesEvaluator.Eval(ctx) + fw.packagesEvalMu.Lock() + defer fw.packagesEvalMu.Unlock() + fw.mu.RLock() + cached, version, err := fw.cachedPackages, fw.linkVersion, fw.linkErr + fw.mu.RUnlock() + if !force && cached != nil { + return cached, nil + } + var pkgs []nixeval.InstalledPackage + if err == nil { + err = evalFlakeJSON(ctx, fw.packagesEvaluator, &pkgs) + } + fw.mu.Lock() + defer fw.mu.Unlock() + if fw.linkVersion != version { + return nil, errLinksChanged + } if err != nil { + fw.cachedPackages = nil return nil, err } + fw.cachedPackages, fw.pkgsUpdated = pkgs, time.Now() + return pkgs, nil +} - var packages []nixeval.InstalledPackage - if err := json.Unmarshal(result, &packages); err != nil { - return nil, err - } +type flakeChange struct { + trigger string // project-relative path, or a symbolic reason for external changes + packages bool + linked bool // module-safe output can change without changing the full config +} - fw.mu.Lock() - fw.cachedPackages = packages - fw.pkgsUpdated = time.Now() - fw.mu.Unlock() +func (fw *FlakeWatcher) refresh(change flakeChange) { + if fw.ctx.Err() != nil { + return + } + if change.trigger != "" && fw.shell != nil { + fw.shell.MarkNixFileChanged(filepath.Join(fw.projectRoot, change.trigger)) + } + fw.mu.RLock() + oldConfig, oldPackages := fw.cachedConfig, fw.cachedPackages + id := fw.diagnostics.ProjectID + fw.mu.RUnlock() + config, err := fw.evaluateConfig(fw.ctx, true) + if err != nil { + log.Warn(). + Str("error", devEvalSummary(err)). + Str("projectId", id). + Msg("Flake config evaluation failed") + + } else if change.trigger != "" && (change.linked || !reflect.DeepEqual(oldConfig, config)) { + fw.publish("flake.config.updated", map[string]any{ + "projectId": id, + "timestamp": time.Now().UTC().Format(time.RFC3339Nano), + "trigger": change.trigger, + }) + } + if !change.packages || fw.ctx.Err() != nil { + return + } + pkgs, err := fw.evaluatePackages(fw.ctx, true) + if err != nil { + log.Warn(). + Str("error", devEvalSummary(err)). + Str("projectId", id). + Msg("Flake packages evaluation failed") + } else if change.trigger != "" && !reflect.DeepEqual(oldPackages, pkgs) { + fw.publish("flake.packages.updated", map[string]any{ + "projectId": id, + "timestamp": time.Now().UTC().Format(time.RFC3339Nano), + "trigger": change.trigger, + "count": len(pkgs), + }) + } +} - return packages, nil +// The watch loop alone owns these maps. Directory watches survive atomic saves; +// anchor parents let us notice when even a source root is created or replaced. +type flakeWatchPaths struct { + watcher *fsnotify.Watcher + project string + config string + links map[string]userconfig.LinkedModule + roots map[string]string // recursive source dir -> input id (empty for project sources) + dirs map[string]bool } -// addWatchRecursive adds a path and its subdirectories to the watcher -func (fw *FlakeWatcher) addWatchRecursive(path string) error { - return filepath.Walk(path, func(p string, info os.FileInfo, err error) error { - if err != nil { - return nil // Skip inaccessible paths - } - // Only watch directories - if info.IsDir() { - _ = fw.watcher.Add(p) +func (p *flakeWatchPaths) watchDir(dir string, wanted map[string]bool) { + if wanted[dir] { + return + } + if err := p.watcher.Add(dir); err != nil { + if !os.IsNotExist(err) { + log.Warn().Err(err).Str("dir", dir).Msg("Cannot watch flake source directory") } - return nil - }) + return + } + wanted[dir] = true } -// watchLoop handles file system events and triggers re-evaluation. -// Uses a 500ms debounce (longer than watchConfigFiles' 100ms) because nix eval -// is expensive and we want to coalesce rapid edits into a single evaluation. -func (fw *FlakeWatcher) watchLoop() { - var debounceTimer *time.Timer - debounceDuration := 500 * time.Millisecond - - for { - select { - case <-fw.stopCh: - if debounceTimer != nil { - debounceTimer.Stop() - } - return - - case event, ok := <-fw.watcher.Events: - if !ok { - return - } - - // Only react to write, create, or remove events - if event.Op&(fsnotify.Write|fsnotify.Create|fsnotify.Remove) == 0 { - continue - } - - // Only .nix, .json, and .lock files can affect flake evaluation - ext := filepath.Ext(event.Name) - if ext != ".nix" && ext != ".json" && ext != ".lock" { - continue - } - - log.Debug(). - Str("file", event.Name). - Str("op", event.Op.String()). - Msg("Relevant file changed") - - // Debounce: reset timer on each event - if debounceTimer != nil { - debounceTimer.Stop() - } - - debounceTimer = time.AfterFunc(debounceDuration, func() { - fw.handleFileChange(event.Name) - }) - - case err, ok := <-fw.watcher.Errors: - if !ok { +func (p *flakeWatchPaths) watchParent(target string, wanted map[string]bool) { + for dir := filepath.Dir(target); ; dir = filepath.Dir(dir) { + if info, err := os.Stat(dir); err == nil && info.IsDir() { + p.watchDir(dir, wanted) + if wanted[dir] { return } - log.Warn().Err(err).Msg("FlakeWatcher error") + } + if filepath.Dir(dir) == dir { + return } } } -// handleFileChange handles a file change event after debouncing. It selectively -// re-evaluates config and/or packages based on which file changed, then only -// broadcasts SSE events if the evaluated output actually differs from the cache. -func (fw *FlakeWatcher) handleFileChange(changedFile string) { - log.Info(). - Str("file", changedFile). - Msg("Re-evaluating flake outputs due to file change") - - // Notify shell manager that nix files changed (shell may be stale) - if fw.server != nil && fw.server.shellManager != nil { - fw.server.shellManager.MarkNixFileChanged(changedFile) - } - - // 5 minutes allows time for Nix to download packages from caches - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) - defer cancel() - - // Determine what needs to be re-evaluated based on the file that changed - filename := filepath.Base(changedFile) - - // If packages.nix changed, definitely re-evaluate packages - // If other .nix files changed, re-evaluate both - reEvalConfig := true - reEvalPackages := filename == "packages.nix" || filename == "flake.nix" || - filename == "flake.lock" - - // For general .nix changes in .stack/data, re-evaluate both - if filepath.Dir(changedFile) == filepath.Join(fw.projectRoot, ".stack", "data") || - filepath.Dir(changedFile) == filepath.Join(fw.projectRoot, ".stackpanel", "data") { - reEvalPackages = true +func skipSourceDir(name string) bool { + switch name { + case ".git", ".direnv", "node_modules": + return true } + return false +} - var configChanged, packagesChanged bool - - if reEvalConfig { - // Invalidate and re-evaluate config - fw.configEvaluator.Invalidate() - oldConfig := fw.cachedConfig - - newConfig, err := fw.evaluateConfig(ctx) +func (p *flakeWatchPaths) watchTree(root string, wanted map[string]bool) { + // WalkDir doesn't follow symlinks to unrelated trees (or cycles). Install + // each watch before reading its children, including a populated moved-in dir. + _ = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { if err != nil { - log.Warn().Err(err).Msg("Failed to re-evaluate config") - } else { - // Check if config actually changed - configChanged = !configEqual(oldConfig, newConfig) - if configChanged { - log.Info().Msg("Config changed, broadcasting update") + if !errors.Is(err, fs.ErrNotExist) { + log.Warn().Err(err).Str("dir", path).Msg("Cannot scan flake source directory") } + return nil } - } - - if reEvalPackages { - // Invalidate and re-evaluate packages - fw.packagesEvaluator.Invalidate() - oldPackages := fw.cachedPackages - - newPackages, err := fw.evaluatePackages(ctx) - if err != nil { - log.Warn().Err(err).Msg("Failed to re-evaluate packages") - } else { - // Check if packages actually changed - packagesChanged = !packagesEqual(oldPackages, newPackages) - if packagesChanged { - log.Info(). - Int("count", len(newPackages)). - Msg("Packages changed, broadcasting update") + if entry.IsDir() { + if path != root && skipSourceDir(entry.Name()) { + return filepath.SkipDir } + p.watchDir(path, wanted) } - } - - // Broadcast SSE events if there were changes - if fw.server != nil { - if configChanged { - fw.server.broadcastSSE(SSEEvent{ - Event: "flake.config.updated", - Data: map[string]any{ - "timestamp": time.Now().Format(time.RFC3339), - "trigger": changedFile, - }, - }) - } + return nil + }) +} - if packagesChanged { - fw.mu.RLock() - packages := fw.cachedPackages - fw.mu.RUnlock() - - fw.server.broadcastSSE(SSEEvent{ - Event: "flake.packages.updated", - Data: map[string]any{ - "timestamp": time.Now().Format(time.RFC3339), - "trigger": changedFile, - "count": len(packages), - }, - }) +func (p *flakeWatchPaths) reconcile(links map[string]userconfig.LinkedModule) { + p.links = links + p.roots = map[string]string{ + filepath.Join(p.project, ".stack"): "", + filepath.Join(p.project, "nix"): "", + } + for id, link := range links { + root := filepath.Clean(link.Path) + p.roots[root] = id + // The CLI canonicalizes linked paths. Also support a hand-written link + // whose root is a symlink; watch both the alias parent and the target + // tree without following arbitrary symlinks inside an extension. + if info, err := os.Lstat(root); err == nil && info.Mode()&fs.ModeSymlink != 0 { + if target, err := filepath.EvalSymlinks(root); err == nil { + p.roots[target] = id + } } } -} - -// InvalidateAll invalidates both caches -func (fw *FlakeWatcher) InvalidateAll() { - fw.mu.Lock() - fw.cachedConfig = nil - fw.cachedPackages = nil - fw.mu.Unlock() - - if fw.configEvaluator != nil { - fw.configEvaluator.Invalidate() + wanted := make(map[string]bool) + p.watchParent(p.config, wanted) + for root := range p.roots { + p.watchParent(root, wanted) + p.watchTree(root, wanted) } - if fw.packagesEvaluator != nil { - fw.packagesEvaluator.Invalidate() + for dir := range p.dirs { + if !wanted[dir] { + _ = p.watcher.Remove(dir) // backend may already have removed it + } } + p.dirs = wanted } -// InvalidatePackages invalidates only the packages cache -func (fw *FlakeWatcher) InvalidatePackages() { - fw.mu.Lock() - fw.cachedPackages = nil - fw.mu.Unlock() - - if fw.packagesEvaluator != nil { - fw.packagesEvaluator.Invalidate() - } +func pathWithin(root, path string) bool { + return path == root || (strings.HasPrefix(path, root) && len(root) > 0 && + (os.IsPathSeparator(root[len(root)-1]) || os.IsPathSeparator(path[len(root)]))) } -// InvalidateConfig invalidates only the config cache -func (fw *FlakeWatcher) InvalidateConfig() { - fw.mu.Lock() - fw.cachedConfig = nil - fw.mu.Unlock() - - if fw.configEvaluator != nil { - fw.configEvaluator.Invalidate() +func createdWatchDir(event fsnotify.Event) bool { + if !event.Has(fsnotify.Create) { + return false } + info, err := os.Lstat(event.Name) + return err == nil && info.IsDir() } -// configEqual compares two config maps by JSON-serializing both sides. -// This is simple but not cheap — acceptable here since it only runs after nix eval. -func configEqual(a, b map[string]any) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false +func (p *flakeWatchPaths) event( + event fsnotify.Event, +) (change flakeChange, reload bool) { + if event.Op&(fsnotify.Create|fsnotify.Write|fsnotify.Rename|fsnotify.Remove) == 0 { + return + } + path := event.Name + if path == p.config { + return flakeChange{}, true + } + structure := event.Op&(fsnotify.Create|fsnotify.Rename|fsnotify.Remove) != 0 + // A parent of the config path appeared, disappeared or was replaced. + if structure && pathWithin(path, p.config) { + p.reconcile(p.links) + return flakeChange{}, true + } + var source, ancestor bool + var linkedID string + for root, id := range p.roots { + inside, above := pathWithin(root, path), pathWithin(path, root) + source, ancestor = source || inside, ancestor || above + if id != "" && (inside || above) { + linkedID = id + } } - - aJSON, err := json.Marshal(a) - if err != nil { - return false + if !source && !ancestor && (filepath.Dir(path) != p.project || + (filepath.Base(path) != "flake.nix" && filepath.Base(path) != "flake.lock")) { + return } - - bJSON, err := json.Marshal(b) - if err != nil { - return false + if structure && (ancestor || p.dirs[path]) { + // Remove stale sub-watches after a rename and rediscover roots when + // any missing ancestor appears. + p.reconcile(p.links) + } else if createdWatchDir(event) { + if skipSourceDir(filepath.Base(path)) { + return + } + p.watchTree(path, p.dirs) + } else { + switch strings.ToLower(filepath.Ext(path)) { + case ".nix", ".json", ".md", ".markdown", ".lock": + default: + return + } } - - return string(aJSON) == string(bJSON) + if linkedID != "" { + return flakeChange{ + trigger: "linked:" + linkedID, + packages: true, + linked: true, + }, false + } + rel, err := filepath.Rel(p.project, path) + if err != nil || !filepath.IsLocal(rel) { + return flakeChange{}, false + } + name := filepath.Base(path) + packages := name == "packages.nix" || name == "flake.nix" || name == "flake.lock" || + ancestor || + pathWithin(filepath.Join(p.project, ".stack", "data"), path) + return flakeChange{trigger: rel, packages: packages}, false } -// packagesEqual compares two package lists for equality -func packagesEqual(a, b []nixeval.InstalledPackage) bool { - if len(a) != len(b) { - return false +func (fw *FlakeWatcher) watchLoop(paths *flakeWatchPaths, jobs chan flakeChange) { + defer close(jobs) + const debounce = 500 * time.Millisecond + timer := time.NewTimer(debounce) + timer.Stop() + defer timer.Stop() + var tick <-chan time.Time + var ready chan flakeChange + var pending flakeChange + var reload bool + for { + select { + case <-fw.ctx.Done(): + return + case e, ok := <-fw.watcher.Events: + if !ok { + return + } + change, config := paths.event(e) + if change.trigger == "" && !config { + continue + } + if change.trigger != "" { + pending.trigger = change.trigger + } + pending.packages = pending.packages || change.packages + pending.linked = pending.linked || change.linked + reload = reload || config + case err, ok := <-fw.watcher.Errors: + if !ok { + return + } + log.Warn().Err(err).Msg("Flake watcher error") + if !errors.Is(err, fsnotify.ErrEventOverflow) { + continue + } + paths.reconcile(paths.links) + pending, reload = flakeChange{ + trigger: "rescan", + packages: true, + linked: true, + }, true + case <-tick: + tick = nil + if reload { + reload = false + if links, changed := fw.reloadLinks(); changed { + paths.reconcile(links) + pending = flakeChange{trigger: "linkedModules", packages: true, linked: true} + } + } + if pending.trigger != "" { + ready = jobs + } + continue + case ready <- pending: + ready, pending = nil, flakeChange{} + continue + } + // Re-arm even when the previous batch was ready but Nix was busy: the + // next job covers all writes (including whether any affected packages). + ready, tick = nil, timer.C + timer.Reset(debounce) } +} - // Create a set of package signatures for comparison - aSet := make(map[string]bool, len(a)) - for _, pkg := range a { - sig := pkg.Name + "@" + pkg.Version + ":" + pkg.AttrPath + ":" + pkg.Source - aSet[sig] = true - } +func (fw *FlakeWatcher) InvalidateAll() { + fw.InvalidateConfig() + fw.InvalidatePackages() +} - for _, pkg := range b { - sig := pkg.Name + "@" + pkg.Version + ":" + pkg.AttrPath + ":" + pkg.Source - if !aSet[sig] { - return false - } - } +func (fw *FlakeWatcher) InvalidateConfig() { + fw.configEvalMu.Lock() + defer fw.configEvalMu.Unlock() + fw.mu.Lock() + defer fw.mu.Unlock() + fw.cachedConfig = nil +} - return true +func (fw *FlakeWatcher) InvalidatePackages() { + fw.packagesEvalMu.Lock() + defer fw.packagesEvalMu.Unlock() + fw.mu.Lock() + defer fw.mu.Unlock() + fw.cachedPackages = nil } -// ConfigStatus returns the status of the cached config func (fw *FlakeWatcher) ConfigStatus() (updated time.Time, cached bool) { fw.mu.RLock() defer fw.mu.RUnlock() return fw.configUpdated, fw.cachedConfig != nil } -// PackagesStatus returns the status of the cached packages func (fw *FlakeWatcher) PackagesStatus() (updated time.Time, count int, cached bool) { fw.mu.RLock() defer fw.mu.RUnlock() return fw.pkgsUpdated, len(fw.cachedPackages), fw.cachedPackages != nil } -// ForceRefresh forces a refresh of both config and packages func (fw *FlakeWatcher) ForceRefresh(ctx context.Context) error { - fw.InvalidateAll() - - if _, err := fw.evaluateConfig(ctx); err != nil { - return err - } - - if _, err := fw.evaluatePackages(ctx); err != nil { + if _, err := fw.evaluateConfig(ctx, true); err != nil { + fw.InvalidatePackages() return err } - - return nil + _, err := fw.evaluatePackages(ctx, true) + return err } diff --git a/apps/stackpanel-go/internal/agent/server/flake_watcher_test.go b/apps/stackpanel-go/internal/agent/server/flake_watcher_test.go new file mode 100644 index 00000000..7ea8603c --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/flake_watcher_test.go @@ -0,0 +1,401 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" + "github.com/fsnotify/fsnotify" +) + +type watchTestEval func(context.Context) ([]byte, error) + +func (f watchTestEval) Eval(ctx context.Context) ([]byte, error) { return f(ctx) } +func (watchTestEval) Invalidate() {} + +func flakeTestRoot(t *testing.T) string { + t.Helper() + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + atomicWatchFile(t, filepath.Join(root, "flake.nix"), "{}") + return root +} + +func atomicWatchFile(t *testing.T, path, value string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path+".tmp", []byte(value), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Rename(path+".tmp", path); err != nil { + t.Fatal(err) + } +} + +func startTestFlakeWatcher( + t *testing.T, + root string, + eval watchTestEval, +) (*FlakeWatcher, <-chan SSEEvent) { + t.Helper() + s := &Server{sseSubscribers: make(map[chan SSEEvent]sseScope)} + stream := s.subscribeSSE(sseScope{root: root, diagnostics: true}, nil) + fw, err := NewFlakeWatcher(FlakeWatcherConfig{ProjectRoot: root, Server: s}) + if err != nil { + t.Fatal(err) + } + fw.configEvaluator = eval + fw.packagesEvaluator = watchTestEval( + func(context.Context) ([]byte, error) { return []byte(`[]`), nil }, + ) + if err := fw.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = fw.Stop() }) + return fw, stream +} + +func nextWatchEval( + t *testing.T, + stream <-chan SSEEvent, + root string, +) ModuleDevDiagnostics { + t.Helper() + deadline := time.After(5 * time.Second) + for { + select { + case e := <-stream: + if e.ProjectRoot != root { + t.Fatalf("event for %q reached %q", e.ProjectRoot, root) + } + if e.Event != moduleDevDiagnosticsEvent { + continue + } + d := e.Data.(ModuleDevDiagnostics) + if d.EvaluatedAt == "" { // subscription or link transition before eval + continue + } + if _, err := time.Parse( + time.RFC3339Nano, + d.EvaluatedAt, + ); err != nil || d.DurationMs == nil || *d.DurationMs < 0 || + d.ProjectID != userconfig.GenerateProjectID(root) { + t.Fatalf("invalid diagnostics: %+v", d) + } + return d + case <-deadline: + t.Fatal("no completed flake evaluation on the project stream") + } + } +} + +func TestFlakeWatcherProjectConfigRoots(t *testing.T) { + root := flakeTestRoot(t) + watcher, err := fsnotify.NewWatcher() + if err != nil { + t.Fatal(err) + } + defer watcher.Close() + paths := flakeWatchPaths{ + project: root, + config: filepath.Join(t.TempDir(), "config.yaml"), + watcher: watcher, + } + dirs := []string{".stack", ".stackpanel", "unrelated"} + for _, dir := range dirs { + atomicWatchFile(t, filepath.Join(root, dir, "data", "modules.nix"), "{}") + } + paths.reconcile(nil) + for _, dir := range dirs { + data := filepath.Join(root, dir, "data") + change, reload := paths.event(fsnotify.Event{Name: filepath.Join(data, "modules.nix"), Op: fsnotify.Write}) + want := dir == ".stack" + if paths.dirs[data] != want || (change.trigger != "") != want || change.packages != want || reload { + t.Errorf("%s: watched=%v change=%+v reload=%v", dir, paths.dirs[data], change, reload) + } + } +} + +// Exercise directory watches on the native backend, not just synthetic suffix +// matching. Keep the evaluated config constant: diagnostics must be sent even +// if an edit changes no serialized panel metadata. +func TestFlakeWatcherLinkedSourcesAndDiagnostics(t *testing.T) { + root, other := flakeTestRoot(t), flakeTestRoot(t) + linked, foreign := flakeTestRoot(t), flakeTestRoot(t) + readme := filepath.Join(linked, "panels", "nested", "README.md") + atomicWatchFile(t, readme, "old") + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "config.yaml")) + m, err := userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + const origin = "http://127.0.0.1:5174" + if err := m.SetLinkedModule( + root, + "author", + userconfig.LinkedModule{Path: linked, UIDevURL: origin + "/private-author-path"}, + ); err != nil { + t.Fatal(err) + } + if err := m.SetLinkedModule( + other, + "foreign", + userconfig.LinkedModule{Path: foreign}, + ); err != nil { + t.Fatal(err) + } + var fail atomic.Bool + fail.Store(true) + fw, stream := startTestFlakeWatcher(t, root, func(context.Context) ([]byte, error) { + if fail.Load() { + return nil, errors.New( + "\x1b[31merror: syntax error at " + linked + "/flake.nix:17:4\n17 | apiKey = \"secret-on-source-line\";\ntrace: /home/private/unrelated.nix\x1b[0m", + ) + } + return []byte(`{"variables":{"private":"never-send-config"}}`), nil + }) + d := nextWatchEval(t, stream, root) + if len(d.LinkedModules) != 1 || d.LinkedModules["author"].UIDevURL != origin || + d.Error != "Nix syntax error." { + t.Fatalf("initial eval failure lost authorized link status: %+v", d) + } + encoded, err := json.Marshal(d) + if err != nil { + t.Fatal(err) + } + for _, private := range []string{linked, "foreign", "private-author-path", "secret-on-source-line", "/home/private/", "flake.nix", "apiKey"} { + if strings.Contains(string(encoded), private) { + t.Errorf("private diagnostic content reached SSE: %q", private) + } + } + // A late subscriber must see the initial failure without waiting for a save. + replay := nextWatchEval( + t, + fw.server.subscribeSSE(sseScope{root: root, diagnostics: true}, fw), + root, + ) + if replay.EvaluatedAt != d.EvaluatedAt || replay.Error != d.Error { + t.Fatalf("failed to replay current diagnostic: %+v", replay) + } + if ch := fw.server.subscribeSSE(sseScope{root: root}, fw); len(ch) != 0 { + t.Fatal("replayed sensitive diagnostics to an unqualified current-project stream") + } + if slices.Contains(fw.watcher.WatchList(), foreign) { + t.Fatal("an unrelated project's linked directory was watched") + } + fail.Store(false) + atomicWatchFile(t, readme, "fixed") + if d := nextWatchEval(t, stream, root); d.Error != "" { + t.Fatalf("successful README save retained the old error: %+v", d) + } + // Move an already-populated tree into the module; then save beneath it. + staging := t.TempDir() + atomicWatchFile(t, filepath.Join(staging, "sub", "data.json"), "{}") + bundle := filepath.Join(linked, "bundle") + if err := os.Rename(staging, bundle); err != nil { + t.Fatal(err) + } + nextWatchEval(t, stream, root) + if !slices.Contains(fw.watcher.WatchList(), filepath.Join(bundle, "sub")) { + t.Fatal("did not watch descendants of moved-in directory") + } + atomicWatchFile(t, filepath.Join(bundle, "sub", "data.json"), "[]") + nextWatchEval(t, stream, root) + // Full config stayed identical. Module readers still need an invalidation + // to re-evaluate their separate serializable projection, never its contents. + select { + case e := <-stream: + data, ok := e.Data.(map[string]any) + if e.Event != "flake.config.updated" || !ok || len(data) != 3 || + data["projectId"] != d.ProjectID || + data["trigger"] != "linked:author" || + data["timestamp"] == nil { + t.Fatalf("expected metadata-only linked edit invalidation, got %+v", e) + } + case <-time.After(5 * time.Second): + t.Fatal("unchanged full config suppressed linked module invalidation") + } + fail.Store(true) + atomicWatchFile(t, filepath.Join(bundle, "sub", "module.nix"), "broken") + if d := nextWatchEval( + t, + stream, + root, + ); d.Error != "Nix syntax error." || + len(d.LinkedModules) != 1 { + t.Fatalf("new eval error was not exposed on subsequent save: %+v", d) + } + if _, cached := fw.ConfigStatus(); cached { + t.Fatal("failed config eval left an apparently successful cached config") + } + // The consumer flake itself is watched by directory, not by inode. + fail.Store(false) + atomicWatchFile(t, filepath.Join(root, "flake.nix"), "{} # saved") + if d := nextWatchEval(t, stream, root); d.Error != "" { + t.Fatalf("consumer flake save did not refresh: %+v", d) + } +} + +func TestFlakeWatcherReloadsLinksWithoutRestart(t *testing.T) { + root, first, second := flakeTestRoot(t), flakeTestRoot(t), flakeTestRoot(t) + config := filepath.Join(t.TempDir(), "not-created-yet", "config.yaml") + t.Setenv("STACKPANEL_USER_CONFIG", config) + fw, stream := startTestFlakeWatcher( + t, + root, + func(context.Context) ([]byte, error) { return []byte(`{}`), nil }, + ) + if d := nextWatchEval( + t, + stream, + root, + ); d.LinkedModules == nil || len(d.LinkedModules) != 0 || + d.Error != "" { + t.Fatalf("bad initial snapshot without user config: %+v", d) + } + m, err := userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + for _, dir := range []string{first, second} { + if err := m.SetLinkedModule( + root, + "module", + userconfig.LinkedModule{Path: dir}, + ); err != nil { + t.Fatal(err) + } + d := nextWatchEval(t, stream, root) + if _, ok := d.LinkedModules["module"]; !ok || d.Error != "" || + !slices.Contains(fw.watcher.WatchList(), dir) { + t.Fatalf("link to %s did not become active: %+v", dir, d) + } + } + if slices.Contains(fw.watcher.WatchList(), first) { + t.Fatal("relink retained the previous input's watch") + } + if err := m.UnlinkModule(root, "module"); err != nil { + t.Fatal(err) + } + d := nextWatchEval(t, stream, root) + if len(d.LinkedModules) != 0 || slices.Contains(fw.watcher.WatchList(), second) { + t.Fatalf("unlink didn't retire status and watches: %+v", d) + } + // A hand-edited config can bypass the CLI setter, but must not mint + // display authority or echo the credential in a validation error. + badConfig, err := json.Marshal(map[string]any{"projects": []any{map[string]any{ + "path": root, "linkedModules": map[string]any{"module": map[string]string{ + "path": second, + "uiDevUrl": "http://localhost:5174/preview?token=private-query#private-fragment", + }}, + }}}) + if err != nil { + t.Fatal(err) + } + atomicWatchFile(t, config, string(badConfig)) + if d := nextWatchEval( + t, + stream, + root, + ); d.Error != "Invalid project link configuration." || + len(d.LinkedModules) != 0 { + t.Fatal("invalid launch URL did not fail closed with a fixed public summary") + } +} + +func TestFlakeWatcherRelinkDuringColdEvaluation(t *testing.T) { + root, module := flakeTestRoot(t), flakeTestRoot(t) + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "config.yaml")) + started, resume := make(chan struct{}), make(chan struct{}) + var cold atomic.Bool + _, stream := startTestFlakeWatcher( + t, + root, + func(ctx context.Context) ([]byte, error) { + if cold.CompareAndSwap(false, true) { + close(started) + select { + case <-resume: + return nil, errors.New("obsolete initial evaluation error") + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return []byte(`{}`), nil + }, + ) + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("cold eval did not start") + } + m, err := userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + if err := m.SetLinkedModule( + root, + "live", + userconfig.LinkedModule{Path: module}, + ); err != nil { + t.Fatal(err) + } + select { + case event := <-stream: + d, ok := event.Data.(ModuleDevDiagnostics) + if _, linked := d.LinkedModules["live"]; !ok || !linked || d.EvaluatedAt != "" { + t.Fatalf("expected new pending snapshot: %+v", event) + } + case <-time.After(5 * time.Second): + t.Fatal("cold eval blocked config-file watcher") + } + close(resume) + if d := nextWatchEval(t, stream, root); d.Error != "" || len(d.LinkedModules) != 1 { + t.Fatalf("superseded eval published a stale result: %+v", d) + } +} + +func TestFlakeWatcherSSEProjectIsolation(t *testing.T) { + s := &Server{sseSubscribers: make(map[chan SSEEvent]sseScope)} + a := s.subscribeSSE(sseScope{root: "/a", diagnostics: true}, nil) + b := s.subscribeSSE(sseScope{root: "/b", diagnostics: true}, nil) + legacy := s.subscribeSSE(sseScope{root: "/a"}, nil) + headless := s.subscribeSSE(sseScope{}, nil) + s.broadcastSSE( + SSEEvent{ + Event: moduleDevDiagnosticsEvent, + Data: ModuleDevDiagnostics{Error: "private"}, + ProjectRoot: "/a", + }, + ) + // An unscoped marker is delivered after any preceding diagnostics to all + // streams. This asserts isolation deterministically without a sleep. + s.broadcastSSE(SSEEvent{Event: "marker"}) + if len(a) != 2 || len(b) != 1 || len(headless) != 1 || len(legacy) != 1 { + t.Fatalf( + "unexpected event counts: a=%d, b=%d, headless=%d, legacy=%d", + len(a), + len(b), + len(headless), + len(legacy), + ) + } + if (<-a).Event != moduleDevDiagnosticsEvent || (<-a).Event != "marker" || + (<-b).Event != "marker" || + (<-headless).Event != "marker" || + (<-legacy).Event != "marker" { + t.Fatal("SSE delivered a project diagnostic to the wrong subscriber") + } +} diff --git a/apps/stackpanel-go/internal/agent/server/local_module_client.go b/apps/stackpanel-go/internal/agent/server/local_module_client.go new file mode 100644 index 00000000..7fa9b088 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/local_module_client.go @@ -0,0 +1,58 @@ +package server + +import ( + "context" + "path/filepath" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/config" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/project" + sharedexec "github.com/darkmatter/stackpanel/stackpanel-go/pkg/exec" +) + +// LocalModules runs the agent's module operations directly for the trusted +// local CLI. There is no listener, pairing token, or saved active project. +type LocalModules struct { + *moduleService +} + +func NewLocalModules( + ctx context.Context, + projectRoot string, +) (context.Context, *LocalModules, error) { + root, err := filepath.Abs(projectRoot) + if err != nil { + return nil, nil, err + } + cfg := config.DefaultConfig() + cfg.ProjectRoot = root + mgr, err := project.NewManager(cfg.DataDir) + if err != nil { + return nil, nil, err + } + s := &Server{config: cfg, projectMgr: mgr} + // Registry reads and config patches do not need an eager, potentially + // minutes-long nix print-dev-env; actions resolve their declared executables. + exec, err := sharedexec.NewWithoutDevshell(root, cfg.AllowedCommands) + if err != nil { + return nil, nil, err + } + rt := s.newProjectRuntime(root, exec) + return context.WithValue( + ctx, + runtimeKey{}, + rt, + ), &LocalModules{ + &moduleService{s: s}, + }, nil +} + +// ExecuteAction delivers the same event stream as RunModuleAction without +// serializing through a loopback HTTP connection. +func (m *LocalModules) ExecuteAction( + ctx context.Context, + req *agentv1.RunModuleActionRequest, + send func(*agentv1.RunModuleActionResponse) error, +) error { + return m.runModuleAction(ctx, req, send) +} diff --git a/apps/stackpanel-go/internal/agent/server/module_actions.go b/apps/stackpanel-go/internal/agent/server/module_actions.go new file mode 100644 index 00000000..19bf474c --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_actions.go @@ -0,0 +1,289 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + + "connectrpc.com/connect" + "github.com/santhosh-tekuri/jsonschema/v6" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" +) + +func (m *moduleService) RunModuleAction( + ctx context.Context, + req *connect.Request[agentv1.RunModuleActionRequest], + stream *connect.ServerStream[agentv1.RunModuleActionResponse], +) error { + return m.runModuleActionWithHeader(ctx, moduleStoreRoot, req.Header(), req.Msg, stream.Send) +} + +func (m *moduleService) runModuleAction( + ctx context.Context, + msg *agentv1.RunModuleActionRequest, + send func(*agentv1.RunModuleActionResponse) error, +) error { + return m.runModuleActionWithHeader(ctx, moduleStoreRoot, nil, msg, send) +} + +func (m *moduleService) runModuleActionWithHeader( + ctx context.Context, + store string, + header http.Header, + msg *agentv1.RunModuleActionRequest, + send func(*agentv1.RunModuleActionResponse) error, +) error { + rt := runtimeFor(ctx) + if rt == nil || !filepath.IsAbs(rt.root) { + return connect.NewError( + connect.CodeFailedPrecondition, + errors.New("module action requires a project runtime"), + ) + } + if msg.GetModuleId() == "" || msg.GetActionId() == "" { + return connect.NewError( + connect.CodeInvalidArgument, + errors.New("module_id and action_id are required"), + ) + } + state, err := loadModuleState(ctx, rt) + if err != nil { + return err + } + // Pin the same immutable environment for the grant check and execution; + // do not resolve the project's mutable profile symlink again after approval. + profileBin := moduleActionProfile(rt.root, store, state) + if err := m.s.checkActionGrant(header, rt, state, msg, profileBin); err != nil { + return err + } + return runEvaluatedModuleAction(ctx, rt.root, store, profileBin, state, msg, send) +} + +func runEvaluatedModuleAction( + ctx context.Context, + root, store, profileBin string, + state map[string]any, + msg *agentv1.RunModuleActionRequest, + send func(*agentv1.RunModuleActionResponse) error, +) error { + id := msg.GetModuleId() + module, err := findModule(state, id) + if err != nil { + return err + } + if enabled, _ := module["enabled"].(bool); !enabled { + return connect.NewError( + connect.CodeFailedPrecondition, + errors.New("module is not enabled"), + ) + } + actions, _ := module["actions"].(map[string]any) + action, ok := actions[msg.GetActionId()].(map[string]any) + if !ok { + return connect.NewError( + connect.CodeNotFound, + errors.New("module action not declared"), + ) + } + mode, _ := action["outputMode"].(string) + if mode != "stream" && mode != "json" { + return connect.NewError( + connect.CodeFailedPrecondition, + errors.New("invalid action outputMode"), + ) + } + stdin, err := moduleActionInput(action["argsSchema"], msg.GetArgs()) + if err != nil { + return err + } + + script, _ := action["script"].(string) + if drvPath, _ := action["scriptDrvPath"].(string); drvPath != "" && + inModuleActionStore(script, store) { + name, _, _ := strings.Cut(strings.TrimPrefix(script, store+"/"), "/") + if err := ensureModuleOutput( + ctx, + root, + filepath.Join(store, name), + drvPath, + ); err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + return connect.NewError(connect.CodeFailedPrecondition, err) + } + } + path, err := moduleActionExecutable(script, store, profileBin, state, id) + if err != nil { + return connect.NewError(connect.CodeFailedPrecondition, err) + } + return execModuleAction(ctx, root, path, profileBin, mode, stdin, send) +} + +// Resolve the Nix buildEnv link that devshell/profile.nix installs in this +// project's state directory. Do not consult the agent's current devshell. +func moduleActionProfile(root, store string, state map[string]any) string { + dir := ".stack/profile" + if dirs, ok := state["dirs"].(map[string]any); ok { + if v, ok := dirs["profile"].(string); ok { + dir = v + } + } + if !filepath.IsLocal(dir) { + return "" + } + bin, err := filepath.EvalSymlinks(filepath.Join(root, dir, "profile", "bin")) + if err != nil || !inModuleActionStore(bin, store) || + strings.ContainsRune(bin, os.PathListSeparator) { + return "" + } + return bin +} + +func inModuleActionStore(path, store string) bool { + rel, ok := strings.CutPrefix(path, store+string(filepath.Separator)) + name, _, _ := strings.Cut(rel, string(filepath.Separator)) + return ok && filepath.Clean(path) == path && moduleStoreName.MatchString(name) +} + +func moduleActionExecutable( + script, store, profileBin string, + state map[string]any, + moduleID string, +) (string, error) { + declared := declaredActionTarget(script, state, moduleID) + if !inModuleActionStore(declared, store) { + return "", errors.New("action script has no declared Nix store executable") + } + path, err := filepath.EvalSymlinks(declared) + if err != nil || !inModuleActionStore(path, store) { + return "", errors.New("action executable is not realized in the Nix store") + } + if !filepath.IsAbs(script) { + if profileBin == "" { + return "", errors.New("project profile is not realized") + } + linked, err := filepath.EvalSymlinks(filepath.Join(profileBin, script)) + if err != nil || linked != path { + return "", errors.New( + "project profile does not contain the evaluated module script", + ) + } + } + fi, err := os.Stat(path) + if err != nil || !fi.Mode().IsRegular() || fi.Mode().Perm()&0o111 == 0 { + return "", errors.New("declared action target is not an executable file") + } + // Execute the immutable target, never the mutable project symlink. + return path, nil +} + +// A bare script name must resolve through this module's own evaluated outputs. +// Use precisely the same declaration to fingerprint and select the executable. +func declaredActionTarget(script string, state map[string]any, moduleID string) string { + if filepath.IsAbs(script) { + return script + } + if script == "" || script == "." || script == ".." || filepath.Base(script) != script { + return "" + } + outputs, _ := state["moduleOutputs"].(map[string]any) + owned, _ := outputs[moduleID].(map[string]any) + scripts, _ := owned["scripts"].([]any) + for _, item := range scripts { + entry, _ := item.(map[string]any) + if entry["name"] == script { + path, _ := entry["binPath"].(string) + return path + } + } + return "" +} + +// Check the whole document, not just eagerly compiled branches: references +// can target arbitrary subschemas by JSON pointer. A loader alone would +// still allow URL references to embedded metaschemas or sibling $id values. +func moduleActionLocalRefs(v any) bool { + switch obj := v.(type) { + case map[string]any: + for k, child := range obj { + switch k { + case "$ref", "$dynamicRef", "$recursiveRef": + if ref, ok := child.(string); ok && ref != "" && !strings.HasPrefix(ref, "#") { + return false + } + } + if !moduleActionLocalRefs(child) { + return false + } + } + case []any: + for _, child := range obj { + if !moduleActionLocalRefs(child) { + return false + } + } + } + return true +} + +func compileModuleActionSchema(rawSchema any) (*jsonschema.Schema, error) { + schema, ok := rawSchema.(map[string]any) + if !ok { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("invalid action argsSchema"), + ) + } + if !moduleActionLocalRefs(schema) { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("external refs are not permitted in action argsSchema"), + ) + } + const resource = "urn:stackpanel:action-args" + compiler := jsonschema.NewCompiler() + compiler.UseLoader( + nil, + ) // local fragments and built-in metaschemas only; no file/network I/O + if err := compiler.AddResource(resource, schema); err != nil { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + fmt.Errorf("invalid action argsSchema: %w", err), + ) + } + compiled, err := compiler.Compile(resource) + if err != nil { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + fmt.Errorf("invalid action argsSchema: %w", err), + ) + } + return compiled, nil +} + +func moduleActionInput(rawSchema any, args *structpb.Struct) ([]byte, error) { + compiled, err := compileModuleActionSchema(rawSchema) + if err != nil { + return nil, err + } + obj := args.AsMap() // an omitted Struct becomes the empty object + if err := compiled.Validate(obj); err != nil { + return nil, connect.NewError( + connect.CodeInvalidArgument, + fmt.Errorf("invalid action arguments: %w", err), + ) + } + b, err := json.Marshal(obj) + if err != nil { + return nil, connect.NewError(connect.CodeInvalidArgument, err) + } + return append(b, '\n'), nil +} diff --git a/apps/stackpanel-go/internal/agent/server/module_actions_exec.go b/apps/stackpanel-go/internal/agent/server/module_actions_exec.go new file mode 100644 index 00000000..33d9fe66 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_actions_exec.go @@ -0,0 +1,176 @@ +package server + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "sync" + "syscall" + "time" + + "connectrpc.com/connect" + "golang.org/x/text/encoding/unicode" + "golang.org/x/text/transform" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" +) + +const maxModuleActionJSON = 1 << 20 + +func execModuleAction( + ctx context.Context, + root, executable, profileBin, mode string, + stdin []byte, + send func(*agentv1.RunModuleActionResponse) error, +) error { + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + cmd := exec.CommandContext(ctx, executable) + cmd.Dir = root + cmd.Stdin = bytes.NewReader(stdin) + if profileBin == "" { + profileBin = os.DevNull // not "" (some shells treat empty PATH entries as the cwd) + } + cmd.Env = []string{ + "PATH=" + profileBin, + "STACKPANEL_ROOT=" + root, + "STACKPANEL_ACTION=1", + } + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.WaitDelay = time.Second // bound stdin teardown if a descendant retained its read end + stdout, err := cmd.StdoutPipe() + if err != nil { + return err + } + stderr, err := cmd.StderrPipe() + if err != nil { + _ = stdout.Close() + if childEnd, ok := cmd.Stdout.(io.Closer); ok { + _ = childEnd.Close() + } + return err + } + cmd.Cancel = func() error { + err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + // Even a process that detached and retained a write fd cannot wedge + // the handler after its client has left. + _ = stdout.Close() + _ = stderr.Close() + if errors.Is(err, syscall.ESRCH) { + return os.ErrProcessDone + } + return err + } + if err := cmd.Start(); err != nil { + return fmt.Errorf("start module action: %w", err) + } + + var mu sync.Mutex // a Connect stream must have only one sender at a time + drain := func(r io.Reader, stderr bool) { + err := streamModuleActionText(r, func(text string) error { + mu.Lock() + defer mu.Unlock() + if err := context.Cause(ctx); err != nil { + return err + } + msg := &agentv1.RunModuleActionResponse{} + if stderr { + msg.Event = &agentv1.RunModuleActionResponse_Stderr{Stderr: text} + } else { + msg.Event = &agentv1.RunModuleActionResponse_Stdout{Stdout: text} + } + return send(msg) + }) + if err != nil { + cancel(err) + } + } + done := make(chan struct{}) + go func() { + defer close(done) + drain(stderr, true) + }() + var data []byte + if mode == "json" { + data, err = io.ReadAll(io.LimitReader(stdout, maxModuleActionJSON+1)) + if err != nil { + cancel(err) + } else if len(data) > maxModuleActionJSON { + cancel( + connect.NewError( + connect.CodeResourceExhausted, + errors.New("module action JSON exceeds 1 MiB"), + ), + ) + } + } else { + drain(stdout, false) + } + <-done + // Drain before reaping: Wait closes the pipes. This also keeps the + // process group addressable if the leader exits before its children. + err = cmd.Wait() + if cause := context.Cause(ctx); cause != nil { + return cause + } + var exit *exec.ExitError + if err != nil && !errors.As(err, &exit) { + return fmt.Errorf("wait for module action: %w", err) + } + code := cmd.ProcessState.ExitCode() + if status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok && + status.Signaled() { + code = 128 + int(status.Signal()) + } + if mode == "json" && code == 0 { + value := &structpb.Value{} + if err := (protojson.UnmarshalOptions{RecursionLimit: 100}).Unmarshal( + data, + value, + ); err != nil { + return connect.NewError( + connect.CodeDataLoss, + fmt.Errorf("invalid module action JSON: %w", err), + ) + } + if err := send( + &agentv1.RunModuleActionResponse{ + Event: &agentv1.RunModuleActionResponse_Json{Json: value}, + }, + ); err != nil { + return err + } + } + return send( + &agentv1.RunModuleActionResponse{ + Event: &agentv1.RunModuleActionResponse_ExitCode{ExitCode: int32(code)}, + }, + ) +} + +type moduleActionTextSink func(string) error + +func (send moduleActionTextSink) Write(p []byte) (int, error) { + if len(p) > 0 { + if err := send(string(p)); err != nil { + return 0, err + } + } + return len(p), nil +} + +// A string oneof must contain valid UTF-8. Decode incrementally so that a +// multibyte rune split across pipe reads survives, without buffering lines. +func streamModuleActionText(r io.Reader, send moduleActionTextSink) error { + w := transform.NewWriter(send, unicode.UTF8.NewDecoder()) + if _, err := io.Copy(w, r); err != nil { + return err + } + return w.Close() +} diff --git a/apps/stackpanel-go/internal/agent/server/module_actions_test.go b/apps/stackpanel-go/internal/agent/server/module_actions_test.go new file mode 100644 index 00000000..6863d2fc --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_actions_test.go @@ -0,0 +1,493 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "connectrpc.com/connect" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1/agentv1connect" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +type actionFixture struct { + root, store, script, profile string + state, module, action map[string]any + req *agentv1.RunModuleActionRequest +} + +func newActionFixture(t *testing.T, program string) *actionFixture { + t.Helper() + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + store := filepath.Join(root, "store") + script := filepath.Join(store, strings.Repeat("0", 32)+"-report", "bin", "report") + profile := filepath.Join(store, strings.Repeat("1", 32)+"-profile") + profileDir := filepath.Join(root, ".stack", "profile") + for _, dir := range []string{filepath.Dir(script), filepath.Join(profile, "bin"), profileDir} { + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile( + script, + []byte("#!/bin/sh\nset -eu\n"+program+"\n"), + 0o700, + ); err != nil { + t.Fatal(err) + } + if err := os.Symlink(script, filepath.Join(profile, "bin", "report")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(profile, filepath.Join(profileDir, "profile")); err != nil { + t.Fatal(err) + } + action := map[string]any{ + "script": "report", + "argsSchema": map[string]any{"type": "object"}, + "outputMode": "stream", + } + module := map[string]any{ + "id": "sample", + "enabled": true, + "actions": map[string]any{"run": action}, + } + state := map[string]any{ + "modulesListAll": []any{module}, + "moduleOutputs": map[string]any{"sample": map[string]any{ + "scripts": []any{map[string]any{"name": "report", "binPath": script}}, + }}, + } + return &actionFixture{ + root, + store, + script, + profile, + state, + module, + action, + &agentv1.RunModuleActionRequest{ModuleId: "sample", ActionId: "run"}, + } +} + +func (f *actionFixture) run( + ctx context.Context, + send func(*agentv1.RunModuleActionResponse) error, +) error { + profileBin := moduleActionProfile(f.root, f.store, f.state) + return runEvaluatedModuleAction(ctx, f.root, f.store, profileBin, f.state, f.req, send) +} + +func TestModuleActionAttributedScript(t *testing.T) { + f := newActionFixture(t, ` +[ "$PWD" = "$STACKPANEL_ROOT" ] && [ -f selected-project ] || exit 11 +[ "$#" = 0 ] && [ "$STACKPANEL_ACTION" = 1 ] || exit 12 +[ -z "${STACKPANEL_AUTH_TOKEN+x}${SSH_AUTH_SOCK+x}" ] || exit 13 +printf '%s\n' "$PATH" >&2 +IFS= read -r args +printf '%s' "$args" +exit 7`) + t.Setenv("STACKPANEL_AUTH_TOKEN", "must-not-leak") + t.Setenv("SSH_AUTH_SOCK", "must-not-leak") + // If resolution (or the child environment) consults ambient PATH this + // executable wins instead of the attributed project script. + t.Setenv("PATH", f.root) + if err := os.WriteFile( + filepath.Join(f.root, "report"), + []byte("#!/bin/sh\nexit 99\n"), + 0o700, + ); err != nil { + t.Fatal(err) + } + if err := os.WriteFile( + filepath.Join(f.root, "selected-project"), + nil, + 0o600, + ); err != nil { + t.Fatal(err) + } + input := "'$(echo injected); \"line\n2" + f.req.Args, _ = structpb.NewStruct(map[string]any{"text": input}) + f.action["argsSchema"] = map[string]any{ + "type": "object", "$defs": map[string]any{"text": map[string]any{"type": "string"}}, + "properties": map[string]any{"text": map[string]any{"$ref": "#/$defs/text"}}, + "required": []any{"text"}, "additionalProperties": false, + } + var stdout, stderr strings.Builder + var codes []int32 + err := f.run(t.Context(), func(msg *agentv1.RunModuleActionResponse) error { + if len(codes) != 0 { + t.Error("event after terminal exit code") + } + switch ev := msg.Event.(type) { + case *agentv1.RunModuleActionResponse_Stdout: + stdout.WriteString(ev.Stdout) + case *agentv1.RunModuleActionResponse_Stderr: + stderr.WriteString(ev.Stderr) + case *agentv1.RunModuleActionResponse_ExitCode: + codes = append(codes, ev.ExitCode) + default: + t.Errorf("unexpected event %T", ev) + } + return nil + }) + var got map[string]string + if err != nil || len(codes) != 1 || codes[0] != 7 || + json.Unmarshal([]byte(stdout.String()), &got) != nil || + got["text"] != input || + stderr.String() != filepath.Join(f.profile, "bin")+"\n" { + t.Fatalf( + "got stdout=%q stderr=%q codes=%v err=%v", + stdout.String(), + stderr.String(), + codes, + err, + ) + } +} + +func TestModuleActionDeniedBeforeExec(t *testing.T) { + for _, tc := range []struct { + name string + code connect.Code + change func(*testing.T, *actionFixture) + }{ + {"disabled", connect.CodeFailedPrecondition, func(_ *testing.T, f *actionFixture) { f.module["enabled"] = false }}, + {"undeclared", connect.CodeNotFound, func(_ *testing.T, f *actionFixture) { f.req.ActionId = "report" }}, + {"cross-module", connect.CodeFailedPrecondition, func(_ *testing.T, f *actionFixture) { + out := f.state["moduleOutputs"].(map[string]any) + out["other"] = out["sample"] + delete(out, "sample") + }}, + {"relative", connect.CodeFailedPrecondition, func(_ *testing.T, f *actionFixture) { f.action["script"] = "../bin/report" }}, + {"outside-store", connect.CodeFailedPrecondition, func(_ *testing.T, f *actionFixture) { f.action["script"] = "/bin/sh" }}, + {"escaped-link", connect.CodeFailedPrecondition, func(t *testing.T, f *actionFixture) { + path := f.script + "-link" + if err := os.Symlink("/bin/sh", path); err != nil { + t.Fatal(err) + } + f.action["script"] = path + }}, + {"stale-profile", connect.CodeFailedPrecondition, func(t *testing.T, f *actionFixture) { + path := filepath.Join(f.profile, "bin", "report") + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("#!/bin/sh\n: >ran"), 0o700); err != nil { + t.Fatal(err) + } + }}, + {"invalid-args", connect.CodeInvalidArgument, func(_ *testing.T, f *actionFixture) { + f.action["argsSchema"] = map[string]any{"required": []any{"text"}} + }}, + {"external-schema", connect.CodeFailedPrecondition, func(t *testing.T, f *actionFixture) { + path := filepath.Join(f.root, "outside.json") + if err := os.WriteFile(path, []byte(`{"type":"object"}`), 0o600); err != nil { + t.Fatal(err) + } + f.action["argsSchema"] = map[string]any{"$ref": "file://" + path} + }}, + {"embedded-meta-ref", connect.CodeFailedPrecondition, func(_ *testing.T, f *actionFixture) { + f.action["argsSchema"] = map[string]any{"allOf": []any{map[string]any{"$ref": "https://json-schema.org/draft/2020-12/schema"}}} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newActionFixture(t, ": >ran") + tc.change(t, f) + err := f.run( + t.Context(), + func(*agentv1.RunModuleActionResponse) error { t.Error("denied action emitted an event"); return nil }, + ) + if connect.CodeOf(err) != tc.code { + t.Fatalf("got %v, want %v", err, tc.code) + } + if _, err := os.Stat( + filepath.Join(f.root, "ran"), + ); !errors.Is( + err, + os.ErrNotExist, + ) { + t.Fatalf("script was not denied: stat: %v", err) + } + }) + } +} + +func TestModuleActionJSON(t *testing.T) { + for _, tc := range []struct { + name, program string + wantErr connect.Code + }{ + {"valid", `printf 'diagnostic' >&2; printf '[null,true]'`, 0}, + {"malformed", `printf '{} {}'`, connect.CodeDataLoss}, + {"oversize", `printf '%01048577d' 0`, connect.CodeResourceExhausted}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newActionFixture(t, tc.program) + f.action["outputMode"], f.action["script"] = "json", f.script + var events []*agentv1.RunModuleActionResponse + err := f.run( + t.Context(), + func(msg *agentv1.RunModuleActionResponse) error { events = append(events, msg); return nil }, + ) + if tc.wantErr != 0 { + if connect.CodeOf(err) != tc.wantErr || len(events) != 0 { + t.Fatalf("events=%v err=%v", events, err) + } + return + } + if err != nil || len(events) != 3 || events[0].GetStderr() != "diagnostic" { + t.Fatalf("events=%v err=%v", events, err) + } + vals := events[1].GetJson().GetListValue().GetValues() + exit, ok := events[2].Event.(*agentv1.RunModuleActionResponse_ExitCode) + if len(vals) != 2 || !vals[1].GetBoolValue() || !ok || exit.ExitCode != 0 { + t.Fatalf("bad JSON or terminal event: %v", events) + } + }) + } +} + +// A held FIFO writer proves the child actually died, without relying on PID +// polling (a dead but unreaped orphan may still answer kill(pid, 0)). +func TestModuleActionCancellationKillsChild(t *testing.T) { + f := newActionFixture(t, `(exec 9>alive; printf ready; exec sleep 10) & +exit 0`) + sleep, err := exec.LookPath("sleep") + if err != nil { + t.Fatal(err) + } + if err := os.Symlink(sleep, filepath.Join(f.profile, "bin", "sleep")); err != nil { + t.Fatal(err) + } + fifo := filepath.Join(f.root, "alive") + if err := syscall.Mkfifo(fifo, 0o600); err != nil { + t.Fatal(err) + } + fd, err := syscall.Open( + fifo, + syscall.O_RDONLY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, + 0, + ) + if err != nil { + t.Fatal(err) + } + defer syscall.Close(fd) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + var ready strings.Builder + err = f.run(ctx, func(msg *agentv1.RunModuleActionResponse) error { + ready.WriteString(msg.GetStdout()) + if ready.String() == "ready" { + cancel() + } + return nil + }) + if !errors.Is(err, context.Canceled) || ready.String() != "ready" { + t.Fatalf("output %q, err=%v", ready.String(), err) + } + deadline := time.Now().Add(2 * time.Second) + for { + n, err := syscall.Read(fd, make([]byte, 1)) + if n == 0 && err == nil { + break + } // EOF: last writer exited + if !errors.Is(err, syscall.EAGAIN) || time.Now().After(deadline) { + t.Fatalf("child retained FIFO after cancellation: n=%d err=%v", n, err) + } + time.Sleep(10 * time.Millisecond) + } +} + +// Exercise the actual generated client and RPC handler with an immutable Nix +// store fixture, without building a flake or doing network I/O. The tests +// above also run on hosts without a Nix installation. +func TestRunModuleActionConnect(t *testing.T) { + nixStore, err := exec.LookPath("nix-store") + if err != nil { + t.Skip("requires a local Nix store") + } + f := newActionFixture(t, `printf ready +IFS= read -r ack < ack +printf diagnostic >&2 +exit 4`) + fifo := filepath.Join(f.root, "ack") + if err := syscall.Mkfifo(fifo, 0o600); err != nil { + t.Fatal(err) + } + ack, err := os.OpenFile(fifo, os.O_RDWR|syscall.O_NONBLOCK, 0) + if err != nil { + t.Fatal(err) + } + defer ack.Close() + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, nixStore, "--add", f.script) + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + t.Fatal(err) + } + f.action["script"] = strings.TrimSpace(string(out)) + client := moduleActionTestClient(t, newUITestServer(t), f.root, f.state) + req := connect.NewRequest(f.req) + req.Header().Set(projectHeader, "selected") + stream, err := client.RunModuleAction(ctx, req) + if err != nil { + t.Fatal(err) + } + defer stream.Close() + var stdout, stderr strings.Builder + var exit *agentv1.RunModuleActionResponse_ExitCode + for stream.Receive() { + if exit != nil { + t.Fatal("event after exit") + } + switch ev := stream.Msg().Event.(type) { + case *agentv1.RunModuleActionResponse_Stdout: + stdout.WriteString(ev.Stdout) + if stdout.String() == "ready" { + // Script cannot exit before its first output reaches the client. + if _, err := ack.WriteString("ack\n"); err != nil { + t.Fatal(err) + } + } + case *agentv1.RunModuleActionResponse_Stderr: + stderr.WriteString(ev.Stderr) + case *agentv1.RunModuleActionResponse_ExitCode: + exit = ev + } + } + if err := stream.Err(); err != nil || stdout.String() != "ready" || + stderr.String() != "diagnostic" || + exit == nil || + exit.ExitCode != 4 { + t.Fatalf( + "stdout=%q stderr=%q exit=%v err=%v", + stdout.String(), + stderr.String(), + exit, + err, + ) + } +} + +func moduleActionTestClient( + t *testing.T, + s *Server, + projectRoot string, + state map[string]any, +) agentv1connect.ModuleServiceClient { + t.Helper() + data, err := json.Marshal(state) + if err != nil { + t.Fatal(err) + } + registry, _ := newTestRegistry() + registry.create = func(root string) (*projectRuntime, error) { + return &projectRuntime{ + root: root, + evalModuleState: func(context.Context, string) ([]byte, error) { return data, nil }, + }, nil + } + scope := projectInterceptor{ + runtimes: registry, + resolve: func(id string) (string, error) { + if id != "selected" { + return "", errors.New("missing project header") + } + return projectRoot, nil + }, + } + mux := http.NewServeMux() + mux.Handle( + agentv1connect.NewModuleServiceHandler( + &moduleService{s: s}, + connect.WithInterceptors(scope), + ), + ) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return agentv1connect.NewModuleServiceClient(srv.Client(), srv.URL) +} + +func TestRunModuleActionChecksPanelGrantBeforeDispatch(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + s := newUITestServer(t) + root := t.TempDir() + for _, tc := range []struct { + name string + want connect.Code + }{ + {"valid", connect.CodeInvalidArgument}, + {"tampered", connect.CodePermissionDenied}, + {"retargeted", connect.CodePermissionDenied}, + {"revoked", connect.CodePermissionDenied}, + } { + t.Run(tc.name, func(t *testing.T) { + state, panel, module := uiTestState() + // Invalid arguments give dispatch a distinct observable outcome on + // every host without requiring Nix or executing a side effect. + action := map[string]any{ + "script": "inspect", + "outputMode": "stream", + "argsSchema": map[string]any{"required": []any{"name"}}, + } + module["actions"] = map[string]any{"inspect": action, "publish": action} + bundle := panel["uiBundle"].(map[string]any) + bundle["actionIds"] = []any{"inspect"} + bundle["permissions"] = []any{"actions:run"} + grant, err := s.issueModuleUIGrant( + root, + state, + "demo", + "inspector", + "", + moduleStoreRoot, + userconfig.LinkedModule{}, + ) + if err != nil { + t.Fatal(err) + } + req := connect.NewRequest( + &agentv1.RunModuleActionRequest{ModuleId: "demo", ActionId: "inspect"}, + ) + switch tc.name { + case "tampered": + grant = "invalid-" + grant + case "retargeted": + req.Msg.ActionId = "publish" + case "revoked": + bundle["permissions"] = []any{} + } + req.Header().Set(projectHeader, "selected") + req.Header().Set(moduleUIGrantHeader, grant) + client := moduleActionTestClient(t, s, root, state) + stream, err := client.RunModuleAction(t.Context(), req) + if err == nil { + defer stream.Close() + if stream.Receive() { + t.Fatal("unexpected action output") + } + err = stream.Err() + } + if connect.CodeOf(err) != tc.want { + t.Fatalf("got %v, want %s", err, tc.want) + } + }) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/module_adoption_answers.go b/apps/stackpanel-go/internal/agent/server/module_adoption_answers.go new file mode 100644 index 00000000..7fbb5c6d --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_adoption_answers.go @@ -0,0 +1,301 @@ +package server + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "connectrpc.com/connect" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" +) + +// Resolve against the fresh enable-only snapshot, never against metadata from +// the client or a plan already modified by answers. Omitted answers stay pending. +func resolveAdoptionAnswers( + id string, + before, enabled []nixeval.AddonSpec, + ledger *reconcile.Ledger, + answers []*agentv1.ModuleAdoptionAnswer, +) (offers []*agentv1.ModuleAdoptionOffer, mutations []reconcile.Mutation, records map[string]reconcile.LedgerEntry, err error) { + if ledger == nil || id == "" { + return nil, nil, nil, invalidModuleState("missing module adoption context") + } + previous := make(map[string]int, len(before)) + for _, a := range before { + if a.ID == "" || a.Revision < 1 || previous[a.ID] != 0 { + return nil, nil, nil, invalidModuleState( + "invalid or duplicate adoption offer identity before enable", + ) + } + previous[a.ID] = a.Revision + } + requested := make(map[string]*agentv1.ModuleAdoptionAnswer, len(answers)) + for _, a := range answers { + if a.GetId() == "" || a.GetRevision() == "" || a.GetAnswer() == nil { + return nil, nil, nil, connect.NewError( + connect.CodeInvalidArgument, + errors.New("adoption answer needs an offer ID, revision and answer"), + ) + } + if requested[a.Id] != nil { + return nil, nil, nil, connect.NewError( + connect.CodeInvalidArgument, + errors.New("duplicate adoption answer"), + ) + } + requested[a.Id] = a + } + + seen := make(map[string]bool, len(enabled)) + assignments := adoptionAssignments{} + records = make(map[string]reconcile.LedgerEntry, len(answers)) + for _, a := range enabled { + if a.ID == "" || a.Revision < 1 || seen[a.ID] { + return nil, nil, nil, invalidModuleState( + "invalid or duplicate adoption offer identity after enable", + ) + } + seen[a.ID] = true + // A flake-level offer is not a dependency. An unrelated offer that + // merely remained pending (or whose revision decreased) isn't one either. + if a.Module == "" || (a.Module != id && a.Revision <= previous[a.ID]) { + continue + } + pending, reason := ledger.ShouldOffer(a.ID, a.Revision, false) + if !pending { + if requested[a.ID] != nil { + return nil, nil, nil, invalidModuleState("adoption offer is no longer pending") + } + continue + } + offer, choices, err := projectAdoptionOffer(a, reason) + if err != nil { + return nil, nil, nil, err + } + offers = append(offers, offer) + request := requested[a.ID] + if request == nil { + continue + } + if request.Revision != offer.Revision { + return nil, nil, nil, invalidModuleState( + "adoption offer revision changed; preview again", + ) + } + answer, err := decodeAdoptionAnswer(a.Question.Type, choices, request.Answer) + if err != nil { + return nil, nil, nil, connect.NewError( + connect.CodeInvalidArgument, + fmt.Errorf("adoption offer %q: %w", a.ID, err), + ) + } + resolved, _ := reconcile.Materialize(a, answer) + for _, m := range resolved { + if !assignments.reserve(nixdata.SplitConfigPath(m.Path)) { + return nil, nil, nil, invalidModuleState( + "adoption answers have overlapping config assignments", + ) + } + } + mutations = append(mutations, resolved...) + records[a.ID] = reconcile.LedgerEntry{ + Revision: a.Revision, + Answer: answer.Record(a.Question), + } + delete(requested, a.ID) + } + if len(requested) != 0 { + return nil, nil, nil, connect.NewError( + connect.CodeInvalidArgument, + errors.New("answer does not name a pending adoption offer for this enable"), + ) + } + return offers, mutations, records, nil +} + +// The public projection is an allowlist. In particular neither config attrset +// (including a choice's config) is copied into the offer or error messages. +func projectAdoptionOffer( + a nixeval.AddonSpec, + reason string, +) (*agentv1.ModuleAdoptionOffer, map[string]bool, error) { + q := a.Question + switch q.Type { + case "bool": + if len(q.Choices) != 0 { + return nil, nil, invalidModuleState("boolean adoption question declares choices") + } + case "select", "multiselect": + if len(q.Choices) == 0 { + return nil, nil, invalidModuleState("adoption question is missing choices") + } + default: + return nil, nil, invalidModuleState("unsupported adoption question type") + } + offer := &agentv1.ModuleAdoptionOffer{ + Id: a.ID, Revision: strconv.Itoa(a.Revision), Module: a.Module, Reason: reason, + Type: q.Type, Label: q.Label, Description: q.Description, + } + if err := validateAdoptionConfig(a.Module, a.Config); err != nil { + return nil, nil, err + } + choices := make(map[string]bool, len(q.Choices)) + for _, c := range q.Choices { + if choices[c.Value] { + return nil, nil, invalidModuleState("duplicate adoption choice value") + } + choices[c.Value] = true + if err := validateAdoptionConfig(a.Module, c.Config); err != nil { + return nil, nil, err + } + label := c.Label + if label == "" { + label = c.Value + } + offer.Choices = append( + offer.Choices, + &agentv1.ModuleAdoptionChoice{Label: label, Value: c.Value}, + ) + } + if q.Default != nil { + v, err := structpb.NewValue(q.Default) + if err != nil { + return nil, nil, invalidModuleState("invalid adoption question default") + } + if _, err := decodeAdoptionAnswer(q.Type, choices, v); err != nil { + return nil, nil, invalidModuleState("invalid adoption question default") + } + offer.Default = v + } + return offer, choices, nil +} + +func decodeAdoptionAnswer( + typ string, + choices map[string]bool, + v *structpb.Value, +) (reconcile.Answer, error) { + var answer reconcile.Answer + switch typ { + case "bool": + b, ok := v.GetKind().(*structpb.Value_BoolValue) + if !ok || b == nil { + return answer, errors.New("expected a boolean answer") + } + answer.Bool = b.BoolValue + case "select": + s, ok := v.GetKind().(*structpb.Value_StringValue) + if !ok || s == nil || !choices[s.StringValue] { + return answer, errors.New("expected a declared choice value") + } + answer.Select = s.StringValue + case "multiselect": + field, ok := v.GetKind().(*structpb.Value_ListValue) + if !ok || field == nil || field.ListValue == nil { + return answer, errors.New("expected a list of choice values") + } + list := field.ListValue + selected := make(map[string]bool, len(list.Values)) + answer.Multi = make([]string, 0, len(list.Values)) + for _, item := range list.Values { + s, ok := item.GetKind().(*structpb.Value_StringValue) + if !ok || s == nil || !choices[s.StringValue] || selected[s.StringValue] { + return answer, errors.New("expected distinct declared choice values") + } + selected[s.StringValue] = true + answer.Multi = append(answer.Multi, s.StringValue) + } + default: + return answer, errors.New("unsupported adoption question type") + } + return answer, nil +} + +// Check the original attrset, before any dotted path codec can discard an +// empty segment. Match the module write boundary, permitting literal dots in +// nested attribute names without granting another module's settings namespace. +func validateAdoptionConfig(module string, config map[string]any) error { + for root, value := range config { + if nixdata.ValidateEntityName(root) != nil { + return invalidModuleState("invalid adoption config namespace") + } + switch root { + case "enable", "stackpanel", "variables", "secrets", "users", "apps", "registries": + return invalidModuleState("adoption config targets a protected namespace") + case "modules": + owners, _ := value.(map[string]any) + own, _ := owners[module].(map[string]any) + if len(owners) != 1 || len(own) == 0 { + return invalidModuleState( + "adoption config must assign within the contributing module", + ) + } + } + } + if !safeAdoptionKeys(config) { + return invalidModuleState("invalid declared adoption config path") + } + return nil +} + +func safeAdoptionKeys(config map[string]any) bool { + for k, v := range config { + if !safeAdoptionSegment(k) { + return false + } + if child, ok := v.(map[string]any); ok && !safeAdoptionKeys(child) { + return false + } + } + return true +} + +func safeAdoptionSegment(s string) bool { + if s == "" || s == "." || s == ".." || s == "imports" || strings.HasPrefix(s, "_") { + return false + } + for _, r := range s { + switch { + case r >= 'A' && r <= 'Z', + r >= 'a' && r <= 'z', + r >= '0' && r <= '9', + r == '_', + r == '-', + r == '.': + default: + return false + } + } + return true +} + +// A nil child marks an assignment; a non-nil child is a namespace. Reject +// duplicates and ancestor/descendant collisions independent of answer order. +type adoptionAssignments map[string]adoptionAssignments + +func (tree adoptionAssignments) reserve(parts []string) bool { + for i, part := range parts { + child, exists := tree[part] + if i == len(parts)-1 { + if exists { + return false + } + tree[part] = nil + return true + } + if !exists { + child = adoptionAssignments{} + tree[part] = child + } else if child == nil { + return false + } + tree = child + } + return false +} diff --git a/apps/stackpanel-go/internal/agent/server/module_adoption_answers_test.go b/apps/stackpanel-go/internal/agent/server/module_adoption_answers_test.go new file mode 100644 index 00000000..836c2ec0 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_adoption_answers_test.go @@ -0,0 +1,192 @@ +package server + +import ( + "testing" + + "connectrpc.com/connect" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" +) + +func TestAdoptionOnlyOffersPendingEnableDelta(t *testing.T) { + spec := func(id, module string, revision int) nixeval.AddonSpec { + return nixeval.AddonSpec{ + ID: id, + Module: module, + Revision: revision, + Question: nixeval.AddonQuestion{Type: "bool"}, + } + } + enabled := []nixeval.AddonSpec{ + spec("mine", "demo", 1), + spec("new", "dep", 1), + spec("bump", "dep", 2), + spec( + "old", + "dep", + 1, + ), + spec("downgrade", "dep", 1), + spec("flake", "", 1), + spec("decided", "demo", 2), + } + before := []nixeval.AddonSpec{ + enabled[0], + spec("bump", "dep", 1), + enabled[3], + spec("downgrade", "dep", 2), + } + ledger := &reconcile.Ledger{ + Seen: map[string]reconcile.LedgerEntry{ + "decided": {Revision: 2}, + "bump": {Revision: 1}, + }, + } + answer := &agentv1.ModuleAdoptionAnswer{ + Id: "bump", + Revision: "2", + Answer: structpb.NewBoolValue(false), + } + offers, mutations, records, err := resolveAdoptionAnswers( + "demo", + before, + enabled, + ledger, + []*agentv1.ModuleAdoptionAnswer{answer}, + ) + require.NoError(t, err) + var ids []string + for _, o := range offers { + ids = append(ids, o.Id) + } + require.Equal(t, []string{"mine", "new", "bump"}, ids) + require.Equal(t, "revised", offers[2].Reason) + require.Empty(t, mutations) + require.Equal( + t, + map[string]reconcile.LedgerEntry{"bump": {Revision: 2, Answer: false}}, + records, + ) + require.Equal( + t, + 1, + ledger.Seen["bump"].Revision, + "resolving a preview must not record anything", + ) + + for _, id := range []string{"old", "downgrade", "flake", "decided", "unknown"} { + answer.Id = id + _, _, _, err := resolveAdoptionAnswers( + "demo", + before, + enabled, + ledger, + []*agentv1.ModuleAdoptionAnswer{answer}, + ) + require.Error(t, err, id) + } +} + +func TestAdoptionRejectsAmbiguousAssignments(t *testing.T) { + // A dotted attrname and a nested path are distinct; neither may overwrite + // the other during materialization, comparison, or preview. + base := map[string]any{"custom": map[string]any{"a.b": 1, "empty": map[string]any{}}} + spec := nixeval.AddonSpec{ + ID: "prefs", + Module: "demo", + Revision: 1, + Config: base, + Question: nixeval.AddonQuestion{ + Type: "select", + Choices: []nixeval.AddonChoice{{Value: "yes"}}, + }, + } + answer := &agentv1.ModuleAdoptionAnswer{ + Id: "prefs", + Revision: "1", + Answer: structpb.NewStringValue("yes"), + } + resolve := func(config map[string]any) ([]reconcile.Mutation, map[string]reconcile.LedgerEntry, error) { + spec.Question.Choices[0].Config = config + _, mutations, records, err := resolveAdoptionAnswers( + "demo", + nil, + []nixeval.AddonSpec{spec}, + &reconcile.Ledger{}, + []*agentv1.ModuleAdoptionAnswer{answer}, + ) + return mutations, records, err + } + m, _, err := resolve( + map[string]any{"custom": map[string]any{"a": map[string]any{"b": 2}}}, + ) + require.NoError(t, err) + require.Equal( + t, + map[string]any{ + "custom": map[string]any{ + "a.b": 1, + "a": map[string]any{"b": 2}, + "empty": map[string]any{}, + }, + }, + reconcile.Overlay(m), + ) + for _, bad := range []map[string]any{ + {"custom": map[string]any{"a.b": 2}}, // same leaf + {"custom": map[string]any{"a.b": map[string]any{"c": 2}}}, // leaf then descendant + {"custom": true}, // descendant then leaf + {"custom": map[string]any{"empty": map[string]any{"child": true}}}, + {"modules": map[string]any{"other": map[string]any{"enable": true}}}, + {"users": map[string]any{"admin": true}}, + {"custom": map[string]any{"_module": true}}, + {"": map[string]any{"custom": true}}, + {"custom": map[string]any{"../outside": true}}, + } { + m, records, err := resolve(bad) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err)) + require.Nil(t, m) + require.Nil(t, records) + } +} + +func TestAdoptionRequiresDistinctTypedAnswers(t *testing.T) { + spec := nixeval.AddonSpec{ + ID: "features", + Module: "demo", + Revision: 3, + Question: nixeval.AddonQuestion{ + Type: "multiselect", + Choices: []nixeval.AddonChoice{{Value: "one"}}, + }, + } + run := func(answers ...*agentv1.ModuleAdoptionAnswer) error { + _, _, _, err := resolveAdoptionAnswers( + "demo", + nil, + []nixeval.AddonSpec{spec}, + &reconcile.Ledger{}, + answers, + ) + return err + } + answer := &agentv1.ModuleAdoptionAnswer{Id: spec.ID, Revision: "3"} + for _, value := range []any{nil, false, "one", []any{true}, []any{"one", "one"}, map[string]any{"path": "modules.other.enable"}} { + v, err := structpb.NewValue(value) + require.NoError(t, err) + answer.Answer = v + require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(run(answer))) + } + answer.Answer = structpb.NewListValue(&structpb.ListValue{}) + require.NoError(t, run(answer)) + require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(run(answer, answer))) + spec.Question.Choices = append( + spec.Question.Choices, + nixeval.AddonChoice{Value: "one"}, + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(run())) +} diff --git a/apps/stackpanel-go/internal/agent/server/module_adoption_commit.go b/apps/stackpanel-go/internal/agent/server/module_adoption_commit.go new file mode 100644 index 00000000..127fbf8e --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_adoption_commit.go @@ -0,0 +1,113 @@ +package server + +import ( + "context" + "encoding/json" + "reflect" + "slices" + + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + nixser "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nix" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" +) + +// commit runs under the same project lock as resolution of the answers. No +// decision is recorded until all edits (including enable) have evaluated +// successfully in this project's pure flake. Undo in reverse source order: a +// single config.nix can contain several mutations and imports can split them. +func (p *moduleAdoptionPlan) commit( + ctx context.Context, + rt *projectRuntime, + id string, +) (err error) { + patches := make([]nixdata.ModulePatch, 1, 1+len(p.mutations)) + patches[0] = nixdata.ModulePatch{Path: p.enablePath, Value: true} + for _, m := range p.mutations { + path := nixdata.SplitConfigPath(m.Path) + if slices.Equal(path, p.enablePath) { + continue + } // already validated as true + patches = append(patches, nixdata.ModulePatch{Path: path, Value: m.Value}) + } + if ctx.Err() != nil { + return moduleEvalError(ctx, ctx.Err()) + } + rollback, err := rt.store.ApplyModulePatches(patches) + if err != nil { + return invalidModuleState("could not apply the module's declared adoption settings") + } + defer func() { + if err != nil && rollback() != nil { + err = invalidModuleState( + "project config changed during adoption rollback; inspect the affected files", + ) + } + if rt.flake != nil { + rt.flake.InvalidateAll() + } + }() + state, err := loadModuleState(ctx, rt) + if err != nil { + return err + } + mod, err := findModule(state, id) + if err != nil { + return err + } + if mod["enabled"] != true { + return invalidModuleState("module did not enable in the selected project") + } + if err := verifyAdoptedValues(ctx, rt, p.mutations); err != nil { + return err + } + if ctx.Err() != nil { + return moduleEvalError(ctx, ctx.Err()) + } + if err := p.ledger.SaveDecisions(rt.root, p.records); err != nil { + return invalidModuleState("could not record adoption decisions; preview again") + } + return nil +} + +func verifyAdoptedValues( + ctx context.Context, + rt *projectRuntime, + muts []reconcile.Mutation, +) error { + if len(muts) == 0 { + return nil + } + paths := make([][]string, len(muts)) + for i, m := range muts { + paths[i] = nixdata.SplitConfigPath(m.Path) + } + selectors, err := json.Marshal(paths) + if err != nil { + return err + } + // Return only the declared leaves to the agent for verification. Never + // put expected values in argv or emit either actual or expected in errors. + data, err := nixeval.EvalOnce(ctx, nixeval.EvalOnceParams{ + ProjectRoot: rt.root, + Expression: ".#legacyPackages." + nixeval.CurrentSystem() + ".stackpanelRawConfig", + Apply: `raw: map (builtins.foldl' (v: k: builtins.getAttr k v) raw) (builtins.fromJSON ` + nixser.QuoteString( + string(selectors), + ) + `)`, + }) + if err != nil { + return moduleEvalError(ctx, err) + } + var values []any + if err := json.Unmarshal(data, &values); err != nil || len(values) != len(muts) { + return invalidModuleState("invalid adoption config readback") + } + for i, m := range muts { + if !reflect.DeepEqual(m.Value, values[i]) { + return invalidModuleState( + "project flake did not apply all declared adoption settings", + ) + } + } + return nil +} diff --git a/apps/stackpanel-go/internal/agent/server/module_preview.go b/apps/stackpanel-go/internal/agent/server/module_preview.go new file mode 100644 index 00000000..b7285921 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_preview.go @@ -0,0 +1,285 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "maps" + "slices" + + "connectrpc.com/connect" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/reconcile" + nixser "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nix" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" +) + +// Never transfer generated file contents to the UI. Compare file plans and +// service/package identities, not naming conventions or the current devshell. +const modulePlanProjection = `project = result: { + services = result.serviceFingerprints; + packages = result.packageFingerprints; + files = map (file: { inherit (file) path; hash = builtins.hashString "sha256" (builtins.toJSON file); }) result.files; +};` + +type modulePreviewPlan struct { + Files []struct{ Path, Hash string } `json:"files"` + Services map[string]string `json:"services"` + Packages map[string]string `json:"packages"` +} + +func (p modulePreviewPlan) fileHashes() (map[string]string, error) { + if p.Files == nil || p.Packages == nil || p.Services == nil { + return nil, invalidModuleState("incomplete speculative plan") + } + files := make(map[string]string, len(p.Files)) + for _, f := range p.Files { + if f.Path == "" || f.Hash == "" { + return nil, invalidModuleState("invalid speculative file entry") + } + if _, ok := files[f.Path]; ok { + return nil, invalidModuleState("duplicate speculative file path") + } + files[f.Path] = f.Hash + } + return files, nil +} + +func modulePreviewDiff(before, after map[string]string) *agentv1.ModulePreviewDiff { + diff := &agentv1.ModulePreviewDiff{ + Before: slices.Sorted(maps.Keys(before)), + After: slices.Sorted(maps.Keys(after)), + } + for _, key := range diff.Before { + if value, ok := after[key]; !ok { + diff.Removed = append(diff.Removed, key) + } else if before[key] != value { + diff.Changed = append(diff.Changed, key) + } + } + for _, key := range diff.After { + if _, ok := before[key]; !ok { + diff.Added = append(diff.Added, key) + } + } + return diff +} + +func evalModulePlan( + ctx context.Context, + rt *projectRuntime, + apply string, + dst any, +) error { + data, err := nixeval.EvalOnce(ctx, nixeval.EvalOnceParams{ + Expression: ".#legacyPackages." + nixeval.CurrentSystem() + ".stackpanelSpeculate", + ProjectRoot: rt.root, Apply: apply, + }) + if err != nil { + return moduleEvalError(ctx, err) + } + if err := json.Unmarshal(data, dst); err != nil { + return invalidModuleState("invalid speculative module plan") + } + return nil +} + +type moduleAdoptionPlan struct { + preview *agentv1.ModulePreview + enablePath []string + mutations []reconcile.Mutation + ledger *reconcile.Ledger + records map[string]reconcile.LedgerEntry +} + +// Inspect the enable-only result first: this is the authority for question +// revisions, possible answers and config mutations, including for a re-preview. +func prepareModuleAdoption( + ctx context.Context, + rt *projectRuntime, + id string, + answers []*agentv1.ModuleAdoptionAnswer, +) (*moduleAdoptionPlan, error) { + state, err := loadModuleState(ctx, rt) + if err != nil { + return nil, err + } + mod, err := findModule(state, id) + if err != nil { + return nil, err + } + path, err := moduleOptionPath(mod, "enablePath") + if err != nil { + return nil, err + } + literal, err := nixser.Serialize(path) + if err != nil { + return nil, err + } + prefix := `f: let ` + modulePlanProjection + ` path = ` + literal + `; enabled = f { enablePath = path; }; ` + var spec struct { + Before, After modulePreviewPlan + Previous, Available []nixeval.AddonSpec + Revision string + } + err = evalModulePlan(ctx, rt, prefix+`base = f {}; in { + before = project base; after = project enabled; + previous = map (a: { inherit (a) id revision; }) base.addons; + available = enabled.addons; + revision = builtins.hashString "sha256" (builtins.toJSON enabled.addons); +}`, &spec) + if err != nil { + return nil, err + } + if spec.Previous == nil || spec.Available == nil || spec.Revision == "" { + return nil, invalidModuleState("incomplete adoption declarations") + } + ledger, err := reconcile.LoadLedger(rt.root) + if err != nil { + return nil, invalidModuleState("could not read adoption ledger") + } + offers, muts, records, err := resolveAdoptionAnswers( + id, + spec.Previous, + spec.Available, + ledger, + answers, + ) + if err != nil { + return nil, err + } + for _, m := range muts { + parts := nixdata.SplitConfigPath(m.Path) + if len(parts) == 0 { + return nil, invalidModuleState("invalid adoption option path") + } + n := min(len(parts), len(path)) + if slices.Equal(path[:n], parts[:n]) && + !(slices.Equal(parts, path) && m.Value == true) { + return nil, invalidModuleState("adoption conflicts with the module enable option") + } + } + if len(muts) != 0 { + // Pass references to fresh declarations, not their private config + // values, on the process command line. Bind the second evaluation + // to the declaration set just validated by the shared resolver. + apply, err := answeredModuleProjection(prefix, spec.Revision, records) + if err != nil { + return nil, err + } + var answered struct{ Before, After modulePreviewPlan } + if err := evalModulePlan(ctx, rt, apply, &answered); err != nil { + return nil, err + } + spec.Before, spec.After = answered.Before, answered.After + } + before, err := spec.Before.fileHashes() + if err != nil { + return nil, err + } + after, err := spec.After.fileHashes() + if err != nil { + return nil, err + } + return &moduleAdoptionPlan{ + enablePath: path, ledger: ledger, records: records, mutations: muts, + preview: &agentv1.ModulePreview{ + Files: modulePreviewDiff( + before, + after, + ), + Services: modulePreviewDiff(spec.Before.Services, spec.After.Services), + Packages: modulePreviewDiff( + spec.Before.Packages, + spec.After.Packages, + ), + Offers: offers, + }, + }, nil +} + +// Resolve the base config and selected choice configs inside Nix. The Go +// resolver has rejected conflicting leaf assignments, so a recursive union +// reproduces exactly the patch that reconcile.Materialize will persist. +func answeredModuleProjection( + prefix, revision string, + records map[string]reconcile.LedgerEntry, +) (string, error) { + type selection struct { + ID string `json:"id"` + Choices []string `json:"choices"` + } + choices := []selection{} + for _, id := range slices.Sorted(maps.Keys(records)) { + sel := selection{ID: id, Choices: []string{}} + switch a := records[id].Answer.(type) { + case bool: + if !a { + continue + } + case string: + if a == "" { + continue + } + sel.Choices = []string{a} + case []string: + if len(a) == 0 { + continue + } + sel.Choices = a + default: + return "", invalidModuleState("invalid resolved adoption answer") + } + choices = append(choices, sel) + } + data, err := json.Marshal(choices) + if err != nil { + return "", err + } + return prefix + `decisions = builtins.fromJSON ` + nixser.QuoteString( + string(data), + ) + `; + by = key: values: builtins.listToAttrs (map (v: { name = v.${key}; value = v; }) values); + specs = by "id" enabled.addons; + configs = builtins.concatMap (s: let a = specs.${s.id}; choices = by "value" (a.question.choices or []); + in [(a.config or {})] ++ map (k: choices.${k}.config or {}) s.choices) decisions; + merge = a: b: builtins.zipAttrsWith (_: vs: if builtins.length vs == 1 then builtins.head vs + else merge (builtins.head vs) (builtins.elemAt vs 1)) [a b]; + adoption = builtins.foldl' merge {} configs; +in assert builtins.hashString "sha256" (builtins.toJSON enabled.addons) == ` + nixser.QuoteString( + revision, + ) + `; + { before = project (f {}); after = project (f { enablePath = path; inherit adoption; }); }`, nil +} + +func (s *moduleService) PreviewModuleEnable( + ctx context.Context, + req *connect.Request[agentv1.PreviewModuleEnableRequest], +) (*connect.Response[agentv1.PreviewModuleEnableResponse], error) { + rt := runtimeFor(ctx) + if rt == nil || rt.root == "" { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("no project selected"), + ) + } + var plan *moduleAdoptionPlan + err := withModuleConfigLock(ctx, rt, func(ctx context.Context) error { + var err error + plan, err = prepareModuleAdoption( + ctx, + rt, + req.Msg.GetModuleId(), + req.Msg.GetAnswers(), + ) + return err + }) + if err != nil { + return nil, err + } + return connect.NewResponse( + &agentv1.PreviewModuleEnableResponse{Preview: plan.preview}, + ), nil +} diff --git a/apps/stackpanel-go/internal/agent/server/module_proxy.go b/apps/stackpanel-go/internal/agent/server/module_proxy.go new file mode 100644 index 00000000..634736e5 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_proxy.go @@ -0,0 +1,268 @@ +package server + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + moduleProxyRequestLimit = 1 << 20 + moduleProxyResponseLimit = 8 << 20 +) + +var errModuleProxyIdentity = errors.New("service identity unavailable") + +func (s *Server) handleModuleProxy(w http.ResponseWriter, r *http.Request) { + // These responses are data, not pages or scripts served by the agent. + w.Header(). + Set("Content-Security-Policy", "sandbox; default-src 'none'; frame-ancestors 'none'") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Cache-Control", "no-store") + rt := runtimeFor(r.Context()) + if rt == nil || rt.root == "" { + http.Error(w, "project scope required", http.StatusForbidden) + return + } + switch r.Method { + case http.MethodGet, + http.MethodHead, + http.MethodPost, + http.MethodPut, + http.MethodPatch, + http.MethodDelete: + default: + w.Header().Set("Allow", "GET, HEAD, POST, PUT, PATCH, DELETE") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + module, service, rest := r.PathValue( + "module", + ), r.PathValue( + "service", + ), r.PathValue( + "rest", + ) + if !moduleProxySegment(module) || !moduleProxySegment(service) || !moduleProxyPath(rest) || + r.URL.IsAbs() || r.URL.Host != "" || r.URL.Opaque != "" || r.URL.User != nil || r.URL.Fragment != "" || + r.URL.ForceQuery || + r.URL.RawQuery != "" || + strings.Contains(r.URL.EscapedPath(), "%") { + http.Error(w, "invalid proxy path", http.StatusBadRequest) + return + } + upgrade, ok := moduleProxyHandshake(r) + if !ok || len(r.Trailer) != 0 || len(r.Header.Values("Trailer")) != 0 || + len(r.Header.Values("Te")) != 0 || + len(r.Header.Values("Expect")) != 0 || + len(r.Header.Values("Content-Encoding")) != 0 || + len(r.Header.Values("Content-Type")) > 1 || + ((r.Method == http.MethodGet || r.Method == http.MethodHead) && r.ContentLength != 0) { + http.Error(w, "unsupported request framing", http.StatusBadRequest) + return + } + if r.ContentLength > moduleProxyRequestLimit { + http.Error(w, "request too large", http.StatusRequestEntityTooLarge) + return + } + state, err := loadModuleState(r.Context(), rt) + if err != nil { + http.Error(w, "project state unavailable", http.StatusServiceUnavailable) + return + } + if err := s.checkModuleProxyGrant(r.Header, rt, state, module); err != nil { + http.Error(w, "service not available", http.StatusForbidden) + return + } + port := moduleProxyPort(state, module, service) + if port == 0 || s.isModuleProxySelf(r, port) { + http.Error(w, "service not available", http.StatusForbidden) + return + } + if err := moduleProxyCheckPort( + rt.root, + service, + port, + state, + moduleStoreRoot, + ); err != nil { + status := http.StatusForbidden + if err == errModuleProxyInventory { + status = http.StatusServiceUnavailable + } + http.Error(w, err.Error(), status) + return + } + target := url.URL{ + Scheme: "http", + Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), + Path: "/" + rest, + } + peer, err := newModuleProxyPeer(rt.root, module, service, target.Host) + if err != nil { + http.Error(w, "service identity unavailable", http.StatusForbidden) + return + } + if upgrade { + target.Scheme = "ws" + s.serveModuleProxyWebSocket(w, r, target, peer) + return + } + serveModuleProxyHTTP(w, r, target, peer) +} + +func moduleProxyPort(state map[string]any, module, name string) int { + mod, err := findModule(state, module) + if err != nil || mod["enabled"] != true { + return 0 + } + services, _ := state["services"].(map[string]any) + svc, _ := services[name].(map[string]any) + proxy, _ := svc["proxy"].(map[string]any) + if svc["module"] != module || svc["enable"] != true || proxy["enable"] != true { + return 0 + } + port, ok := proxy["port"].(float64) // json.Unmarshal of the evaluated Nix state + if !ok || !(1 <= port && port <= 65535) || port != float64(int(port)) { + return 0 + } + return int(port) +} + +func (s *Server) isModuleProxySelf(r *http.Request, port int) bool { + if s.config != nil && port == s.config.Port { + return true + } + // LocalAddr also covers ephemeral listeners. Never trust r.Host for this. + addr, _ := r.Context().Value(http.LocalAddrContextKey).(*net.TCPAddr) + return addr != nil && addr.Port == port +} + +func moduleProxySegment(segment string) bool { + if segment == "" || segment == "." || segment == ".." { + return false + } + for _, c := range segment { + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("-._~", c)) { + return false + } + } + return true +} + +func moduleProxyPath(rest string) bool { + // Empty rest is the root. Allow a trailing slash, but not empty interior + // segments, escaping, scheme/authority syntax, or path normalization. + for rest != "" { + var segment string + segment, rest, _ = strings.Cut(rest, "/") + if !moduleProxySegment(segment) { + return false + } + } + return true +} + +func serveModuleProxyHTTP( + w http.ResponseWriter, + r *http.Request, + target url.URL, + peer moduleProxyPeer, +) { + // Finish validating unknown-length bodies (including undeclared trailers) + // before sending even the first byte of a mutating request to the service. + var body []byte + if r.Body != nil && r.Body != http.NoBody { + var err error + body, err = io.ReadAll(http.MaxBytesReader(w, r.Body, moduleProxyRequestLimit)) + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + http.Error(w, "request too large", http.StatusRequestEntityTooLarge) + return + } + if err != nil || len(r.Trailer) != 0 { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + out, err := http.NewRequestWithContext( + ctx, + r.Method, + target.String(), + bytes.NewReader(body), + ) + if err != nil { + http.Error(w, "invalid proxy request", http.StatusBadRequest) + return + } + // Build from scratch: never forward bearer, cookies, Origin, project, + // Forwarded, method override, or arbitrary extension headers. + for _, key := range []string{"Accept", "Content-Type"} { + if v := r.Header.Get(key); v != "" { + out.Header.Set(key, v) + } + } + // No proxy environment, redirects, cookies or reusable TCP connections. + transport := http.Transport{ + DialContext: peer.dial, DisableKeepAlives: true, DisableCompression: true, + MaxResponseHeaderBytes: 32 << 10, ResponseHeaderTimeout: 10 * time.Second, + } + resp, err := transport.RoundTrip(out) + if err != nil { + http.Error(w, "service unavailable", http.StatusBadGateway) + return + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 && resp.StatusCode < 400 || resp.StatusCode > 599 || + len(resp.Trailer) != 0 || + len(resp.Header.Values("Trailer")) != 0 || + resp.Header.Get("Content-Encoding") != "" || + (r.Method != http.MethodHead && resp.ContentLength > moduleProxyResponseLimit) { + http.Error(w, "unsupported service response", http.StatusBadGateway) + return + } + data, err := io.ReadAll(io.LimitReader(resp.Body, moduleProxyResponseLimit+1)) + if err != nil || len(data) > moduleProxyResponseLimit || len(resp.Trailer) != 0 { + http.Error(w, "invalid service response", http.StatusBadGateway) + return + } + // Keep outer middleware's CORS policy; do not relay cookies, redirects, + // refreshes, hop-by-hop metadata or upstream authentication challenges. + mediaType := resp.Header.Get("Content-Type") + if mediaType == "" || moduleProxyConnectionNames(resp.Header, "Content-Type") { + mediaType = "application/octet-stream" + } + w.Header().Set("Content-Type", mediaType) + w.Header().Set("Content-Disposition", "attachment") + // Studio must distinguish an upstream 401/403 from an agent rejecting its + // document grant. This marker is set here, never copied from the service. + w.Header().Set("X-Stackpanel-Service-Response", "1") + w.Header().Add("Access-Control-Expose-Headers", "X-Stackpanel-Service-Response") + if r.Method == http.MethodHead && resp.ContentLength >= 0 { + w.Header().Set("Content-Length", strconv.FormatInt(resp.ContentLength, 10)) + } + w.WriteHeader(resp.StatusCode) + if len(data) != 0 { + _, _ = w.Write(data) + } +} + +func moduleProxyConnectionNames(header http.Header, name string) bool { + for _, list := range header.Values("Connection") { + for token := range strings.SplitSeq(list, ",") { + if strings.EqualFold(strings.TrimSpace(token), name) { + return true + } + } + } + return false +} diff --git a/apps/stackpanel-go/internal/agent/server/module_proxy_inventory.go b/apps/stackpanel-go/internal/agent/server/module_proxy_inventory.go new file mode 100644 index 00000000..b64d4e00 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_proxy_inventory.go @@ -0,0 +1,120 @@ +package server + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +var ( + errModuleProxyConflict = errors.New("port claimed by another service") + errModuleProxyInventory = errors.New( + "service inventory unavailable; re-enter registered projects' dev shells", + ) +) + +// Never evaluate another project's flake, start its runtime, or use the +// agent's own shell environment. For other projects, use only the immutable +// port projection installed by their last applied dev shell. +func moduleProxyCheckPort( + root, service string, + port int, + state map[string]any, + store string, +) error { + services, ok := state["services"].(map[string]any) + if !ok { + return errModuleProxyInventory + } + for name, entry := range services { + if name == service { + continue + } + svc, _ := entry.(map[string]any) + enabled, ok := svc["enable"].(bool) + if !ok { + return errModuleProxyInventory + } + if !enabled { + continue + } + proxy, _ := svc["proxy"].(map[string]any) + if svc["port"] == float64(port) || + proxy["enable"] == true && proxy["port"] == float64(port) { + return errModuleProxyConflict + } + } + registry, err := userconfig.NewManager() + if err != nil { + return errModuleProxyInventory + } + selected := false + for _, project := range registry.ListProjects() { + if project.Path == root { + if selected { + return errModuleProxyInventory + } + selected = true + continue + } + ports, err := moduleProxyAppliedPorts(project.Path, store) + if err != nil { + return errModuleProxyInventory + } + if slices.Contains(ports, port) { + return errModuleProxyConflict + } + } + if !selected { + return errModuleProxyInventory + } + return nil +} + +func moduleProxyAppliedPorts(root, store string) ([]int, error) { + const name = "module-proxy-ports.json" + if !filepath.IsAbs(root) { + return nil, errModuleProxyInventory + } + profile := root + for _, component := range []string{".stack", "profile"} { + profile = filepath.Join(profile, component) + info, err := os.Lstat(profile) + if err != nil || !info.IsDir() { + return nil, errModuleProxyInventory + } + } + target, err := os.Readlink(filepath.Join(profile, name)) + if err != nil || !validModulePackage(target, store) || + !strings.HasSuffix(target, "-stackpanel-"+name) { + return nil, errModuleProxyInventory + } + info, err := os.Lstat(target) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o222 != 0 || + info.Size() > 1<<20 { + return nil, errModuleProxyInventory + } + data, err := os.ReadFile(target) + if err != nil { + return nil, errModuleProxyInventory + } + var index struct { + SchemaVersion int `json:"schemaVersion"` + Ports []int `json:"ports"` + } + if json.Unmarshal(data, &index) != nil || index.SchemaVersion != 1 || + index.Ports == nil { + return nil, errModuleProxyInventory + } + for _, port := range index.Ports { + if port < 1 || port > 65535 { + return nil, errModuleProxyInventory + } + } + return index.Ports, nil +} diff --git a/apps/stackpanel-go/internal/agent/server/module_proxy_peer_other.go b/apps/stackpanel-go/internal/agent/server/module_proxy_peer_other.go new file mode 100644 index 00000000..396aefa1 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_proxy_peer_other.go @@ -0,0 +1,20 @@ +//go:build !darwin && !linux + +package server + +import ( + "context" + "net" +) + +// No portable kernel evidence of which process owns an accepted TCP socket. +// Never degrade to a bare dial on an unsupported platform. +type moduleProxyPeer struct{} + +func newModuleProxyPeer(_, _, _, _ string) (moduleProxyPeer, error) { + return moduleProxyPeer{}, errModuleProxyIdentity +} + +func (moduleProxyPeer) dial(context.Context, string, string) (net.Conn, error) { + return nil, errModuleProxyIdentity +} diff --git a/apps/stackpanel-go/internal/agent/server/module_proxy_peer_test.go b/apps/stackpanel-go/internal/agent/server/module_proxy_peer_test.go new file mode 100644 index 00000000..455f09c1 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_proxy_peer_test.go @@ -0,0 +1,223 @@ +package server + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +func moduleProxyRegister(t *testing.T, roots ...string) { + t.Helper() + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "registry.yaml")) + reg, err := userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + for _, root := range roots { + if _, err := reg.AddProject(root, ""); err != nil { + t.Fatal(err) + } + } +} + +func moduleProxyMarker(t *testing.T, root string) string { + t.Helper() + dir := filepath.Join(root, ".stack/state/proxy/demo") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "api.identity") + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatal(err) + } + return path +} + +// The actual service socket must be owned by a process distinct from the +// agent, as it would be under process-compose. The fixture relays bytes to a +// test-owned httptest handler so protocol assertions report to the parent T. +func moduleProxyManagedPort(t *testing.T, root, backend string) int { + t.Helper() + ln, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + fd, err := ln.File() + if err != nil { + t.Fatal(err) + } + defer fd.Close() + marker, err := os.Open(moduleProxyMarker(t, root)) + if err != nil { + t.Fatal(err) + } + defer marker.Close() + reader, ready, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer reader.Close() + cmd := exec.Command(os.Args[0], "-test.run=^TestModuleProxyFixtureProcess$") + cmd.Env = append(os.Environ(), "STACKPANEL_TEST_PROXY_BACKEND="+backend) + cmd.ExtraFiles = []*os.File{fd, ready, nil, nil, nil, nil, marker} // fd 3, 4, 9 + if err := cmd.Start(); err != nil { + ready.Close() + t.Fatal(err) + } + ready.Close() + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }) + _ = reader.SetReadDeadline(time.Now().Add(10 * time.Second)) + var b [1]byte + if _, err := io.ReadFull(reader, b[:]); err != nil { + t.Fatal(err) + } + return ln.Addr().(*net.TCPAddr).Port +} + +func TestModuleProxyFixtureProcess(t *testing.T) { + backend := os.Getenv("STACKPANEL_TEST_PROXY_BACKEND") + if backend == "" { + return + } + addr, err := net.ResolveTCPAddr("tcp4", backend) + if err != nil || !addr.IP.Equal(net.IPv4(127, 0, 0, 1)) { + t.Fatal("invalid fixture endpoint") + } + fd := os.NewFile(3, "listener") + ln, err := net.FileListener(fd) + if err != nil { + t.Fatal(err) + } + fd.Close() + ready := os.NewFile(4, "ready") + _, _ = ready.Write([]byte{1}) + ready.Close() + for { + in, err := ln.Accept() + if err != nil { + return + } + go func() { + defer in.Close() + out, err := net.DialTimeout("tcp4", backend, time.Second) + if err != nil { + return + } + defer out.Close() + go func() { _, _ = io.Copy(out, in); _ = out.(*net.TCPConn).CloseWrite() }() + _, _ = io.Copy(in, out) + }() + } +} + +func TestModuleProxyRegisteredPortConflict(t *testing.T) { + selected, other, store := t.TempDir(), t.TempDir(), t.TempDir() + moduleProxyRegister(t, selected, other) + service := httptest.NewServer( + http.HandlerFunc( + func(http.ResponseWriter, *http.Request) { t.Error("denied service received bytes") }, + ), + ) + defer service.Close() + port := moduleProxyManagedPort(t, other, service.Listener.Addr().String()) + state := moduleProxyTestState(port) + // Same data shape as live Nix, after json.Unmarshal into map[string]any. + state["services"].(map[string]any)["api"].(map[string]any)["proxy"].(map[string]any)["port"] = float64( + port, + ) + if err := moduleProxyCheckPort( + selected, + "api", + port, + state, + store, + ); err != errModuleProxyInventory { + t.Fatalf("missing inventory: %v", err) + } + dir := filepath.Join(other, ".stack/profile") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + for i, ports := range []string{fmt.Sprintf("[%d]", port), "[]"} { + path := filepath.Join( + store, + fmt.Sprintf("%032d-stackpanel-module-proxy-ports.json", i), + ) + if err := os.WriteFile( + path, + []byte(`{"schemaVersion":1,"ports":`+ports+`}`), + 0o444, + ); err != nil { + t.Fatal(err) + } + link := filepath.Join(dir, "module-proxy-ports.json") + if i != 0 { + if err := os.Remove(link); err != nil { + t.Fatal(err) + } + } + if err := os.Symlink(path, link); err != nil { + t.Fatal(err) + } + err := moduleProxyCheckPort(selected, "api", port, state, store) + if i == 0 && err != errModuleProxyConflict || i == 1 && err != nil { + t.Fatalf("inventory %s: %v", ports, err) + } + } + // A stale last-applied inventory may miss a collision; it still cannot + // grant access to the unambiguously *other* project's physical listener. + moduleProxyMarker(t, selected) + address := fmt.Sprintf("127.0.0.1:%d", port) + peer, err := newModuleProxyPeer(selected, "demo", "api", address) + if err != nil { + t.Fatal(err) + } + if c, err := peer.dial(context.Background(), "tcp", address); err == nil { + c.Close() + t.Fatal("cross-project peer accepted") + } +} + +func TestModuleProxyRejectsUnsafeMarkers(t *testing.T) { + for _, kind := range []string{"missing", "public", "symlink", "hardlink", "directory alias"} { + t.Run(kind, func(t *testing.T) { + root := t.TempDir() + path := moduleProxyMarker(t, root) + var err error + switch kind { + case "missing": + err = os.Remove(path) + case "public": + err = os.Chmod(path, 0o644) + case "symlink": + if err = os.Rename(path, path+".other"); err == nil { + err = os.Symlink(path+".other", path) + } + case "hardlink": + err = os.Link(path, path+".other") + case "directory alias": + dir := filepath.Dir(path) + if err = os.Rename(dir, dir+".other"); err == nil { + err = os.Symlink(dir+".other", dir) + } + } + if err != nil { + t.Fatal(err) + } + if _, err := newModuleProxyPeer(root, "demo", "api", "127.0.0.1:1"); err == nil { + t.Fatal("unsafe marker accepted") + } + }) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/module_proxy_peer_unix.go b/apps/stackpanel-go/internal/agent/server/module_proxy_peer_unix.go new file mode 100644 index 00000000..ca35992e --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_proxy_peer_unix.go @@ -0,0 +1,227 @@ +//go:build darwin || linux + +package server + +import ( + "context" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +// The process-compose launcher gives the service an inherited, read-only fd 9 +// for this marker. This is local process attribution, not a boundary against +// hostile same-UID executables (which can also read the agent's credentials). +// Never inspect process environments, argv, or traffic to establish identity. +type moduleProxyPeer struct { + address, marker, dev, inode, uid, lsof string +} + +func newModuleProxyPeer( + root, module, service, address string, +) (moduleProxyPeer, error) { + var peer moduleProxyPeer + if !filepath.IsAbs(root) || !moduleProxySegment(module) || + !moduleProxySegment(service) { + return peer, errModuleProxyIdentity + } + // Open directory components individually with no-follow. In particular a + // marker symlink/hard link must not alias another module or checkout. + real, err := filepath.EvalSymlinks(root) + if err != nil { + return peer, errModuleProxyIdentity + } + fd, err := unix.Open( + real, + unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, + 0, + ) + if err != nil { + return peer, errModuleProxyIdentity + } + for _, part := range []string{".stack", "state", "proxy", module} { + next, err := unix.Openat( + fd, + part, + unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, + 0, + ) + unix.Close(fd) + if err != nil { + return peer, errModuleProxyIdentity + } + fd = next + } + defer unix.Close(fd) + var stat unix.Stat_t + leaf := service + ".identity" + if unix.Fstatat(fd, leaf, &stat, unix.AT_SYMLINK_NOFOLLOW) != nil || stat.Mode&unix.S_IFMT != unix.S_IFREG || + stat.Uid != uint32(os.Geteuid()) || stat.Mode&0o7777 != 0o600 || + stat.Nlink != 1 { + return peer, errModuleProxyIdentity + } + binary := moduleProxyLsof() + if binary == "" { + return peer, errModuleProxyIdentity + } + return moduleProxyPeer{ + address: address, + marker: filepath.Join(real, ".stack", "state", "proxy", module, leaf), + dev: "0x" + strconv.FormatUint( + uint64(stat.Dev), + 16, + ), + inode: strconv.FormatUint(stat.Ino, 10), + uid: strconv.Itoa(os.Geteuid()), + lsof: binary, + }, nil +} + +func moduleProxyLsof() string { + for _, path := range []string{"/usr/sbin/lsof", "/usr/bin/lsof", "/run/current-system/sw/bin/lsof"} { + if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() { + return path + } + } + // A Nix shell needn't install lsof system-wide. Never execute a binary + // from a checkout, a user-writable PATH entry or the process's current dir. + if path, err := exec.LookPath("lsof"); err == nil { + if real, err := filepath.EvalSymlinks( + path, + ); err == nil && + strings.HasPrefix(real, "/nix/store/") { + return real + } + } + return "" +} + +func (p moduleProxyPeer) dial( + ctx context.Context, + network, addr string, +) (net.Conn, error) { + if network != "tcp" || addr != p.address { + return nil, errModuleProxyIdentity + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + // Check the listening owner before even opening a socket. Then verify the + // *accepted* connection using both endpoints. A port reused between the two + // checks can never receive HTTP bytes. No second dial after verification. + if !p.ownsSocket(ctx, p.address, "LISTEN") { + return nil, errModuleProxyIdentity + } + conn, err := (&net.Dialer{}).DialContext(ctx, "tcp4", p.address) + if err != nil { + return nil, errModuleProxyIdentity + } + if !p.ownsSocket(ctx, p.address+"->"+conn.LocalAddr().String(), "ESTABLISHED") { + conn.Close() + return nil, errModuleProxyIdentity + } + return conn, nil +} + +func (p moduleProxyPeer) ownsSocket(ctx context.Context, endpoint, state string) bool { + _, port, err := net.SplitHostPort(p.address) + if err != nil { + return false + } + // OR selectors: include records for both the marker and relevant TCP FDs. + // -nP disables DNS/service lookups. A bounded machine-readable snapshot; + // don't send output, paths or stderr to either HTTP clients or agent logs. + cmd := exec.CommandContext( + ctx, + p.lsof, + "-nP", + "-F0pufatDinT", + "-i4TCP:"+port, + "--", + p.marker, + ) + cmd.Env = []string{"LC_ALL=C"} + out, err := cmd.StdoutPipe() + if err != nil || cmd.Start() != nil { + return false + } + const max = 1 << 20 + var data strings.Builder + n, err := io.Copy(&data, io.LimitReader(out, max+1)) + if err != nil || n > max { + _ = cmd.Process.Kill() + } + if cmd.Wait() != nil || err != nil || n > max { + return false + } + return p.matchesSnapshot(data.String(), endpoint, state, port) +} + +func (p moduleProxyPeer) matchesSnapshot(data, endpoint, state, port string) bool { + owners := 0 + var pid, uid string + var marker, socket bool + ownerOK := func() bool { + if !socket { + return true + } + owners++ + return owners == 1 && marker && uid == p.uid && pid != "" && + pid != strconv.Itoa(os.Getpid()) + } + // lsof -F0: fields end in NUL, process and file records in NUL/newline. + for record := range strings.SplitSeq(data, "\x00\n") { + if len(record) == 0 { + continue + } + if record[0] == 'p' { + if !ownerOK() { + return false + } + uid, marker, socket = "", false, false + } + var fd, access, kind, dev, ino, name, tcp string + for field := range strings.SplitSeq(record, "\x00") { + if len(field) < 2 { + continue + } + v := field[1:] + switch field[0] { + case 'p': + pid = v + case 'u': + uid = v + case 'f': + fd = v + case 'a': + access = v + case 't': + kind = v + case 'D': + dev = v + case 'i': + ino = v + case 'n': + name = v + case 'T': + if strings.HasPrefix(v, "ST=") { + tcp = v[3:] + } + } + } + if fd == "9" && access == "r" && kind == "REG" && dev == p.dev && ino == p.inode { + marker = true + } + if kind == "IPv4" && tcp == state && + (name == endpoint || state == "LISTEN" && name == "*:"+port) { + socket = true + } + } + return ownerOK() && owners == 1 +} diff --git a/apps/stackpanel-go/internal/agent/server/module_proxy_test.go b/apps/stackpanel-go/internal/agent/server/module_proxy_test.go new file mode 100644 index 00000000..f3bf984b --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_proxy_test.go @@ -0,0 +1,492 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/http/httptrace" + "net/textproto" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" + + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/config" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +const moduleProxyTestPrefix = "/api/v1/modules/demo/services/api/proxy/" + +func moduleProxyTestState(port int) map[string]any { + return map[string]any{ + "modulesListAll": []map[string]any{{"id": "demo", "enabled": true}}, + "services": map[string]any{"api": map[string]any{ + "module": "demo", + "enable": true, + "proxy": map[string]any{"enable": true, "port": port}, + }}, + } +} + +func moduleProxyTestRuntime( + t *testing.T, + root string, + state map[string]any, +) *projectRuntime { + t.Helper() + data, err := json.Marshal(state) + if err != nil { + t.Fatal(err) + } + return &projectRuntime{ + root: root, + evalModuleState: func(_ context.Context, got string) ([]byte, error) { + if got != root { + return nil, fmt.Errorf("wrong evaluation root") + } + return data, nil + }, + } +} + +func moduleProxyTestAgent(t *testing.T, upstream *httptest.Server) *httptest.Server { + t.Helper() + root := t.TempDir() + moduleProxyRegister(t, root) + port := moduleProxyManagedPort(t, root, upstream.Listener.Addr().String()) + state, panel, _ := uiTestState() + panel["uiBundle"].(map[string]any)["permissions"] = []any{"service:proxy"} + state["services"] = moduleProxyTestState(port)["services"] + rt := moduleProxyTestRuntime(t, root, state) + s := newUITestServer(t) + grant, err := s.issueModuleUIGrant( + root, + state, + "demo", + "inspector", + "", + moduleStoreRoot, + userconfig.LinkedModule{}, + ) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc( + "/api/v1/modules/{module}/services/{service}/proxy/{rest...}", + func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(moduleUIGrantHeader) == "" { + r.Header.Set(moduleUIGrantHeader, grant) + } + w.Header().Set("Access-Control-Allow-Origin", "https://studio.example") + s.handleModuleProxy( + w, + r.WithContext(context.WithValue(r.Context(), runtimeKey{}, rt)), + ) + }, + ) + agent := httptest.NewServer(mux) + t.Cleanup(agent.Close) + return agent +} + +func TestModuleProxyHTTP(t *testing.T) { + payload := []byte{0, 0xff, 1, 2} + var calls atomic.Int32 + service := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if !strings.HasPrefix(r.Host, "127.0.0.1:") || + r.URL.RequestURI() != "/items/v1.2" { + t.Errorf("unexpected service target: %s %s", r.Host, r.URL.RequestURI()) + } + if r.Header.Get("Content-Type") != "application/octet-stream" || + r.Header.Get("Accept") != "application/json" { + t.Error("missing representation headers") + } + for _, k := range []string{moduleUIGrantHeader, "Authorization", "Cookie", "Origin", projectHeader, "X-Stackpanel-Token", "Proxy-Authorization", "X-Forwarded-Host", "Forwarded", "X-HTTP-Method-Override", "Referer"} { + if r.Header.Get(k) != "" { + t.Errorf("relayed request header %s", k) + } + } + got, err := io.ReadAll(r.Body) + want := payload + if r.Method == "GET" || r.Method == "HEAD" { + want = nil + } + if err != nil || !bytes.Equal(got, want) { + t.Errorf("unexpected %s request body: %x, %v", r.Method, got, err) + } + w.Header().Set("Set-Cookie", "from=service") + w.Header().Set("X-Stackpanel-Service-Response", "untrusted") + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Location", "https://unused.invalid/") + w.Header().Set("Refresh", "0") + w.Header().Set("Link", "; rel=preload") + w.WriteHeader(http.StatusEarlyHints) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(r.Method)) + }), + ) + defer service.Close() + agent := moduleProxyTestAgent(t, service) + for _, method := range []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"} { + t.Run(method, func(t *testing.T) { + ctx := httptrace.WithClientTrace( + t.Context(), + &httptrace.ClientTrace{Got1xxResponse: func(int, textproto.MIMEHeader) error { + return fmt.Errorf("upstream informational headers escaped") + }}, + ) + var body io.Reader + if method != "GET" && method != "HEAD" { + body = bytes.NewReader(payload) + } + req, err := http.NewRequestWithContext( + ctx, + method, + agent.URL+moduleProxyTestPrefix+"items/v1.2", + body, + ) + if err != nil { + t.Fatal(err) + } + req.Host = "virtual-host.invalid:12345" + req.Header.Set("Origin", "https://studio.example") + req.Header.Set("Content-Type", "application/octet-stream") + req.Header.Set("Accept", "application/json") + for _, k := range []string{"Authorization", "Cookie", projectHeader, "X-Stackpanel-Token", "Proxy-Authorization", "X-Forwarded-Host", "Forwarded", "X-HTTP-Method-Override", "Referer"} { + req.Header.Set(k, "private") + } + res, err := agent.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + got, err := io.ReadAll(res.Body) + want := method + if method == "HEAD" { + want = "" + } + if err != nil || res.StatusCode != http.StatusCreated || string(got) != want { + t.Fatalf("response: %d %q %v", res.StatusCode, got, err) + } + if res.Header.Get("X-Stackpanel-Service-Response") != "1" { + t.Fatal("service response metadata did not come from agent") + } + if res.Header.Get("Content-Type") != "application/json" || + res.Header.Get("Access-Control-Allow-Origin") != "https://studio.example" || + !strings.Contains(res.Header.Get("Content-Security-Policy"), "sandbox") || + res.Header.Get("Cache-Control") != "no-store" { + t.Errorf("unexpected response policy: %v", res.Header) + } + for _, k := range []string{"Set-Cookie", "Location", "Refresh", "Link"} { + if res.Header.Get(k) != "" { + t.Errorf("relayed service header %s", k) + } + } + }) + } + if n := calls.Load(); n != 6 { + t.Errorf("service handled %d requests; want 6", n) + } +} + +func TestModuleProxyWebSocket(t *testing.T) { + service := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.RequestURI() != "/ws" || !strings.HasPrefix(r.Host, "127.0.0.1:") { + t.Error("wrong websocket target") + } + for _, k := range []string{moduleUIGrantHeader, "Origin", "Authorization", "Cookie", projectHeader, "Sec-WebSocket-Extensions"} { + if r.Header.Get(k) != "" { + t.Errorf("relayed handshake header %s", k) + } + } + upgrader := websocket.Upgrader{} + c, err := upgrader.Upgrade( + w, + r, + http.Header{ + "Set-Cookie": {"service=secret"}, + "Access-Control-Allow-Origin": {"*"}, + }, + ) + if err != nil { + t.Error(err) + return + } + defer c.Close() + kind, data, err := c.ReadMessage() + if err != nil || kind != websocket.BinaryMessage || + !bytes.Equal(data, []byte{0, 0xff}) { + t.Errorf("service received %d %x %v", kind, data, err) + return + } + if err := c.WriteMessage(websocket.TextMessage, []byte("reply")); err != nil { + t.Error(err) + } + }), + ) + defer service.Close() + agent := moduleProxyTestAgent(t, service) + dialer := websocket.Dialer{EnableCompression: true, HandshakeTimeout: 5 * time.Second} + c, resp, err := dialer.DialContext( + t.Context(), + "ws"+strings.TrimPrefix(agent.URL, "http")+moduleProxyTestPrefix+"ws", + http.Header{ + "Origin": { + "https://studio.example", + }, + "Authorization": {"Bearer private"}, + "Cookie": {"agent=session"}, + projectHeader: {"demo"}, + }, + ) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if resp.Header.Get("Set-Cookie") != "" || + resp.Header.Get("Access-Control-Allow-Origin") == "*" || + resp.Header.Get("Sec-WebSocket-Extensions") != "" { + t.Errorf("relayed upstream handshake: %v", resp.Header) + } + _ = c.SetReadDeadline(time.Now().Add(5 * time.Second)) + if err := c.WriteMessage(websocket.BinaryMessage, []byte{0, 0xff}); err != nil { + t.Fatal(err) + } + kind, data, err := c.ReadMessage() + if err != nil || kind != websocket.TextMessage || string(data) != "reply" { + t.Errorf("client received %d %q %v", kind, data, err) + } +} + +func TestModuleProxyRejectsUntrustedServiceResponses(t *testing.T) { + service := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/redirect": + http.Redirect(w, r, "/never", http.StatusTemporaryRedirect) + case "/trailers": + w.Header().Set("Trailer", "X-End") + _, _ = w.Write([]byte("private")) + w.Header().Set("X-End", "private") + case "/late-trailers": + w.(http.Flusher).Flush() + _, _ = w.Write([]byte("private")) + w.Header().Set(http.TrailerPrefix+"X-End", "private") + case "/excess": + w.Header().Set("Content-Length", fmt.Sprint(moduleProxyResponseLimit+1)) + default: + t.Errorf("unexpected service request: %s", r.URL.Path) + } + }), + ) + defer service.Close() + agent := moduleProxyTestAgent(t, service) + for _, rest := range []string{"redirect", "trailers", "late-trailers", "excess"} { + res, err := agent.Client().Get(agent.URL + moduleProxyTestPrefix + rest) + if err != nil { + t.Fatal(err) + } + b, err := io.ReadAll(res.Body) + res.Body.Close() + if err != nil || res.StatusCode != http.StatusBadGateway || + res.Header.Get("Location") != "" || + len(res.Trailer) > 0 || + bytes.Contains(b, []byte("private")) { + t.Errorf( + "%s: %d %v %v %q %v", + rest, + res.StatusCode, + res.Header, + res.Trailer, + b, + err, + ) + } + } +} + +func TestModuleProxyRejectsInvalidUIGrant(t *testing.T) { + service := httptest.NewServer( + http.HandlerFunc( + func(http.ResponseWriter, *http.Request) { t.Error("invalid grant reached service") }, + ), + ) + defer service.Close() + agent := moduleProxyTestAgent(t, service) + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + agent.URL+moduleProxyTestPrefix, + nil, + ) + if err != nil { + t.Fatal(err) + } + req.Header.Set(moduleUIGrantHeader, "not-a-grant") + resp, err := agent.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + t.Errorf("invalid grant: %d", resp.StatusCode) + } +} + +func TestModuleProxyFailsClosed(t *testing.T) { + var dials atomic.Int32 + service := httptest.NewServer( + http.HandlerFunc(func(http.ResponseWriter, *http.Request) { dials.Add(1) }), + ) + defer service.Close() + port := service.Listener.Addr().(*net.TCPAddr).Port + s := &Server{config: &config.Config{Port: 9876, ProjectRoot: "/current"}} + for _, name := range []string{ + "unscoped", "different project", "unknown module", "unknown service", "disabled module", "disabled service", "other owner", "no opt in", + "no proxy port", "string port", "fractional port", "port overflow", "zero port", "configured self", "listener self", + "shared primary port", "shared proxy port", + "query", "empty query", "absolute uri", "dot segment", "empty segment", "leading slash", "encoded slash", "double escape", "backslash", "scheme", + "method", "get body", "trailer", "connection nomination", "alternate upgrade", "incomplete websocket", "subprotocol", "large body", + } { + t.Run(name, func(t *testing.T) { + state := moduleProxyTestState(port) + svc := state["services"].(map[string]any)["api"].(map[string]any) + proxy := svc["proxy"].(map[string]any) + r := httptest.NewRequest("GET", moduleProxyTestPrefix+"items", nil) + r.SetPathValue("module", "demo") + r.SetPathValue("service", "api") + r.SetPathValue("rest", "items") + want := http.StatusBadRequest + switch name { + case "unscoped": + want = http.StatusForbidden + case "different project": + // Current project declarations cannot fill gaps in the scoped runtime. + delete(state, "services") + r.Header.Set(projectHeader, s.config.ProjectRoot) + want = http.StatusForbidden + case "unknown module": + r.SetPathValue("module", "absent") + want = http.StatusForbidden + case "unknown service": + r.SetPathValue("service", "absent") + want = http.StatusForbidden + case "disabled module": + state["modulesListAll"].([]map[string]any)[0]["enabled"] = false + want = http.StatusForbidden + case "disabled service": + svc["enable"], want = false, http.StatusForbidden + case "other owner": + svc["module"], want = "other", http.StatusForbidden + case "no opt in": + proxy["enable"], want = false, http.StatusForbidden + case "no proxy port": + svc["port"] = port // must not fall back to the primary service port + delete(proxy, "port") + want = http.StatusForbidden + case "string port": + proxy["port"], want = fmt.Sprint(port), http.StatusForbidden + case "fractional port": + proxy["port"], want = float64(port)+0.5, http.StatusForbidden + case "port overflow": + proxy["port"], want = 65536, http.StatusForbidden + case "zero port": + proxy["port"], want = 0, http.StatusForbidden + case "configured self": + proxy["port"], want = s.config.Port, http.StatusForbidden + case "listener self": + r = r.WithContext( + context.WithValue( + r.Context(), + http.LocalAddrContextKey, + service.Listener.Addr(), + ), + ) + want = http.StatusForbidden + case "shared primary port": + state["services"].(map[string]any)["other"] = map[string]any{ + "enable": true, + "port": port, + } + want = http.StatusForbidden + case "shared proxy port": + state["services"].(map[string]any)["other"] = map[string]any{ + "enable": true, + "proxy": map[string]any{"enable": true, "port": port}, + } + want = http.StatusForbidden + case "query": + r.URL.RawQuery = "token=private" + case "empty query": + r.URL.ForceQuery = true + case "absolute uri": + r.URL.Scheme, r.URL.Host = "http", "unused.invalid" + case "dot segment": + r.SetPathValue("rest", "items/../other") + case "empty segment": + r.SetPathValue("rest", "items//other") + case "leading slash": + r.SetPathValue("rest", "/other") + case "encoded slash": + r.URL.Path, r.URL.RawPath = moduleProxyTestPrefix+"items/one", moduleProxyTestPrefix+"items%2fone" + r.SetPathValue("rest", "items/one") + case "double escape": + r.SetPathValue("rest", "items%2fone") + case "backslash": + r.SetPathValue("rest", `items\other`) + case "scheme": + r.SetPathValue("rest", "http://unused.invalid") + case "method": + r.Method, want = http.MethodConnect, http.StatusMethodNotAllowed + case "get body": + r.Body, r.ContentLength = io.NopCloser(strings.NewReader("data")), 4 + case "trailer": + r.Method, r.Trailer = http.MethodPost, http.Header{"X-End": nil} + case "connection nomination": + r.Header.Set("Connection", "Content-Type") + case "alternate upgrade": + r.Header.Set("Upgrade", "other") + r.Header.Set("Connection", "Upgrade") + case "incomplete websocket": + r.Header.Set("Upgrade", "websocket") + case "subprotocol": + r.Header.Set("Upgrade", "websocket") + r.Header.Set("Connection", "Upgrade") + r.Header.Set("Sec-WebSocket-Version", "13") + r.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + r.Header.Set("Sec-WebSocket-Protocol", "private") + case "large body": + r.Method, r.ContentLength, want = "POST", moduleProxyRequestLimit+1, http.StatusRequestEntityTooLarge + } + if name != "unscoped" { + r = r.WithContext( + context.WithValue( + r.Context(), + runtimeKey{}, + moduleProxyTestRuntime(t, "/selected", state), + ), + ) + } + w := httptest.NewRecorder() + s.handleModuleProxy(w, r) + if w.Code != want { + t.Errorf("status %d, want %d", w.Code, want) + } + }) + } + if n := dials.Load(); n != 0 { + t.Errorf("service received %d denied requests", n) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/module_proxy_ws.go b/apps/stackpanel-go/internal/agent/server/module_proxy_ws.go new file mode 100644 index 00000000..cc409948 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_proxy_ws.go @@ -0,0 +1,166 @@ +package server + +import ( + "context" + "encoding/base64" + "io" + "math" + "net" + "net/http" + "net/url" + "strings" + "time" + + "github.com/gorilla/websocket" +) + +// Only WebSocket is an upgrade capability. Reject ambiguous handshakes and +// Connection nominations rather than accidentally forwarding hop-only fields. +func moduleProxyHandshake(r *http.Request) (upgrade, valid bool) { + for _, list := range r.Header.Values("Connection") { + for token := range strings.SplitSeq(list, ",") { + switch strings.ToLower(strings.TrimSpace(token)) { + case "upgrade": + upgrade = true + case "close", "keep-alive": + default: + return false, false + } + } + } + if !upgrade { + for k := range r.Header { + if k == "Upgrade" || strings.HasPrefix(k, "Sec-Websocket-") { + return false, false + } + } + return false, true + } + if r.Method != http.MethodGet || r.ProtoMajor != 1 || r.ProtoMinor != 1 || r.Close || + len( + r.Header.Values("Upgrade"), + ) != 1 || !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") || + len( + r.Header.Values("Sec-WebSocket-Version"), + ) != 1 || r.Header.Get("Sec-WebSocket-Version") != "13" || + len( + r.Header.Values("Sec-WebSocket-Key"), + ) != 1 || len(r.Header.Values("Sec-WebSocket-Protocol")) != 0 { + return false, false + } + key := r.Header.Get("Sec-WebSocket-Key") + var decoded [18]byte // maximum decoded size for a padded 24-byte key + if len(key) != 24 { + return false, false + } + n, err := base64.StdEncoding.Strict().Decode(decoded[:], []byte(key)) + return true, err == nil && n == 16 +} + +// Gorilla reads HTTP upgrade headers directly from its connection. Bound that +// read before the validated handshake switches to message framing/read limits. +type moduleProxyHandshakeConn struct { + net.Conn + reader io.LimitedReader +} + +func (c *moduleProxyHandshakeConn) Read( + p []byte, +) (int, error) { + return c.reader.Read(p) +} + +func (s *Server) serveModuleProxyWebSocket( + w http.ResponseWriter, + r *http.Request, + target url.URL, + peer moduleProxyPeer, +) { + var handshake *moduleProxyHandshakeConn + dialer := websocket.Dialer{ + HandshakeTimeout: 10 * time.Second, + NetDialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := peer.dial(ctx, network, addr) + if err != nil { + return nil, err + } + handshake = &moduleProxyHandshakeConn{ + Conn: conn, + reader: io.LimitedReader{R: conn, N: 32 << 10}, + } + return handshake, nil + }, + } + // Independent handshakes, not a raw upgrade tunnel: neither endpoint can + // set the peer's headers, negotiate unsolicited extensions or redirect. + upstream, resp, err := dialer.DialContext(r.Context(), target.String(), nil) + if resp != nil { + defer resp.Body.Close() + } + if err != nil { + http.Error(w, "service websocket unavailable", http.StatusBadGateway) + return + } + defer upstream.Close() + if len(resp.Header.Values("Sec-WebSocket-Protocol")) != 0 || len(resp.Header.Values("Sec-WebSocket-Extensions")) != 0 || + len(resp.Trailer) != 0 || + len(resp.Header.Values("Trailer")) != 0 { + http.Error(w, "unsupported service handshake", http.StatusBadGateway) + return + } + handshake.reader.N = math.MaxInt64 + upgrader := websocket.Upgrader{ + HandshakeTimeout: 10 * time.Second, + // The parent route already enforces the agent's origin policy. Gorilla's + // default is a different policy (same Host) and would reject Studio. + CheckOrigin: func(*http.Request) bool { return true }, + } + client, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer client.Close() + client.SetReadLimit(moduleProxyRequestLimit) + upstream.SetReadLimit(moduleProxyResponseLimit) + done := make(chan struct{}, 2) + go relayModuleProxyMessages(upstream, client, done) + go relayModuleProxyMessages(client, upstream, done) + select { + case <-done: + case <-r.Context().Done(): + case <-s.done: // http.Server.Shutdown does not close hijacked connections + } + // Closing both endpoints unblocks the other direction as well. +} + +func relayModuleProxyMessages(dst, src *websocket.Conn, done chan<- struct{}) { + defer func() { done <- struct{}{} }() + for { + kind, reader, err := src.NextReader() + if err != nil { + if websocket.IsCloseError( + err, + websocket.CloseNormalClosure, + websocket.CloseGoingAway, + ) { + _ = dst.WriteControl( + websocket.CloseMessage, + websocket.FormatCloseMessage(err.(*websocket.CloseError).Code, ""), + time.Now().Add(time.Second), + ) + } + return + } + _ = dst.SetWriteDeadline(time.Now().Add(30 * time.Second)) + writer, err := dst.NextWriter(kind) + if err != nil { + return + } + if _, err := io.Copy(writer, reader); err != nil { + return + } + if err := writer.Close(); err != nil { + return + } + } +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets.go new file mode 100644 index 00000000..19ba137d --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets.go @@ -0,0 +1,402 @@ +package server + +import ( + "context" + "errors" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "connectrpc.com/connect" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +const moduleStoreRoot = "/nix/store" + +var ( + moduleRouteID = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$`) + // The package must be a single Nix output, not a path into another output. + moduleStoreName = regexp.MustCompile( + `^[0-9abcdfghijklmnpqrsvwxyz]{32}-[a-zA-Z0-9+._?=-]+$`, + ) + uiAuthority = regexp.MustCompile( + `^([a-zA-Z0-9.-]+|\[[a-fA-F0-9:]+\])(:[0-9]{1,5})?$`, + ) +) + +func (s *Server) mountModuleCapabilities(mux *http.ServeMux) { + const base = "/api/v1/modules/{module}/" + mux.HandleFunc( + base+"services/{service}/proxy/{rest...}", + s.withModuleProject(s.handleModuleProxy), + ) + mux.HandleFunc(base+"ui/{panel}/{rest...}", s.withModuleProject(s.handleModuleAsset)) + // The ticket route intentionally does not enter the agent auth/CORS stack: + // an opaque iframe presents a bundle-read capability, never an agent credential. + mux.HandleFunc(base+"ui/{panel}/_ticket/{ticket}/{rest...}", s.handleTicketAsset) +} + +func (s *Server) withModuleProject(next http.HandlerFunc) http.HandlerFunc { + return s.withCORS(s.withAllowedOrigin(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if err := (authInterceptor{valid: s.isValidToken}).check("", r.Header); err != nil { + s.writeAPIError(w, http.StatusUnauthorized, "valid bearer credential required") + return + } + id := strings.TrimSpace(r.Header.Get(projectHeader)) + if id == "" || len(r.Header.Values(projectHeader)) != 1 { + s.writeAPIError(w, http.StatusBadRequest, "explicit project required") + return + } + rt, err := s.requestRuntime(r.Header) + if err != nil { + s.writeAPIError(w, http.StatusNotFound, "project unavailable") + return + } + next(w, r.WithContext(context.WithValue(r.Context(), runtimeKey{}, rt))) + })) +} + +type moduleBundle struct { + root, entry, drv string + permissions []string + actionIDs []string + apps map[string]any + module map[string]any + slot string + appSettings map[string]any + appSchemas map[string]any +} + +func customUIDisabled() bool { return os.Getenv("STACKPANEL_DISABLE_CUSTOM_UI") == "1" } + +// Resolve ownership and visibility from the same current project snapshot used +// for dispatch. A request never supplies the document, package, or executable. +func evaluatedUIPanel(state map[string]any, module, panel string) (mod, p map[string]any, err error) { + unavailable := connect.NewError( + connect.CodeNotFound, + errors.New("module panel unavailable"), + ) + if !moduleRouteID.MatchString(module) || !moduleRouteID.MatchString(panel) { + return nil, nil, unavailable + } + mod, err = findModule(state, module) + if err != nil || mod["enabled"] != true { + return nil, nil, unavailable + } + panels, _ := state["panelsList"].([]any) + for _, item := range panels { + entry, _ := item.(map[string]any) + if entry["id"] != panel { + continue + } + if p != nil || entry["module"] != module || entry["enabled"] != true { + return nil, nil, unavailable + } + p = entry + } + if p == nil { + return nil, nil, unavailable + } + return mod, p, nil +} + +func evaluatedModuleBundle(state map[string]any, module, panel, storeRoot string) (*moduleBundle, error) { + mod, p, err := evaluatedUIPanel(state, module, panel) + if err != nil { + return nil, err + } + return customModuleBundle(mod, p, storeRoot) +} + +func customModuleBundle(mod, p map[string]any, storeRoot string) (*moduleBundle, error) { + if p["type"] != "PANEL_TYPE_CUSTOM" { + return nil, connect.NewError(connect.CodeNotFound, errors.New("custom panel unavailable")) + } + if customUIDisabled() { + return nil, connect.NewError(connect.CodePermissionDenied, errors.New("custom UI disabled by agent operator")) + } + bundle, _ := p["uiBundle"].(map[string]any) + root, _ := bundle["package"].(string) + entry, _ := bundle["entry"].(string) + if !validModulePackage(root, storeRoot) || !validAssetPath(entry) { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("invalid UI bundle declaration"), + ) + } + result := &moduleBundle{root: root, entry: entry, module: mod} + result.drv, _ = bundle["drvPath"].(string) + apps, validApps := p["apps"].(map[string]any) + slot, validSlot := p["slot"].(string) + if p["apps"] != nil && !validApps || p["slot"] != nil && !validSlot { + return nil, uiGrantDenied() + } + result.apps, result.slot = apps, slot + result.appSettings, _ = bundle["appSettings"].(map[string]any) + result.appSchemas, _ = bundle["appSchemas"].(map[string]any) + grants, _ := bundle["permissions"].([]any) + for _, grant := range grants { + switch grant { + case "config:read", "config:patch", "actions:run", "service:proxy": + result.permissions = append(result.permissions, grant.(string)) + } + } + result.actionIDs = effectiveUIActions(bundle["actionIds"], mod, result.permissions) + return result, nil +} + +func validModulePackage(root, storeRoot string) bool { + return root == filepath.Join(storeRoot, filepath.Base(root)) && + moduleStoreName.MatchString(filepath.Base(root)) +} + +func requestModuleBundle( + ctx context.Context, + module, panel, storeRoot string, +) (*moduleBundle, error) { + rt := runtimeFor(ctx) + if rt == nil { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("project required"), + ) + } + state, err := loadModuleState(ctx, rt) + if err != nil { + return nil, err + } + return evaluatedModuleBundle(state, module, panel, storeRoot) +} + +func (m *moduleService) OpenModuleUI( + ctx context.Context, + req *connect.Request[agentv1.OpenModuleUIRequest], +) (*connect.Response[agentv1.OpenModuleUIResponse], error) { + return m.openModuleUI(ctx, req, moduleStoreRoot) +} + +func (m *moduleService) openModuleUI( + ctx context.Context, + req *connect.Request[agentv1.OpenModuleUIRequest], + storeRoot string, +) (*connect.Response[agentv1.OpenModuleUIResponse], error) { + module, panel := req.Msg.GetModuleId(), req.Msg.GetPanelId() + rt := runtimeFor(ctx) + state, err := loadModuleState(ctx, rt) + if err != nil { + return nil, err + } + mod, p, err := evaluatedUIPanel(state, module, panel) + if err != nil { + return nil, err + } + root := rt.root + origin := req.Header().Get("Origin") + if !validStudioOrigin(origin) { + return nil, connect.NewError( + connect.CodePermissionDenied, + errors.New("invalid embedding origin"), + ) + } + // Recompute the host's displayed review against this fresh evaluation. + // No package realization, ticket issuance, HMR launch or authority before + // this check. Only an already sealed config-read grant can refresh below. + var profileBin string + var links map[string]userconfig.LinkedModule + _, bound := req.Header()[http.CanonicalHeaderKey(moduleUIGrantHeader)] + if bound { + if p["type"] != "PANEL_TYPE_CUSTOM" || req.Msg.GetReviewRevision() != "" { + return nil, uiGrantDenied() + } + links, err = userconfig.LoadLinkedModules(root) + if err != nil { + return nil, uiGrantDenied() + } + profileBin = moduleActionProfile(root, storeRoot, state) + } else { + if req.Msg.GetReviewRevision() == "" { + return nil, uiGrantDenied() + } + snapshot := newUIReviewSnapshot(root, storeRoot, state, m.s.config.Port) + profileBin, links = snapshot.profileBin, snapshot.links + review, _ := snapshot.review(mod, p) + if review == "" || review != req.Msg.GetReviewRevision() { + return nil, uiGrantDenied() + } + } + if p["type"] == "PANEL_TYPE_SPEC" { + return m.openSpecUI(root, profileBin, state, req, mod, p) + } + if req.Msg.GetStatusAction() != "" || len(req.Msg.GetStatusApps()) != 0 { + return nil, uiGrantDenied() + } + bundle, err := customModuleBundle(mod, p, storeRoot) + if err != nil { + return nil, err + } + // Use only machine-local linked state for this project and module. HMR + // intentionally does not require a prebuilt production bundle. + appID := req.Msg.GetAppId() + revision, err := uiGrantRevision( + root, + state, + module, + panel, + appID, + bundle, + links[module], + profileBin, + ) + if err != nil { + return nil, uiGrantDenied() + } + grant := moduleUIGrant{ + Module: module, + ReviewRevision: req.Msg.GetReviewRevision(), + Panel: panel, + App: appID, + Revision: revision, + Expires: time.Now().Add(moduleUIGrantLifetime).Unix(), + } + var token string + if bound { + // Refreshing settings reads the original grant only. Never extend + // its lifetime or transfer a previous frame to the new revision. + previous, err := m.s.decodeUIGrant(req.Header()) + if err != nil || previous.Spec || previous.ReviewRevision == "" || previous.Revision != revision || previous.Module != module || + previous.Panel != panel || + previous.App != appID || + !slices.Contains(bundle.permissions, "config:read") { + return nil, uiGrantDenied() + } + grant, token = previous, req.Header().Get(moduleUIGrantHeader) + } else { + token, err = m.s.encodeUIGrant(grant) + if err != nil { + return nil, uiGrantDenied() + } + } + res := &agentv1.OpenModuleUIResponse{ + ReviewRevision: grant.ReviewRevision, + Permissions: bundle.permissions, + ActionIds: bundle.actionIDs, + } + if slices.Contains(bundle.permissions, "config:read") { + var settings map[string]any + if appID == "" { + settings, _ = mod["settings"].(map[string]any) + } else if slices.Contains(bundle.permissions, "config:patch") { + // uiGrantRevision validated the writable projection for this exact app. + settings, _ = bundle.appSettings[appID].(map[string]any) + } else { + app, _ := bundle.apps[appID].(map[string]any) + settings, _ = app["config"].(map[string]any) + } + if settings == nil { + return nil, invalidModuleState("panel settings projection missing") + } + res.Settings, err = structpb.NewStruct(settings) + if err != nil { + return nil, invalidModuleState("invalid panel settings") + } + } + if !bound { + res.Url, res.DevUrl, err = m.launchCustomBundle(ctx, root, origin, module, panel, bundle, links[module]) + if err != nil { + return nil, err + } + } + return moduleUIResponse(res, bundle.module, token, grant.Expires) +} + +func (m *moduleService) launchCustomBundle(ctx context.Context, root, origin, module, panel string, bundle *moduleBundle, link userconfig.LinkedModule) (string, string, error) { + var devURL string + if link.Path != "" && link.UIDevURL != "" { + if !validModuleDevURL(link.UIDevURL, m.s.config.Port) { + return "", "", connect.NewError(connect.CodeFailedPrecondition, errors.New("invalid linked UI server")) + } + devURL = link.UIDevURL + } else { + if bundle.drv != "" { + if err := ensureModuleOutput(ctx, root, bundle.root, bundle.drv); err != nil { + return "", "", connect.NewError(connect.CodeFailedPrecondition, err) + } + } + entry, _, err := openBundleAsset(bundle.root, bundle.entry) + if err != nil { + return "", "", connect.NewError(connect.CodeFailedPrecondition, errors.New("UI bundle entry is not realized or is outside its package")) + } + entry.Close() + } + claims := uiTicketClaims{ + Project: userconfig.GenerateProjectID(root), Package: bundle.root, Parent: origin, + Expires: time.Now().Add(uiTicketLifetime).Unix(), + } + prefix := moduleUIBase(module, panel) + ticket, err := m.s.sealUITicket(prefix, claims) + if err != nil { + return "", "", connect.NewError(connect.CodeInternal, errors.New("cannot issue UI ticket")) + } + return prefix + "_ticket/" + ticket + "/" + (&url.URL{Path: bundle.entry}).EscapedPath(), devURL, nil +} + +func moduleUIResponse(res *agentv1.OpenModuleUIResponse, mod map[string]any, token string, expires int64) (*connect.Response[agentv1.OpenModuleUIResponse], error) { + if len(res.ActionIds) != 0 { + actions, _ := mod["actions"].(map[string]any) + res.Actions = make(map[string]*agentv1.ModuleAction, len(res.ActionIds)) + for _, id := range res.ActionIds { + action := &agentv1.ModuleAction{} + if err := decodeModuleProjection(actions[id], action); err != nil { + return nil, err + } + res.Actions[id] = action + } + } + response := connect.NewResponse(res) + response.Header().Set("Cache-Control", "no-store") + response.Header().Set(moduleUIGrantHeader, token) + response.Header().Set(moduleUIExpiryHeader, strconv.FormatInt(expires, 10)) + return response, nil +} + +func moduleUIBase(module, panel string) string { + return "/api/v1/modules/" + module + "/ui/" + panel + "/" +} + +func validStudioOrigin(origin string) bool { + if origin == "" { + return true + } + u, err := url.Parse(origin) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && + uiAuthority.MatchString(u.Host) && + origin == u.Scheme+"://"+u.Host +} + +func validModuleDevURL(raw string, agentPort int) bool { + if userconfig.ValidateUIDevURL(raw) != nil { + return false + } + u, err := url.Parse(raw) + if err != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return false + } + port := 80 + if u.Scheme == "https" { + port = 443 + } + if u.Port() != "" { + port, err = strconv.Atoi(u.Port()) + } + return err == nil && port > 0 && port <= 65535 && port != agentPort +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets_app.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets_app.go new file mode 100644 index 00000000..da2a37f9 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets_app.go @@ -0,0 +1,201 @@ +package server + +import ( + "math" + "net/http" + "slices" + "strings" + "unicode" + + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/santhosh-tekuri/jsonschema/v6" +) + +func appPanelSlot(slot string) bool { + switch slot { + case "app:runtime", "app:framework", "app:container", "app:deployment", "app:tab": + return true + } + return false +} + +// Visibility applies to every capability, not just writable settings. A +// missing panel-specific filter means any enabled app in THIS project, not +// an arbitrary app string, and a module-global panel never accepts an app. +func validPanelApp(state map[string]any, slot, app string, panelApps map[string]any) bool { + if !strings.HasPrefix(slot, "app:") { + return app == "" + } + if !appPanelSlot(slot) || !validStatusID(app) { + return false + } + apps, _ := state["apps"].(map[string]any) + projectApp, _ := apps[app].(map[string]any) + entry, _ := panelApps[app].(map[string]any) + return projectApp["enable"] == true && (len(panelApps) == 0 || entry["enabled"] == true) +} + +// Return a writable projection only for the authenticated grant's exact app. +// The typed namespace values come from uiBundle.appSettings, never from +// display strings. Both projections must explicitly name each writable field. +func (b *moduleBundle) writableApp(app string) (map[string]any, error) { + if !slices.Contains(b.permissions, "config:patch") { + return nil, nil + } + if app == "" && !strings.HasPrefix(b.slot, "app:") { + return nil, nil // module-global panel + } + if !appPanelSlot(b.slot) || nixdata.ValidateEntityName(app) != nil { + return nil, uiGrantDenied() + } + entry, _ := b.apps[app].(map[string]any) + fields, _ := entry["config"].(map[string]any) + public, _ := b.appSettings[app].(map[string]any) + moduleID, _ := b.module["id"].(string) + if entry["enabled"] != true || !publicAppKey(moduleID) || len(public) == 0 { + return nil, uiGrantDenied() + } + for k, v := range public { + if _, declared := fields[k].(string); !declared || !publicAppKey(k) || + !portableAppValue(v) { + return nil, uiGrantDenied() + } + } + if !validWritableAppSchema(b.appSchemas[app], public) { + return nil, uiGrantDenied() + } + return public, nil +} + +// A writable grant requires the declared option schema, not an inferred +// schema from today's values (an empty list says nothing about item type). +func validWritableAppSchema(raw any, public map[string]any) bool { + schema, _ := raw.(map[string]any) + properties, _ := schema["properties"].(map[string]any) + if schema["type"] != "object" || schema["additionalProperties"] != false || + len(properties) != len(public) || + !moduleActionLocalRefs(schema) { + return false + } + for k := range public { + if !typedAppOption(properties[k]) { + return false + } + } + const resource = "urn:stackpanel:app-options" + c := jsonschema.NewCompiler() + c.UseLoader(nil) + if err := c.AddResource(resource, schema); err != nil { + return false + } + compiled, err := c.Compile(resource) + return err == nil && compiled.Validate(public) == nil +} + +func typedAppOption(raw any) bool { + schema, _ := raw.(map[string]any) + if enum, _ := schema["enum"].([]any); len(enum) != 0 { + return true + } + if alternatives, _ := schema["anyOf"].([]any); len(alternatives) != 0 { + for _, branch := range alternatives { + if !typedAppOption(branch) { + return false + } + } + return true + } + switch v := schema["type"].(type) { + case string: + if v == "array" { + return typedAppOption(schema["items"]) + } + return v != "" // The compiler checks the JSON Schema type name. + case []any: + if slices.Contains(v, any("array")) { + return typedAppOption(schema["items"]) + } + return len(v) != 0 + } + return false +} + +func publicAppKey(k string) bool { + switch k { + case "", + "constructor", + "prototype", + "env", + "envs", + "environments", + "variables", + "secrets", + "imports", + "outPath": + return false + } + return !strings.HasPrefix(k, "_") && !strings.ContainsFunc(k, unicode.IsControl) +} + +func portableAppValue(v any) bool { + switch x := v.(type) { + case nil, bool: + return true + case float64: + return !math.IsNaN(x) && !math.IsInf(x, 0) && + (math.Trunc(x) != x || math.Abs(x) <= 9007199254740991) + case string: + return !strings.HasPrefix(x, moduleStoreRoot+"/") + case []any: + for _, item := range x { + if !portableAppValue(item) { + return false + } + } + case map[string]any: + for k, item := range x { + if !publicAppKey(k) || !portableAppValue(item) { + return false + } + } + default: + return false + } + return true +} + +// Object keys are the relative patch surface. JSON sorts map keys during +// revision hashing; no current setting value belongs in this fingerprint. +func appKeyShape(value any) map[string]any { + fields, ok := value.(map[string]any) + if !ok || fields == nil { + return nil + } + shape := make(map[string]any, len(fields)) + for k, v := range fields { + shape[k] = appKeyShape(v) + } + return shape +} + +func (s *Server) moduleUIConfigPatchScope( + h http.Header, + rt *projectRuntime, + state map[string]any, + id string, +) ([]string, map[string]any, error) { + if _, present := h[http.CanonicalHeaderKey(moduleUIGrantHeader)]; !present { + return nil, nil, nil + } + c, b, err := s.verifiedModuleUIGrant(h, rt, state, id, "config:patch") + if err != nil { + return nil, nil, err + } + if c.App == "" { + return nil, nil, nil + } + // verifiedModuleUIGrant checked this exact projection while computing the + // revision. Never fall through to the module config path for an app grant. + public := b.appSettings[c.App].(map[string]any) + return []string{"apps", c.App, c.Module}, public, nil +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets_app_test.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets_app_test.go new file mode 100644 index 00000000..b7739900 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets_app_test.go @@ -0,0 +1,137 @@ +package server + +import ( + "net/http" + "path/filepath" + "slices" + "testing" + + "connectrpc.com/connect" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +func TestUIAppPatchScope(t *testing.T) { + root := t.TempDir() + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(root, "user.yaml")) + s := newUITestServer(t) + for _, scenario := range []string{"own", "value change", "changed item schema", "schema missing", "schema key mismatch", "untyped schema", "untyped items", "value violates schema", "new nested key", "removed key", "undeclared key", "private field", "store value", "malformed", "wrong slot", "missing app", "no downgrade", "disabled", "different app"} { + t.Run(scenario, func(t *testing.T) { + state, panel, _ := uiTestState() + panel["slot"] = "app:tab" + b := panel["uiBundle"].(map[string]any) + b["permissions"] = []any{"config:read", "config:patch"} + fields := map[string]any{"label": map[string]any{"count": float64(1)}} + b["appSettings"] = map[string]any{"web": fields} + prop := map[string]any{ + "type": "object", + "properties": map[string]any{ + "count": map[string]any{"type": "integer"}, + }, + "additionalProperties": false, + } + props := map[string]any{"label": prop} + b["appSchemas"] = map[string]any{ + "web": map[string]any{ + "type": "object", + "properties": props, + "additionalProperties": false, + }, + } + appID := "web" + switch scenario { + case "schema missing": + delete(b, "appSchemas") + case "schema key mismatch": + delete(props, "label") + props["other"] = prop + case "untyped schema": + props["label"] = map[string]any{} + case "untyped items": + fields["label"] = []any{} + props["label"] = map[string]any{"type": "array"} + case "value violates schema": + fields["label"] = false + case "changed item schema": + fields["label"] = []any{} + props["label"] = map[string]any{ + "type": "array", + "items": map[string]any{"type": "string"}, + } + case "wrong slot": + panel["slot"] = "sidebar" + case "missing app": + appID = "missing" + case "no downgrade": + appID = "" + case "disabled": + panel["apps"].(map[string]any)["web"].(map[string]any)["enabled"] = false + case "undeclared key": + fields["undeclared"] = true + case "private field": + fields["label"] = []any{map[string]any{"secrets": "hidden"}} + case "store value": + fields["label"] = moduleStoreRoot + "/hidden" + case "malformed": + b["appSettings"] = "invalid" + } + token, err := s.issueModuleUIGrant( + root, + state, + "demo", + "inspector", + appID, + moduleStoreRoot, + userconfig.LinkedModule{}, + ) + switch scenario { + case "schema missing", + "schema key mismatch", + "untyped schema", + "untyped items", + "value violates schema", + "wrong slot", + "missing app", + "no downgrade", + "disabled", + "undeclared key", + "private field", + "store value", + "malformed": + if connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("bad grant not rejected: %v", err) + } + return + } + if err != nil { + t.Fatal(err) + } + h := http.Header{} + h.Set(moduleUIGrantHeader, token) + rt := &projectRuntime{root: root} + switch scenario { + case "different app": + b["appSettings"] = map[string]any{"api": fields} + case "changed item schema": + props["label"].(map[string]any)["items"] = map[string]any{"type": "integer"} + case "removed key": + delete(fields, "label") + case "new nested key": + fields["label"].(map[string]any)["extra"] = true + case "value change": + fields["label"].(map[string]any)["count"] = float64(3) + } + path, public, err := s.moduleUIConfigPatchScope(h, rt, state, "demo") + if scenario != "own" && scenario != "value change" { + if connect.CodeOf(err) != connect.CodePermissionDenied || path != nil || + public != nil { + t.Fatal("stale grant did not fail closed") + } + return + } + if err != nil || !slices.Equal(path, []string{"apps", "web", "demo"}) || + len(public) != 1 { + t.Fatal("wrong app scope", err) + } + }) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets_grant.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets_grant.go new file mode 100644 index 00000000..401698b7 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets_grant.go @@ -0,0 +1,241 @@ +package server + +import ( + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "maps" + "net/http" + "path/filepath" + "slices" + "time" + + "connectrpc.com/connect" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +// The host keeps this credential outside the frame. It supplements (never +// replaces) agent authentication. It is not interchangeable with an asset +// ticket and is never accepted by the static asset handler. +const ( + moduleUIGrantHeader = "X-Stackpanel-UI-Grant" + moduleUIExpiryHeader = "X-Stackpanel-UI-Expires-At" + moduleUIGrantLifetime = time.Hour + moduleUIGrantPurpose = "stackpanel-ui-operation-grant-v1" + // Independent aggregate transport bound, including AEAD and base64; + // reject oversized Unicode target sets rather than returning an unusable token. + maxUIGrantBytes = 32 << 10 +) + +type moduleUIGrant struct { + Spec bool `json:"s,omitempty"` // absent on iframe grants + Module string `json:"m"` + Panel string `json:"p"` + App string `json:"a"` + StatusAction string `json:"x,omitempty"` + StatusApps []string `json:"t,omitempty"` + ReviewRevision string `json:"v,omitempty"` + Revision [32]byte `json:"r"` + Expires int64 `json:"e"` +} + +func uiGrantDenied() error { + return connect.NewError( + connect.CodePermissionDenied, + errors.New("extension grant invalid or changed; reopen the panel"), + ) +} + +// Encoding/json encodes string-keyed maps in sorted order. Include authority +// and resolved targets, not ordinary live settings or action results. Changing +// a value through the settings form need not revoke an otherwise unchanged UI. +func uiGrantRevision( + root string, + state map[string]any, + id, panel, app string, + b *moduleBundle, + link userconfig.LinkedModule, + profileBin string, +) ([32]byte, error) { + if !validPanelApp(state, b.slot, app, b.apps) { + return [32]byte{}, uiGrantDenied() + } + physicalRoot, err := filepath.EvalSymlinks(root) + if err != nil { + return [32]byte{}, err + } + mod := b.module + owned, _ := state["moduleOutputs"].(map[string]any) + outputs, _ := owned[id].(map[string]any) + services, _ := state["services"].(map[string]any) + svcTargets := make(map[string]any) + for k, v := range services { + svc, _ := v.(map[string]any) + if svc["module"] == id { + svcTargets[k] = []any{svc["enable"], svc["proxy"]} + } + } + actions, _ := mod["actions"].(map[string]any) + actionTargets := make(map[string]any, len(b.actionIDs)) + for _, k := range b.actionIDs { + actionTargets[k] = actions[k] + } + appDef, _ := b.apps[app].(map[string]any) + public, err := b.writableApp(app) + if err != nil { + return [32]byte{}, err + } + var appSchema any + if public != nil { + appSchema = b.appSchemas[app] + } + // Only dirs.profile selects the action executable environment. dirs.config + // can point into a new flake source path after an unrelated checkout edit. + dirs, _ := state["dirs"].(map[string]any) + data, err := json.Marshal([]any{ + root, + physicalRoot, + id, + panel, + app, + appDef["enabled"], + b.slot, + appKeyShape(public), + appSchema, + link.Path, + link.UIDevURL, + b.root, + b.entry, + b.drv, + b.permissions, + mod["configPath"], + mod["configSchema"], + actionTargets, + outputs["scripts"], + dirs["profile"], + profileBin, + svcTargets, + }) + if err != nil { + return [32]byte{}, err + } + return sha256.Sum256(data), nil +} + +func effectiveUIActions( + selector any, + module map[string]any, + permissions []string, +) []string { + if !slices.Contains(permissions, "actions:run") { + return nil + } + actions, _ := module["actions"].(map[string]any) + if selector == nil { + return slices.Sorted(maps.Keys(actions)) + } + allowed, _ := selector.([]any) + var result []string + for _, v := range allowed { + if id, ok := v.(string); ok && actions[id] != nil { + result = append(result, id) + } + } + slices.Sort(result) + return slices.Compact(result) +} + +func (s *Server) encodeUIGrant(c moduleUIGrant) (string, error) { + aead, err := s.uiCapabilityCipher(moduleUIGrantPurpose) + if err != nil { + return "", err + } + msg, err := json.Marshal(c) + if err != nil { + return "", err + } + if base64.RawURLEncoding.EncodedLen(len(msg)+aead.Overhead()) > maxUIGrantBytes { + return "", uiGrantDenied() + } + return base64.RawURLEncoding.EncodeToString(aead.Seal(nil, nil, msg, nil)), nil +} + +func (s *Server) decodeUIGrant(header http.Header) (moduleUIGrant, error) { + var c moduleUIGrant + v := header.Values(moduleUIGrantHeader) + if len(v) != 1 || len(v[0]) > maxUIGrantBytes { + return c, uiGrantDenied() + } + sealed, err := base64.RawURLEncoding.Strict().DecodeString(v[0]) + if err != nil { + return c, uiGrantDenied() + } + aead, err := s.uiCapabilityCipher(moduleUIGrantPurpose) + if err != nil || len(sealed) < aead.Overhead() { + return c, uiGrantDenied() + } + msg, err := aead.Open(nil, nil, sealed, nil) + if err != nil || json.Unmarshal(msg, &c) != nil || c.Expires <= time.Now().Unix() || (!c.Spec && customUIDisabled()) { + return c, uiGrantDenied() + } + return c, nil +} + +func (s *Server) checkModuleProxyGrant( + header http.Header, + rt *projectRuntime, + state map[string]any, + moduleID string, +) error { + if _, present := header[http.CanonicalHeaderKey(moduleUIGrantHeader)]; !present { + return nil + } + _, _, err := s.verifiedModuleUIGrant(header, rt, state, moduleID, "service:proxy") + return err +} + +func (s *Server) verifiedModuleUIGrant( + header http.Header, + rt *projectRuntime, + state map[string]any, + moduleID, operation string, +) (moduleUIGrant, *moduleBundle, error) { + c, err := s.decodeUIGrant(header) + if err != nil { + return c, nil, err + } + if rt == nil { + return c, nil, uiGrantDenied() + } + b, err := verifiedCustomBundle(c, rt, state, moduleID, operation, moduleActionProfile(rt.root, moduleStoreRoot, state)) + return c, b, err +} + +func verifiedCustomBundle(c moduleUIGrant, rt *projectRuntime, state map[string]any, moduleID, operation, profileBin string) (*moduleBundle, error) { + if c.Spec || rt == nil || c.Module != moduleID { + return nil, uiGrantDenied() + } + b, err := evaluatedModuleBundle(state, moduleID, c.Panel, moduleStoreRoot) + if err != nil || !slices.Contains(b.permissions, operation) { + return nil, uiGrantDenied() + } + links, err := userconfig.LoadLinkedModules(rt.root) + if err != nil { + return nil, uiGrantDenied() + } + digest, err := uiGrantRevision( + rt.root, + state, + moduleID, + c.Panel, + c.App, + b, + links[moduleID], + profileBin, + ) + if err != nil || digest != c.Revision { + return nil, uiGrantDenied() + } + return b, nil +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets_grant_test.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets_grant_test.go new file mode 100644 index 00000000..55841694 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets_grant_test.go @@ -0,0 +1,310 @@ +package server + +import ( + "context" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "connectrpc.com/connect" + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +func TestUIGrantChecksDispatchSnapshot(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + s := newUITestServer(t) + root := t.TempDir() + for _, scenario := range []string{"valid", "different project", "other module", "config path", "new package", "disabled app", "new link", "revoked", "new executable", "new schema", "service port", "new issuer", "expired", "duplicate header", "empty header", "different operation"} { + t.Run(scenario, func(t *testing.T) { + state, panel, module := uiTestState() + bundle := panel["uiBundle"].(map[string]any) + bundle["permissions"] = []any{"actions:run", "config:read", "service:proxy"} + action := map[string]any{ + "script": "before", + "argsSchema": map[string]any{"type": "object"}, + } + module["actions"] = map[string]any{"inspect": action} + svc := map[string]any{ + "module": "demo", + "enable": true, + "proxy": map[string]any{"enable": true, "port": float64(9000)}, + } + state["services"] = map[string]any{"api": svc} + link := userconfig.LinkedModule{} + if scenario == "new link" { + link = userconfig.LinkedModule{Path: root, UIDevURL: "http://localhost:3100/"} + } + app := "" + if scenario == "disabled app" { + panel["slot"] = "app:tab" + app = "web" + } + if scenario == "different operation" { + bundle["permissions"] = []any{"config:read"} + } + grant, err := s.issueModuleUIGrant( + root, + state, + "demo", + "inspector", + app, + moduleStoreRoot, + link, + ) + if err != nil { + t.Fatal(err) + } + h := http.Header{} + h.Set(moduleUIGrantHeader, grant) + selected, id := root, "demo" + issuer := s + switch scenario { + case "different project": + selected = t.TempDir() + case "other module": + id = "other" + case "config path": + module["configPath"] = "differently.scoped" + case "new package": + bundle["package"] = bundle["package"].(string) + "-new" + case "revoked": + bundle["permissions"] = []any{} + case "new executable": + action["script"] = "after" + case "new schema": + action["argsSchema"] = map[string]any{ + "type": "object", + "additionalProperties": false, + } + case "service port": + svc["proxy"].(map[string]any)["port"] = float64(9001) + case "new issuer": + issuer = newUITestServer(t) + case "expired": + c, err := s.decodeUIGrant(h) + if err != nil { + t.Fatal(err) + } + c.Expires = time.Now().Unix() - 1 + expired, err := s.encodeUIGrant(c) + if err != nil { + t.Fatal(err) + } + h.Set(moduleUIGrantHeader, expired) + case "duplicate header": + h.Add(moduleUIGrantHeader, grant) + case "empty header": + h.Set(moduleUIGrantHeader, "") + case "disabled app": + panel["apps"].(map[string]any)[app].(map[string]any)["enabled"] = false + } + err = issuer.checkModuleProxyGrant(h, &projectRuntime{root: selected}, state, id) + if scenario == "valid" { + if err != nil { + t.Fatal(err) + } + } else if connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("expected denial: %v", err) + } + }) + } +} + +func TestUIGrantEffectiveActions(t *testing.T) { + state, panel, module := uiTestState() + module["actions"] = map[string]any{ + "deploy": map[string]any{}, + "status": map[string]any{}, + } + b := panel["uiBundle"].(map[string]any) + for _, tc := range []struct { + sel any + run bool + count int + }{{nil, true, 2}, {[]any{}, true, 0}, {[]any{"status", "status", "missing"}, true, 1}, {nil, false, 0}} { + b["actionIds"] = tc.sel + b["permissions"] = []any{"config:read"} + if tc.run { + b["permissions"] = []any{"actions:run"} + } + got, err := evaluatedModuleBundle(state, "demo", "inspector", moduleStoreRoot) + if err != nil { + t.Fatal(err) + } + if len(got.actionIDs) != tc.count || tc.count == 1 && got.actionIDs[0] != "status" { + t.Errorf("selector %v, actions %v", tc.sel, got.actionIDs) + } + } +} + +func TestCustomPanelLaunchEligibility(t *testing.T) { + for _, op := range []string{"actions:run", "service:proxy", "config:read"} { + state, panel, _ := uiTestState() + panel["slot"] = "app:tab" + panel["uiBundle"].(map[string]any)["permissions"] = []any{op} + b, err := evaluatedModuleBundle(state, "demo", "inspector", moduleStoreRoot) + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + revision := func(app string) error { + _, err := uiGrantRevision(root, state, "demo", "inspector", app, b, userconfig.LinkedModule{}, "") + return err + } + if err := revision("web"); err != nil { + t.Fatal("eligible app denied:", err) + } + for _, app := range []string{"", "api", "absent"} { + if err := revision(app); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("%s accepted ineligible app %q: %v", op, app, err) + } + } + state["apps"].(map[string]any)["web"].(map[string]any)["enable"] = false + if err := revision("web"); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("%s accepted a now-disabled project app: %v", op, err) + } + } +} + +func TestMaxStatusAppSetRoundTrips(t *testing.T) { + c := moduleUIGrant{Spec: true, Module: "demo", Panel: "panel", StatusAction: "status", Expires: time.Now().Add(time.Minute).Unix()} + for i := range 128 { + // Each route ID is exactly 128 ASCII bytes. + c.StatusApps = append(c.StatusApps, fmt.Sprintf("%0128x", i)) + } + s := newUITestServer(t) + token, err := s.encodeUIGrant(c) + if err != nil { + t.Fatal(err) + } + h := http.Header{} + h.Set(moduleUIGrantHeader, token) + got, err := s.decodeUIGrant(h) + if err != nil || len(got.StatusApps) != 128 || got.StatusApps[127] != c.StatusApps[127] { + t.Fatalf("maximum grant lost targets: %v", err) + } +} + +func testReviewRevision(t *testing.T, root, store string, state map[string]any, id, panel string) string { + t.Helper() + mod, p, err := evaluatedUIPanel(state, id, panel) + if err != nil { + t.Fatal(err) + } + revision, _ := newUIReviewSnapshot(root, store, state, 9876).review(mod, p) + if len(revision) != 64 { + t.Fatal("no review for test panel", panel) + } + return revision +} + +func (s *Server) issueModuleUIGrant( + root string, + state map[string]any, + id, panel, app, storeRoot string, + link userconfig.LinkedModule, +) (string, error) { + b, err := evaluatedModuleBundle(state, id, panel, storeRoot) + if err != nil { + return "", err + } + digest, err := uiGrantRevision(root, state, id, panel, app, b, link, moduleActionProfile(root, storeRoot, state)) + if err != nil { + return "", err + } + return s.encodeUIGrant( + moduleUIGrant{ + Module: id, + Panel: panel, + App: app, + Revision: digest, + Expires: time.Now().Add(moduleUIGrantLifetime).Unix(), + }, + ) +} + +// Exercise the production evaluator twice, not a shared in-memory map: an +// unrelated source edit changes the flake's store path in dirs.config even +// though the panel, executable, schema and profile are exactly the same. +func TestUIGrantSurvivesIndependentFlakeEvaluations(t *testing.T) { + if _, err := exec.LookPath("nix"); err != nil { + t.Skip("requires a local Nix installation") + } + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv( + "NIX_SYSTEM", + "aarch64-darwin", + ) // fixture is data only; builds no derivations + root := t.TempDir() + write := func(name, body string, perm os.FileMode) { + t.Helper() + if err := os.WriteFile(filepath.Join(root, name), []byte(body), perm); err != nil { + t.Fatal(err) + } + } + if err := os.Mkdir(filepath.Join(root, "bundle"), 0o700); err != nil { + t.Fatal(err) + } + write("bundle/index.html", "Test", 0o600) + write("report", "#!/bin/sh\nprintf ready", 0o700) + write("profile", ".stack/profile", 0o600) + write("flake.nix", `{ + outputs = { self }: { legacyPackages.aarch64-darwin.stackpanelSerializable = { + dirs = { config = "${self.outPath}/.stack/config.nix"; profile = builtins.readFile ./profile; }; + modulesListAll = [{ id = "demo"; enabled = true; actions.report = { + script = toString (builtins.path { path = ./report; name = "report"; }); + argsSchema.type = "object"; outputMode = "stream"; + }; }]; + panelsList = [{ module = "demo"; id = "preview"; enabled = true; type = "PANEL_TYPE_CUSTOM"; + uiBundle = { package = toString (builtins.path { path = ./bundle; name = "panel"; }); + entry = "index.html"; permissions = [ "actions:run" ]; actionIds = [ "report" ]; }; + }]; + }; }; +}`, 0o600) + rt := &projectRuntime{root: root} // nil evalModuleState uses the live selected flake + ctx := context.WithValue(t.Context(), runtimeKey{}, rt) + m := &moduleService{s: newUITestServer(t)} + state, err := loadModuleState(ctx, rt) + if err != nil { + t.Fatal(err) + } + review := testReviewRevision(t, root, moduleStoreRoot, state, "demo", "preview") + opened, err := m.OpenModuleUI( + ctx, + connect.NewRequest( + &agentv1.OpenModuleUIRequest{ModuleId: "demo", PanelId: "preview", ReviewRevision: review}, + ), + ) + if err != nil { + t.Fatal(err) + } + h := http.Header{} + h.Set(moduleUIGrantHeader, opened.Header().Get(moduleUIGrantHeader)) + write("notes", "a changed project snapshot, not a changed authority", 0o600) + var out strings.Builder + run := func() error { + return m.runModuleActionWithHeader( + ctx, + moduleStoreRoot, + h, + &agentv1.RunModuleActionRequest{ModuleId: "demo", ActionId: "report"}, + func(event *agentv1.RunModuleActionResponse) error { + out.WriteString(event.GetStdout()) + return nil + }, + ) + } + if err := run(); err != nil || out.String() != "ready" { + t.Fatalf("unchanged action: output %q, err %v", out.String(), err) + } + write("profile", ".stack/replacement", 0o600) + if err := run(); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("changed profile accepted: %v", err) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets_realize.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets_realize.go new file mode 100644 index 00000000..06b3fa81 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets_realize.go @@ -0,0 +1,61 @@ +package server + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "time" +) + +// A pure eval instantiates a derivation, not necessarily its outputs. On an +// authenticated open/run only, realize the derivation for that exact output. +// No flake input, shell command, ambient PATH, or mutable profile is accepted. +func ensureModuleOutput(ctx context.Context, projectRoot, output, drv string) error { + if !validModulePackage(output, moduleStoreRoot) || + !validModulePackage(drv, moduleStoreRoot) || + !strings.HasSuffix(drv, ".drv") { + return errors.New("invalid module derivation declaration") + } + if _, err := os.Lstat(output); err == nil { + return nil + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + var nixStore string + for _, bin := range []string{"/nix/var/nix/profiles/default/bin/nix-store", "/run/current-system/sw/bin/nix-store"} { + if _, err := os.Stat(bin); err == nil { + nixStore = bin + break + } + } + if nixStore == "" { + return errors.New("cannot realize module output: system nix-store not installed") + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + command := func(args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, nixStore, args...) + cmd.Dir = projectRoot + cmd.Env = []string{ + "PATH=" + filepath.Dir(nixStore) + ":/usr/bin:/bin", + "HOME=" + os.Getenv("HOME"), + } + return cmd + } + outs, err := command("--query", "--outputs", drv).Output() + if err != nil || !slices.Contains(strings.Fields(string(outs)), output) { + return errors.New("module output does not belong to its declared derivation") + } + if err := command("--realise", "--no-build-output", drv).Run(); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return errors.New("could not realize evaluated module output") + } + _, err = os.Lstat(output) + return err +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets_test.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets_test.go new file mode 100644 index 00000000..01f20225 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets_test.go @@ -0,0 +1,514 @@ +package server + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "connectrpc.com/connect" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/config" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +const testUIStoreName = "00000000000000000000000000000000-demo" + +func newUITestServer(t *testing.T) *Server { + t.Helper() + mgr, err := NewJWTManager() + if err != nil { + t.Fatal(err) + } + return &Server{ + jwtManager: mgr, + config: &config.Config{Port: 9876, AuthToken: "studio-credential"}, + } +} + +func uiTestState() (state, panel, module map[string]any) { + module = map[string]any{"id": "demo", "enabled": true} + panel = map[string]any{ + "id": "inspector", "module": "demo", "enabled": true, "type": "PANEL_TYPE_CUSTOM", + "uiBundle": map[string]any{ + "package": moduleStoreRoot + "/" + testUIStoreName, "entry": "site/index.html", + "permissions": []any{"config:read"}, + }, + "apps": map[string]any{ + "web": map[string]any{"enabled": true, "config": map[string]any{"label": "demo"}}, + "api": map[string]any{ + "enabled": false, + "config": map[string]any{"label": "other"}, + }, + }, + // Must never grant a dev URL supplied by the project. + "uiDevUrl": "https://example.com", + } + return map[string]any{ + "modulesListAll": []any{module}, + "apps": map[string]any{"web": map[string]any{"enable": true}, "api": map[string]any{"enable": true}}, + "panelsList": []any{panel}, + }, panel, module +} + +func TestOpenModuleUIIssuesOnlyEvaluatedProjectGrants(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + s := newUITestServer(t) + state, panel, mod := uiTestState() + mod["settings"] = map[string]any{"label": "global"} + panel["slot"] = "app:tab" + root := t.TempDir() + store := t.TempDir() + bundle := filepath.Join(store, testUIStoreName) + if err := os.MkdirAll(filepath.Join(bundle, "site"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile( + filepath.Join(bundle, "site/index.html"), + nil, + 0o600, + ); err != nil { + t.Fatal(err) + } + panel["uiBundle"].(map[string]any)["package"] = bundle + rt := &projectRuntime{ + root: root, + evalModuleState: func(_ context.Context, project string) ([]byte, error) { + if project != root { + t.Fatalf("evaluated wrong project: %s", project) + } + return json.Marshal(state) + }, + } + ctx := context.WithValue(t.Context(), runtimeKey{}, rt) + var launchGrant string + open := func(app string) *agentv1.OpenModuleUIResponse { + t.Helper() + req := connect.NewRequest( + &agentv1.OpenModuleUIRequest{ModuleId: "demo", PanelId: "inspector", AppId: app}, + ) + req.Msg.ReviewRevision = testReviewRevision(t, root, store, state, "demo", "inspector") + req.Header().Set("Origin", "https://stackpanel.com") + req.Header().Set("Authorization", "Bearer "+s.config.AuthToken) + res, err := (&moduleService{s: s}).openModuleUI(ctx, req, store) + if err != nil { + t.Fatal(err) + } + if res.Msg.ReviewRevision != req.Msg.ReviewRevision { + t.Fatal("missing or incorrect launch review revision") + } + grant := res.Header().Get(moduleUIGrantHeader) + if grant == "" || strings.Contains(res.Msg.Url, grant) || s.isValidToken(grant) || + res.Header().Get(moduleUIExpiryHeader) == "" { + t.Fatal("missing or misplaced host-only launch grant") + } + if _, ok := s.openUITicket(moduleUIBase("demo", "inspector"), grant); ok { + t.Fatal("host grant accepted as asset ticket") + } + launchGrant = grant + return res.Msg + } + res := open("web") + if len(res.Permissions) != 1 || res.Permissions[0] != "config:read" || + res.Settings.AsMap()["label"] != "demo" || + res.DevUrl != "" { + t.Fatalf("wrong bundle grants: %v", res) + } + bound := connect.NewRequest( + &agentv1.OpenModuleUIRequest{ModuleId: "demo", PanelId: "inspector", AppId: "web"}, + ) + bound.Header().Set(moduleUIGrantHeader, launchGrant) + refreshed, err := (&moduleService{s: s}).openModuleUI(ctx, bound, store) + if err != nil || refreshed.Header().Get(moduleUIGrantHeader) != launchGrant || + refreshed.Msg.Url != "" || refreshed.Msg.DevUrl != "" || refreshed.Msg.ReviewRevision != res.ReviewRevision || + refreshed.Msg.GetSettings().AsMap()["label"] != "demo" { + t.Fatal("app refresh lost its launch binding", err) + } + bound.Msg.AppId = "api" + if _, err := (&moduleService{s: s}).openModuleUI( + ctx, + bound, + store, + ); connect.CodeOf( + err, + ) != connect.CodePermissionDenied { + t.Fatal("grant could read another app", err) + } + bound.Msg.AppId = "web" + prefix := moduleUIBase("demo", "inspector") + if !strings.HasPrefix(res.Url, prefix+"_ticket/") || + !strings.HasSuffix(res.Url, "/site/index.html") || + strings.Contains(res.Url, s.config.AuthToken) || + strings.Contains(res.Url, "?") { + t.Fatal("expected relative scoped path ticket") + } + ticket, _, _ := strings.Cut(strings.TrimPrefix(res.Url, prefix+"_ticket/"), "/") + c, valid := s.openUITicket(prefix, ticket) + if !valid || c.Project != userconfig.GenerateProjectID(root) || c.Package != bundle || + c.Parent != "https://stackpanel.com" || + s.isValidToken(ticket) { + t.Fatal("invalid ticket binding") + } + if _, ok := newUITestServer(t).openUITicket(prefix, ticket); ok { + t.Fatal("accepted a ticket from another agent") + } + if _, ok := s.openUITicket(prefix, ticket[1:]); ok { + t.Fatal("accepted a tampered ticket") + } + deny := func(app, review string) { + t.Helper() + req := connect.NewRequest(&agentv1.OpenModuleUIRequest{ModuleId: "demo", PanelId: "inspector", AppId: app, ReviewRevision: review}) + got, err := (&moduleService{s: s}).openModuleUI(ctx, req, store) + if got != nil || connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("unreviewed or ineligible launch succeeded: %v %v", got, err) + } + } + deny("api", res.ReviewRevision) + deny("", res.ReviewRevision) + deny("web", "") + panel["uiBundle"].(map[string]any)["permissions"] = []any{} + deny("web", res.ReviewRevision) + if _, err := (&moduleService{s: s}).openModuleUI( + ctx, + bound, + store, + ); connect.CodeOf( + err, + ) != connect.CodePermissionDenied { + t.Fatal("revoked app grant accepted", err) + } + if open("web").Settings != nil { + t.Fatal("app metadata disclosed without config:read") + } + panel["slot"] = "module" + deny("web", testReviewRevision(t, root, store, state, "demo", "inspector")) + panel["uiBundle"].(map[string]any)["permissions"] = []any{"config:read"} + global := open("") + if global.GetSettings().AsMap()["label"] != "global" { + t.Fatal("module panel did not receive module settings") + } + mod["settings"] = map[string]any{"label": "changed"} + bound.Msg.AppId = "" + bound.Header().Set(moduleUIGrantHeader, launchGrant) + refreshed, err = (&moduleService{s: s}).openModuleUI(ctx, bound, store) + if err != nil || refreshed.Msg.GetSettings().AsMap()["label"] != "changed" || refreshed.Msg.ReviewRevision != global.ReviewRevision || refreshed.Msg.Url != "" { + t.Fatal("module settings refresh lost its launch binding", err) + } + delete(mod, "settings") + if got, err := (&moduleService{s: s}).openModuleUI(ctx, bound, store); got != nil || connect.CodeOf(err) != connect.CodeFailedPrecondition { + t.Fatal("refresh accepted a missing settings projection", err) + } + mod["settings"] = map[string]any{} + if open("").Settings == nil { + t.Fatal("explicit empty settings projection lost") + } + other, author := t.TempDir(), t.TempDir() + for _, dir := range []string{root, other, author} { + if err := os.WriteFile( + filepath.Join(dir, "flake.nix"), + []byte("{}"), + 0o600, + ); err != nil { + t.Fatal(err) + } + } + mgr, err := userconfig.NewManager() + if err != nil { + t.Fatal(err) + } + link := userconfig.LinkedModule{Path: author, UIDevURL: "http://127.0.0.1:3100/ui/"} + if err := mgr.SetLinkedModule(other, "demo", link); err != nil { + t.Fatal(err) + } + if got := open("").DevUrl; got != "" { + t.Fatal("disclosed other project's dev link") + } + productionReview := testReviewRevision(t, root, store, state, "demo", "inspector") + if err := mgr.SetLinkedModule(root, "demo", link); err != nil { + t.Fatal(err) + } + deny("", productionReview) // changing from production to HMR requires a new review + if err := os.Remove(filepath.Join(bundle, "site/index.html")); err != nil { + t.Fatal(err) + } + if got := open("").DevUrl; got != link.UIDevURL { + t.Fatal("did not use scoped development link") + } + devLaunch := connect.NewRequest(&agentv1.OpenModuleUIRequest{ModuleId: "demo", PanelId: "inspector", ReviewRevision: testReviewRevision(t, root, store, state, "demo", "inspector")}) + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "1") + if _, err := (&moduleService{s: s}).openModuleUI(ctx, devLaunch, store); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("opened disabled custom UI with a linked HMR server: %v", err) + } +} + +func TestModuleBundleMustBeAttributedAndEnabled(t *testing.T) { + for _, tc := range []struct { + field string + value any + }{ + {"module", "other"}, {"enabled", false}, {"type", "PANEL_TYPE_TABLE"}, {"id", "another-panel"}, {"uiBundle", nil}, + } { + state, panel, _ := uiTestState() + panel[tc.field] = tc.value + if _, err := evaluatedModuleBundle( + state, + "demo", + "inspector", + moduleStoreRoot, + ); err == nil { + t.Errorf("accepted mismatched %s", tc.field) + } + } + state, _, module := uiTestState() + module["enabled"] = false + if _, err := evaluatedModuleBundle( + state, + "demo", + "inspector", + moduleStoreRoot, + ); err == nil { + t.Fatal("accepted disabled module") + } + for _, p := range []string{"", ".", moduleStoreRoot, "/tmp/" + testUIStoreName, moduleStoreRoot + "/" + testUIStoreName + "/other", moduleStoreRoot + "/../" + testUIStoreName} { + if validModulePackage(p, moduleStoreRoot) { + t.Errorf("accepted non-package path %q", p) + } + } +} + +func TestModuleCapabilityRoutesRequireAuthAndScope(t *testing.T) { + s := newUITestServer(t) + mux := http.NewServeMux() + s.mountModuleCapabilities(mux) + for _, endpoint := range []string{"services/db/proxy/state", "ui/inspector/index.html"} { + for _, tc := range []struct { + auth, origin, project, query string + want int + }{ + {"", "", "other", "", 401}, + {"", "", "", "?token=studio-credential", 401}, + {"Bearer studio-credential", "null", "other", "", 403}, + {"Bearer studio-credential", "", "", "", 400}, + } { + r := httptest.NewRequest("GET", "/api/v1/modules/demo/"+endpoint+tc.query, nil) + r.Header.Set("Authorization", tc.auth) + r.Header.Set("Origin", tc.origin) + r.Header.Set(projectHeader, tc.project) + w := httptest.NewRecorder() + mux.ServeHTTP(w, r) + if w.Code != tc.want { + t.Errorf("%s: got %d, want %d", endpoint, w.Code, tc.want) + } + } + } +} + +func TestUITicketServesRelativeAssetsAndRejectsEscapes(t *testing.T) { + s := newUITestServer(t) + store := t.TempDir() + bundle := filepath.Join(store, testUIStoreName) + if err := os.MkdirAll(filepath.Join(bundle, "site"), 0o700); err != nil { + t.Fatal(err) + } + for name, body := range map[string]string{"site/index.html": ``, "site/main.js": "export default 1"} { + if err := os.WriteFile( + filepath.Join(bundle, name), + []byte(body), + 0o600, + ); err != nil { + t.Fatal(err) + } + } + outside := filepath.Join(store, "secret") + if err := os.WriteFile(outside, []byte("outside-data"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(bundle, "escape")); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc( + "/api/v1/modules/{module}/ui/{panel}/_ticket/{ticket}/{rest...}", + func(w http.ResponseWriter, r *http.Request) { + s.serveTicketAsset(w, r, store) + }, + ) + srv := httptest.NewServer(guardModuleCapabilityPaths(mux.ServeHTTP)) + defer srv.Close() + srv.Client().CheckRedirect = func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse } + const prefix = "/api/v1/modules/demo/ui/inspector/" + claim := uiTicketClaims{ + Project: "p1", + Parent: "https://stackpanel.com", + Package: bundle, + Expires: time.Now().Add(time.Minute).Unix(), + } + issue := func(c uiTicketClaims) string { + t.Helper() + tok, err := s.sealUITicket(prefix, c) + if err != nil { + t.Fatal(err) + } + return prefix + "_ticket/" + tok + "/" + } + base := issue(claim) + fetch := func(method, path, origin, project, dest string, want int) (http.Header, string) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), method, srv.URL+path, nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Origin", origin) + req.Header.Set(projectHeader, project) + req.Header.Set("Sec-Fetch-Dest", dest) + res, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + body, err := io.ReadAll(res.Body) + if err != nil || res.StatusCode != want || + strings.Contains(string(body), "outside-data") { + t.Fatalf( + "%s %s: status %d want %d, read %v", + method, + path, + res.StatusCode, + want, + err, + ) + } + return res.Header, string(body) + } + entry, err := url.Parse(base + "site/index.html") + if err != nil { + t.Fatal(err) + } + h, body := fetch("GET", entry.Path, "", "", "iframe", 200) + if !strings.Contains(body, `src="./main.js"`) || + h.Get("Referrer-Policy") != "no-referrer" || + h.Get("Cache-Control") != "no-store" || + h.Get("X-Content-Type-Options") != "nosniff" { + t.Fatal("missing document or isolation headers") + } + for _, policy := range []string{"sandbox allow-scripts;", "connect-src 'none'", "base-uri 'none'", "default-src 'none'", "frame-ancestors 'self' https://stackpanel.com"} { + if !strings.Contains(h.Get("Content-Security-Policy"), policy) { + t.Errorf("missing policy: %s", policy) + } + } + script := entry.ResolveReference(&url.URL{Path: "main.js"}).Path + h, body = fetch("GET", script, "null", "", "script", 200) + if h.Get("Access-Control-Allow-Origin") != "null" || + h.Get("Access-Control-Allow-Credentials") != "" || + body != "export default 1" { + t.Fatal("opaque-origin subasset not isolated") + } + fetch("POST", script, "null", "", "", 405) + fetch("OPTIONS", script, "null", "", "", 204) + fetch("HEAD", script, "null", "", "", 200) + fetch("GET", script, "https://other.invalid", "", "", 404) + fetch("GET", script, "null", "p2", "", 404) + fetch("GET", script, "null", "", "serviceworker", 404) + fetch("GET", strings.Replace(script, "/demo/", "/other/", 1), "", "", "", 404) + fetch("GET", strings.Replace(script, "/inspector/", "/other/", 1), "", "", "", 404) + for _, path := range []string{"site", "escape", "site/../escape", "%2e%2e/secret", "site%2fmain.js", "%252e%252e/secret", "%5csecret"} { + fetch("GET", base+path, "", "", "", 404) + } + claim.Expires = time.Now().Add(-time.Second).Unix() + fetch("GET", issue(claim)+"site/main.js", "", "", "", 404) + claim.Expires = time.Now().Add(time.Minute).Unix() + claim.Package = filepath.Join( + store, + strings.Replace(testUIStoreName, "-demo", "-link", 1), + ) + if err := os.Symlink(bundle, claim.Package); err != nil { + t.Fatal(err) + } + fetch("GET", issue(claim)+"site/main.js", "", "", "", 404) + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "1") + fetch("GET", entry.Path, "", "", "iframe", 404) + fetch("OPTIONS", script, "null", "", "", 404) + fetch("GET", script, "null", "", "script", 404) +} + +func TestLinkedUIOnlyAcceptsNonAgentLoopback(t *testing.T) { + for _, u := range []string{"https://example.org/", "file:///etc/passwd", "http://127.0.0.1:9876/status", "http://localhost:09876/", "http://localhost:3100/?token=credential", "http://u:p@localhost:3100/"} { + if validModuleDevURL(u, 9876) { + t.Errorf("accepted %s", u) + } + } + if !validModuleDevURL("http://127.0.0.1:3100/module/", 9876) { + t.Error("rejected loopback dev server") + } +} + +func TestPairDoesNotMintForEmbeddedDocuments(t *testing.T) { + // No token issuer or template. Every rejection must happen before either. + s := &Server{config: &config.Config{}} + for _, tc := range []struct{ dest, mode, origin string }{ + {"iframe", "navigate", "http://localhost:3100"}, + {"frame", "navigate", "http://localhost:3100"}, + {"empty", "cors", "http://localhost:3100"}, + {"script", "no-cors", "http://localhost:3100"}, + {"document", "navigate", "null"}, + {"document", "cors", "http://localhost:3100"}, + } { + r := httptest.NewRequest( + "POST", + "/pair", + strings.NewReader("state="+strings.Repeat("a", 64)), + ) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r.Header.Set("Sec-Fetch-Dest", tc.dest) + r.Header.Set("Sec-Fetch-Mode", tc.mode) + r.Header.Set("Origin", tc.origin) + w := httptest.NewRecorder() + s.handlePair(w, r) + if w.Code != http.StatusForbidden || + w.Header().Get("Content-Security-Policy") != "frame-ancestors 'none'" || + w.Header().Get("X-Frame-Options") != "DENY" || + w.Header().Get("Cache-Control") != "no-store" { + t.Errorf("pairing not isolated for %+v", tc) + } + } +} + +func TestModuleProxyCannotRequestPairingCredentials(t *testing.T) { + // Even if a second agent is listening on a declared service port, the + // proxy cannot provide the query or Referer that starts a pairing flow. + other := &Server{config: &config.Config{}} + upstream := httptest.NewServer(http.HandlerFunc(other.handlePair)) + defer upstream.Close() + proxy := moduleProxyTestAgent(t, upstream) + for _, tc := range []struct { + suffix string + status int + }{{"pair", 403}, {"pair?origin=http://localhost:3100", 400}} { + r, err := http.NewRequestWithContext( + t.Context(), + "GET", + proxy.URL+moduleProxyTestPrefix+tc.suffix, + nil, + ) + if err != nil { + t.Fatal(err) + } + r.Header.Set("Referer", "http://localhost:3100/") + res, err := proxy.Client().Do(r) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + if res.StatusCode != tc.status { + t.Errorf("unexpected proxy status: %d", res.StatusCode) + } + } +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_assets_ticket.go b/apps/stackpanel-go/internal/agent/server/module_ui_assets_ticket.go new file mode 100644 index 00000000..6a937b9c --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_assets_ticket.go @@ -0,0 +1,276 @@ +package server + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/hkdf" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "io/fs" + "mime" + "net/http" + "os" + "path" + "strings" + "time" + "unicode" +) + +const uiTicketLifetime = 5 * time.Minute + +// A snapshot grants only GET/HEAD of one immutable bundle. No lookup of a +// mutable current project, no local dev URL, and no agent credential. The +// authenticated associated data binds it to the issuing module and panel. +// Encrypt rather than merely sign: the URL is visible to untrusted scripts. +type uiTicketClaims struct { + Project string `json:"p"` + Package string `json:"b"` + Parent string `json:"o"` + Expires int64 `json:"e"` +} + +func (s *Server) uiTicketCipher() (cipher.AEAD, error) { + return s.uiCapabilityCipher("stackpanel-ui-read-ticket-v1") +} + +func (s *Server) uiCapabilityCipher(purpose string) (cipher.AEAD, error) { + if s.jwtManager == nil || len(s.jwtManager.signingKey) == 0 { + return nil, errors.New("UI ticket issuer unavailable") + } + key, err := hkdf.Key(sha256.New, s.jwtManager.signingKey, nil, purpose, 32) + if err != nil { + return nil, err + } + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + return cipher.NewGCMWithRandomNonce(block) +} + +func (s *Server) sealUITicket(prefix string, c uiTicketClaims) (string, error) { + cipher, err := s.uiTicketCipher() + if err != nil { + return "", err + } + msg, err := json.Marshal(c) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString( + cipher.Seal(nil, nil, msg, []byte(prefix)), + ), nil +} + +func (s *Server) openUITicket(prefix, ticket string) (c uiTicketClaims, valid bool) { + if len(ticket) == 0 || len(ticket) > 2048 { + return c, false + } + sealed, err := base64.RawURLEncoding.Strict().DecodeString(ticket) + if err != nil { + return c, false + } + cipher, err := s.uiTicketCipher() + if err != nil || len(sealed) < cipher.Overhead() { + return c, false + } + msg, err := cipher.Open(nil, nil, sealed, []byte(prefix)) + if err != nil || json.Unmarshal(msg, &c) != nil || c.Project == "" || + !validStudioOrigin(c.Parent) { + return c, false + } + now := time.Now() + return c, c.Expires > now.Unix() && c.Expires <= now.Add(uiTicketLifetime).Unix() +} + +func validAssetPath(relative string) bool { + return relative != "." && fs.ValidPath(relative) && + !strings.ContainsAny(relative, `\%?#`) && + strings.IndexFunc(relative, unicode.IsControl) == -1 +} + +// ServeMux normally redirects paths containing dot segments before dispatch. +// Do not redirect a request containing a scoped capability to a different URL. +func guardModuleCapabilityPaths(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/api/v1/modules/") { + rel := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), "/") + if !validAssetPath(rel) || + strings.Contains(strings.ToLower(r.URL.EscapedPath()), "%2f") { + http.NotFound(w, r) + return + } + } + next(w, r) + } +} + +func (s *Server) handleModuleAsset(w http.ResponseWriter, r *http.Request) { + module, panel := r.PathValue("module"), r.PathValue("panel") + if !validAssetRequest(w, r, false) { + return + } + bundle, err := requestModuleBundle(r.Context(), module, panel, moduleStoreRoot) + if err != nil { + http.NotFound(w, r) + return + } + serveModuleAsset( + w, + r, + bundle.root, + moduleUIBase(module, panel), + r.Header.Get("Origin"), + ) +} + +func (s *Server) handleTicketAsset(w http.ResponseWriter, r *http.Request) { + s.serveTicketAsset(w, r, moduleStoreRoot) +} + +func (s *Server) serveTicketAsset( + w http.ResponseWriter, + r *http.Request, + storeRoot string, +) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Referrer-Policy", "no-referrer") + if !validAssetRequest(w, r, true) { + return + } + module, panel, ticket := r.PathValue( + "module", + ), r.PathValue( + "panel", + ), r.PathValue( + "ticket", + ) + if !moduleRouteID.MatchString(module) || !moduleRouteID.MatchString(panel) { + http.NotFound(w, r) + return + } + prefix := moduleUIBase(module, panel) + claim, ok := s.openUITicket(prefix, ticket) + if !ok || !validModulePackage(claim.Package, storeRoot) || + (r.Header.Get(projectHeader) != "" && r.Header.Get(projectHeader) != claim.Project) { + http.NotFound(w, r) + return + } + // ES module imports/fonts from sandboxed frames have Origin: null. Limit + // that exception to a valid ticket; never opt any agent API into null CORS. + origin := r.Header.Get("Origin") + if origin != "" && origin != "null" && origin != claim.Parent { + http.NotFound(w, r) + return + } + if origin != "" { + w.Header().Set("Vary", "Origin") + w.Header().Set("Access-Control-Allow-Origin", origin) + } + if r.Method == http.MethodOptions { + w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD") + w.Header().Set("Access-Control-Allow-Private-Network", "true") + w.WriteHeader(http.StatusNoContent) + return + } + serveModuleAsset(w, r, claim.Package, prefix+"_ticket/"+ticket+"/", claim.Parent) +} + +func validAssetRequest(w http.ResponseWriter, r *http.Request, ticket bool) bool { + // Tickets outlive launch and do not ordinarily consult project state. + // Enforce the machine policy here too, for both asset routes and preflight. + if customUIDisabled() { + http.NotFound(w, r) + return false + } + if r.Method != http.MethodGet && r.Method != http.MethodHead && + !(ticket && r.Method == http.MethodOptions) { + w.Header().Set("Allow", "GET, HEAD") + w.WriteHeader(http.StatusMethodNotAllowed) + return false + } + if !validAssetPath(r.PathValue("rest")) || !uiAuthority.MatchString(r.Host) || + r.Header.Get( + "Service-Worker", + ) != "" || r.Header.Get("Sec-Fetch-Dest") == "serviceworker" { + http.NotFound(w, r) + return false + } + return true +} + +func openBundleAsset(bundle, name string) (*os.File, os.FileInfo, error) { + // The store is immutable. Reject a symlink at the output root itself; + // os.Root then prevents races and symlink escapes within that directory. + info, err := os.Lstat(bundle) + if err != nil || !info.IsDir() { + return nil, nil, fs.ErrNotExist + } + root, err := os.OpenRoot(bundle) + if err != nil { + return nil, nil, err + } + defer root.Close() + info, err = root.Stat(name) + if err != nil || !info.Mode().IsRegular() { + return nil, nil, fs.ErrNotExist + } + f, err := root.Open(name) + if err != nil { + return nil, nil, err + } + info, err = f.Stat() + if err != nil || !info.Mode().IsRegular() { + f.Close() + return nil, nil, fs.ErrNotExist + } + return f, info, nil +} + +func serveModuleAsset( + w http.ResponseWriter, + r *http.Request, + bundle, prefix, parent string, +) { + name := r.PathValue("rest") + f, info, err := openBundleAsset(bundle, name) + if err != nil { + http.NotFound(w, r) + return + } + defer f.Close() + typeName := mime.TypeByExtension(path.Ext(name)) + if typeName == "" { + typeName = "application/octet-stream" + } + h := w.Header() + h.Set("Content-Type", typeName) + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("Cache-Control", "no-store") + h.Set("Cross-Origin-Opener-Policy", "same-origin") + h.Set("Cross-Origin-Embedder-Policy", "require-corp") + h.Set("Cross-Origin-Resource-Policy", "cross-origin") // opaque frame subresources + h.Set( + "Permissions-Policy", + "camera=(), microphone=(), geolocation=(), display-capture=(), payment=(), usb=(), serial=()", + ) + ancestors := "'self'" + if parent != "" && validStudioOrigin(parent) { + ancestors += " " + parent + } + // A path source (rather than 'self') allows only the bundle, not the rest + // of the agent origin. An explicit source also works with an opaque origin. + scheme := "http://" + if r.TLS != nil { + scheme = "https://" + } + source := scheme + r.Host + prefix + h.Set( + "Content-Security-Policy", + "sandbox allow-scripts; default-src 'none'; script-src "+source+"; style-src 'unsafe-inline' "+source+"; img-src data: "+source+"; font-src "+source+"; connect-src 'none'; worker-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors "+ancestors, + ) + http.ServeContent(w, r, name, info.ModTime(), f) +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_review.go b/apps/stackpanel-go/internal/agent/server/module_ui_review.go new file mode 100644 index 00000000..737ac0b7 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_review.go @@ -0,0 +1,306 @@ +package server + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "maps" + "net/netip" + "net/url" + "path/filepath" + "slices" + "strconv" + "strings" + + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +// A review is a comparison value, not a credential. GetNixConfig and Open +// each build one snapshot from their own evaluation. projectConfig inherits +// modulesListAll (including script/scriptDrvPath), moduleOutputs (including +// scripts[].binPath), and panelsList *verbatim* from projectState. Do not +// substitute the protobuf ListModules projection or do a second eval here. +// The two evaluations differ for apps/services: select only common authority +// fields, not the full editor config with private service/app environments. +type uiReviewSnapshot struct { + profileBin string + links map[string]userconfig.LinkedModule // nil iff the load failed + storeRoot string + agentPort int + project string // hash of inputs shared by every panel + owners map[string]*uiReviewOwner + panels map[string]map[string]any +} + +type uiReviewOwner struct { + module map[string]any + outputs map[string]any + services map[string]any + // Computed only for owners of executable panels. Reuse across their panels. + digest string + scriptPaths map[string]string +} + +// encoding/json sorts string-keyed maps, including nested evaluated records. +// Keep list order: declaredActionTarget, for example, uses the first match. +func uiReviewHash(value any) string { + data, err := json.Marshal(value) + if err != nil { + return "" + } + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +func newUIReviewSnapshot(root, storeRoot string, state map[string]any, agentPort int) *uiReviewSnapshot { + links, err := userconfig.LoadLinkedModules(root) + if err == nil && links == nil { + links = map[string]userconfig.LinkedModule{} + } + s := &uiReviewSnapshot{ + links: links, profileBin: moduleActionProfile(root, storeRoot, state), storeRoot: storeRoot, agentPort: agentPort, + owners: make(map[string]*uiReviewOwner), panels: make(map[string]map[string]any), + } + physicalRoot, err := filepath.EvalSymlinks(root) + if err != nil || !filepath.IsAbs(physicalRoot) { + return s + } + dirs, _ := state["dirs"].(map[string]any) + apps, _ := state["apps"].(map[string]any) + enabledApps := make(map[string]bool, len(apps)) + for id, raw := range apps { + app, _ := raw.(map[string]any) + enabledApps[id] = app["enable"] == true + } + s.project = uiReviewHash([]any{"stackpanel-ui-review-v1", root, physicalRoot, dirs["profile"], s.profileBin, enabledApps}) + + outputs, _ := state["moduleOutputs"].(map[string]any) + modules, _ := state["modulesListAll"].([]any) + for _, raw := range modules { + mod, _ := raw.(map[string]any) + id, _ := mod["id"].(string) + if _, duplicate := s.owners[id]; duplicate || mod["enabled"] != true || !moduleRouteID.MatchString(id) { + s.owners[id] = nil + continue + } + owned, _ := outputs[id].(map[string]any) + s.owners[id] = &uiReviewOwner{module: mod, outputs: owned} + } + services, _ := state["services"].(map[string]any) + for name, raw := range services { + svc, _ := raw.(map[string]any) + id, _ := svc["module"].(string) + if owner := s.owners[id]; owner != nil { + if owner.services == nil { + owner.services = make(map[string]any) + } + proxy, _ := svc["proxy"].(map[string]any) + owner.services[name] = []any{svc["enable"] == true, proxy["enable"] == true, proxy["port"]} + } + } + panels, _ := state["panelsList"].([]any) + for _, raw := range panels { + p, _ := raw.(map[string]any) + id, _ := p["id"].(string) + if _, duplicate := s.panels[id]; duplicate || p["enabled"] != true || !moduleRouteID.MatchString(id) { + s.panels[id] = nil + continue + } + s.panels[id] = p + } + return s +} + +// Absolute declarations need not have been realized yet. Bare executable names +// must have an actual binPath in this owner's outputs, not just a label or a +// script of the same name elsewhere in the project. Mirror the first-declared +// rule in declaredActionTarget, indexing once rather than scanning per action. +func (o *uiReviewOwner) hasTarget(script, store string) bool { + if !filepath.IsAbs(script) { + if script == "" || script == "." || script == ".." || filepath.Base(script) != script { + return false + } + if o.scriptPaths == nil { + scripts, _ := o.outputs["scripts"].([]any) + o.scriptPaths = make(map[string]string, len(scripts)) + for _, raw := range scripts { + entry, _ := raw.(map[string]any) + name, _ := entry["name"].(string) + if _, seen := o.scriptPaths[name]; !seen { + o.scriptPaths[name], _ = entry["binPath"].(string) + } + } + } + script = o.scriptPaths[script] + } + return inModuleActionStore(script, store) +} + +// Report the browser origin only, never the author-supplied path. Bind the +// complete URL separately: moving /one to /two must invalidate the review. +func reviewedDevOrigin(link userconfig.LinkedModule, agentPort int) (string, bool) { + if link.UIDevURL == "" { + return "", true + } + if link.Path == "" || !validModuleDevURL(link.UIDevURL, agentPort) { + return "", false + } + u, err := url.Parse(link.UIDevURL) + if err != nil || !uiAuthority.MatchString(u.Host) { + return "", false + } + host := strings.ToLower(u.Hostname()) + if strings.HasPrefix(u.Host, "[") { + // A browser rejects bracketed IPv4/localhost. Only literal IPv6 + // loopback is a valid bracketed extension development origin. + if addr, err := netip.ParseAddr(host); err != nil || addr.String() != "::1" { + return "", false + } + host = "[::1]" + } + if rawPort := u.Port(); rawPort != "" { + port, _ := strconv.Atoi(rawPort) // validModuleDevURL checked range + if !(u.Scheme == "http" && port == 80 || u.Scheme == "https" && port == 443) { + host += ":" + strconv.Itoa(port) + } + } + return u.Scheme + "://" + host, true +} + +func (s *uiReviewSnapshot) review(mod, p map[string]any) (revision, devOrigin string) { + id, _ := mod["id"].(string) + panelID, _ := p["id"].(string) + owner := s.owners[id] + p = s.panels[panelID] // Only the actual unique, enabled evaluated panel. + if owner == nil || p == nil || p["module"] != id || s.project == "" { + return "", "" + } + actions, _ := owner.module["actions"].(map[string]any) + var ids []string + var link userconfig.LinkedModule + switch p["type"] { + case "PANEL_TYPE_SPEC": + spec, _ := p["spec"].(map[string]any) + if p["uiBundle"] != nil || spec == nil { + return "", "" + } + var err error + ids, err = statusActionIDs(spec, actions) + if err != nil || len(ids) == 0 { + return "", "" + } + case "PANEL_TYPE_CUSTOM": + bundle, err := customModuleBundle(owner.module, p, s.storeRoot) + if err != nil || s.links == nil { + return "", "" + } + link = s.links[id] + var ok bool + devOrigin, ok = reviewedDevOrigin(link, s.agentPort) + if !ok { + return "", "" + } + ids = bundle.actionIDs + default: + return "", "" + } + for _, k := range ids { + action, _ := actions[k].(map[string]any) + script, _ := action["script"].(string) + if !owner.hasTarget(script, s.storeRoot) { + return "", "" + } + } + if owner.digest == "" { + owner.digest = uiReviewHash([]any{owner.module, owner.outputs, owner.services}) + if owner.digest == "" { + return "", "" + } + } + p = withoutUIReview(p) + revision = uiReviewHash([]any{s.project, owner.digest, p, ids, link, devOrigin}) + if revision == "" { + return "", "" + } + return revision, devOrigin +} + +func withoutUIReview(p map[string]any) map[string]any { + if _, forged := p["uiReview"]; forged { + p = maps.Clone(p) + delete(p, "uiReview") + } + return p +} + +// Don't resolve filesystem/machine authority, hash documents or walk action +// schemas just to serve a project of ordinary declarative layouts. This cheap +// filter is not authorization; review checks the real reachable action set. +func mayReviewPanel(p map[string]any) bool { + if p["enabled"] != true { + return false + } + switch p["type"] { + case "PANEL_TYPE_CUSTOM": + return true + case "PANEL_TYPE_SPEC": + spec, _ := p["spec"].(map[string]any) + elements, _ := spec["elements"].(map[string]any) + if p["uiBundle"] == nil && len(elements) <= 64 { + for _, raw := range elements { + node, _ := raw.(map[string]any) + if node["type"] == "StatusView" { + return true + } + } + } + } + return false +} + +// Annotate only panelsList. Never mutate the watcher's cached response. +func configWithUIReviews(root, store string, state map[string]any, port int) map[string]any { + var snapshot *uiReviewSnapshot + panels, _ := state["panelsList"].([]any) + var updated []any + for i, raw := range panels { + p, ok := raw.(map[string]any) + if !ok { + continue + } + var marker map[string]any + if mayReviewPanel(p) { + if snapshot == nil { + snapshot = newUIReviewSnapshot(root, store, state, port) + } + id, _ := p["module"].(string) + if owner := snapshot.owners[id]; owner != nil { + if rev, origin := snapshot.review(owner.module, p); rev != "" { + marker = map[string]any{"revision": rev} + if origin != "" { + marker["devOrigin"] = origin + } + } + } + } + if _, forged := p["uiReview"]; marker == nil && !forged { + continue + } + if updated == nil { + updated = slices.Clone(panels) + } + p = maps.Clone(p) + updated[i] = p + if marker == nil { + delete(p, "uiReview") + } else { + p["uiReview"] = marker + } + } + if updated == nil { + return state + } + result := maps.Clone(state) + result["panelsList"] = updated + return result +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_review_test.go b/apps/stackpanel-go/internal/agent/server/module_ui_review_test.go new file mode 100644 index 00000000..9ffae893 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_review_test.go @@ -0,0 +1,239 @@ +package server + +import ( + "context" + "encoding/json" + "maps" + "os" + "path/filepath" + "strings" + "testing" + + "connectrpc.com/connect" + "github.com/stretchr/testify/require" + + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/project" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +// Exercise the actual cached RPC. In particular an ineligible entry with a +// project-provided marker must be stripped, not left alone on an early exit. +func TestGetNixConfigReviewsCopiesOfCachedPanels(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "0") + root := t.TempDir() + state, panel, mod := uiTestState() + forged := map[string]any{"revision": strings.Repeat("f", 64), "devOrigin": "https://example.org"} + panel["uiReview"] = forged + list := []any{panel} + add := func(id string, fields map[string]any) { + p := maps.Clone(panel) + p["id"] = id + maps.Copy(p, fields) + list = append(list, p) + } + add("disabled", map[string]any{"enabled": false}) + add("orphaned", map[string]any{"module": "unknown"}) + add("duplicate", nil) + add("duplicate", map[string]any{"module": "other"}) + add("layout", map[string]any{"type": "PANEL_TYPE_SPEC", "uiBundle": nil, "spec": map[string]any{ + "root": "heading", "elements": map[string]any{"heading": map[string]any{"type": "Heading", "props": map[string]any{}}}, + }}) + add("builtin", map[string]any{"type": "PANEL_TYPE_TABS"}) + add("off", map[string]any{"module": "off"}) + state["modulesListAll"] = []any{mod, map[string]any{"id": "off", "enabled": false}} + state["panelsList"] = list + before, err := json.Marshal(state) + require.NoError(t, err) + + s := newUITestServer(t) + s.config.ProjectRoot = root + s.projectMgr, err = project.NewManager(t.TempDir()) + require.NoError(t, err) + s.runtimes, _ = newTestRegistry() + s.runtimes.create = func(selected string) (*projectRuntime, error) { + require.Equal(t, root, selected) + return &projectRuntime{root: selected, flake: &FlakeWatcher{cachedConfig: state}, evalModuleState: func(context.Context, string) ([]byte, error) { + t.Fatal("reviewing the cached config must not re-evaluate module state") + return nil, nil + }}, nil + } + res, err := NewAgentServiceServer(s).GetNixConfig(t.Context(), connect.NewRequest(&gopb.GetNixConfigRequest{})) + require.NoError(t, err) + require.True(t, res.Msg.Cached) + var result map[string]any + require.NoError(t, json.Unmarshal([]byte(res.Msg.ConfigJson), &result)) + rows := result["panelsList"].([]any) + require.Len(t, rows, len(list)) + marker := rows[0].(map[string]any)["uiReview"].(map[string]any) + require.Len(t, marker, 1) + require.Regexp(t, "^[0-9a-f]{64}$", marker["revision"]) + for _, raw := range rows[1:] { + require.NotContains(t, raw, "uiReview") + } + require.NotContains(t, res.Msg.ConfigJson, forged["revision"]) + after, err := json.Marshal(state) + require.NoError(t, err) + require.Equal(t, before, after, "the next cache reader must get the original maps AND list entries") + delete(panel, "uiReview") + revision, _ := newUIReviewSnapshot(root, moduleStoreRoot, state, s.config.Port).review(mod, panel) + require.Equal(t, revision, marker["revision"], "an injected marker must not influence the agent's revision") +} + +func TestUIReviewMatchesExecutionSnapshot(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "0") + for _, change := range []string{"action script", "producer", "bare script target", "profile symlink", "panel", "module config", "proxy", "app visibility", "permissions"} { + t.Run(change, func(t *testing.T) { + f := newActionFixture(t, ":") + _, p, _ := uiTestState() + p["module"] = "sample" + bundle := p["uiBundle"].(map[string]any) + bundle["package"] = filepath.Join(f.store, testUIStoreName) + bundle["permissions"] = []any{"actions:run", "service:proxy"} + f.state["panelsList"] = []any{p} + app := map[string]any{"enable": true} + proxy := map[string]any{"enable": true, "port": float64(8111)} + svc := map[string]any{"module": "sample", "enable": true, "proxy": proxy} + f.state["services"], f.state["apps"] = map[string]any{"api": svc}, map[string]any{"web": app} + // projectConfig contains editor-only service and app options; + // neither a raw env nor another owner's outputs belong in this hash. + full := maps.Clone(f.state) + full["apps"] = map[string]any{"web": map[string]any{"enable": true, "env": "private"}} + full["services"] = map[string]any{"api": map[string]any{"module": "sample", "enable": true, "command": "private", "proxy": proxy}} + cfg := configWithUIReviews(f.root, f.store, full, 9876) + marker := cfg["panelsList"].([]any)[0].(map[string]any)["uiReview"].(map[string]any) + current := func() string { + snapshot := newUIReviewSnapshot(f.root, f.store, f.state, 9876) + rev, _ := snapshot.review(f.module, p) + return rev + } + require.Equal(t, marker["revision"], current()) + switch change { + case "action script": + f.action["script"] = f.script + case "producer": + f.action["scriptDrvPath"] = f.script + ".drv" + case "bare script target": + owned := f.state["moduleOutputs"].(map[string]any)["sample"].(map[string]any) + owned["scripts"].([]any)[0].(map[string]any)["binPath"] = f.script + "-other" + case "profile symlink": + other := f.profile + "-next" + require.NoError(t, os.MkdirAll(filepath.Join(other, "bin"), 0o700)) + link := filepath.Join(f.root, ".stack", "profile", "profile") + require.NoError(t, os.Remove(link)) + require.NoError(t, os.Symlink(other, link)) + case "panel": + p["title"] = "Different document" + case "module config": + f.module["configPath"] = "other.settings" + case "proxy": + proxy["port"] = float64(8112) + case "app visibility": + app["enable"] = false + case "permissions": + bundle["permissions"] = []any{"actions:run"} + } + rev := current() + require.NotEmpty(t, rev) + require.NotEqual(t, marker["revision"], rev) + }) + } +} + +func TestUIReviewSpecRequiresExecutableProjection(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + f := newActionFixture(t, ":") + p := map[string]any{ + "id": "status", "type": "PANEL_TYPE_SPEC", "module": "sample", "enabled": true, + "spec": map[string]any{"root": "status", "elements": map[string]any{"status": map[string]any{ + "type": "StatusView", "props": map[string]any{"action": "run"}, + }}}, + } + f.state["panelsList"] = []any{p} + check := func() string { + rev, origin := newUIReviewSnapshot(f.root, f.store, f.state, 9876).review(f.module, p) + require.Empty(t, origin) + return rev + } + rev := check() + require.NotEmpty(t, rev) + f.action["script"] = f.script + changed := check() + require.NotEmpty(t, changed) + require.NotEqual(t, rev, changed) + delete(f.action, "script") // public protobuf descriptor only + require.Empty(t, check()) + f.action["script"] = "report" + delete(f.state, "moduleOutputs") // bare name without an attributed binPath + require.Empty(t, check()) + f.action["script"] = f.script + f.action["confirm"] = "Mutate resources?" + require.Empty(t, check()) + delete(f.action, "confirm") + f.state["modulesListAll"] = []any{f.module, maps.Clone(f.module)} + require.Empty(t, check()) +} + +func TestUIReviewPinsCustomLinkAndPhysicalRoot(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "0") + state, p, mod := uiTestState() + root, first, second, author := filepath.Join(t.TempDir(), "current"), t.TempDir(), t.TempDir(), t.TempDir() + for _, dir := range []string{first, second, author} { + moduleFixtureFile(t, dir, "flake.nix", "{}") + } + require.NoError(t, os.Symlink(first, root)) + check := func() (string, string) { + return newUIReviewSnapshot(root, moduleStoreRoot, state, 9876).review(mod, p) + } + initial, origin := check() + require.NotEmpty(t, initial) + require.Empty(t, origin) + require.NoError(t, os.Remove(root)) + require.NoError(t, os.Symlink(second, root)) + next, _ := check() + require.NotEmpty(t, next) + require.NotEqual(t, initial, next) + + mgr, err := userconfig.NewManager() + require.NoError(t, err) + set := func(url string) { + require.NoError(t, mgr.SetLinkedModule(root, "demo", userconfig.LinkedModule{Path: author, UIDevURL: url})) + } + set("http://LOCALHOST:080/one") + pinned := newUIReviewSnapshot(root, moduleStoreRoot, state, 9876) + linked, origin := pinned.review(mod, p) + require.NotEmpty(t, linked) + require.NotEqual(t, next, linked) + require.Equal(t, "http://localhost", origin) + set("http://LOCALHOST:080/two") + changed, sameOrigin := check() + require.NotEmpty(t, changed) + require.NotEqual(t, linked, changed) + require.Equal(t, origin, sameOrigin) + stillPinned, _ := pinned.review(mod, p) + require.Equal(t, linked, stillPinned) + set("http://127.0.0.1:9876/agent") // loopback alone does not make the agent a valid target + invalid, origin := check() + require.Empty(t, invalid) + require.Empty(t, origin) +} + +func TestUIReviewRequiresKnownCustomLinkState(t *testing.T) { + path := filepath.Join(t.TempDir(), "user.yaml") + t.Setenv("STACKPANEL_USER_CONFIG", path) + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "0") + root := t.TempDir() + state, p, mod := uiTestState() + snapshot := newUIReviewSnapshot(root, moduleStoreRoot, state, 9876) + require.NotNil(t, snapshot.links) + require.Empty(t, snapshot.links) + require.NoError(t, os.WriteFile(path, []byte("projects: ["), 0o600)) + snapshot = newUIReviewSnapshot(root, moduleStoreRoot, state, 9876) + require.Nil(t, snapshot.links) + rev, origin := snapshot.review(mod, p) + require.Empty(t, rev) + require.Empty(t, origin) +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_spec.go b/apps/stackpanel-go/internal/agent/server/module_ui_spec.go new file mode 100644 index 00000000..997406b1 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_spec.go @@ -0,0 +1,333 @@ +package server + +import ( + "crypto/sha256" + "encoding/json" + "maps" + "net/http" + "path/filepath" + "regexp" + "slices" + "strings" + "time" + "unicode" + "unicode/utf8" + + "connectrpc.com/connect" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" +) + +const maxStatusApps = 128 + +var specKeyPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$`) + +func reservedUIName(key string) bool { + switch key { + case "prototype", "constructor", "__proto__", "__defineGetter__", "__defineSetter__", + "__lookupGetter__", "__lookupSetter__", "hasOwnProperty", "isPrototypeOf", + "propertyIsEnumerable", "toLocaleString", "toString", "valueOf": + return true + } + return false +} + +func validSpecKey(key string) bool { + return specKeyPattern.MatchString(key) && !reservedUIName(key) +} + +func validStatusID(id string) bool { + // These are values on stdin, not paths, object keys, or URL segments. + if id == "" || len(id) > 128*utf8.UTFMax || !utf8.ValidString(id) || utf8.RuneCountInString(id) > 128 || strings.TrimSpace(id) != id || reservedUIName(id) { + return false + } + for _, r := range id { + if unicode.IsOneOf([]*unicode.RangeTable{unicode.Cc, unicode.Cf, unicode.Zl, unicode.Zp}, r) { + return false + } + } + return true +} + +func specReference(raw any, directive, prefix string) (string, bool) { + ref, _ := raw.(map[string]any) + path, _ := ref[directive].(string) + key, ok := strings.CutPrefix(path, prefix) + return key, len(ref) == 1 && ok && validSpecKey(key) +} + +type statusTargets map[string]bool // "" represents {}, never {app:""} + +func pickerTargets(props, state map[string]any) (string, statusTargets, bool) { + key, ok := specReference(props["value"], "$bindState", "/local/") + if !ok { + return "", nil, false + } + local, _ := state["local"].(map[string]any) + initial, ok := local[key].(string) + if !ok { + return "", nil, false + } + raw := props["apps"] + if _, ref := raw.(map[string]any); ref { + dataKey, ok := specReference(raw, "$state", "/data/") + if !ok { + return "", nil, false + } + data, _ := state["data"].(map[string]any) + raw = data[dataKey] + } + apps, ok := raw.([]any) + if !ok || len(apps) > maxStatusApps { + return "", nil, false + } + targets := make(statusTargets, len(apps)) + for _, raw := range apps { + app, _ := raw.(string) + if !validStatusID(app) || targets[app] { + return "", nil, false + } + targets[app] = true + } + return key, targets, initial == "" || targets[initial] +} + +func statusViewTargets(props map[string]any, pickers map[string]statusTargets) (statusTargets, bool) { + raw, present := props["app"] + if !present { + return statusTargets{"": true}, true + } + if app, ok := raw.(string); ok { + if app == "" { + return nil, true // an empty selection is not an argument-less view + } + return statusTargets{app: true}, validStatusID(app) + } + key, ok := specReference(raw, "$state", "/local/") + targets, exists := pickers[key] + return targets, ok && exists +} + +// Walk only explicit child references. Each view offers its own targets: +// two views of the same action do not authorize the union of their choices. +func statusOffers(spec, actions map[string]any) (map[string][]statusTargets, error) { + root, _ := spec["root"].(string) + elements, _ := spec["elements"].(map[string]any) + if root == "" || len(elements) == 0 || len(elements) > 64 { + return nil, invalidModuleState("invalid spec element tree") + } + seen := make(map[string]bool, len(elements)) + state, _ := spec["state"].(map[string]any) + pickers := make(map[string]statusTargets) + var views []map[string]any + var visit func(string, int) bool + visit = func(key string, depth int) bool { + node, _ := elements[key].(map[string]any) + kind, _ := node["type"].(string) + props, ok := node["props"].(map[string]any) + if !validSpecKey(key) || depth > 16 || seen[key] || kind == "" || !ok { + return false + } + seen[key] = true + switch kind { + case "StatusView": + views = append(views, props) + case "AppPicker": + key, targets, ok := pickerTargets(props, state) + if _, present := pickers[key]; !ok || present { + return false + } + pickers[key] = targets + } + if raw, present := node["children"]; present { + // Only the host's containers expose child slots. Do not infer + // reachability through a leaf or a future unknown component. + children, ok := raw.([]any) + if !ok || len(children) > len(elements) || (len(children) > 0 && kind != "Stack" && kind != "Section") { + return false + } + for _, child := range children { + id, ok := child.(string) + if !ok || !visit(id, depth+1) { + return false + } + } + } + return true + } + if !visit(root, 1) || len(seen) != len(elements) { + return nil, invalidModuleState("invalid spec element tree or app picker") + } + offers := make(map[string][]statusTargets) + for _, props := range views { + id, _ := props["action"].(string) + targets, ok := statusViewTargets(props, pickers) + if !validStatusID(id) || !ok { + return nil, invalidModuleState("invalid status action or app reference") + } + if action, ok := actions[id].(map[string]any); ok && (action["confirm"] == nil || action["confirm"] == "") { + offers[id] = append(offers[id], targets) + } + } + return offers, nil +} + +func statusActionIDs(spec, actions map[string]any) ([]string, error) { + offers, err := statusOffers(spec, actions) + if err != nil { + return nil, err + } + return slices.Sorted(maps.Keys(offers)), nil +} + +func (targets statusTargets) offers(apps []string) bool { + if len(apps) == 0 { + return targets[""] + } + for _, app := range apps { + if !targets[app] { + return false + } + } + return true +} + +func checkStatusReview(mod, panel map[string]any, c moduleUIGrant) error { + if !validStatusID(c.StatusAction) || len(c.StatusApps) > maxStatusApps || + (c.App != "" && (len(c.StatusApps) != 1 || c.StatusApps[0] != c.App)) { + return uiGrantDenied() + } + seen := make(map[string]bool, len(c.StatusApps)) + for _, app := range c.StatusApps { + if !validStatusID(app) || seen[app] { + return uiGrantDenied() + } + seen[app] = true + } + spec, _ := panel["spec"].(map[string]any) + actions, _ := mod["actions"].(map[string]any) + offers, err := statusOffers(spec, actions) + if err != nil { + return err + } + if !slices.ContainsFunc(offers[c.StatusAction], func(targets statusTargets) bool { return targets.offers(c.StatusApps) }) { + return uiGrantDenied() + } + // Use the normal runner's compiler and ref policy, once for all reviewed + // targets. Dispatch still validates its actual stdin via moduleActionInput. + action := actions[c.StatusAction].(map[string]any) + schema, err := compileModuleActionSchema(action["argsSchema"]) + if err != nil { + return err + } + args := map[string]any{} + if len(c.StatusApps) == 0 && schema.Validate(args) != nil { + return uiGrantDenied() + } + for _, app := range c.StatusApps { + args["app"] = app + if schema.Validate(args) != nil { + return uiGrantDenied() + } + } + return nil +} + +func specGrantRevision(root, profileBin string, state, mod, p map[string]any, c moduleUIGrant) ([32]byte, error) { + var empty [32]byte + spec, ok := p["spec"].(map[string]any) + if p["type"] != "PANEL_TYPE_SPEC" || !ok || p["uiBundle"] != nil { + return empty, uiGrantDenied() + } + slot, validSlot := p["slot"].(string) + apps, validApps := p["apps"].(map[string]any) + if p["slot"] != nil && !validSlot || p["apps"] != nil && !validApps || !validPanelApp(state, slot, c.App, apps) { + return empty, uiGrantDenied() + } + app, _ := apps[c.App].(map[string]any) + actions, _ := mod["actions"].(map[string]any) + action, ok := actions[c.StatusAction].(map[string]any) + if !ok { + return empty, uiGrantDenied() + } + script, _ := action["script"].(string) + physicalRoot, err := filepath.EvalSymlinks(root) + if err != nil { + return empty, err + } + // The sealed claims already restrict action and arguments. Bind them to + // the exact graph and executable under which that subset was approved. + dirs, _ := state["dirs"].(map[string]any) + body, err := json.Marshal([]any{"spec", root, physicalRoot, c.Module, c.Panel, c.App, slot, app["enabled"], + spec, c.StatusAction, action, declaredActionTarget(script, state, c.Module), dirs["profile"], profileBin}) + if err != nil { + return empty, err + } + return sha256.Sum256(body), nil +} + +func (m *moduleService) openSpecUI(root, profileBin string, state map[string]any, req *connect.Request[agentv1.OpenModuleUIRequest], mod, panel map[string]any) (*connect.Response[agentv1.OpenModuleUIResponse], error) { + if _, bound := req.Header()[http.CanonicalHeaderKey(moduleUIGrantHeader)]; bound { + return nil, uiGrantDenied() // no refresh or transfer, even at the same revision + } + c := moduleUIGrant{ + Spec: true, Module: req.Msg.GetModuleId(), Panel: req.Msg.GetPanelId(), App: req.Msg.GetAppId(), + StatusAction: req.Msg.GetStatusAction(), StatusApps: req.Msg.GetStatusApps(), Expires: time.Now().Add(moduleUIGrantLifetime).Unix(), + } + if err := checkStatusReview(mod, panel, c); err != nil { + return nil, err + } + revision, err := specGrantRevision(root, profileBin, state, mod, panel, c) + if err != nil { + return nil, err + } + c.Revision = revision + token, err := m.s.encodeUIGrant(c) + if err != nil { + return nil, uiGrantDenied() + } + return moduleUIResponse(&agentv1.OpenModuleUIResponse{ + Permissions: []string{"actions:run"}, ActionIds: []string{c.StatusAction}, ReviewRevision: req.Msg.GetReviewRevision(), + }, mod, token, c.Expires) +} + +// Native calls have no UI credential. With any grant header present we must +// authorize the original grant or deny, never retry as a native action. +func (s *Server) checkActionGrant(h http.Header, rt *projectRuntime, state map[string]any, msg *agentv1.RunModuleActionRequest, profileBin string) error { + if _, present := h[http.CanonicalHeaderKey(moduleUIGrantHeader)]; !present { + return nil + } + c, err := s.decodeUIGrant(h) + if err != nil || c.Module != msg.GetModuleId() { + return uiGrantDenied() + } + if !c.Spec { + b, err := verifiedCustomBundle(c, rt, state, c.Module, "actions:run", profileBin) + if err != nil || !slices.Contains(b.actionIDs, msg.GetActionId()) { + return uiGrantDenied() + } + return nil + } + if rt == nil || c.StatusAction == "" || c.StatusAction != msg.GetActionId() || !validStatusArgs(msg.GetArgs(), c) { + return uiGrantDenied() + } + mod, p, err := evaluatedUIPanel(state, c.Module, c.Panel) + if err != nil { + return uiGrantDenied() + } + revision, err := specGrantRevision(rt.root, profileBin, state, mod, p, c) + if err != nil || revision != c.Revision { + return uiGrantDenied() + } + return nil +} + +func validStatusArgs(args *structpb.Struct, c moduleUIGrant) bool { + fields := args.GetFields() + if len(fields) == 0 { + return c.App == "" && len(c.StatusApps) == 0 + } + app, ok := fields["app"].GetKind().(*structpb.Value_StringValue) + return len(fields) == 1 && ok && (c.App == "" || app.StringValue == c.App) && slices.Contains(c.StatusApps, app.StringValue) +} diff --git a/apps/stackpanel-go/internal/agent/server/module_ui_spec_test.go b/apps/stackpanel-go/internal/agent/server/module_ui_spec_test.go new file mode 100644 index 00000000..dee9d82c --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/module_ui_spec_test.go @@ -0,0 +1,484 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "connectrpc.com/connect" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +type specUIFixture struct { + *actionFixture + m *moduleService + rt *projectRuntime + panel map[string]any + elements map[string]any +} + +func newSpecUIFixture(t *testing.T) *specUIFixture { + t.Helper() + f := newActionFixture(t, `: >ran; IFS= read -r args; printf '%s' "$args"`) + f.action["label"], f.action["outputMode"] = "Status", "json" + actions := f.module["actions"].(map[string]any) + actions["remove"] = maps.Clone(f.action) + actions["remove"].(map[string]any)["confirm"] = "Delete resources?" + actions["other"], actions["buttonsOnly"] = maps.Clone(f.action), maps.Clone(f.action) + selection := map[string]any{"$state": "/local/selection"} + elements := map[string]any{ + "main": map[string]any{"type": "Stack", "props": map[string]any{}, "children": []any{"status", "picked", "second", "literal", "picker", "buttons", "unsafe", "missing"}}, + "status": map[string]any{"type": "StatusView", "props": map[string]any{"action": "run"}}, + "picked": map[string]any{"type": "StatusView", "props": map[string]any{"action": "run", "app": selection}}, + "second": map[string]any{"type": "StatusView", "props": map[string]any{"action": "other", "app": selection}}, + "literal": map[string]any{"type": "StatusView", "props": map[string]any{"action": "run", "app": "edge"}}, + "picker": map[string]any{"type": "AppPicker", "props": map[string]any{ + "apps": map[string]any{"$state": "/data/targets"}, "value": map[string]any{"$bindState": "/local/selection"}, + }}, + "buttons": map[string]any{"type": "Actions", "props": map[string]any{}}, + "unsafe": map[string]any{"type": "StatusView", "props": map[string]any{"action": "remove"}}, + "missing": map[string]any{"type": "StatusView", "props": map[string]any{"action": "undeclared"}}, + } + p := map[string]any{ + "id": "inspector", "module": "sample", "enabled": true, "type": "PANEL_TYPE_SPEC", "slot": "module", + "spec": map[string]any{"root": "main", "elements": elements, "state": map[string]any{ + "data": map[string]any{"targets": []any{"web", "api", "worker"}}, "local": map[string]any{"selection": "web"}, + }}, + } + f.state["panelsList"] = []any{p} + f.state["apps"] = map[string]any{"web": map[string]any{"enable": true}} + rt := &projectRuntime{root: f.root, evalModuleState: func(context.Context, string) ([]byte, error) { return json.Marshal(f.state) }} + return &specUIFixture{f, &moduleService{s: newUITestServer(t)}, rt, p, elements} +} + +func (f *specUIFixture) request(t *testing.T, app, action string, targets ...string) *connect.Request[agentv1.OpenModuleUIRequest] { + t.Helper() + return connect.NewRequest(&agentv1.OpenModuleUIRequest{ + ModuleId: "sample", PanelId: "inspector", AppId: app, StatusAction: action, StatusApps: targets, + ReviewRevision: testReviewRevision(t, f.root, f.store, f.state, "sample", "inspector"), + }) +} + +func (f *specUIFixture) open(t *testing.T, app string, targets ...string) http.Header { + t.Helper() + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + req := f.request(t, app, "run", targets...) + res, err := f.m.openModuleUI(ctx, req, f.store) + if err != nil { + t.Fatal(err) + } + msg := res.Msg + if msg.Url != "" || msg.DevUrl != "" || msg.Settings != nil || msg.ReviewRevision != req.Msg.ReviewRevision || + !slices.Equal(msg.Permissions, []string{"actions:run"}) || !slices.Equal(msg.ActionIds, []string{"run"}) || + len(msg.Actions) != 1 || msg.Actions["run"].GetLabel() != "Status" { + t.Fatalf("unexpected spec grant projection: %v", msg) + } + h := http.Header{} + h.Set(moduleUIGrantHeader, res.Header().Get(moduleUIGrantHeader)) + if h.Get(moduleUIGrantHeader) == "" || res.Header().Get(moduleUIExpiryHeader) == "" || res.Header().Get("Cache-Control") != "no-store" { + t.Fatal("missing host grant headers") + } + return h +} + +func TestSpecUIGrantDispatch(t *testing.T) { + // A declarative layout does not launch a dev server or need a realized UI + // bundle; the machine custom UI policy must not block its action grant. + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "1") + picker := []string{"api", "web"} // deliberately omits the third offered app, worker + web := []string{"web"} + for _, tc := range []struct { + name, app string + reviewed []string + args map[string]any + want connect.Code + }{ + {"global", "", nil, nil, 0}, + {"picker", "", picker, map[string]any{"app": "api"}, 0}, + {"second reviewed app", "", picker, map[string]any{"app": "web"}, 0}, + {"unreviewed picker option", "", picker, map[string]any{"app": "worker"}, connect.CodePermissionDenied}, + {"unreviewed literal", "", picker, map[string]any{"app": "edge"}, connect.CodePermissionDenied}, + {"empty object with picker grant", "", picker, nil, connect.CodePermissionDenied}, + {"app with no-args grant", "", nil, map[string]any{"app": "api"}, connect.CodePermissionDenied}, + {"literal", "", []string{"edge"}, map[string]any{"app": "edge"}, 0}, + {"selected", "web", web, map[string]any{"app": "web"}, 0}, + {"other app", "web", web, map[string]any{"app": "api"}, connect.CodePermissionDenied}, + {"omitted app", "web", web, nil, connect.CodePermissionDenied}, + {"extra arg", "", picker, map[string]any{"app": "api", "force": true}, connect.CodePermissionDenied}, + {"wrong key", "", picker, map[string]any{"name": "api"}, connect.CodePermissionDenied}, + {"nonstring", "", picker, map[string]any{"app": nil}, connect.CodePermissionDenied}, + {"schema changed", "", picker, map[string]any{"app": "api"}, connect.CodePermissionDenied}, + {"wrong action", "", picker, map[string]any{"app": "api"}, connect.CodePermissionDenied}, + {"confirmation", "", nil, nil, connect.CodePermissionDenied}, + {"wrong module", "", nil, nil, connect.CodePermissionDenied}, + {"other project", "", nil, nil, connect.CodePermissionDenied}, + {"spec changed", "", nil, nil, connect.CodePermissionDenied}, + {"executable changed", "", nil, nil, connect.CodePermissionDenied}, + {"owned target changed", "", nil, nil, connect.CodePermissionDenied}, + {"profile changed", "", nil, nil, connect.CodePermissionDenied}, + {"warning added", "", nil, nil, connect.CodePermissionDenied}, + {"converted to iframe", "", nil, nil, connect.CodePermissionDenied}, + {"lost owner", "", nil, nil, connect.CodePermissionDenied}, + {"disabled module", "", nil, nil, connect.CodePermissionDenied}, + {"disabled app", "web", web, map[string]any{"app": "web"}, connect.CodePermissionDenied}, + {"disabled panel", "", nil, nil, connect.CodePermissionDenied}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newSpecUIFixture(t) + if tc.app != "" { + f.panel["slot"] = "app:tab" + } + h := f.open(t, tc.app, tc.reviewed...) + switch tc.name { + case "wrong action": + f.req.ActionId = "other" // independently eligible at the very same app + case "schema changed": + f.action["argsSchema"] = map[string]any{"type": "object", "required": []any{"newArg"}} + case "disabled app": + f.state["apps"].(map[string]any)["web"].(map[string]any)["enable"] = false + case "confirmation": + f.req.ActionId = "remove" + case "wrong module": + f.req.ModuleId = "other" + case "other project": + f.rt.root = t.TempDir() + case "spec changed": + f.panel["spec"].(map[string]any)["state"] = map[string]any{"data": map[string]any{"label": "new"}} + case "executable changed": + f.action["script"] = f.script + case "owned target changed": + delete(f.state, "moduleOutputs") + case "profile changed": + if err := os.Remove(filepath.Join(f.root, ".stack/profile/profile")); err != nil { + t.Fatal(err) + } + case "warning added": + f.action["confirm"] = "Proceed?" + case "converted to iframe": + f.panel["type"] = "PANEL_TYPE_CUSTOM" + case "lost owner": + f.panel["module"] = "other" + case "disabled module": + f.module["enabled"] = false + case "disabled panel": + f.panel["enabled"] = false + } + if tc.args != nil { + var err error + f.req.Args, err = structpb.NewStruct(tc.args) + if err != nil { + t.Fatal(err) + } + } + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + var events []*agentv1.RunModuleActionResponse + err := f.m.runModuleActionWithHeader(ctx, f.store, h, f.req, func(msg *agentv1.RunModuleActionResponse) error { + events = append(events, msg) + return nil + }) + if tc.want != 0 { + if connect.CodeOf(err) != tc.want || len(events) != 0 { + t.Fatalf("got %v (%d events), want %v before exec", err, len(events), tc.want) + } + if _, err := os.Stat(filepath.Join(f.root, "ran")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("rejected status action executed") + } + return + } + if err != nil || len(events) != 2 || events[0].GetJson().GetStructValue() == nil || !maps.Equal(events[0].GetJson().GetStructValue().AsMap(), tc.args) { + t.Fatalf("status read: %v, events %v", err, events) + } + }) + } +} + +func TestStatusValueIDs(t *testing.T) { + for _, valid := range []string{"_api", "café / east", strings.Repeat("界", 128)} { + if !validStatusID(valid) { + t.Errorf("rejected literal value %q", valid) + } + } + for _, invalid := range []string{"", " trailing ", "a\nb", "a\u202eb", "a\u2028b", "a\u2029b", "__proto__", "prototype", strings.Repeat("界", 129)} { + if validStatusID(invalid) { + t.Errorf("accepted invalid value %q", invalid) + } + } +} + +func TestSpecScopedValueIDsExecute(t *testing.T) { + f := newSpecUIFixture(t) + f.panel["slot"] = "app:tab" + f.state["apps"] = map[string]any{"_api": map[string]any{"enable": true}} + f.module["actions"].(map[string]any)["_action"] = f.action + f.elements["literal"].(map[string]any)["props"] = map[string]any{"action": "_action", "app": "_api"} + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + res, err := f.m.openModuleUI(ctx, f.request(t, "_api", "_action", "_api"), f.store) + if err != nil { + t.Fatal(err) + } + f.req.ActionId = "_action" + f.req.Args, _ = structpb.NewStruct(map[string]any{"app": "_api"}) + var app string + err = f.m.runModuleActionWithHeader(ctx, f.store, res.Header(), f.req, func(ev *agentv1.RunModuleActionResponse) error { + if obj := ev.GetJson().GetStructValue(); obj != nil { + app = obj.GetFields()["app"].GetStringValue() + } + return nil + }) + if err != nil || app != "_api" { + t.Fatalf("scoped status read: app=%q, err=%v", app, err) + } +} + +func TestSpecOpenRejectsUnreviewableTargets(t *testing.T) { + for _, tc := range []struct { + name, action, app string + targets []string + }{ + {"no action", "", "", nil}, + {"wildcard button only", "buttonsOnly", "", nil}, + {"confirmed action", "remove", "", nil}, + {"undeclared action", "undeclared", "", nil}, + {"picker is not a no-args view", "other", "", nil}, + {"not offered", "run", "", []string{"absent"}}, + {"union of different views", "run", "", []string{"web", "edge"}}, + {"empty app", "run", "", []string{""}}, + {"duplicate apps", "run", "", []string{"api", "api"}}, + {"unsafe app", "run", "", []string{"prototype"}}, + {"excess apps", "run", "", make([]string, 129)}, + {"scope mismatch", "run", "web", []string{"api"}}, + {"scope widened", "run", "web", []string{"web", "api"}}, + {"scoped no-args", "run", "web", nil}, + {"no project app", "run", "api", []string{"api"}}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newSpecUIFixture(t) + if tc.app != "" { + f.panel["slot"] = "app:tab" + } + req := f.request(t, tc.app, tc.action, tc.targets...) + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + if res, err := f.m.openModuleUI(ctx, req, f.store); res != nil || connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("opened outside review: response %v, err %v", res, err) + } + }) + } +} + +func TestSpecStatusPreflightReportsBothEligibleActions(t *testing.T) { + f := newSpecUIFixture(t) + ids, err := statusActionIDs(f.panel["spec"].(map[string]any), f.module["actions"].(map[string]any)) + if err != nil || !slices.Equal(ids, []string{"other", "run"}) { + t.Fatalf("preflight actions: %v, %v", ids, err) + } + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + res, err := f.m.openModuleUI(ctx, f.request(t, "", "other", "api"), f.store) + if err != nil || !slices.Equal(res.Msg.ActionIds, []string{"other"}) || len(res.Msg.Actions) != 1 || res.Msg.Actions["other"] == nil { + t.Fatalf("second action's separate review: %v, %v", res, err) + } +} + +func TestSpecOpenChecksEachTargetAgainstActionSchema(t *testing.T) { + f := newSpecUIFixture(t) + f.action["argsSchema"] = map[string]any{ + "type": "object", "required": []any{"app"}, + "properties": map[string]any{"app": map[string]any{"$ref": "#/$defs/app"}}, + "$defs": map[string]any{"app": map[string]any{"not": map[string]any{"const": "worker"}}}, + } + f.open(t, "", "web", "api") + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + for _, targets := range [][]string{nil, {"web", "worker"}} { + req := f.request(t, "", "run", targets...) + if res, err := f.m.openModuleUI(ctx, req, f.store); res != nil || connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("approved schema-invalid targets %v: %v, %v", targets, res, err) + } + } +} + +func TestSpecOpenRejectsStaleReview(t *testing.T) { + f := newSpecUIFixture(t) + req := f.request(t, "", "run", "web") + // Still a valid open for the same action and app, but no longer what was reviewed. + f.panel["title"] = "Renamed panel" + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + if res, err := f.m.openModuleUI(ctx, req, f.store); res != nil || connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("stale review opened: %v, %v", res, err) + } +} + +func TestSpecPickerMaximumLiteralList(t *testing.T) { + f := newSpecUIFixture(t) + apps, targets := make([]any, 128), make([]string, 128) + for i := range targets { + targets[i] = fmt.Sprintf("%0128d", i) + apps[i] = targets[i] + } + picker := f.elements["picker"].(map[string]any)["props"].(map[string]any) + picker["apps"] = apps + spec := f.panel["spec"].(map[string]any) + spec["state"].(map[string]any)["local"] = map[string]any{"selection": ""} + h := f.open(t, "", targets...) + f.req.Args, _ = structpb.NewStruct(map[string]any{"app": targets[127]}) + if err := f.m.s.checkActionGrant(h, f.rt, f.state, f.req, moduleActionProfile(f.root, f.store, f.state)); err != nil { + t.Fatalf("valid maximum-size grant unusable: %v", err) + } + picker["apps"] = append(apps, "overflow") + if _, err := statusActionIDs(spec, f.module["actions"].(map[string]any)); err == nil { + t.Fatal("129 unique safe options eligible for review") + } +} + +func TestSpecUIGrantOperationIsolation(t *testing.T) { + f := newSpecUIFixture(t) + h := f.open(t, "") + ctx := context.WithValue(t.Context(), runtimeKey{}, f.rt) + req := f.request(t, "", "run") + req.Header().Set(moduleUIGrantHeader, h.Get(moduleUIGrantHeader)) + if _, err := f.m.openModuleUI(ctx, req, f.store); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("refreshed spec grant: %v", err) + } + if err := f.m.s.checkModuleProxyGrant(h, f.rt, f.state, "sample"); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Errorf("spec grant accepted for proxy: %v", err) + } + if _, _, err := f.m.s.moduleUIConfigPatchScope(h, f.rt, f.state, "sample"); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("granted settings patch: %v", err) + } + if _, err := evaluatedModuleBundle(f.state, "sample", "inspector", f.store); err == nil { + t.Fatal("spec resolved as authenticated asset bundle") + } + _, custom, _ := uiTestState() + f.panel["type"], f.panel["uiBundle"] = "PANEL_TYPE_CUSTOM", custom["uiBundle"] + f.panel["uiBundle"].(map[string]any)["permissions"] = []any{"actions:run", "config:read"} + if err := f.m.s.checkActionGrant(h, f.rt, f.state, f.req, moduleActionProfile(f.root, f.store, f.state)); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("transferred status grant to replacement iframe: %v", err) + } +} + +func TestSpecUIRejectsMalformedTree(t *testing.T) { + for _, scenario := range []string{"missing root", "dangling child", "cycle", "shared child", "unreachable", "leaf children", "nonliteral action", "missing type", "wrong props", "nonlist children"} { + t.Run(scenario, func(t *testing.T) { + f := newSpecUIFixture(t) + spec := f.panel["spec"].(map[string]any) + main := f.elements["main"].(map[string]any) + status := f.elements["status"].(map[string]any) + switch scenario { + case "missing root": + spec["root"] = "none" + case "dangling child": + delete(f.elements, "status") + case "cycle": + main["children"] = []any{"main"} + case "shared child": + main["children"] = append(main["children"].([]any), "status") + case "unreachable": + f.elements["ghost"] = status + case "leaf children": + main["type"] = "Actions" + case "nonliteral action": + status["props"].(map[string]any)["action"] = map[string]any{"$state": "/data/name"} + case "missing type": + delete(main, "type") + case "wrong props": + main["props"] = []any{} + case "nonlist children": + main["children"] = "status" + } + if _, err := statusActionIDs(spec, f.module["actions"].(map[string]any)); connect.CodeOf(err) != connect.CodeFailedPrecondition { + t.Fatalf("malformed graph eligible for review: %v", err) + } + }) + } +} + +func TestSpecRejectsMalformedAppSources(t *testing.T) { + for _, tc := range []struct { + name, node, prop string + value any + }{ + {"null target", "picked", "app", nil}, + {"unsafe literal", "picked", "app", "constructor"}, + {"ambient app", "picked", "app", map[string]any{"$state": "/app/id"}}, + {"missing picker", "picked", "app", map[string]any{"$state": "/local/other"}}, + {"nested path", "picked", "app", map[string]any{"$state": "/local/selection/child"}}, + {"mixed expression", "picked", "app", map[string]any{"$state": "/local/selection", "fallback": "web"}}, + {"read-only picker", "picker", "value", map[string]any{"$state": "/local/selection"}}, + {"undeclared local", "picker", "value", map[string]any{"$bindState": "/local/missing"}}, + {"unsafe data path", "picker", "apps", map[string]any{"$state": "/data/toString"}}, + {"missing public data", "picker", "apps", map[string]any{"$state": "/data/missing"}}, + {"private options", "picker", "apps", map[string]any{"$state": "/local/selection"}}, + {"nonstring option", "picker", "apps", []any{"web", false}}, + {"duplicate option", "picker", "apps", []any{"web", "web"}}, + {"unsafe option", "picker", "apps", []any{"web", "api\nother"}}, + {"prototype option", "picker", "apps", []any{"web", "prototype"}}, + {"unoffered initial value", "picker", "apps", []any{"api"}}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newSpecUIFixture(t) + f.elements[tc.node].(map[string]any)["props"].(map[string]any)[tc.prop] = tc.value + if _, err := statusActionIDs(f.panel["spec"].(map[string]any), f.module["actions"].(map[string]any)); err == nil { + t.Fatal("malformed authority eligible for review") + } + }) + } + t.Run("two pickers write same local", func(t *testing.T) { + f := newSpecUIFixture(t) + f.elements["buttons"] = f.elements["picker"] + if _, err := statusActionIDs(f.panel["spec"].(map[string]any), f.module["actions"].(map[string]any)); err == nil { + t.Fatal("ambiguous binding eligible for review") + } + }) +} + +func TestExistingCustomGrantDeniedByPolicyOrSpec(t *testing.T) { + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + f := newSpecUIFixture(t) + _, custom, _ := uiTestState() + f.panel["type"], f.panel["uiBundle"] = "PANEL_TYPE_CUSTOM", custom["uiBundle"] + f.panel["uiBundle"].(map[string]any)["permissions"] = []any{"actions:run"} + grant, err := f.m.s.issueModuleUIGrant(f.root, f.state, "sample", "inspector", "", moduleStoreRoot, userconfig.LinkedModule{}) + if err != nil { + t.Fatal(err) + } + h := http.Header{} + h.Set(moduleUIGrantHeader, grant) + check := func() error { return f.m.s.checkActionGrant(h, f.rt, f.state, f.req, "") } + if err := check(); err != nil { + t.Fatal("custom grant unusable before policy change:", err) + } + t.Run("disable", func(t *testing.T) { + t.Setenv("STACKPANEL_DISABLE_CUSTOM_UI", "1") + if err := check(); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("old iframe grant accepted after opt-out: %v", err) + } + // Authenticated direct reads must stop before resolving a package too. + f.rt.evalModuleState = func(context.Context, string) ([]byte, error) { + t.Fatal("disabled direct asset request evaluated a bundle") + return nil, nil + } + r := httptest.NewRequestWithContext(context.WithValue(t.Context(), runtimeKey{}, f.rt), "GET", "http://localhost/index.html", nil) + r.SetPathValue("module", "sample") + r.SetPathValue("panel", "inspector") + r.SetPathValue("rest", "index.html") + w := httptest.NewRecorder() + f.m.s.handleModuleAsset(w, r) + if w.Code != http.StatusNotFound { + t.Fatalf("disabled authenticated asset route returned %d", w.Code) + } + }) + f.panel["type"], f.panel["uiBundle"] = "PANEL_TYPE_SPEC", nil + if err := check(); connect.CodeOf(err) != connect.CodePermissionDenied { + t.Fatalf("transferred iframe grant to spec: %v", err) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/modules.go b/apps/stackpanel-go/internal/agent/server/modules.go index 212f57d4..7e27f044 100644 --- a/apps/stackpanel-go/internal/agent/server/modules.go +++ b/apps/stackpanel-go/internal/agent/server/modules.go @@ -1,854 +1,167 @@ -// modules.go implements the module browser API: listing, inspecting, configuring, -// and enabling/disabling Stackpanel modules. -// -// Module definitions come from the evaluated Nix config (ui.modulesList or ui.modules). -// Per-module configuration is stored as YAML in .stack/data/modules/.yaml and -// takes effect on the next devshell re-entry. -// -// Module "outputs" (files, scripts, healthchecks, packages) are resolved from the -// Nix config, with some heuristic matching by naming convention for scripts that -// don't yet have explicit source tracking. package server import ( "context" "encoding/json" - "fmt" - "net/http" - "os" - "path/filepath" + "errors" "strings" - "time" - gopb "github.com/darkmatter/stackpanel/packages/proto/gen/gopb" - "github.com/rs/zerolog/log" - "gopkg.in/yaml.v3" -) - -// Module represents a Stackpanel module from Nix config -type Module struct { - ID string `json:"id"` - Enabled bool `json:"enabled"` - Meta ModuleMeta `json:"meta"` - Source ModuleSource `json:"source"` - Features ModuleFeatures `json:"features"` - Requires []string `json:"requires,omitempty"` - Conflicts []string `json:"conflicts,omitempty"` - Priority int `json:"priority"` - Tags []string `json:"tags,omitempty"` - ConfigSchema *string `json:"configSchema,omitempty"` - Panels []ModulePanel `json:"panels,omitempty"` - Apps map[string]any `json:"apps,omitempty"` - HealthModule *string `json:"healthcheckModule,omitempty"` - Health *ModuleHealth `json:"health,omitempty"` -} - -// ModuleMeta contains display metadata for a module -type ModuleMeta struct { - Name string `json:"name"` - Description *string `json:"description,omitempty"` - Icon *string `json:"icon,omitempty"` - Category string `json:"category"` - Author *string `json:"author,omitempty"` - Version *string `json:"version,omitempty"` - Homepage *string `json:"homepage,omitempty"` -} - -// ModuleSource describes where a module comes from -type ModuleSource struct { - Type string `json:"type"` // builtin, local, flake-input, registry - FlakeInput *string `json:"flakeInput,omitempty"` - Path *string `json:"path,omitempty"` - RegistryID *string `json:"registryId,omitempty"` - Ref *string `json:"ref,omitempty"` -} + "connectrpc.com/connect" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" -// ModuleFeatures describes which stackpanel features a module uses -type ModuleFeatures struct { - Files bool `json:"files"` - Scripts bool `json:"scripts"` - Tasks bool `json:"tasks"` - Healthchecks bool `json:"healthchecks"` - Services bool `json:"services"` - Secrets bool `json:"secrets"` - Packages bool `json:"packages"` - AppModule bool `json:"appModule"` -} - -// ModulePanel represents a UI panel provided by a module -type ModulePanel struct { - ID string `json:"id"` - Title string `json:"title"` - Description *string `json:"description,omitempty"` - Type string `json:"type"` - Order int `json:"order"` - Fields []PanelField `json:"fields,omitempty"` -} - -// PanelField represents a field in a module panel -type PanelField struct { - Name string `json:"name"` - Type string `json:"type"` - Value string `json:"value"` - Options []string `json:"options,omitempty"` -} - -// ModulesResponse is the response for the modules list endpoint -type ModulesResponse struct { - Modules []Module `json:"modules"` - Total int `json:"total"` - Enabled int `json:"enabled"` - LastUpdated string `json:"lastUpdated"` -} - -// ModuleConfig represents stored configuration for a module -type ModuleConfig struct { - Enable *bool `yaml:"enable,omitempty" json:"enable,omitempty"` - Settings map[string]any `yaml:"settings,omitempty" json:"settings,omitempty"` -} - -// handleModules routes module-related API requests -func (s *Server) handleModules(w http.ResponseWriter, r *http.Request) { - // Extract module name from path if present - // /api/modules -> list all - // /api/modules/postgres -> single module - // /api/modules/postgres/config -> module config - // /api/modules/postgres/enable -> enable/disable module - - path := strings.TrimPrefix(r.URL.Path, "/api/modules") - path = strings.TrimPrefix(path, "/") - - parts := strings.Split(path, "/") - - switch { - case path == "" || path == "/": - // List all modules - s.handleModulesList(w, r) - case len(parts) == 1: - // Single module: /api/modules/{name} - s.handleModuleGet(w, r, parts[0]) - case len(parts) == 2 && parts[1] == "config": - // Module config: /api/modules/{name}/config - s.handleModuleConfig(w, r, parts[0]) - case len(parts) == 2 && parts[1] == "enable": - // Enable/disable: /api/modules/{name}/enable - s.handleModuleEnable(w, r, parts[0]) - default: - s.writeAPIError(w, http.StatusNotFound, "endpoint not found") - } -} - -// handleModulesList returns all modules -func (s *Server) handleModulesList(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - s.writeAPIError(w, http.StatusMethodNotAllowed, "method not allowed") - return - } - - includeHealth := r.URL.Query().Get("includeHealth") == "true" - includeDisabled := r.URL.Query().Get("includeDisabled") == "true" - category := r.URL.Query().Get("category") + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" +) - modules, err := s.getModules(includeDisabled) - if err != nil { - s.writeAPIError( - w, - http.StatusInternalServerError, - "failed to get modules: "+err.Error(), +// loadModuleState is shared by metadata, actions, UI and registry services. +// Never fall back to the daemon's shell/profile or a previously selected project. +func loadModuleState(ctx context.Context, rt *projectRuntime) (map[string]any, error) { + if rt == nil || rt.root == "" { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("no project selected"), ) - return } - - // Filter by category if specified - if category != "" { - var filtered []Module - for _, m := range modules { - if m.Meta.Category == category { - filtered = append(filtered, m) - } - } - modules = filtered - } - - // Optionally include health status - if includeHealth { - modules = s.hydrateModulesWithHealth(r.Context(), modules) - } - - enabledCount := 0 - for _, m := range modules { - if m.Enabled { - enabledCount++ - } + eval := rt.evalModuleState + if eval == nil { + eval = nixeval.EvalModuleState } - - s.writeAPI(w, http.StatusOK, ModulesResponse{ - Modules: modules, - Total: len(modules), - Enabled: enabledCount, - LastUpdated: time.Now().Format(time.RFC3339), - }) -} - -// handleModuleGet returns a single module by name -func (s *Server) handleModuleGet(w http.ResponseWriter, r *http.Request, name string) { - if r.Method != http.MethodGet { - s.writeAPIError(w, http.StatusMethodNotAllowed, "method not allowed") - return - } - - includeHealth := r.URL.Query().Get("includeHealth") == "true" - - modules, err := s.getModules(true) // Include disabled to find the module + data, err := eval(ctx, rt.root) if err != nil { - s.writeAPIError( - w, - http.StatusInternalServerError, - "failed to get modules: "+err.Error(), - ) - return - } - - var module *Module - for i := range modules { - if modules[i].ID == name { - module = &modules[i] - break - } - } - - if module == nil { - s.writeAPIError(w, http.StatusNotFound, "module not found: "+name) - return + return nil, moduleEvalError(ctx, err) } - - // Optionally include health status - if includeHealth && module.HealthModule != nil { - health := s.getModuleHealth(r.Context(), *module.HealthModule) - module.Health = health - } - - // Include stored config - config, _ := s.loadModuleConfig(name) - - response := map[string]any{ - "module": module, - "config": config, - } - - s.writeAPI(w, http.StatusOK, response) -} - -// handleModuleConfig handles reading and writing module configuration -func (s *Server) handleModuleConfig( - w http.ResponseWriter, - r *http.Request, - name string, -) { - switch r.Method { - case http.MethodGet: - config, err := s.loadModuleConfig(name) - if err != nil { - if os.IsNotExist(err) { - // Return empty config if file doesn't exist - s.writeAPI(w, http.StatusOK, ModuleConfig{}) - return - } - s.writeAPIError( - w, - http.StatusInternalServerError, - "failed to load config: "+err.Error(), - ) - return - } - s.writeAPI(w, http.StatusOK, config) - - case http.MethodPost, http.MethodPut: - var config ModuleConfig - if err := json.NewDecoder(r.Body).Decode(&config); err != nil { - s.writeAPIError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) - return - } - - if err := s.saveModuleConfig(name, config); err != nil { - s.writeAPIError( - w, - http.StatusInternalServerError, - "failed to save config: "+err.Error(), - ) - return - } - - // Broadcast config change - s.broadcastSSE(SSEEvent{ - Event: "module.config.updated", - Data: map[string]any{ - "module": name, - "config": config, - }, - }) - - s.writeAPI(w, http.StatusOK, map[string]any{ - "success": true, - "message": "Configuration saved. Re-enter devshell to apply changes.", - }) - - default: - s.writeAPIError(w, http.StatusMethodNotAllowed, "method not allowed") + var state map[string]any + if err := json.Unmarshal(data, &state); err != nil || state == nil { + return nil, invalidModuleState("invalid stackpanelSerializable result") } + return state, nil } -// handleModuleEnable handles enabling/disabling a module -func (s *Server) handleModuleEnable( - w http.ResponseWriter, - r *http.Request, - name string, -) { - if r.Method != http.MethodPost { - s.writeAPIError(w, http.StatusMethodNotAllowed, "method not allowed") - return +func moduleEvalError(ctx context.Context, err error) error { + if errors.Is(err, context.DeadlineExceeded) || + errors.Is(ctx.Err(), context.DeadlineExceeded) { + return connect.NewError(connect.CodeDeadlineExceeded, context.DeadlineExceeded) } - - var request struct { - Enable bool `json:"enable"` + if errors.Is(err, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) { + return connect.NewError(connect.CodeCanceled, context.Canceled) } - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - s.writeAPIError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) - return - } - - // Load existing config - config, err := s.loadModuleConfig(name) - if err != nil && !os.IsNotExist(err) { - s.writeAPIError( - w, - http.StatusInternalServerError, - "failed to load config: "+err.Error(), - ) - return - } - - // Update enable state - config.Enable = &request.Enable - - if err := s.saveModuleConfig(name, config); err != nil { - s.writeAPIError( - w, - http.StatusInternalServerError, - "failed to save config: "+err.Error(), - ) - return - } - - // Broadcast enable change - s.broadcastSSE(SSEEvent{ - Event: "module.enabled.changed", - Data: map[string]any{ - "module": name, - "enabled": request.Enable, - }, - }) - - action := "enabled" - if !request.Enable { - action = "disabled" - } - - s.writeAPI(w, http.StatusOK, map[string]any{ - "success": true, - "message": fmt.Sprintf("Module %s. Re-enter devshell to apply changes.", action), - }) + // Nix stderr can include snippets of private project configuration. + return invalidModuleState( + "module evaluation failed; check the project's flake configuration", + ) } -// getModules retrieves module list from Nix config -func (s *Server) getModules(includeDisabled bool) ([]Module, error) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - - var config map[string]any - var err error - - // Try FlakeWatcher first - if s.flakeWatcher != nil { - config, err = s.flakeWatcher.GetConfig(ctx) - } - - // Fallback to direct evaluation - if config == nil || err != nil { - config, err = s.evaluateConfig() - if err != nil { - return nil, err - } - } +func invalidModuleState(message string) error { + return connect.NewError(connect.CodeFailedPrecondition, errors.New(message)) +} - // Try to get modules from ui.modules or ui.modulesList - ui, ok := config["ui"].(map[string]any) +func evaluatedModules(state map[string]any) ([]any, error) { + list, ok := state["modulesListAll"].([]any) if !ok { - log.Debug().Msg("No ui section in config") - return []Module{}, nil + return nil, invalidModuleState("project does not expose modulesListAll") } - - // Try modulesList first (flat list) - var modules []Module - if modulesList, ok := ui["modulesList"]; ok { - data, err := json.Marshal(modulesList) - if err != nil { - return nil, fmt.Errorf("failed to marshal modulesList: %w", err) - } - if err := json.Unmarshal(data, &modules); err != nil { - return nil, fmt.Errorf("failed to unmarshal modulesList: %w", err) - } - } else if modulesMap, ok := ui["modules"].(map[string]any); ok { - // Fall back to modules map - for name, modData := range modulesMap { - data, err := json.Marshal(modData) - if err != nil { - log.Warn().Str("module", name).Err(err).Msg("Failed to marshal module") - continue - } - var module Module - if err := json.Unmarshal(data, &module); err != nil { - log.Warn().Str("module", name).Err(err).Msg("Failed to unmarshal module") - continue - } - module.ID = name - modules = append(modules, module) - } - } - - // Filter disabled if requested - if !includeDisabled { - var enabled []Module - for _, m := range modules { - if m.Enabled { - enabled = append(enabled, m) - } - } - modules = enabled - } - - return modules, nil + return list, nil } -// hydrateModulesWithHealth adds health information to modules -func (s *Server) hydrateModulesWithHealth( - ctx context.Context, - modules []Module, -) []Module { - for i := range modules { - if modules[i].HealthModule != nil { - modules[i].Health = s.getModuleHealth(ctx, *modules[i].HealthModule) - } +func findModule(state map[string]any, id string) (map[string]any, error) { + if strings.TrimSpace(id) == "" { + return nil, connect.NewError( + connect.CodeInvalidArgument, + errors.New("module_id is required"), + ) } - return modules -} - -// getModuleHealth gets health status for a specific health module -func (s *Server) getModuleHealth( - ctx context.Context, - healthModule string, -) *ModuleHealth { - healthchecks, err := s.getHealthcheckDefinitions() + list, err := evaluatedModules(state) if err != nil { - log.Warn().Err(err).Msg("Failed to get healthcheck definitions") - return nil + return nil, err } - - // Filter to checks for this module - var moduleChecks []Healthcheck - for _, check := range healthchecks { - if check.Module == healthModule && check.Enabled { - moduleChecks = append(moduleChecks, check) - } - } - - if len(moduleChecks) == 0 { - return nil - } - - // Run checks (use cached results) - var results []HealthcheckResult - for _, check := range moduleChecks { - result := s.getCachedResult(check.ID) - if result == nil { - result = s.runHealthcheck(ctx, check) - s.cacheResult(result) + for _, item := range list { + m, ok := item.(map[string]any) + if !ok { + return nil, invalidModuleState("invalid modulesListAll entry") } - result.Check = &check - results = append(results, *result) - } - - // Build module health - health := &ModuleHealth{ - Module: healthModule, - DisplayName: healthModule, // Will be overridden if we have better info - Checks: results, - TotalCount: len(results), - LastUpdated: time.Now().Format(time.RFC3339), - } - - // Count healthy and determine overall status - health.Status = HealthStatusHealthy - for _, r := range results { - if r.Status == HealthStatusHealthy { - health.HealthyCount++ - } else if r.Status == HealthStatusUnhealthy { - health.Status = HealthStatusUnhealthy - } else if r.Status == HealthStatusDegraded && health.Status != HealthStatusUnhealthy { - health.Status = HealthStatusDegraded + if m["id"] == id { + return m, nil } } - - return health -} - -// loadModuleConfig loads configuration for a module from disk -func (s *Server) loadModuleConfig(name string) (ModuleConfig, error) { - configPath := s.moduleConfigPath(name) - - data, err := os.ReadFile(configPath) - if err != nil { - return ModuleConfig{}, err - } - - var config ModuleConfig - if err := yaml.Unmarshal(data, &config); err != nil { - return ModuleConfig{}, fmt.Errorf("failed to parse YAML: %w", err) - } - - return config, nil -} - -// saveModuleConfig saves configuration for a module to disk -func (s *Server) saveModuleConfig(name string, config ModuleConfig) error { - configPath := s.moduleConfigPath(name) - - // Ensure directory exists - dir := filepath.Dir(configPath) - if err := os.MkdirAll(dir, 0o755); err != nil { - return fmt.Errorf("failed to create config directory: %w", err) - } - - data, err := yaml.Marshal(config) - if err != nil { - return fmt.Errorf("failed to marshal YAML: %w", err) - } - - // Add header comment - content := fmt.Sprintf( - "# Stackpanel module configuration for %s\n# This file is managed by the Stackpanel UI\n# Re-enter devshell to apply changes\n\n%s", - name, - string(data), + return nil, connect.NewError( + connect.CodeNotFound, + errors.New("module not found in project"), ) - - if err := os.WriteFile(configPath, []byte(content), 0o644); err != nil { - return fmt.Errorf("failed to write config: %w", err) - } - - return nil -} - -// moduleConfigPath returns the path to a module's config file -func (s *Server) moduleConfigPath(name string) string { - // Config stored in .stack/data/modules/{name}.yaml - return filepath.Join(s.config.ProjectRoot, ".stack", "data", "modules", name+".yaml") } -// getPendingModuleEnables returns a set of module IDs that have been enabled via UI -// but may not yet be reflected in the Nix config (requires devshell re-entry). -func (s *Server) getPendingModuleEnables() map[string]bool { - pendingEnables := make(map[string]bool) - - // Scan the modules data directory for config files - modulesDir := filepath.Join(s.config.ProjectRoot, ".stack", "data", "modules") - entries, err := os.ReadDir(modulesDir) - if err != nil { - // Directory doesn't exist or can't be read - no pending enables - return pendingEnables - } - - for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".yaml") { - continue - } - - // Extract module name from filename - moduleName := strings.TrimSuffix(entry.Name(), ".yaml") - - // Load and check if enabled - config, err := s.loadModuleConfig(moduleName) - if err != nil { - continue - } - - // Only add if explicitly enabled - if config.Enable != nil && *config.Enable { - pendingEnables[moduleName] = true - } - } - - return pendingEnables -} - -// ============================================================================= -// Module Outputs - What a module creates -// ============================================================================= - -// getModuleFiles returns files generated by a specific module -func (s *Server) getModuleFiles(moduleID string) ([]*gopb.ModuleOutputFile, error) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - var config map[string]any - var err error - - if s.flakeWatcher != nil { - config, err = s.flakeWatcher.GetConfig(ctx) +func moduleOptionPath(module map[string]any, field string) ([]string, error) { + id, _ := module["id"].(string) + declared, ok := module[field].(string) + if !ok || declared == "" || strings.HasPrefix(declared, "stackpanel.") { + return nil, invalidModuleState("invalid module option path") } - if config == nil || err != nil { - config, err = s.evaluateConfig() - if err != nil { - return nil, err + parts := strings.Split(declared, ".") + for _, p := range parts { + if nixdata.ValidateEntityName(p) != nil || p == "imports" || + strings.HasPrefix(p, "_") { + return nil, invalidModuleState("invalid declared module option path") } } - - // Get files from config - filesConfig, ok := config["files"].(map[string]any) - if !ok { - return nil, nil - } - - entries, ok := filesConfig["entries"].(map[string]any) - if !ok { - return nil, nil - } - - var files []*gopb.ModuleOutputFile - for path, entry := range entries { - entryMap, ok := entry.(map[string]any) - if !ok { - continue - } - - // Check if this file belongs to the module - source, _ := entryMap["source"].(string) - if source != moduleID { - continue - } - - file := &gopb.ModuleOutputFile{ - Path: path, - Type: "text", // default - } - - if desc, ok := entryMap["description"].(string); ok { - file.Description = &desc + switch parts[0] { + case "variables", "secrets", "users", "apps", "registries": + // The owner can toggle its declared boolean enable switch. Neither its + // settings RPC nor another module can select data within this namespace. + if field == "enablePath" && len(parts) == 2 && parts[0] == id && + parts[1] == "enable" { + break } - if t, ok := entryMap["type"].(string); ok { - file.Type = t + return nil, invalidModuleState("module option path targets a protected namespace") + case "modules": + if len(parts) < 3 || parts[1] != id { + return nil, invalidModuleState("module option path is outside this module") } - - files = append(files, file) } - - return files, nil + return parts, nil } -// getModuleHealthchecks returns healthchecks defined by a specific module -func (s *Server) getModuleHealthchecks( - moduleID string, -) ([]*gopb.ModuleOutputHealthcheck, error) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - var config map[string]any - var err error - - if s.flakeWatcher != nil { - config, err = s.flakeWatcher.GetConfig(ctx) +// decodeModuleProjection only exposes fields in the public protobuf schema. +// Unknown Nix metadata (including executable paths) stays on the agent. +func decodeModuleProjection(data any, target proto.Message) error { + b, err := json.Marshal(data) + if err == nil { + err = (protojson.UnmarshalOptions{DiscardUnknown: true}).Unmarshal(b, target) } - if config == nil || err != nil { - config, err = s.evaluateConfig() - if err != nil { - return nil, err - } - } - - // Get healthchecks from config - try healthchecksList first - var checks []*gopb.ModuleOutputHealthcheck - - if hcList, ok := config["healthchecksList"].([]any); ok { - for _, hc := range hcList { - hcMap, ok := hc.(map[string]any) - if !ok { - continue - } - - // Check if this healthcheck belongs to the module - module, _ := hcMap["module"].(string) - if module != moduleID { - continue - } - - check := &gopb.ModuleOutputHealthcheck{ - Id: getString(hcMap, "id"), - Name: getString(hcMap, "name"), - Severity: getString(hcMap, "severity"), - Type: getString(hcMap, "type"), - } - if desc := getString(hcMap, "description"); desc != "" { - check.Description = &desc - } - - checks = append(checks, check) - } - } else if hcModules, ok := config["healthchecks"].(map[string]any); ok { - // Fallback to healthchecks.modules structure - if modules, ok := hcModules["modules"].(map[string]any); ok { - if moduleChecks, ok := modules[moduleID].(map[string]any); ok { - if checksMap, ok := moduleChecks["checks"].(map[string]any); ok { - for checkName, checkData := range checksMap { - checkMap, ok := checkData.(map[string]any) - if !ok { - continue - } - - check := &gopb.ModuleOutputHealthcheck{ - Id: fmt.Sprintf("%s-%s", moduleID, checkName), - Name: getString(checkMap, "name"), - Severity: getString(checkMap, "severity"), - Type: getString(checkMap, "type"), - } - if check.Name == "" { - check.Name = checkName - } - if desc := getString(checkMap, "description"); desc != "" { - check.Description = &desc - } - - checks = append(checks, check) - } - } - } - } + if err != nil { + return invalidModuleState("invalid evaluated module metadata") } - - return checks, nil + return nil } -// getModuleScripts returns scripts provided by a module. Scripts with an explicit -// "module" field are matched directly. For modules without explicit tracking, -// a naming-convention heuristic is used (e.g., oxlint → "lint*", postgres → "db-*"). -func (s *Server) getModuleScripts(moduleID string) ([]*gopb.ModuleOutputScript, error) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - var config map[string]any - var err error - - if s.flakeWatcher != nil { - config, err = s.flakeWatcher.GetConfig(ctx) +func moduleOutputData( + ctx context.Context, + rt *projectRuntime, + id string, +) (map[string]any, error) { + state, err := loadModuleState(ctx, rt) + if err != nil { + return nil, err } - if config == nil || err != nil { - config, err = s.evaluateConfig() - if err != nil { - return nil, err - } + if _, err := findModule(state, id); err != nil { + return nil, err } - - // Get scripts from config - // Currently scripts don't have source tracking, so we use naming conventions - // e.g., scripts starting with "lint-" might belong to oxlint module - scriptsConfig, ok := config["scripts"].(map[string]any) + outputs, _ := state["moduleOutputs"].(map[string]any) + out, ok := outputs[id].(map[string]any) if !ok { - return nil, nil + return nil, invalidModuleState( + "project does not expose this module's attributed outputs", + ) } - - var scripts []*gopb.ModuleOutputScript - - // Check for scripts with module prefix pattern - // e.g., oxlint module might have: lint, lint-fix, lint-{app} - for name, scriptData := range scriptsConfig { - scriptMap, ok := scriptData.(map[string]any) + out["moduleId"] = id + // Only expose whether a proxy is offered, not its internal port or URL. + services, _ := out["services"].([]any) + for _, item := range services { + svc, ok := item.(map[string]any) if !ok { - continue + return nil, invalidModuleState("invalid attributed service") } - - // Check if script has explicit module field (future-proofing) - if source, ok := scriptMap["module"].(string); ok && source == moduleID { - script := &gopb.ModuleOutputScript{ - Name: name, - } - if desc := getString(scriptMap, "description"); desc != "" { - script.Description = &desc - } - scripts = append(scripts, script) - continue - } - - // Fallback: use naming convention for common modules - // This is a heuristic - modules like oxlint create lint-* scripts - matched := false - switch moduleID { - case "oxlint": - matched = strings.HasPrefix(name, "lint") - case "postgres": - matched = strings.HasPrefix(name, "db-") || strings.HasPrefix(name, "pg-") - case "turbo": - matched = name == "turbo" || strings.HasPrefix(name, "turbo-") - } - - if matched { - script := &gopb.ModuleOutputScript{ - Name: name, - } - if desc := getString(scriptMap, "description"); desc != "" { - script.Description = &desc - } - scripts = append(scripts, script) - } - } - - return scripts, nil -} - -// getModulePackages returns packages added by a module -func (s *Server) getModulePackages( - moduleID string, -) ([]*gopb.ModuleOutputPackage, error) { - // Currently packages don't have source tracking - // We can only infer from known modules - // This is a placeholder for future implementation - - // Known package mappings for common modules - knownPackages := map[string][]string{ - "oxlint": {"oxlint"}, - "postgres": {"postgresql"}, - "redis": {"redis"}, - "go": {"go"}, - "bun": {"bun"}, - "turbo": {"turbo"}, - } - - pkgNames, ok := knownPackages[moduleID] - if !ok { - return nil, nil - } - - var packages []*gopb.ModuleOutputPackage - for _, name := range pkgNames { - packages = append(packages, &gopb.ModuleOutputPackage{ - Name: name, - }) - } - - return packages, nil -} - -// getString safely extracts a string from a map -func getString(m map[string]any, key string) string { - if v, ok := m[key].(string); ok { - return v + proxy, _ := svc["proxy"].(map[string]any) + svc["proxyEnabled"], _ = proxy["enable"].(bool) } - return "" + return out, nil } diff --git a/apps/stackpanel-go/internal/agent/server/nix_config.go b/apps/stackpanel-go/internal/agent/server/nix_config.go index 5aa1e419..5a1cee77 100644 --- a/apps/stackpanel-go/internal/agent/server/nix_config.go +++ b/apps/stackpanel-go/internal/agent/server/nix_config.go @@ -21,7 +21,7 @@ import ( "sync" "time" - sharedexec "github.com/darkmatter/stackpanel/stackpanel-go/pkg/exec" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" "github.com/rs/zerolog/log" ) @@ -219,40 +219,14 @@ func (s *Server) evaluateConfig() (map[string]any, error) { return nil, err } -// evaluateConfigFromFlake tries multiple flake attribute paths in priority order. -// stackpanelFullConfig is intentionally avoided — it contains non-serializable -// Nix values (functions, modules) that would break JSON serialization. +// Read the editor configuration, not the module capability projection. func (s *Server) evaluateConfigFromFlake() (map[string]any, error) { - // Try paths in priority order: - // 1. devshell passthru (for user projects consuming stackpanel) - // 2. stackpanelConfig flake output (for stackpanel repo itself) - // Note: Do NOT use stackpanelFullConfig - it contains non-serializable values (functions, modules) - attributePaths := []string{ - ".#legacyPackages." + getCurrentSystem() + ".stackpanelConfig", - // User projects: devshell passthru has the stackpanel config - ".#devShells." + getCurrentSystem() + ".default.passthru.stackSerializable", - ".#devShells." + getCurrentSystem() + ".default.passthru.stackConfig", - // Stackpanel repo: direct flake outputs - ".#stackpanelConfig", - } - - var res *sharedexec.Result - var err error - - for _, attrPath := range attributePaths { - args := []string{"eval", "--no-update-lock-file", "--no-write-lock-file", "--json", attrPath} - res, err = s.exec.RunNix(args...) - if err == nil && res.ExitCode == 0 { - break - } + res, err := s.exec.RunNix("eval", "--no-update-lock-file", "--no-write-lock-file", "--json", nixeval.ProjectAttr("stackpanelConfig")) + if err != nil { + return nil, err } - - if res == nil || res.ExitCode != 0 { - errMsg := "all attribute paths failed" - if res != nil && res.Stderr != "" { - errMsg = strings.TrimSpace(res.Stderr) - } - return nil, &evalError{stderr: errMsg} + if res.ExitCode != 0 { + return nil, &evalError{stderr: strings.TrimSpace(res.Stderr)} } var config map[string]any diff --git a/apps/stackpanel-go/internal/agent/server/nix_data.go b/apps/stackpanel-go/internal/agent/server/nix_data.go index 8ff2ffe7..c0d3598c 100644 --- a/apps/stackpanel-go/internal/agent/server/nix_data.go +++ b/apps/stackpanel-go/internal/agent/server/nix_data.go @@ -12,10 +12,12 @@ package server import ( "context" "encoding/json" + "fmt" "net/http" "os" "strings" + "connectrpc.com/connect" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixdata" "github.com/rs/zerolog/log" ) @@ -76,7 +78,7 @@ func (s *Server) handleNixDataRead(w http.ResponseWriter, r *http.Request) { return } - if err := nixdata.ValidateEntityName(entity); err != nil { + if err := validateDataEntity(entity); err != nil { s.writeAPIError(w, http.StatusBadRequest, err.Error()) return } @@ -229,7 +231,7 @@ func (s *Server) handleNixDataWrite(w http.ResponseWriter, r *http.Request) { return } - if err := nixdata.ValidateEntityName(req.Entity); err != nil { + if err := validateDataEntity(req.Entity); err != nil { log.Error(). Err(err). Str("entity", req.Entity). @@ -280,7 +282,7 @@ func (s *Server) handleNixDataDelete(w http.ResponseWriter, r *http.Request) { return } - if err := nixdata.ValidateEntityName(entity); err != nil { + if err := validateDataEntity(entity); err != nil { s.writeAPIError(w, http.StatusBadRequest, err.Error()) return } @@ -332,7 +334,7 @@ func (s *Server) handleNixDataList(w http.ResponseWriter, r *http.Request) { continue } name := strings.TrimSuffix(entry.Name(), ".nix") - if name == "config" { + if name == "config" || moduleDataEntity(name) { continue } if _, ok := seen[name]; ok { @@ -357,7 +359,7 @@ func (s *Server) handleNixDataList(w http.ResponseWriter, r *http.Request) { continue } name := strings.TrimSuffix(entry.Name(), ".nix") - if nixdata.PrefersConsolidatedConfig(name) { + if moduleDataEntity(name) || nixdata.PrefersConsolidatedConfig(name) { continue } if _, ok := seen[name]; ok { @@ -375,6 +377,9 @@ func (s *Server) handleNixDataList(w http.ResponseWriter, r *http.Request) { continue } name := "external-" + strings.TrimSuffix(entry.Name(), ".nix") + if moduleDataEntity(name) { + continue + } if _, ok := seen[name]; ok { continue } @@ -462,48 +467,70 @@ func (s *Server) handleKeyLevelWrite(w http.ResponseWriter, req nixDataRequest) // The real work is done by s.store (pkg/nixdata). // ============================================================================= -// readNixEntityJSON reads a Nix data entity and returns its JSON representation. -// Used by generated Connect handlers for Get* methods. -// -// For evaluated entities (like "variables") the merged flake output is tried -// first via the FlakeWatcher / evaluateConfig (server-specific), falling back -// to the raw data file through the store. +// readNixEntityJSON is the current-project reader used by secret resolution. func (s *Server) readNixEntityJSON(entity string) ([]byte, error) { - if err := nixdata.ValidateEntityName(entity); err != nil { + return NewAgentServiceServer( + s, + ).readProjectEntityJSON(context.Background(), nil, entity) +} + +func (s *AgentServiceServer) readProjectEntityJSON( + ctx context.Context, + header http.Header, + entity string, +) ([]byte, error) { + rt, err := s.server.requestRuntime(header) + if err != nil { return nil, err } - - // For evaluated entities, use the merged config from the flake first. - if nixdata.IsEvaluatedEntity(entity) { - if data, ok, err := s.readEvaluatedEntityData(entity); err == nil { + if entity != "apps" && !nixdata.IsEvaluatedEntity(entity) { + data, err := rt.store.ReadEntityJSON(entity) + if err != nil { + return nil, connect.NewError( + connect.CodeInternal, + fmt.Errorf("could not read project %s", entity), + ) + } + return data, nil + } + state, _, _, err := authenticatedProjectConfig(ctx, rt) + if err != nil { + return nil, err + } + value := state[entity] + if entity == "variables" { + // Full config also carries backend configuration in this namespace. + // Only Variable entries belong in the typed GetVariables map. + items, _ := value.(map[string]any) + vars := make(map[string]any, len(items)) + for key, item := range items { + entry, ok := item.(map[string]any) if !ok { - // Entity not present in evaluated config — return empty envelope. - if nixdata.IsMapEntity(entity) { - return nixdata.NixJSONToCamelCase( - mustMarshalJSON(map[string]any{entity: map[string]any{}}), - nixdata.MapFieldNames(), - ) - } - return nixdata.NixJSONToCamelCase( - mustMarshalJSON(map[string]any{}), - nixdata.MapFieldNames(), - ) + continue } - - wrapped := data - if nixdata.IsMapEntity(entity) { - wrapped = map[string]any{entity: data} + if _, hasValue := entry["value"]; hasValue || entry["id"] != nil { + vars[key] = entry } - return nixdata.NixJSONToCamelCase( - mustMarshalJSON(wrapped), - nixdata.MapFieldNames(), - ) } - // Evaluated read failed — fall through to file-based read. + value = vars } - - // Delegate the file-based read to the shared store. - return s.store.ReadEntityJSON(entity) + if value == nil { + value = map[string]any{} + } + if nixdata.IsMapEntity(entity) { + value = map[string]any{entity: value} + } + raw, err := json.Marshal(value) + if err == nil { + raw, err = nixdata.NixJSONToCamelCase(raw, nixdata.MapFieldNames()) + } + if err != nil { + return nil, connect.NewError( + connect.CodeInternal, + fmt.Errorf("could not encode project %s", entity), + ) + } + return raw, nil } // readConsolidatedData reads the entire .stack/config.nix as a map. @@ -516,70 +543,13 @@ func (s *Server) writeConsolidatedData(data map[string]any) error { return s.store.WriteConsolidatedData(data) } -// patchConsolidatedData patches a value at a nested path within config.nix. -func (s *Server) patchConsolidatedData(path string, value any) error { - return s.store.PatchConsolidatedData(path, value) -} - -// nixDataFilePath returns the path to the consolidated config.nix file. -// Used by connect_patch.go for logging. -func (s *Server) nixDataFilePath() string { - return s.store.Paths().ConfigFilePath() -} - -// readEvaluatedEntityData reads an entity from the evaluated config, using -// the FlakeWatcher when available and falling back to direct evaluation. -// This is server-specific because it depends on the FlakeWatcher and -// evaluateConfig, which are not part of the shared nixdata package. -func (s *Server) readEvaluatedEntityData(entity string) (any, bool, error) { - ctx := context.Background() - - if s.flakeWatcher != nil { - config, err := s.flakeWatcher.GetConfig(ctx) - if err == nil { - data, ok := config[entity] - return data, ok, nil - } - } - - config, err := s.evaluateConfig() - if err != nil { - return nil, false, err +func validateDataEntity(name string) error { + if moduleDataEntity(name) { + return fmt.Errorf("modules are managed by ModuleService, not a data entity") } - - data, ok := config[entity] - return data, ok, nil -} - -// ============================================================================= -// Compatibility Aliases -// -// Package-level functions that forward to pkg/nixdata. These exist so that -// other files in the server package (connect_patch.go, etc.) continue to -// compile without modification. New code should use nixdata.* directly. -// ============================================================================= - -func validateEntityName( - name string, -) error { return nixdata.ValidateEntityName(name) } -func isExternalEntity(name string) bool { return nixdata.IsExternalEntity(name) } -func parseConfigPath( - configPath string, -) string { - return nixdata.ParseConfigPath(configPath) -} - -// ============================================================================= -// Local Helpers -// ============================================================================= - -func mustMarshalJSON(value any) []byte { - data, err := json.Marshal(value) - if err != nil { - return []byte("{}") - } - return data +func moduleDataEntity(name string) bool { + return name == "modules" || name == "external-modules" } diff --git a/apps/stackpanel-go/internal/agent/server/pair.go b/apps/stackpanel-go/internal/agent/server/pair.go index f0c72846..78f87c8c 100644 --- a/apps/stackpanel-go/internal/agent/server/pair.go +++ b/apps/stackpanel-go/internal/agent/server/pair.go @@ -2,33 +2,60 @@ package server import ( "bytes" - "encoding/json" - "html/template" "net/http" + "net/netip" "net/url" "strings" + "time" "github.com/rs/zerolog/log" ) -// Pairing flow: the web UI opens /pair?origin= in a popup window. -// The page shows the project info and a "Pair" button. On click, it posts a -// JWT token back to the opener via window.postMessage, scoped to the origin. -// The UI stores this token in localStorage for subsequent API calls. +// Studio submits a top-level form into its pairing popup. A POST navigation +// carries the browser's Origin even when a cross-origin Referer is omitted. +// Never take the recipient of a bearer credential from a URL parameter. // pairTemplateData is injected into the pair.html popup template. type pairTemplateData struct { ProjectRoot string - TargetOrigin template.JS // JS-safe quoted origin for postMessage targetOrigin - ReturnURL template.JS // JS-safe quoted URL for no-opener redirect fallback - Token template.JS // JS-safe quoted JWT for postMessage payload + TargetOrigin string + ReturnURL string + State string + ReturnCode string + Token string +} + +func validPairNonce(value string) bool { + if len(value) != 64 { + return false + } + for _, c := range value { + if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { + return false + } + } + return true } // handlePair serves the pairing popup page. It validates the requesting origin, // generates a fresh JWT, and renders an HTML page that posts the token back. func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { - origin := s.getPairOrigin(r) - if origin == "" || !s.isOriginAllowed(origin) { + // Pairing is a standalone navigation, never an embeddable document or + // a resource the sandbox may fetch. Apply both browser enforcement and + // Fetch Metadata checks before minting any credential. + w.Header().Set("Content-Security-Policy", "frame-ancestors 'none'") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Referrer-Policy", "no-referrer") + dest, mode := r.Header.Get("Sec-Fetch-Dest"), r.Header.Get("Sec-Fetch-Mode") + if r.Method != http.MethodPost || (dest != "" && dest != "document") || + (mode != "" && mode != "navigate") || r.Header.Get("Sec-Fetch-Site") == "same-origin" { + http.Error(w, "pairing requires a standalone navigation", http.StatusForbidden) + return + } + origin := r.Header.Get("Origin") + if !s.validPairPeer(origin, r) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusForbidden) _, _ = w.Write( @@ -36,6 +63,22 @@ func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { ) return } + r.Body = http.MaxBytesReader(w, r.Body, 16<<10) + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid pairing form", http.StatusBadRequest) + return + } + state := r.PostForm.Get("state") + if !validPairNonce(state) { + http.Error(w, "missing pairing state", http.StatusBadRequest) + return + } + returnURL := pairReturnURL(r.PostForm.Get("return_to"), origin) + verifier := r.PostForm.Get("verifier") + if returnURL != "" && (!validPairNonce(verifier) || verifier == state) { + http.Error(w, "invalid return verifier", http.StatusBadRequest) + return + } // Generate a JWT token for this pairing request token, err := s.jwtManager.GenerateToken(origin) @@ -47,9 +90,19 @@ func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { data := pairTemplateData{ ProjectRoot: s.config.ProjectRoot, - TargetOrigin: jsString(origin), - ReturnURL: jsString(s.getPairReturnURL(r, origin)), - Token: jsString(token), + TargetOrigin: origin, + ReturnURL: returnURL, + State: state, + Token: token, + } + if data.ReturnURL != "" { + data.ReturnCode = s.pairReturns.issue(pairReturnGrant{ + origin: origin, endpoint: pairEndpoint(r), state: state, verifier: verifier, + }, time.Now()) + // Saturation disables redirect only; direct popup approval still works. + if data.ReturnCode == "" { + data.ReturnURL = "" + } } var buf bytes.Buffer @@ -64,60 +117,68 @@ func (s *Server) handlePair(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(buf.Bytes()) } -// getPairOrigin extracts the origin for the pairing request, checking the -// ?origin query param first (explicit), then falling back to the Referer header. -func (s *Server) getPairOrigin(r *http.Request) string { - if q := strings.TrimSpace(r.URL.Query().Get("origin")); q != "" { - origin, ok := normalizeOrigin(q) - if ok { - return origin - } - return "" +func (s *Server) validPairPeer(origin string, r *http.Request) bool { + peer, err := url.Parse(origin) + if err != nil || (peer.Scheme != "http" && peer.Scheme != "https") || peer.Hostname() == "" || + peer.User != nil || + origin != peer.Scheme+"://"+peer.Host { + return false } + agent := url.URL{Scheme: "http", Host: r.Host} + if r.TLS != nil { + agent.Scheme = "https" + } + if peer.Scheme == agent.Scheme && samePairHost(peer.Hostname(), agent.Hostname()) && + pairPort(peer) == pairPort(&agent) { + return false + } + return s.isOriginAllowed(origin) +} + +func samePairHost(a, b string) bool { + if strings.EqualFold(a, b) { + return true + } + // An IPv6 address may arrive in compressed or expanded form. + ip, err := netip.ParseAddr(a) + if err != nil { + return false + } + other, err := netip.ParseAddr(b) + return err == nil && ip == other +} - ref := strings.TrimSpace(r.Referer()) - if ref == "" { - return "" +func pairPort(u *url.URL) string { + if port := u.Port(); port != "" { + return strings.TrimLeft(port, "0") } - u, err := url.Parse(ref) - if err != nil || u.Scheme == "" || u.Host == "" { - return "" + if u.Scheme == "https" { + return "443" } - return u.Scheme + "://" + u.Host + return "80" } // normalizeOrigin strips path/query from a URL and returns just scheme://host. func normalizeOrigin(raw string) (string, bool) { u, err := url.Parse(raw) - if err != nil || u.Scheme == "" || u.Host == "" { + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Hostname() == "" || + u.User != nil { return "", false } return u.Scheme + "://" + u.Host, true } -func jsString(value string) template.JS { - encoded, err := json.Marshal(value) - if err != nil { - return template.JS("null") - } - return template.JS(encoded) -} - -func (s *Server) getPairReturnURL(r *http.Request, origin string) string { - raw := strings.TrimSpace(r.URL.Query().Get("return_to")) +func pairReturnURL(raw, origin string) string { if raw == "" { - return origin + return "" // popup-only pairing; no URL-selected remote agent fallback } - u, err := url.Parse(raw) - if err != nil || u.Scheme == "" || u.Host == "" { - return origin - } - - returnOrigin := u.Scheme + "://" + u.Host - if returnOrigin != origin { - return origin + if err != nil || u.User != nil || u.Scheme+"://"+u.Host != origin || + (u.Path != "/studio" && !strings.HasPrefix(u.Path, "/studio/")) { + return origin + "/studio" } - - return raw + // Only Studio routing metadata is needed for the fallback. Never nest the + // caller's fragment or a legacy ?token= in a network-visible return URL. + u.RawQuery, u.Fragment, u.RawFragment = studioHandoff(u.Query()).Encode(), "", "" + return u.String() } diff --git a/apps/stackpanel-go/internal/agent/server/pair_return.go b/apps/stackpanel-go/internal/agent/server/pair_return.go new file mode 100644 index 00000000..873f4289 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/pair_return.go @@ -0,0 +1,127 @@ +package server + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/hex" + "net/http" + "sync" + "time" +) + +const ( + pairReturnLimit = 128 + pairReturnTTL = 5 * time.Minute +) + +// No JWT is stored or returned in a URL. Possession of a code and state is +// insufficient: redemption needs the private verifier from the initiating tab. +type pairReturnGrant struct { + origin, endpoint, state, verifier string + expires time.Time +} + +type pairReturnStore struct { + mu sync.Mutex + grants map[string]pairReturnGrant +} + +func (s *pairReturnStore) issue(grant pairReturnGrant, now time.Time) string { + s.mu.Lock() + defer s.mu.Unlock() + for code, existing := range s.grants { + if !now.Before(existing.expires) { + delete(s.grants, code) + } + } + if len(s.grants) >= pairReturnLimit { + return "" + } + var random [32]byte + if _, err := rand.Read(random[:]); err != nil { + return "" + } + if s.grants == nil { + s.grants = make(map[string]pairReturnGrant) + } + code := hex.EncodeToString(random[:]) + grant.expires = now.Add(pairReturnTTL) + s.grants[code] = grant + return code +} + +func (s *pairReturnStore) consume( + code string, + want pairReturnGrant, + now time.Time, +) bool { + s.mu.Lock() + defer s.mu.Unlock() + grant, ok := s.grants[code] + if !ok { + return false + } + if !now.Before(grant.expires) { + delete(s.grants, code) + return false + } + if grant.origin != want.origin || grant.endpoint != want.endpoint || + grant.state != want.state || + subtle.ConstantTimeCompare([]byte(grant.verifier), []byte(want.verifier)) != 1 { + return false + } + delete(s.grants, code) + return true +} + +func pairEndpoint(r *http.Request) string { + if r.TLS != nil { + return "https://" + r.Host + } + return "http://" + r.Host +} + +func (s *Server) handlePairRedeem(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + origin := r.Header.Get("Origin") + if !s.validPairPeer(origin, r) { + http.Error(w, "invalid pairing peer", http.StatusForbidden) + return + } + var body struct { + Code string `json:"code"` + State string `json:"state"` + Verifier string `json:"verifier"` + } + if r.URL.RawQuery != "" || r.Header.Get("Content-Type") != "application/json" || + s.readJSON(http.MaxBytesReader(w, r.Body, 1024), &body) != nil { + http.Error( + w, + "expected a pairing exchange in the request body", + http.StatusBadRequest, + ) + return + } + grant := pairReturnGrant{ + origin: origin, + endpoint: pairEndpoint(r), + state: body.State, + verifier: body.Verifier, + } + if !s.pairReturns.consume(body.Code, grant, time.Now()) { + http.Error(w, "invalid or expired pairing exchange", http.StatusForbidden) + return + } + token, err := s.jwtManager.GenerateToken(origin) + if err != nil { + http.Error(w, "could not finish pairing", http.StatusInternalServerError) + return + } + s.writeJSON(w, http.StatusOK, map[string]string{"token": token}) +} diff --git a/apps/stackpanel-go/internal/agent/server/pair_return_test.go b/apps/stackpanel-go/internal/agent/server/pair_return_test.go new file mode 100644 index 00000000..f7d0c65f --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/pair_return_test.go @@ -0,0 +1,130 @@ +package server + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/config" +) + +func TestPairRedeemRequiresExactProof(t *testing.T) { + jwt, err := NewJWTManager() + if err != nil { + t.Fatal(err) + } + s := &Server{config: &config.Config{}, jwtManager: jwt} + const agent = "http://localhost:9876" + grant := pairReturnGrant{ + origin: "http://localhost:3000", + endpoint: agent, + state: "test-state", + verifier: "private-tab-proof", + } + code := s.pairReturns.issue(grant, time.Now()) + if code == "" { + t.Fatal("expected code") + } + redeem := func(method, endpoint, origin, state, verifier, query string, want int) { + t.Helper() + body, err := json.Marshal( + map[string]string{"code": code, "state": state, "verifier": verifier}, + ) + if err != nil { + t.Fatal(err) + } + r := httptest.NewRequest( + method, + endpoint+"/pair/redeem"+query, + bytes.NewReader(body), + ) + r.Header.Set("Origin", origin) + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + s.handlePairRedeem(w, r) + if w.Code != want || w.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("unexpected redemption status %d (want %d)", w.Code, want) + } + if want == http.StatusOK { + var result struct { + Token string `json:"token"` + } + if err := json.Unmarshal( + w.Body.Bytes(), + &result, + ); err != nil || + !jwt.IsValidToken(result.Token) { + t.Fatal("expected valid agent credential only in response body") + } + } + } + redeem("GET", agent, grant.origin, grant.state, grant.verifier, "", 405) + redeem("POST", agent, "", grant.state, grant.verifier, "", 403) + redeem("POST", agent, "http://127.0.0.1:3000", grant.state, grant.verifier, "", 403) + redeem( + "POST", + "http://127.0.0.1:9876", + grant.origin, + grant.state, + grant.verifier, + "", + 403, + ) + redeem("POST", agent, grant.origin, "wrong-state", grant.verifier, "", 403) + redeem("POST", agent, grant.origin, grant.state, "", "", 403) + redeem("POST", agent, grant.origin, grant.state, grant.verifier, "?code="+code, 400) + redeem("POST", agent, grant.origin, grant.state, grant.verifier, "", 200) + redeem("POST", agent, grant.origin, grant.state, grant.verifier, "", 403) +} + +func TestPairReturnBoundedExpiryAndConcurrentReplay(t *testing.T) { + var store pairReturnStore + now := time.Now() + grant := pairReturnGrant{ + origin: "studio", + endpoint: "agent", + state: "state", + verifier: "verifier", + } + var first string + for i := range pairReturnLimit { + code := store.issue(grant, now) + if code == "" { + t.Fatal("did not issue return code") + } + if i == 0 { + first = code + } + } + if store.issue(grant, now) != "" { + t.Fatal("store exceeded limit") + } + now = now.Add(pairReturnTTL) + if store.consume(first, grant, now) { + t.Fatal("expired code accepted") + } + code := store.issue(grant, now) + if code == "" || len(store.grants) != 1 { + t.Fatal("expired entries not reclaimed") + } + var count atomic.Int32 + var wg sync.WaitGroup + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + if store.consume(code, grant, now) { + count.Add(1) + } + }() + } + wg.Wait() + if count.Load() != 1 { + t.Fatalf("code consumed %d times", count.Load()) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/project_handlers.go b/apps/stackpanel-go/internal/agent/server/project_handlers.go index 9e1871e7..fbee0c6c 100644 --- a/apps/stackpanel-go/internal/agent/server/project_handlers.go +++ b/apps/stackpanel-go/internal/agent/server/project_handlers.go @@ -1,6 +1,6 @@ // project_handlers.go contains REST API handlers for project lifecycle management: // listing, opening, closing, validating, and setting default projects. -// Project state is persisted in ~/.config/stackpanel/stackpanel.yaml. +// Project state is persisted in ~/.config/stackpanel/config.yaml. package server diff --git a/apps/stackpanel-go/internal/agent/server/registry.go b/apps/stackpanel-go/internal/agent/server/registry.go index 51aa79ce..d8e9f173 100644 --- a/apps/stackpanel-go/internal/agent/server/registry.go +++ b/apps/stackpanel-go/internal/agent/server/registry.go @@ -1,664 +1,201 @@ -// registry.go implements the module registry: browsing, searching, and installing -// external Stackpanel modules from a remote JSON registry. -// -// Installation uses tree-sitter (via flakeedit) to parse and modify flake.nix, -// adding the required flake input and stackpanelImports entry. If auto-editing -// fails, a fallback returns code snippets for manual installation. -// -// When the registry is unreachable, sample/builtin modules are returned so the -// UI always has something to display. package server import ( - "encoding/json" + "context" + "errors" "fmt" - "io" - "net/http" - "os" - "os/exec" - "path/filepath" - "sort" - "strings" - "time" - "github.com/rs/zerolog/log" + "connectrpc.com/connect" - "github.com/darkmatter/stackpanel/stackpanel-go/internal/flakeedit" + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/registry" ) -// Default registry URL - can be overridden via config -const DefaultRegistryURL = "https://raw.githubusercontent.com/darkmatter/stackpanel-registry/main/modules.json" - -// RegistryModule represents a module available in the registry -type RegistryModule struct { - ID string `json:"id"` - Meta ModuleMeta `json:"meta"` - Features ModuleFeatures `json:"features"` - Requires []string `json:"requires,omitempty"` - Conflicts []string `json:"conflicts,omitempty"` - Tags []string `json:"tags,omitempty"` - FlakeURL string `json:"flakeUrl"` - FlakePath string `json:"flakePath,omitempty"` - Ref string `json:"ref,omitempty"` - Downloads int `json:"downloads,omitempty"` - Rating float64 `json:"rating,omitempty"` - UpdatedAt string `json:"updatedAt,omitempty"` - Installed bool `json:"installed,omitempty"` // True if module is active in Nix config - PendingInstall bool `json:"pendingInstall,omitempty"` // True if enabled but requires devshell re-entry - Builtin bool `json:"builtin,omitempty"` // True for modules that are built into stackpanel -} - -// RegistrySource represents a module registry source -type RegistrySource struct { - ID string `json:"id"` - Name string `json:"name"` - URL string `json:"url"` - Official bool `json:"official,omitempty"` - Enabled bool `json:"enabled"` -} - -// RegistryManifest is the format of the registry JSON file -type RegistryManifest struct { - Version int `json:"version"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - Modules []RegistryModule `json:"modules"` - UpdatedAt string `json:"updatedAt"` -} - -// RegistryModulesResponse is the API response for registry modules -type RegistryModulesResponse struct { - Modules []RegistryModule `json:"modules"` - Total int `json:"total"` - Sources []RegistrySource `json:"sources"` - LastUpdated string `json:"lastUpdated"` -} - -// InstallModuleRequest is the request to install a module -type InstallModuleRequest struct { - ModuleID string `json:"moduleId"` - FlakeURL string `json:"flakeUrl"` - FlakePath string `json:"flakePath,omitempty"` - Ref string `json:"ref,omitempty"` -} - -// InstallModuleResponse is the response from installing a module -type InstallModuleResponse struct { - Success bool `json:"success"` - Message string `json:"message"` - InputAdded bool `json:"inputAdded,omitempty"` - ImportAdded bool `json:"importAdded,omitempty"` - InputAlreadyExists bool `json:"inputAlreadyExists,omitempty"` - LockUpdated bool `json:"lockUpdated,omitempty"` - // Legacy fields — returned when auto-edit fails and the user must edit manually - FlakeInputCode string `json:"flakeInputCode,omitempty"` - ModuleImportCode string `json:"moduleImportCode,omitempty"` -} - -// handleRegistry routes registry-related API requests -func (s *Server) handleRegistry(w http.ResponseWriter, r *http.Request) { - path := strings.TrimPrefix(r.URL.Path, "/api/registry") - path = strings.TrimPrefix(path, "/") - - parts := strings.Split(path, "/") - - switch { - case path == "" || path == "modules" || path == "modules/": - // List registry modules - s.handleRegistryModules(w, r) - case len(parts) == 2 && parts[0] == "modules" && parts[1] == "install": - // Install a module - s.handleRegistryInstall(w, r) - default: - s.writeAPIError(w, http.StatusNotFound, "endpoint not found") - } +// registryView couples the catalog selected by this project's configuration to +// this project's lock. Neither is derived from the agent's current shell. +type registryView struct { + client *registry.Client + modules []registry.Module + lock *registryLock + state map[string]any } -// handleRegistryModules returns modules available in the registry -func (s *Server) handleRegistryModules(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - s.writeAPIError(w, http.StatusMethodNotAllowed, "method not allowed") - return - } - - category := r.URL.Query().Get("category") - search := r.URL.Query().Get("search") - - // Get registry sources (for now just use default) - sources := []RegistrySource{ - { - ID: "official", - Name: "Stackpanel Official", - URL: DefaultRegistryURL, - Official: true, - Enabled: true, - }, - } - - // Fetch modules from all enabled registries - var allModules []RegistryModule - for _, source := range sources { - if !source.Enabled { - continue - } - - modules, err := s.fetchRegistryModules(source.URL) - if err != nil { - log.Warn(). - Str("source", source.Name). - Err(err). - Msg("Failed to fetch registry modules") - continue - } - allModules = append(allModules, modules...) - } - - // If registry fetch failed or is empty, provide sample modules - if len(allModules) == 0 { - allModules = getSampleRegistryModules() - } - - // Get installed modules to mark which are already installed - installedModules, _ := s.getModules(true) - installedSet := make(map[string]bool) - for _, m := range installedModules { - installedSet[m.ID] = true - } - - // Also check pending enables from data files (not yet in Nix config) - pendingEnables := s.getPendingModuleEnables() - for moduleID := range pendingEnables { - installedSet[moduleID] = true - } - - // Mark installed modules and filter - var filteredModules []RegistryModule - for _, m := range allModules { - m.Installed = installedSet[m.ID] - - // Filter by category - if category != "" && m.Meta.Category != category { - continue +func (s *moduleService) loadRegistry( + ctx context.Context, + rt *projectRuntime, +) (*registryView, error) { + state, err := loadModuleState(ctx, rt) + if err != nil { + return nil, err + } + var projectURLs []string + if value, ok := state["registries"]; ok { + urls, ok := value.([]any) + if !ok { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("stackpanel.registries must be a list of URLs"), + ) } - - // Filter by search - if search != "" { - searchLower := strings.ToLower(search) - if !strings.Contains(strings.ToLower(m.ID), searchLower) && - !strings.Contains(strings.ToLower(m.Meta.Name), searchLower) && - (m.Meta.Description == nil || !strings.Contains(strings.ToLower(*m.Meta.Description), searchLower)) { - continue + for _, item := range urls { + u, ok := item.(string) + if !ok || u == "" { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + errors.New("invalid URL in stackpanel.registries"), + ) } + projectURLs = append(projectURLs, u) } - - filteredModules = append(filteredModules, m) } - - // Sort by downloads (popularity) - sort.Slice(filteredModules, func(i, j int) bool { - return filteredModules[i].Downloads > filteredModules[j].Downloads - }) - - s.writeAPI(w, http.StatusOK, RegistryModulesResponse{ - Modules: filteredModules, - Total: len(filteredModules), - Sources: sources, - LastUpdated: time.Now().Format(time.RFC3339), - }) -} - -// handleRegistryInstall installs a module by editing flake.nix with tree-sitter. -// On success it also runs `nix flake lock --update-input` to fetch the new input. -// If any step fails, the original flake.nix is restored from a backup. -func (s *Server) handleRegistryInstall(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - s.writeAPIError(w, http.StatusMethodNotAllowed, "method not allowed") - return - } - - var request InstallModuleRequest - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - s.writeAPIError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) - return - } - - if request.ModuleID == "" || request.FlakeURL == "" { - s.writeAPIError(w, http.StatusBadRequest, "moduleId and flakeUrl are required") - return - } - - // Skip auto-install for builtin modules - if request.FlakeURL == "builtin" { - s.writeAPI(w, http.StatusOK, InstallModuleResponse{ - Success: true, - Message: fmt.Sprintf( - "Module %s is builtin — enable it in your stackpanel config", - request.ModuleID, - ), - }) - return - } - - inputName := sanitizeFlakeInputName(request.ModuleID) - flakePath := request.FlakePath - if flakePath == "" { - flakePath = "stackpanelModules.default" - } - - // Determine project root - projectRoot := s.config.ProjectRoot - if projectRoot == "" { - s.handleRegistryInstallFallback(w, request, inputName, flakePath) - return + var machineURLs []string + var headers map[string]map[string]string + if s.s != nil && s.s.projectMgr != nil { + mgr := s.s.projectMgr.UserConfigManager() + machineURLs, headers = mgr.RegistrySources(), mgr.RegistryHeaders() } - - flakeNixPath := filepath.Join(projectRoot, "flake.nix") - - // Read flake.nix - source, err := os.ReadFile(flakeNixPath) + client := registry.NewClient(projectURLs, machineURLs, headers) + modules, err := client.List(ctx) if err != nil { - log.Warn(). - Err(err). - Str("path", flakeNixPath). - Msg("Could not read flake.nix, falling back to manual install") - s.handleRegistryInstallFallback(w, request, inputName, flakePath) - return + return nil, connect.NewError( + connect.CodeUnavailable, + fmt.Errorf("read module catalog: %w", err), + ) } - - // Parse with tree-sitter - editor, err := flakeedit.NewFlakeEditor(source) + lock, err := readRegistryLock(rt.root) if err != nil { - log.Warn().Err(err).Msg("Could not parse flake.nix, falling back to manual install") - s.handleRegistryInstallFallback(w, request, inputName, flakePath) - return - } - defer editor.Close() - - // Build the import expression - importExpr := fmt.Sprintf("inputs.%s.%s", inputName, flakePath) - - // Perform the edit - editResult, err := editor.AddInputAndImport( - flakeedit.FlakeInput{ - Name: inputName, - URL: request.FlakeURL, - FollowsNixpkgs: true, - }, - importExpr, - ) - if err != nil { - log.Warn().Err(err).Msg("Failed to edit flake.nix, falling back to manual install") - s.handleRegistryInstallFallback(w, request, inputName, flakePath) - return - } - - // Write backup - backupPath := flakeNixPath + ".bak" - if err := os.WriteFile(backupPath, source, 0o644); err != nil { - log.Warn().Err(err).Msg("Could not write flake.nix backup") + return nil, connect.NewError(connect.CodeFailedPrecondition, err) } + return ®istryView{client: client, modules: modules, lock: lock, state: state}, nil +} - // Write modified flake.nix - if err := os.WriteFile(flakeNixPath, editResult.Modified, 0o644); err != nil { - s.writeAPIError( - w, - http.StatusInternalServerError, - fmt.Sprintf("failed to write flake.nix: %v", err), +func (v *registryView) lookup(id string) (*registry.Module, error) { + if id == "" { + return nil, connect.NewError( + connect.CodeInvalidArgument, + errors.New("module_id is required"), ) - return } + for i := range v.modules { + m := &v.modules[i] + if m.ID == id || m.Slug == id { + return m, nil + } + } + return nil, connect.NewError( + connect.CodeNotFound, + fmt.Errorf("module %q is not in the configured registries", id), + ) +} - // Lock the new input - lockUpdated := false - if editResult.InputAdded { - lockCmd := exec.Command("nix", "flake", "lock", "--update-input", inputName) - lockCmd.Dir = projectRoot - if lockErr := lockCmd.Run(); lockErr != nil { - log.Warn(). - Err(lockErr). - Str("input", inputName). - Msg("nix flake lock failed, rolling back") - // Rollback - if rbErr := os.WriteFile(flakeNixPath, source, 0o644); rbErr != nil { - log.Error().Err(rbErr).Msg("Failed to rollback flake.nix") +// Normally only one catalog release has this pin. Do not invent a version +// when several releases share the same floating source, or a user pinned a +// different branch of the same module. +func registryProjection( + m *registry.Module, + lock *registryLock, +) (*agentv1.RegistryModule, error) { + input, exists, err := lock.input(m.Slug) + if err != nil { + return nil, connect.NewError(connect.CodeFailedPrecondition, err) + } + out := &agentv1.RegistryModule{ + Id: m.ID, Slug: m.Slug, Name: m.Name, Description: m.Description, + Category: m.Category, Icon: m.Icon, Author: m.Author, Tier: m.Tier, + LatestVersion: m.LatestVersion, Features: m.Features, UiSlots: m.UISlots, + Tags: m.Tags, ReadmeUrl: m.ReadmeURL, Homepage: m.Homepage, + } + matches := 0 + for i := range m.Versions { + v := &m.Versions[i] + release := &agentv1.RegistryModuleVersion{ + Version: v.Version, FlakeUrl: v.FlakeURL, Ref: v.Ref, Rev: v.Rev, + FollowsNixpkgs: v.FollowsNixpkgs, FlakePath: v.FlakePath, + } + for _, dep := range v.FlakeInputs { + d := &agentv1.ModuleFlakeInput{ + Name: dep.Name, + Url: dep.URL, + FollowsNixpkgs: dep.FollowsNixpkgs, + } + if dep.Ref != "" { + d.Ref = &dep.Ref + } + release.FlakeInputs = append(release.FlakeInputs, d) + } + out.Versions = append(out.Versions, release) + if exists && input.matchesSource(v.FlakeURL) { + out.Installed = true + if input.matchesPin(v.FlakeURL, v.Ref, v.Rev) { + out.InstalledVersion = &v.Version + matches++ } - s.writeAPIError( - w, - http.StatusInternalServerError, - fmt.Sprintf("nix flake lock failed for input %s: %v", inputName, lockErr), - ) - return } - lockUpdated = true } - - // Clean up backup on success - os.Remove(backupPath) - - // Broadcast SSE event - s.broadcastSSE(SSEEvent{ - Event: "module.installed", - Data: map[string]any{ - "moduleId": request.ModuleID, - "flakeUrl": request.FlakeURL, - "flakePath": flakePath, - "inputAdded": editResult.InputAdded, - "importAdded": editResult.ImportAdded, - "inputAlreadyExists": editResult.InputAlreadyExists, - "lockUpdated": lockUpdated, - }, - }) - - message := fmt.Sprintf("Module %s installed successfully", request.ModuleID) - if editResult.InputAlreadyExists { - message = fmt.Sprintf("Input %s already exists; added module import", inputName) + if matches != 1 { + out.InstalledVersion = nil } - - s.writeAPI(w, http.StatusOK, InstallModuleResponse{ - Success: true, - Message: message, - InputAdded: editResult.InputAdded, - ImportAdded: editResult.ImportAdded, - InputAlreadyExists: editResult.InputAlreadyExists, - LockUpdated: lockUpdated, - }) + return out, nil } -// handleRegistryInstallFallback returns code snippets for manual installation -// when auto-editing is not possible (no project root, parse failure, etc.). -func (s *Server) handleRegistryInstallFallback( - w http.ResponseWriter, - request InstallModuleRequest, - inputName, flakePath string, -) { - flakeInputCode := fmt.Sprintf(` %s.url = "%s"; - %s.inputs.nixpkgs.follows = "nixpkgs";`, inputName, request.FlakeURL, inputName) - - moduleImportCode := fmt.Sprintf(` inputs.%s.%s`, inputName, flakePath) - - s.broadcastSSE(SSEEvent{ - Event: "module.install.manual", - Data: map[string]any{ - "moduleId": request.ModuleID, - "flakeUrl": request.FlakeURL, - "flakePath": flakePath, - }, - }) - - s.writeAPI(w, http.StatusOK, InstallModuleResponse{ - Success: true, - Message: fmt.Sprintf( - "Auto-install not available. To install %s, add the following to your flake.nix:", - request.ModuleID, - ), - FlakeInputCode: flakeInputCode, - ModuleImportCode: moduleImportCode, - }) -} - -// fetchRegistryModules fetches modules from a registry URL -func (s *Server) fetchRegistryModules(url string) ([]RegistryModule, error) { - client := &http.Client{Timeout: 10 * time.Second} - - resp, err := client.Get(url) +func (s *moduleService) ListRegistryModules( + ctx context.Context, + req *connect.Request[agentv1.ListRegistryModulesRequest], +) (*connect.Response[agentv1.ListRegistryModulesResponse], error) { + rt := runtimeFor(ctx) + if rt == nil { + return nil, invalidModuleState("no project selected") + } + rt.moduleMu.Lock() + defer rt.moduleMu.Unlock() + view, err := s.loadRegistry(ctx, rt) if err != nil { - return nil, fmt.Errorf("failed to fetch registry: %w", err) + return nil, err + } + out := &agentv1.ListRegistryModulesResponse{} + for i := range view.modules { + m := &view.modules[i] + if m.Matches(req.Msg.Query, req.Msg.Category, req.Msg.Tag) { + item, err := registryProjection(m, view.lock) + if err != nil { + return nil, err + } + out.Modules = append(out.Modules, item) + } } - defer resp.Body.Close() + return connect.NewResponse(out), nil +} - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("registry returned status %d", resp.StatusCode) +func (s *moduleService) GetRegistryModule( + ctx context.Context, + req *connect.Request[agentv1.GetRegistryModuleRequest], +) (*connect.Response[agentv1.GetRegistryModuleResponse], error) { + rt := runtimeFor(ctx) + if rt == nil { + return nil, invalidModuleState("no project selected") + } + rt.moduleMu.Lock() + defer rt.moduleMu.Unlock() + view, err := s.loadRegistry(ctx, rt) + if err != nil { + return nil, err } - - body, err := io.ReadAll(resp.Body) + m, err := view.lookup(req.Msg.ModuleId) if err != nil { - return nil, fmt.Errorf("failed to read response: %w", err) + return nil, err } - - var manifest RegistryManifest - if err := json.Unmarshal(body, &manifest); err != nil { - return nil, fmt.Errorf("failed to parse registry manifest: %w", err) + item, err := registryProjection(m, view.lock) + if err != nil { + return nil, err } - - return manifest.Modules, nil -} - -// sanitizeFlakeInputName converts a module ID to a valid flake input name -func sanitizeFlakeInputName(moduleID string) string { - // Replace invalid characters with underscores - name := strings.ReplaceAll(moduleID, "-", "_") - name = strings.ReplaceAll(name, ".", "_") - return name -} - -// getSampleRegistryModules returns sample modules when registry is unavailable -func getSampleRegistryModules() []RegistryModule { - // Built-in module descriptions - oxlintDesc := "Blazing fast JavaScript/TypeScript linter written in Rust. Supports React, TypeScript, and more." - goDesc := "Go application support with air live reload, gomod2nix, and automatic file generation." - gitHooksDesc := "Git hooks integration with pre-commit linting and formatting support." - turboDesc := "Turborepo task integration for monorepo build orchestration." - - // External module descriptions - sampleDesc1 := "Production-ready PostgreSQL with replication, backups, and monitoring" - sampleDesc2 := "Redis cluster with high availability and automatic failover" - sampleDesc3 := "S3-compatible object storage for local development" - sampleDesc4 := "Full observability stack with Prometheus, Grafana, and Loki" - sampleDesc5 := "Automated SSL certificates with Let's Encrypt" - sampleAuthor := "Stackpanel Team" - - return []RegistryModule{ - // Built-in modules (already available, just need to enable) - { - ID: "oxlint", - Meta: ModuleMeta{ - Name: "OxLint", - Description: &oxlintDesc, - Category: "development", - Author: &sampleAuthor, - Version: strPtr("1.0.0"), - Icon: strPtr("search-code"), - Homepage: strPtr("https://oxc.rs"), - }, - Features: ModuleFeatures{ - Files: true, - Scripts: true, - Healthchecks: true, - Packages: true, - }, - Tags: []string{ - "linting", - "javascript", - "typescript", - "react", - "rust", - "oxc", - }, - FlakeURL: "builtin", - FlakePath: "stackpanel.apps..linting.oxlint.enable = true", - Downloads: 5000, - Rating: 4.9, - UpdatedAt: "2024-01-22T10:00:00Z", - Builtin: true, - }, - { - ID: "go", - Meta: ModuleMeta{ - Name: "Go Support", - Description: &goDesc, - Category: "development", - Author: &sampleAuthor, - Version: strPtr("1.0.0"), - Icon: strPtr("code"), - }, - Features: ModuleFeatures{ - Files: true, - Scripts: true, - Healthchecks: true, - Packages: true, - }, - Tags: []string{"go", "golang", "air", "live-reload", "gomod2nix"}, - FlakeURL: "builtin", - FlakePath: "stackpanel.apps..go.enable = true", - Downloads: 3500, - Rating: 4.8, - UpdatedAt: "2024-01-20T10:00:00Z", - Builtin: true, - }, - { - ID: "git-hooks", - Meta: ModuleMeta{ - Name: "Git Hooks", - Description: &gitHooksDesc, - Category: "development", - Author: &sampleAuthor, - Version: strPtr("1.0.0"), - Icon: strPtr("git-branch"), - }, - Features: ModuleFeatures{ - Scripts: true, - }, - Tags: []string{"git", "hooks", "pre-commit", "linting", "formatting"}, - FlakeURL: "builtin", - FlakePath: "stackpanel.git-hooks.enable = true", - Downloads: 4200, - Rating: 4.7, - UpdatedAt: "2024-01-18T10:00:00Z", - Builtin: true, - }, - { - ID: "turbo", - Meta: ModuleMeta{ - Name: "Turborepo", - Description: &turboDesc, - Category: "development", - Author: &sampleAuthor, - Version: strPtr("1.0.0"), - Icon: strPtr("zap"), - }, - Features: ModuleFeatures{ - Files: true, - Scripts: true, - Tasks: true, - }, - Tags: []string{"turbo", "turborepo", "monorepo", "build", "tasks"}, - FlakeURL: "builtin", - FlakePath: "stackpanel.turbo.enable = true", - Downloads: 3800, - Rating: 4.6, - UpdatedAt: "2024-01-19T10:00:00Z", - Builtin: true, - }, - // External/installable modules - { - ID: "postgres-ha", - Meta: ModuleMeta{ - Name: "PostgreSQL HA", - Description: &sampleDesc1, - Category: "database", - Author: &sampleAuthor, - Version: strPtr("1.2.0"), - }, - Features: ModuleFeatures{ - Services: true, - Healthchecks: true, - Secrets: true, - }, - Tags: []string{"database", "postgres", "ha", "production"}, - FlakeURL: "github:stackpanel/modules", - FlakePath: "stackpanelModules.postgres-ha", - Downloads: 1250, - Rating: 4.8, - UpdatedAt: "2024-01-15T10:00:00Z", - }, - { - ID: "redis-cluster", - Meta: ModuleMeta{ - Name: "Redis Cluster", - Description: &sampleDesc2, - Category: "database", - Author: &sampleAuthor, - Version: strPtr("1.0.0"), - }, - Features: ModuleFeatures{ - Services: true, - Healthchecks: true, - }, - Tags: []string{"database", "redis", "cache", "cluster"}, - FlakeURL: "github:stackpanel/modules", - FlakePath: "stackpanelModules.redis-cluster", - Downloads: 890, - Rating: 4.5, - UpdatedAt: "2024-01-10T10:00:00Z", - }, - { - ID: "minio-server", - Meta: ModuleMeta{ - Name: "MinIO Server", - Description: &sampleDesc3, - Category: "infrastructure", - Author: &sampleAuthor, - Version: strPtr("1.1.0"), - }, - Features: ModuleFeatures{ - Services: true, - Healthchecks: true, - Files: true, - }, - Tags: []string{"storage", "s3", "minio", "object-storage"}, - FlakeURL: "github:stackpanel/modules", - FlakePath: "stackpanelModules.minio", - Downloads: 670, - Rating: 4.3, - UpdatedAt: "2024-01-08T10:00:00Z", - }, - { - ID: "observability", - Meta: ModuleMeta{ - Name: "Observability Stack", - Description: &sampleDesc4, - Category: "monitoring", - Author: &sampleAuthor, - Version: strPtr("2.0.0"), - }, - Features: ModuleFeatures{ - Services: true, - Healthchecks: true, - Files: true, - Packages: true, - }, - Tags: []string{"monitoring", "prometheus", "grafana", "loki", "metrics"}, - FlakeURL: "github:stackpanel/modules", - FlakePath: "stackpanelModules.observability", - Downloads: 2100, - Rating: 4.9, - UpdatedAt: "2024-01-20T10:00:00Z", - }, - { - ID: "acme-certs", - Meta: ModuleMeta{ - Name: "ACME Certificates", - Description: &sampleDesc5, - Category: "infrastructure", - Author: &sampleAuthor, - Version: strPtr("1.0.0"), - }, - Features: ModuleFeatures{ - Scripts: true, - Healthchecks: true, - Secrets: true, - }, - Tags: []string{"ssl", "tls", "certificates", "letsencrypt"}, - FlakeURL: "github:stackpanel/modules", - FlakePath: "stackpanelModules.acme", - Downloads: 450, - Rating: 4.2, - UpdatedAt: "2024-01-05T10:00:00Z", - }, + readme, err := view.client.Readme(ctx, *m) + if err != nil { + return nil, connect.NewError( + connect.CodeUnavailable, + fmt.Errorf("read README for %s: %w", m.ID, err), + ) } -} - -// Helper to create string pointer -func strPtr(s string) *string { - return &s + return connect.NewResponse( + &agentv1.GetRegistryModuleResponse{Module: item, Readme: readme}, + ), nil } diff --git a/apps/stackpanel-go/internal/agent/server/registry_dep_ownership.go b/apps/stackpanel-go/internal/agent/server/registry_dep_ownership.go new file mode 100644 index 00000000..f97da0ef --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/registry_dep_ownership.go @@ -0,0 +1,158 @@ +package server + +import ( + "maps" + + "github.com/darkmatter/stackpanel/stackpanel-go/internal/flakeedit" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/registry" +) + +// authorizeDependencyUpdates supplies catalog evidence, not permission to edit +// an arbitrary matching URL. The editor must independently verify its marker +// and the complete live declaration. Without proof, normal add/reuse rules apply. +func (op registryOperation) authorizeDependencyUpdates( + previous *registry.Version, + deps []flakeedit.FlakeInput, +) error { + for i := range deps { + deps[i].PreviousDependency = nil + } + if previous == nil || len(deps) == 0 { + return nil + } + + lock, module := op.view.lock, op.module + input, exists, err := lock.input(module.Slug) + if err != nil || !exists { + return err + } + // installedRelease can choose a representative for import removal even + // when the pin is custom or ambiguous. That isn't dependency ownership. + var prior *registry.Version + for i := range module.Versions { + v := &module.Versions[i] + if input.matchesPin(v.FlakeURL, v.Ref, v.Rev) { + if prior != nil { + return nil + } + prior = v + } + } + if prior == nil || prior.Version != previous.Version || len(prior.FlakeInputs) == 0 { + return nil + } + available := make(map[string]*registry.FlakeInput, len(prior.FlakeInputs)) + for i := range prior.FlakeInputs { + d := &prior.FlakeInputs[i] + available[d.Name] = d + } + + // Catalog consumers need not appear as lock edges: a module can use the + // project's inputs at evaluation time. A possible consumer is enough to + // withhold authorization, even if its requested pin differs from ours. + for i := range op.view.modules { + other := &op.view.modules[i] + if other.Slug == module.Slug { + continue + } + n, exists, err := lock.input(other.Slug) + if err != nil { + return err + } + if !exists { + continue + } + for _, v := range installedCandidates(n, other) { + delete(available, other.Slug) + if v.FollowsNixpkgs { + delete(available, "nixpkgs") + } + for i := range v.FlakeInputs { + d := &v.FlakeInputs[i] + delete(available, d.Name) + if d.FollowsNixpkgs { + delete(available, "nixpkgs") + } + } + } + if len(available) == 0 { + return nil + } + } + + for i := range deps { + d := available[deps[i].Name] + if d == nil { + continue + } + n, exists, err := lock.input(d.Name) + if err != nil { + return err + } + if exists && n.matchesPin(d.URL, d.Ref, "") && + lock.exclusiveDependency(module.Slug, d.Name) { + deps[i].PreviousDependency = &flakeedit.FlakeInput{ + Name: d.Name, URL: d.URL, Ref: d.Ref, FollowsNixpkgs: d.FollowsNixpkgs, + } + } + } + return nil +} + +func (l *registryLock) exclusiveDependency(owner, dep string) bool { + depKey, direct := l.root.inputs[dep].(string) + if !direct || l.root.inputs[owner] == depKey { + return false + } + + // Don't mistake the module following its own dependency, or a nested + // input following [dep, child], for a second consumer. Direct edges + // identify the nodes introduced by these two inputs. They are private + // only if no independent input also reaches them. + private := make(map[*registryLockNode]bool) + var markDirect func(*registryLockNode) + markDirect = func(n *registryLockNode) { + if private[n] { + return + } + private[n] = true + for _, input := range n.inputs { + if key, ok := input.(string); ok { + markDirect(l.nodes[key]) + } + } + } + markDirect(l.nodes[l.root.inputs[owner].(string)]) + markDirect(l.nodes[depKey]) + + // In the validated lock, every independent edge must still resolve + // without the dependency node. This catches aliases and follows paths + // that pass THROUGH dep to another node, including chained follows. + without := registryLock{root: l.root, nodes: maps.Clone(l.nodes)} + delete(without.nodes, depKey) + resolved := make(map[registryLockEdge]*registryLockNode) + checked := make(map[*registryLockNode]bool) + var independent func(*registryLockNode) bool + independent = func(n *registryLockNode) bool { + if checked[n] { + return true + } + checked[n] = true + for name := range n.inputs { + if n == l.root && (name == owner || name == dep) { + continue + } + child, err := without.resolve(n, name, resolved) + if err != nil || !independent(child) { + return false + } + } + return true + } + for _, n := range l.nodes { + if !private[n] && !independent(n) { + return false + } + } + return true +} diff --git a/apps/stackpanel-go/internal/agent/server/registry_integration_test.go b/apps/stackpanel-go/internal/agent/server/registry_integration_test.go new file mode 100644 index 00000000..3771f186 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/registry_integration_test.go @@ -0,0 +1,810 @@ +package server + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/cgi" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "connectrpc.com/connect" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/structpb" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1/agentv1connect" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/config" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/agent/project" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/registry" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +const registryFixtureID = "local.probe" // deliberately distinct from the input and Nix ID + +func TestProjectRegistryLifecycle(t *testing.T) { + f := newRegistryIntegration(t) + + t.Run( + "install, preview, adopt, update and uninstall in one project", + func(t *testing.T) { + userDep := fmt.Sprintf("userTool.url = %q;", f.gitURL+"?dir=foreign&ref=one") + p := f.project(t, "primary.json", userDep) + other := f.project(t, "other.json", "") + otherFiles := other.files(t) + f.assertCatalog(t, p, "Primary catalog", false, "") + f.assertCatalog(t, other, "Other catalog", false, "") + + ctx := t.Context() + installed, err := f.client.InstallModule( + ctx, + registryRequest( + p, + &agentv1.InstallModuleRequest{ModuleId: registryFixtureID, Version: "1.0"}, + ), + ) + require.NoError(t, err) + require.Equal(t, "probe", installed.Msg.GetModuleId()) + revs := p.lockedRevs(t) + require.Equal(t, f.v1, revs["probe"]) + require.Equal(t, f.v1, revs["support"]) + f.assertCatalog(t, p, "Primary catalog", true, "1.0") // not enabled, not latest + f.assertCatalog(t, other, "Other catalog", false, "") + _, err = f.client.GetModule( + ctx, + registryRequest(other, &agentv1.GetModuleRequest{ModuleId: "probe"}), + ) + require.Equal(t, connect.CodeNotFound, connect.CodeOf(err), "%v", err) + + m := f.module(t, p) + require.False(t, m.GetEnabled()) + require.Equal(t, "1.0", m.GetMeta().GetVersion()) + beforePreview := p.files(t) + preview, err := f.client.PreviewModuleEnable( + ctx, + registryRequest(p, &agentv1.PreviewModuleEnableRequest{ModuleId: "probe"}), + ) + require.NoError(t, err) + require.Equal( + t, + []string{"probe.conf"}, + preview.Msg.GetPreview().GetFiles().GetAdded(), + ) + require.Equal( + t, + []string{"probe-tool"}, + preview.Msg.GetPreview().GetPackages().GetAdded(), + ) + require.Equal( + t, + []string{"probe-worker"}, + preview.Msg.GetPreview().GetServices().GetAdded(), + ) + require.Equal( + t, + beforePreview, + p.files(t), + "preview must not adopt or relock the module", + ) + + _, err = f.client.EnableModule( + ctx, + registryRequest(p, &agentv1.EnableModuleRequest{ModuleId: "probe"}), + ) + require.NoError(t, err) + settings, err := structpb.NewStruct(map[string]any{"color": "blue"}) + require.NoError(t, err) + _, err = f.client.UpdateModuleConfig( + ctx, + registryRequest( + p, + &agentv1.UpdateModuleConfigRequest{ModuleId: "probe", Settings: settings}, + ), + ) + require.NoError(t, err) + m = f.module(t, p) + require.True(t, m.GetEnabled()) + require.Equal(t, "blue", m.GetSettings().GetFields()["color"].GetStringValue()) + + // This release exists in the catalog, but not in Git. A real failed + // lock must leave the installed release (and its config) intact. + beforeUpdate := p.files(t) + _, err = f.client.UpdateModule( + ctx, + registryRequest( + p, + &agentv1.UpdateModuleRequest{ModuleId: "probe", Version: "broken"}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.Equal(t, beforeUpdate, p.files(t)) + f.assertCatalog(t, p, "Primary catalog", true, "1.0") + + _, err = f.client.UpdateModule( + ctx, + registryRequest( + p, + &agentv1.UpdateModuleRequest{ModuleId: "probe", Version: "2.0"}, + ), + ) + require.NoError(t, err) + revs = p.lockedRevs(t) + require.Equal(t, f.v2, revs["probe"]) + require.Equal(t, f.v2, revs["support"]) + require.Equal(t, f.v1, revs["userTool"]) + require.Contains(t, p.files(t)["flake.nix"], userDep) + f.assertCatalog(t, p, "Primary catalog", true, "2.0") + m = f.module(t, p) + require.Equal(t, "2.0", m.GetMeta().GetVersion()) + require.True(t, m.GetEnabled()) + require.Equal(t, "blue", m.GetSettings().GetFields()["color"].GetStringValue()) + + links := f.manager.UserConfigManager() + require.NoError( + t, + links.SetLinkedModule( + p.root, + "probe", + userconfig.LinkedModule{Path: f.localProbe}, + ), + ) + beforeUninstall := p.files(t) + _, err = f.client.UninstallModule( + ctx, + registryRequest( + p, + &agentv1.UninstallModuleRequest{ModuleId: registryFixtureID}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.ErrorContains(t, err, "stack module unlink probe") + require.Equal(t, beforeUninstall, p.files(t)) + require.NoError(t, links.UnlinkModule(p.root, "probe")) + + _, err = f.client.UninstallModule( + ctx, + registryRequest( + p, + &agentv1.UninstallModuleRequest{ModuleId: registryFixtureID}, + ), + ) + require.NoError(t, err) + require.NotContains(t, p.lockedRevs(t), "probe") + // mkFlake rejects dangling enable *or* options after the input is + // removed. This read also forces the unrelated sibling config value. + f.assertCatalog(t, p, "Primary catalog", false, "") + _, err = f.client.GetModule( + ctx, + registryRequest(p, &agentv1.GetModuleRequest{ModuleId: "probe"}), + ) + require.Equal(t, connect.CodeNotFound, connect.CodeOf(err), "%v", err) + require.Equal(t, otherFiles, other.files(t)) + }, + ) + + t.Run( + "catalog omitting a required input cannot report a successful install", + func(t *testing.T) { + p := f.project(t, "primary.json", "") + cfg := p.files(t)[".stack/config.nix"] + registryWrite( + t, + p.root, + ".stack/config.nix", + strings.Replace(cfg, "{", "{ requireHelper = true;", 1), + ) + before := p.files(t) + _, err := f.client.InstallModule( + t.Context(), + registryRequest(p, &agentv1.InstallModuleRequest{ModuleId: "probe"}), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err)) + require.Equal(t, before, p.files(t)) + }, + ) + + t.Run("matching user dependency cannot be migrated", func(t *testing.T) { + p := f.project( + t, + "primary.json", + fmt.Sprintf("support.url = %q;", f.gitURL+"?dir=support&ref=one"), + ) + _, err := f.client.InstallModule( + t.Context(), + registryRequest( + p, + &agentv1.InstallModuleRequest{ModuleId: "probe", Version: "1.0"}, + ), + ) + require.NoError(t, err) + before := p.files(t) + _, err = f.client.UpdateModule( + t.Context(), + registryRequest( + p, + &agentv1.UpdateModuleRequest{ModuleId: "probe", Version: "2.0"}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.Equal(t, before, p.files(t)) + }) + + t.Run( + "same source at an unpublished commit has no installed version", + func(t *testing.T) { + p := f.project(t, "primary.json", "") + _, err := f.client.InstallModule( + t.Context(), + registryRequest( + p, + &agentv1.InstallModuleRequest{ModuleId: "probe", Ref: "main"}, + ), + ) + require.NoError(t, err) + require.Equal(t, f.dev, p.lockedRevs(t)["probe"]) + f.assertCatalog(t, p, "Primary catalog", true, "") + }, + ) + + t.Run( + "concurrent installs and a failed removal preserve project config", + func(t *testing.T) { + p := f.project(t, "primary.json", "") + start, results := make(chan struct{}), make(chan error, 2) + for range 2 { + go func() { + <-start + _, err := f.client.InstallModule( + t.Context(), + registryRequest(p, &agentv1.InstallModuleRequest{ModuleId: "probe"}), + ) + results <- err + }() + } + close(start) + a, b := <-results, <-results + if a != nil { + a, b = b, a + } + require.NoError(t, a) + require.Equal(t, connect.CodeAlreadyExists, connect.CodeOf(b), "%v", b) + _, err := f.client.EnableModule( + t.Context(), + registryRequest(p, &agentv1.EnableModuleRequest{ModuleId: "probe"}), + ) + require.NoError(t, err) + // This independently declared project option also needs probe. It + // isn't owned by the module and the agent must not silently delete it. + config := p.files(t)[".stack/config.nix"] + registryWrite( + t, + p.root, + ".stack/config.nix", + strings.Replace(config, "{", "{\n requireProbe = true;", 1), + ) + before := p.files(t) + _, err = f.client.UninstallModule( + t.Context(), + registryRequest(p, &agentv1.UninstallModuleRequest{ModuleId: "probe"}), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.Equal( + t, + before, + p.files(t), + "failed validation must restore both config and flake files", + ) + require.True(t, f.module(t, p).GetEnabled()) + }, + ) + + for _, name := range []string{"probe", "support"} { + t.Run("unrelated input named "+name, func(t *testing.T) { + // Same repository as the catalog; only ?dir differs. A name or + // repository-only match would steal this user-owned input. + p := f.project( + t, + "primary.json", + fmt.Sprintf("%s.url = %q;", name, f.gitURL+"?dir=foreign&ref=one"), + ) + f.assertCatalog(t, p, "Primary catalog", false, "") + before := p.files(t) + _, err := f.client.InstallModule( + t.Context(), + registryRequest(p, &agentv1.InstallModuleRequest{ModuleId: registryFixtureID}), + ) + want := connect.CodeFailedPrecondition + if name == "probe" { + want = connect.CodeAlreadyExists + } + require.Equal(t, want, connect.CodeOf(err), "%v", err) + require.Equal(t, before, p.files(t)) + if name == "probe" { + _, err = f.client.UpdateModule( + t.Context(), + registryRequest(p, &agentv1.UpdateModuleRequest{ModuleId: registryFixtureID}), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.Equal(t, before, p.files(t)) + _, err = f.client.UninstallModule( + t.Context(), + registryRequest( + p, + &agentv1.UninstallModuleRequest{ModuleId: registryFixtureID}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.Equal(t, before, p.files(t)) + } + }) + } + + t.Run("unresolvable version, lock and catalog", func(t *testing.T) { + p := f.project(t, "primary.json", "") + before := p.files(t) + _, err := f.client.InstallModule( + t.Context(), + registryRequest( + p, + &agentv1.InstallModuleRequest{ModuleId: "probe", Version: "does-not-exist"}, + ), + ) + require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err), "%v", err) + require.Equal(t, before, p.files(t)) + + // A valid flake that locks successfully but doesn't export the catalog + // module is not a successful install. Roll back both input additions. + _, err = f.client.InstallModule( + t.Context(), + registryRequest( + p, + &agentv1.InstallModuleRequest{ModuleId: "probe", Version: "no-export"}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.Equal(t, before, p.files(t)) + + // This release exports probe but remains enabled even after the agent + // writes false to its declared enable path. + _, err = f.client.InstallModule( + t.Context(), + registryRequest( + p, + &agentv1.InstallModuleRequest{ModuleId: "probe", Version: "always-on"}, + ), + ) + require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err), "%v", err) + require.Equal(t, before, p.files(t)) + + registryWrite(t, p.root, "flake.lock", `{"invalid":`) + brokenLock := p.files(t) + _, err = f.client.GetRegistryModule( + t.Context(), + registryRequest(p, &agentv1.GetRegistryModuleRequest{ModuleId: "probe"}), + ) + require.Equal( + t, + connect.CodeFailedPrecondition, + connect.CodeOf(err), + "invalid lock is not an empty project: %v", + err, + ) + require.Equal(t, brokenLock, p.files(t)) + + bad := f.project(t, "unavailable.json", "") // never cached; HTTP 404 + before = bad.files(t) + _, err = f.client.ListRegistryModules( + t.Context(), + registryRequest(bad, &agentv1.ListRegistryModulesRequest{}), + ) + require.Equal(t, connect.CodeUnavailable, connect.CodeOf(err), "%v", err) + _, err = f.client.InstallModule( + t.Context(), + registryRequest(bad, &agentv1.InstallModuleRequest{ModuleId: "probe"}), + ) + require.Equal(t, connect.CodeUnavailable, connect.CodeOf(err), "%v", err) + require.Equal(t, before, bad.files(t)) + }) +} + +type registryIntegration struct { + client agentv1connect.ModuleServiceClient + manager *project.Manager + projects, framework, catalog string + gitURL, v1, v2, dev string + localProbe string +} + +type registryProject struct{ root, id string } + +func registryRequest[T any](p registryProject, msg *T) *connect.Request[T] { + r := connect.NewRequest(msg) + r.Header().Set(projectHeader, p.id) + return r +} + +func (f *registryIntegration) assertCatalog( + t *testing.T, + p registryProject, + name string, + installed bool, + version string, +) { + t.Helper() + list, err := f.client.ListRegistryModules( + t.Context(), + registryRequest( + p, + &agentv1.ListRegistryModulesRequest{ + Query: "probe", + Category: "tools", + Tag: "offline", + }, + ), + ) + require.NoError(t, err) + require.Len(t, list.Msg.GetModules(), 1) + get, err := f.client.GetRegistryModule( + t.Context(), + registryRequest(p, &agentv1.GetRegistryModuleRequest{ModuleId: registryFixtureID}), + ) + require.NoError(t, err) + m := get.Msg.GetModule() + require.True( + t, + proto.Equal(list.Msg.GetModules()[0], m), + "list and detail disagree: %v vs %v", + list.Msg.GetModules()[0], + m, + ) + require.Equal(t, registryFixtureID, m.GetId()) + require.Equal(t, "probe", m.GetSlug()) + require.Equal(t, name, m.GetName()) + require.Equal(t, "2.0", m.GetLatestVersion()) + require.Equal(t, installed, m.GetInstalled()) + if version == "" { + require.Nil(t, m.InstalledVersion, "unknown version must be absent") + } else { + require.Equal(t, version, m.GetInstalledVersion()) + } + require.Equal(t, "# Local probe\n", get.Msg.GetReadme()) +} + +func (f *registryIntegration) module(t *testing.T, p registryProject) *agentv1.Module { + t.Helper() + r, err := f.client.GetModule( + t.Context(), + registryRequest(p, &agentv1.GetModuleRequest{ModuleId: "probe"}), + ) + require.NoError(t, err) + require.Equal(t, "probe", r.Msg.GetModule().GetId()) + return r.Msg.GetModule() +} + +func (p registryProject) files(t *testing.T) map[string]string { + t.Helper() + files := map[string]string{} + for _, name := range []string{"flake.nix", "flake.lock", ".stack/config.nix"} { + data, err := os.ReadFile(filepath.Join(p.root, name)) + require.NoError(t, err) + files[name] = string(data) + } + return files +} + +// Follow the root edges rather than assuming node keys are input names. +func (p registryProject) lockedRevs(t *testing.T) map[string]string { + t.Helper() + var lock struct { + Root string + Nodes map[string]struct { + Inputs map[string]string + Locked struct{ Rev, NarHash string } + } + } + data, err := os.ReadFile(filepath.Join(p.root, "flake.lock")) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(data, &lock)) + revs := map[string]string{} + for input, node := range lock.Nodes[lock.Root].Inputs { + locked := lock.Nodes[node].Locked + require.NotEmpty(t, locked.NarHash, "unlocked input %s", input) + revs[input] = locked.Rev + } + return revs +} + +func (f *registryIntegration) project( + t *testing.T, + catalog, extraInputs string, +) registryProject { + t.Helper() + root, err := os.MkdirTemp(f.projects, "consumer-") + require.NoError(t, err) + registryWrite(t, root, "flake.nix", fmt.Sprintf(`{ + inputs = { + stackpanel.url = %q; + %s + }; + outputs = { self, stackpanel, ... }@inputs: stackpanel.lib.mkFlake { inherit inputs self; }; +} +`, f.framework, extraInputs)) + registryWrite(t, root, ".stack/config.nix", fmt.Sprintf(`{ + registries = [ %q ]; + tooling.keep = "user value"; +} +`, f.catalog+"/"+catalog)) + registryCommand(t, root, "git", "init", "-q", "-b", "main") + registryCommand(t, root, "git", "add", "-f", "flake.nix", ".stack/config.nix") + registryGitCommit(t, root, "consumer") + registryCommand(t, root, "nix", "flake", "lock") + registryCommand(t, root, "git", "add", "-f", "flake.lock") + registryGitCommit(t, root, "lock local framework and initial inputs") + registered, err := f.manager.UserConfigManager().AddProject(root, "") + require.NoError(t, err) + return registryProject{root: root, id: registered.ID} +} + +func newRegistryIntegration(t *testing.T) *registryIntegration { + t.Helper() + if _, err := exec.LookPath("nix"); err != nil { + t.Skip("registry lifecycle integration requires Nix with flakes") + } + f := ®istryIntegration{projects: t.TempDir()} + // Production project resolution deliberately rejects projects under /tmp + // and /var (including macOS TMPDIR). Use disposable Git worktrees in a + // valid location, not a stubbed project resolver or a real saved project. + if errors.Is(project.QuickValidate(f.projects), project.ErrSuspiciousPath) { + home, err := os.UserHomeDir() + require.NoError(t, err) + f.projects, err = os.MkdirTemp(home, ".stackpanel-test-projects-") + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, os.RemoveAll(f.projects)) }) + } + t.Setenv("STACKPANEL_USER_CONFIG", filepath.Join(t.TempDir(), "user.yaml")) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv( + "IN_NIX_SHELL", + "1", + ) // the tiny framework doesn't provide a devshell to hydrate + t.Setenv( + "NIX_CONFIG", + os.Getenv( + "NIX_CONFIG", + )+"\nexperimental-features = nix-command flakes\nsubstituters =\nflake-registry =\n", + ) + + pack := t.TempDir() + registryCommand(t, pack, "git", "init", "-q", "-b", "main") + registryWrite( + t, + pack, + "framework/flake.nix", + fmt.Sprintf(registryFixtureFramework, nixeval.CurrentSystem()), + ) + registryWrite( + t, + pack, + "support/flake.nix", + `{ outputs = { self }: { token = "support"; }; }`, + ) + registryWrite( + t, + pack, + "foreign/flake.nix", + `{ outputs = { self }: { token = "foreign"; }; }`, + ) + f.localProbe = filepath.Join(pack, "probe") + release := func(version, enabled string) string { + registryWrite( + t, + pack, + "probe/flake.nix", + fmt.Sprintf(registryFixtureModule, version, enabled), + ) + registryCommand( + t, + pack, + "git", + "add", + "-f", + "framework", + "support", + "foreign", + "probe", + ) + registryGitCommit(t, pack, version) + return registryCommand(t, pack, "git", "rev-parse", "HEAD") + } + const configurable = "cfg.tooling.probe.enable or true" + f.v1 = release("1.0", configurable) + registryCommand(t, pack, "git", "branch", "one") + f.v2 = release("2.0", configurable) + registryCommand(t, pack, "git", "branch", "two") + alwaysOn := release("always-on", "true") + registryCommand(t, pack, "git", "branch", "always-on") + f.dev = release("development", configurable) + f.framework = (&url.URL{Scheme: "git+file", Path: pack, RawQuery: "dir=framework&ref=one&rev=" + f.v1}).String() + + // Catalogs accept remote-style flake URLs, not arbitrary filesystem + // paths. Serve the same local Git history over loopback with Git itself. + repos := t.TempDir() + registryCommand(t, repos, "git", "clone", "-q", "--bare", pack, "pack.git") + backend := filepath.Join( + registryCommand(t, repos, "git", "--exec-path"), + "git-http-backend", + ) + gitHTTP := httptest.NewServer( + &cgi.Handler{ + Path: backend, + Env: []string{"GIT_PROJECT_ROOT=" + repos, "GIT_HTTP_EXPORT_ALL=1"}, + }, + ) + t.Cleanup(gitHTTP.Close) + f.gitURL = "git+" + gitHTTP.URL + "/pack.git" + + catalogDir := t.TempDir() + catalogHTTP := httptest.NewServer(http.FileServer(http.Dir(catalogDir))) + t.Cleanup(catalogHTTP.Close) + f.catalog = catalogHTTP.URL + registryWrite(t, catalogDir, "README.md", "# Local probe\n") + version := func(v, ref, rev string) registry.Version { + return registry.Version{ + Version: v, + Ref: ref, + Rev: rev, + FlakeURL: f.gitURL + "?dir=probe", + FlakeInputs: []registry.FlakeInput{ + {Name: "support", URL: f.gitURL + "?dir=support", Ref: "one"}, + }, + } + } + noExport := version("no-export", "one", f.v1) + noExport.FlakeURL = f.gitURL + "?dir=support" + v2 := version("2.0", "two", f.v2) + v2.FlakeInputs[0].Ref = "two" + m := registry.Module{ + ID: registryFixtureID, + Slug: "probe", + Description: "Local registry integration probe", + Category: "tools", + Icon: "box", + Author: "local", + Tier: "community", + LatestVersion: "2.0", + ReadmeURL: f.catalog + "/README.md", + Features: []string{"files"}, + UISlots: []string{}, + Tags: []string{"offline"}, + Versions: []registry.Version{ + version("1.0", "one", f.v1), + v2, + version("broken", "missing-branch", ""), + noExport, + version("always-on", "always-on", alwaysOn), + }, + } + for file, name := range map[string]string{"primary.json": "Primary catalog", "other.json": "Other catalog"} { + m.Name = name + data, err := json.Marshal( + registry.Catalog{SchemaVersion: 1, Modules: []registry.Module{m}}, + ) + require.NoError(t, err) + registryWrite(t, catalogDir, file, string(data)) + } + + var err error + f.manager, err = project.NewManager(t.TempDir()) + require.NoError(t, err) + s := &Server{config: &config.Config{}, projectMgr: f.manager} + s.runtimes = newRuntimeRegistry(s) + scope := projectInterceptor{resolve: s.resolveProjectRoot, runtimes: s.runtimes} + mux := http.NewServeMux() + mux.Handle( + agentv1connect.NewModuleServiceHandler( + &moduleService{s: s}, + connect.WithInterceptors(scope), + ), + ) + rpc := httptest.NewServer(mux) + t.Cleanup(rpc.Close) + f.client = agentv1connect.NewModuleServiceClient(rpc.Client(), rpc.URL) + return f +} + +func registryCommand(t *testing.T, dir, program string, args ...string) string { + t.Helper() + cmd := exec.CommandContext(t.Context(), program, args...) + cmd.Dir = dir + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s %v: %s", program, args, out) + return strings.TrimSpace(string(out)) +} + +func registryWrite(t *testing.T, dir, name, body string) { + t.Helper() + file := filepath.Join(dir, name) + require.NoError(t, os.MkdirAll(filepath.Dir(file), 0o755)) + require.NoError(t, os.WriteFile(file, []byte(body), 0o644)) +} + +func registryGitCommit(t *testing.T, dir, message string) { + t.Helper() + registryCommand( + t, + dir, + "git", + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "-qm", + message, + ) +} + +// Only the framework is miniature. Its exported function discovers real +// locked outputs, reads real project config and computes both sides of a +// preview without depending on nixpkgs, a derivation, or the host project. +const registryFixtureFramework = `{ + outputs = { self }: { + lib.mkFlake = { self, inputs }: + let + cfg = import (self.outPath + "/.stack/config.nix"); + names = builtins.attrNames (builtins.removeAttrs inputs [ "self" "stackpanel" ]); + discovered = builtins.filter (n: inputs.${n} ? stackpanelModules) names; + modules = map (n: inputs.${n}.stackpanelModules.default { inherit cfg inputs; }) discovered; + installed = builtins.any (m: m.id == "probe") modules; + plan = enabled: { + files = if enabled then [ { path = "probe.conf"; type = "text"; } ] else []; + packages = if enabled then [ "probe-tool" ] else []; + services = if enabled then [ "probe-worker" ] else []; + packageFingerprints = if enabled then { + probe-tool = builtins.hashString "sha256" inputs.probe.rev; + } else {}; + serviceFingerprints = if enabled then { + probe-worker = builtins.hashString "sha256" (builtins.toJSON (cfg.tooling.probe.options or {})); + } else {}; + addons = []; + }; + enabled = builtins.any (m: m.enabled) modules; + state = assert cfg.tooling.keep == "user value"; + assert !(cfg.requireProbe or false) || installed; + assert installed || (cfg.tooling.probe or {}) == {}; + { inherit (cfg) registries; modulesListAll = modules; }; + in { legacyPackages.%s = { + stackpanelConfig = state; + stackpanelSerializable = state; + stackpanelSpeculate = { enablePath ? null, ... }: + plan (installed && (enabled || enablePath == [ "tooling" "probe" "enable" ])); + }; }; + }; +}` + +const registryFixtureModule = `{ + outputs = { self }: { + stackpanelModules.default = { cfg, inputs }: + assert inputs.support.token == "support"; + { + id = "probe"; + meta = { name = "Probe"; category = "tools"; version = %q; }; + missingFlakeInputs = if cfg.requireHelper or false && !(inputs ? helper) then [ { name = "helper"; } ] else []; + source = { type = "flake-input"; flakeInput = "probe"; }; + enablePath = "tooling.probe.enable"; + configPath = "tooling.probe.options"; + enabled = %s; + settings = cfg.tooling.probe.options or {}; + }; + }; +}` diff --git a/apps/stackpanel-go/internal/agent/server/registry_lifecycle.go b/apps/stackpanel-go/internal/agent/server/registry_lifecycle.go new file mode 100644 index 00000000..a6de7851 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/registry_lifecycle.go @@ -0,0 +1,541 @@ +package server + +import ( + "context" + "errors" + "fmt" + "slices" + + "connectrpc.com/connect" + + agentv1 "github.com/darkmatter/stackpanel/packages/proto/gen/gopb/stackpanel/agent/v1" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/flakeedit" + "github.com/darkmatter/stackpanel/stackpanel-go/internal/registry" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" +) + +func registrySelection( + m *registry.Module, + version, ref string, +) (*registry.Version, flakeedit.FlakeInput, []flakeedit.FlakeInput, error) { + if version == "" { + version = m.LatestVersion + } + for i := range m.Versions { + v := &m.Versions[i] + if v.Version != version { + continue + } + input := flakeedit.FlakeInput{ + Name: m.Slug, + URL: v.FlakeURL, + Ref: v.Ref, + Rev: v.Rev, + FollowsNixpkgs: v.FollowsNixpkgs, + } + if ref != "" && ref != v.Ref { + // An explicit ref intentionally selects a different commit of + // the same source, not another release's dependencies/import. + input.Ref, input.Rev = ref, "" + } + if _, err := input.PinnedURL(); err != nil { + return nil, input, nil, connect.NewError(connect.CodeInvalidArgument, err) + } + deps := make([]flakeedit.FlakeInput, 0, len(v.FlakeInputs)) + for _, dep := range v.FlakeInputs { + deps = append( + deps, + flakeedit.FlakeInput{ + Name: dep.Name, + URL: dep.URL, + Ref: dep.Ref, + FollowsNixpkgs: dep.FollowsNixpkgs, + }, + ) + } + return v, input, deps, nil + } + return nil, flakeedit.FlakeInput{}, nil, connect.NewError( + connect.CodeInvalidArgument, + fmt.Errorf("unknown version %q of %s", version, m.ID), + ) +} + +// Use exact releases when possible. For a user-selected ref, the source is +// still known but only operations safe for every matching release are allowed. +func installedCandidates( + node registryLockedInput, + m *registry.Module, +) []*registry.Version { + var source, exact []*registry.Version + for i := range m.Versions { + v := &m.Versions[i] + if node.matchesSource(v.FlakeURL) { + source = append(source, v) + if node.matchesPin(v.FlakeURL, v.Ref, v.Rev) { + exact = append(exact, v) + } + } + } + if len(exact) != 0 { + return exact + } + return source +} + +// Match the *previous* source and explicit import to a catalog release. In a +// custom-ref checkout there may be no exact pin. Such an input is editable +// only if all matching catalog entries agree which import would be removed. +func installedRelease( + lock *registryLock, + m *registry.Module, +) (*registry.Version, error) { + node, exists, err := lock.input(m.Slug) + if err != nil { + return nil, connect.NewError(connect.CodeFailedPrecondition, err) + } + if !exists { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + fmt.Errorf("no locked root input %q", m.Slug), + ) + } + candidates := installedCandidates(node, m) + if len(candidates) == 0 { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + fmt.Errorf("root input %q is not owned by catalog module %q", m.Slug, m.ID), + ) + } + for _, other := range candidates[1:] { + if other.FlakePath != candidates[0].FlakePath { + return nil, connect.NewError( + connect.CodeFailedPrecondition, + fmt.Errorf( + "cannot identify installed import for %q; check the pin in flake.nix", + m.Slug, + ), + ) + } + } + return candidates[0], nil +} + +// Another installed catalog entry may use this root input even if its module +// is disabled and doesn't force it during evaluation. Never break a satisfied +// dependency when updating/uninstalling its provider. +func (op registryOperation) checkDependents(after *registryLock) error { + name := op.module.Slug + before, occupied, err := op.view.lock.input(name) + if err != nil || !occupied { + return err + } + now, exists, err := after.input(name) + if err != nil { + return err + } + for i := range op.view.modules { + m := &op.view.modules[i] + if m.Slug == name { + continue + } + node, occupied, err := op.view.lock.input(m.Slug) + if err != nil { + return err + } + if !occupied { + continue + } + for _, v := range installedCandidates(node, m) { + for _, dep := range v.FlakeInputs { + if dep.Name == name && before.matchesPin(dep.URL, dep.Ref, "") && + (!exists || !now.matchesPin(dep.URL, dep.Ref, "")) { + return fmt.Errorf( + "installed module %q requires the existing pin of input %q", + m.ID, + name, + ) + } + } + } + } + return nil +} + +// A linked local module is useful for preview, but cannot prove that the +// installed catalog release itself exports a valid module. +func lockedModuleState(ctx context.Context, root string) (map[string]any, error) { + return loadModuleState( + ctx, + &projectRuntime{root: root, evalModuleState: nixeval.EvalLockedModuleState}, + ) +} + +// Verify Nix locked the requested direct inputs, *and* that the expected +// module can actually be discovered. A valid flake isn't necessarily a +// module. Validation runs inside flakeedit's rollback boundary. +func (op registryOperation) validateInstall( + ctx context.Context, + input flakeedit.FlakeInput, + deps []flakeedit.FlakeInput, +) (map[string]any, error) { + rt := op.rt + lock, err := readRegistryLock(rt.root) + if err != nil { + return nil, err + } + if err := op.checkDependents(lock); err != nil { + return nil, err + } + check := func(dep flakeedit.FlakeInput) error { + node, exists, err := lock.input(dep.Name) + if err != nil { + return err + } + if !exists || !node.matchesPin(dep.URL, dep.Ref, dep.Rev) { + return fmt.Errorf( + "flake.lock does not contain the requested pin for %q", + dep.Name, + ) + } + return nil + } + if err := check(input); err != nil { + return nil, err + } + for _, dep := range deps { + if err := check(dep); err != nil { + return nil, err + } + } + return lockedRegistration(ctx, rt.root, input.Name) +} + +func lockedRegistration(ctx context.Context, root, id string) (map[string]any, error) { + state, err := lockedModuleState(ctx, root) + if err != nil { + return nil, err + } + module, err := findModule(state, id) + if err != nil { + if connect.CodeOf(err) == connect.CodeNotFound { + return nil, fmt.Errorf("locked input %q does not register the catalog module", id) + } + return nil, err + } + // The catalog is the list of inputs the consumer agreed to add. A stale + // listing must not silently install a module whose requirements are unmet. + if missing := module["missingFlakeInputs"]; missing != nil { + inputs, ok := missing.([]any) + if !ok || len(inputs) != 0 { + return nil, fmt.Errorf( + "locked module %q still requires flake inputs; check its registry version's flakeInputs", + id, + ) + } + } + return module, nil +} + +type registryOperation struct { + rt *projectRuntime + view *registryView + module *registry.Module +} + +func (s *moduleService) mutateRegistry( + ctx context.Context, + id string, + lockedView bool, + apply func(context.Context, registryOperation) error, +) (string, error) { + rt := runtimeFor(ctx) + if rt == nil || rt.store == nil { + return "", invalidModuleState("no project config store") + } + rt.moduleMu.Lock() + defer rt.moduleMu.Unlock() + var slug string + err := flakeedit.WithModuleProject(ctx, rt.root, func(ctx context.Context) error { + project := rt + if lockedView { + // Resolve removal against installed sources, not an authoring + // override (which itself might no longer evaluate). + project = &projectRuntime{ + root: rt.root, + evalModuleState: nixeval.EvalLockedModuleState, + } + } + view, err := s.loadRegistry(ctx, project) + if err != nil { + return err + } + m, err := view.lookup(id) + if err != nil { + return err + } + slug = m.Slug + return apply(ctx, registryOperation{rt: rt, view: view, module: m}) + }) + if err != nil { + if ctx.Err() != nil { + return "", moduleEvalError(ctx, err) + } + var rpcError *connect.Error + if errors.As(err, &rpcError) { + return "", err + } + return "", connect.NewError(connect.CodeFailedPrecondition, err) + } + if rt.flake != nil { + rt.flake.InvalidateAll() + } + return slug, nil +} + +func (s *moduleService) InstallModule( + ctx context.Context, + req *connect.Request[agentv1.InstallModuleRequest], +) (*connect.Response[agentv1.InstallModuleResponse], error) { + slug, err := s.mutateRegistry( + ctx, + req.Msg.ModuleId, + false, + func(ctx context.Context, op registryOperation) error { + return op.applyVersion(ctx, req.Msg.Version, req.Msg.Ref, false) + }, + ) + if err != nil { + return nil, err + } + return connect.NewResponse( + &agentv1.InstallModuleResponse{ + ModuleId: slug, + Message: "Installed " + slug + "; preview before enabling it", + }, + ), nil +} + +func (s *moduleService) UpdateModule( + ctx context.Context, + req *connect.Request[agentv1.UpdateModuleRequest], +) (*connect.Response[agentv1.UpdateModuleResponse], error) { + slug, err := s.mutateRegistry( + ctx, + req.Msg.ModuleId, + false, + func(ctx context.Context, op registryOperation) error { + return op.applyVersion(ctx, req.Msg.Version, req.Msg.Ref, true) + }, + ) + if err != nil { + return nil, err + } + return connect.NewResponse( + &agentv1.UpdateModuleResponse{Message: "Updated " + slug}, + ), nil +} + +func (op registryOperation) applyVersion( + ctx context.Context, + version, ref string, + update bool, +) error { + m, rt, view := op.module, op.rt, op.view + v, input, deps, err := registrySelection(m, version, ref) + if err != nil { + return err + } + if auto, ok := view.state["autoImportInputs"].(bool); ok { + input.ExplicitImport = !auto + } + if update { + previous, err := installedRelease(view.lock, m) + if err != nil { + return err + } + input.PreviousURL = previous.FlakeURL + if err := op.authorizeDependencyUpdates(previous, deps); err != nil { + return err + } + validate := func() error { + _, err := op.validateInstall(ctx, input, deps) + return err + } + return flakeedit.UpdateModuleWithImports( + ctx, + rt.root, + input, + previous.FlakePath, + v.FlakePath, + deps, + validate, + ) + } + if _, exists, err := view.lock.input(m.Slug); err != nil { + return err + } else if exists { + return connect.NewError( + connect.CodeAlreadyExists, + fmt.Errorf("project already has a locked input %q", m.Slug), + ) + } + if _, err := findModule(view.state, m.Slug); err == nil { + return connect.NewError( + connect.CodeAlreadyExists, + fmt.Errorf("project already defines module %q", m.Slug), + ) + } else if connect.CodeOf(err) != connect.CodeNotFound { + return err + } + // Discovered modules can default to enabled. Defer adoption even for + // these modules, without changing defaults for manual flake consumers. + var undo func() error + err = flakeedit.InstallModule(ctx, rt.root, input, v.FlakePath, deps, func() error { + module, err := op.validateInstall(ctx, input, deps) + if err != nil { + return err + } + enabled, ok := module["enabled"].(bool) + if !ok { + return fmt.Errorf("module %q does not declare its enabled state", m.Slug) + } + if !enabled { + return nil + } + path, err := moduleOptionPath(module, "enablePath") + if err != nil { + return err + } + undo, err = rt.store.PatchModuleDataReversible(path, false) + if err != nil { + return err + } + module, err = lockedRegistration(ctx, rt.root, m.Slug) + if err != nil { + return err + } + if module["enabled"] != false { + return fmt.Errorf( + "could not install %q in a disabled state; check its declared enablePath", + m.Slug, + ) + } + return nil + }) + if err != nil && undo != nil { + return errors.Join(err, undo()) + } + return err +} + +func (s *moduleService) UninstallModule( + ctx context.Context, + req *connect.Request[agentv1.UninstallModuleRequest], +) (*connect.Response[agentv1.UninstallModuleResponse], error) { + slug, err := s.mutateRegistry( + ctx, + req.Msg.ModuleId, + true, + func(ctx context.Context, op registryOperation) error { return op.uninstall(ctx) }, + ) + if err != nil { + return nil, err + } + return connect.NewResponse( + &agentv1.UninstallModuleResponse{Message: "Uninstalled " + slug}, + ), nil +} + +func (op registryOperation) uninstall(ctx context.Context) error { + m, rt, view := op.module, op.rt, op.view + links, err := userconfig.LoadLinkedModules(rt.root) + if err != nil { + return err + } + if _, linked := links[m.Slug]; linked { + return fmt.Errorf( + "module %q is linked in this project; run `stack module unlink %s` before uninstalling", + m.Slug, + m.Slug, + ) + } + previous, err := installedRelease(view.lock, m) + if err != nil { + return err + } + module, err := findModule(view.state, m.Slug) + if err != nil { + return err + } + // Setting enable=false alone would leave an unknown option behind once + // the declaring module disappears. Remove both persisted option roots. + paths := [][]string{{"modules", m.Slug}} + for _, field := range []string{"enablePath", "configPath"} { + path, err := moduleOptionPath(module, field) + if err != nil { + return err + } + if path[0] == "modules" { + continue // own namespace is already removed as a unit + } + if field == "enablePath" || slices.Contains(path, m.Slug) { + paths = append(paths, path) + continue + } + // A module's configPath can be a shared namespace. Remove only the + // settings declared by the module, not adjacent user data. + settings, _ := module["settings"].(map[string]any) + for key := range settings { + paths = append(paths, append(slices.Clip(path), key)) + } + } + rollback, err := rt.store.RemoveModuleData(paths) + if err != nil { + return err + } + input := flakeedit.FlakeInput{Name: m.Slug, URL: previous.FlakeURL} + err = flakeedit.UninstallRegistryModule( + ctx, + rt.root, + input, + previous.FlakePath, + func() error { + lock, err := readRegistryLock(rt.root) + if err != nil { + return err + } + if err := op.checkDependents(lock); err != nil { + return err + } + if _, exists, err := lock.input(m.Slug); err != nil { + return err + } else if exists { + return fmt.Errorf("removed input %q is still in flake.lock", m.Slug) + } + // User-written .nix files can still refer to this module, including + // app-specific options. Refuse removal rather than editing arbitrary + // files or leaving the project in a state it cannot evaluate. + state, err := lockedModuleState(ctx, rt.root) + if err != nil { + return err + } + _, err = findModule(state, m.Slug) + if connect.CodeOf(err) == connect.CodeNotFound { + return nil + } + if err == nil { + return fmt.Errorf( + "project still defines module %q after removing its input", + m.Slug, + ) + } + return err + }, + ) + if err != nil { + return errors.Join(err, rollback()) + } + return nil +} diff --git a/apps/stackpanel-go/internal/agent/server/registry_lock.go b/apps/stackpanel-go/internal/agent/server/registry_lock.go new file mode 100644 index 00000000..780fb254 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/registry_lock.go @@ -0,0 +1,519 @@ +package server + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "net/url" + "os" + "path/filepath" + "strings" + + "github.com/darkmatter/stackpanel/stackpanel-go/internal/flakeedit" +) + +// Node keys are local to a lock file. Only a direct edge in the designated +// root's inputs can establish ownership of a catalog slug. +type registryLock struct { + root *registryLockNode + nodes map[string]*registryLockNode +} + +type registryLockNode struct { + inputs map[string]any + input registryLockedInput +} + +type registryLockedInput struct { + root, name string + original registryReference + lockedRev string +} + +type registryReference struct { + source registrySource + ref, rev string +} + +type registrySource struct { + kind string + location string // forge host, full transport URL, or absolute filesystem path + owner string + repo string + dir string // flake subdirectory within the fetched tree +} + +func readRegistryLock(root string) (*registryLock, error) { + if root == "" { + return nil, errors.New("cannot read flake.lock without a project root") + } + root, err := filepath.Abs(root) + if err != nil { + return nil, err + } + path := filepath.Join(root, "flake.lock") + info, err := os.Lstat(path) + if errors.Is(err, fs.ErrNotExist) { + return ®istryLock{root: ®istryLockNode{}}, nil + } + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, errors.New("flake.lock must be a regular project file") + } + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var doc map[string]any + if err := json.Unmarshal(data, &doc); err != nil { + return nil, fmt.Errorf("decode flake.lock: %w", err) + } + // v5 and earlier separate the lock evidence across different fields. + if v := doc["version"]; v != float64(6) && v != float64(7) { + return nil, errors.New("flake.lock: missing or unsupported lock file version") + } + rootKey, _ := doc["root"].(string) + nodes, _ := doc["nodes"].(map[string]any) + if rootKey == "" || nodes[rootKey] == nil { + return nil, fmt.Errorf("flake.lock: missing root node %q", rootKey) + } + lock := ®istryLock{nodes: make(map[string]*registryLockNode, len(nodes))} + for key, raw := range nodes { + fields, ok := raw.(map[string]any) + if !ok || key == "" { + return nil, fmt.Errorf("flake.lock: invalid node %q", key) + } + n := new(registryLockNode) + if rawInputs, exists := fields["inputs"]; exists { + if n.inputs, ok = rawInputs.(map[string]any); !ok { + return nil, fmt.Errorf("flake.lock: node %q inputs must be an object", key) + } + } + lock.nodes[key] = n + if key == rootKey { + _, orig := fields["original"] + if _, locked := fields["locked"]; orig || locked { + return nil, fmt.Errorf("flake.lock: root node %q has source attributes", key) + } + lock.root = n + continue + } + n.input, err = registryNodeInput(root, fields) + if err != nil { + return nil, fmt.Errorf("flake.lock: node %q: %w", key, err) + } + } + // A dangling edge anywhere in the graph invalidates it as installation + // evidence, even when that edge isn't itself the requested module. + seen := make(map[registryLockEdge]*registryLockNode) + for key, n := range lock.nodes { + for name := range n.inputs { + if name == "" { + return nil, fmt.Errorf("flake.lock: empty input name in node %q", key) + } + if _, err := lock.resolve(n, name, seen); err != nil { + return nil, fmt.Errorf("node %q: %w", key, err) + } + } + } + return lock, nil +} + +func registryNodeInput(root string, node map[string]any) (registryLockedInput, error) { + original, err := registryAttrs(root, node["original"], false) + if err != nil { + return registryLockedInput{}, fmt.Errorf("original: %w", err) + } + locked, err := registryAttrs(root, node["locked"], true) + if err != nil { + return registryLockedInput{}, fmt.Errorf("locked: %w", err) + } + if raw, ok := node["flake"]; ok { + flake, ok := raw.(bool) + if !ok { + return registryLockedInput{}, errors.New("flake must be a boolean") + } + if !flake { + return registryLockedInput{}, nil + } + } + if raw, ok := node["parent"]; ok { + parent, ok := raw.([]any) + if !ok { + return registryLockedInput{}, errors.New("parent must be an input path") + } + for _, part := range parent { + if s, ok := part.(string); !ok || s == "" { + return registryLockedInput{}, errors.New("invalid parent input path") + } + } + // Relative path inputs of another flake are not project-relative. + if len(parent) != 0 { + return registryLockedInput{}, nil + } + } + // An override can preserve the original URL while locking a different + // source. Neither source then proves catalog ownership of the binding. + if original.source != locked.source { + return registryLockedInput{}, nil + } + return registryLockedInput{root: root, original: original, lockedRev: locked.rev}, nil +} + +// input distinguishes an unbound name from an occupied but non-matching name +// (including follows). A broken edge is never evidence that a name is free. +func (l *registryLock) input(name string) (registryLockedInput, bool, error) { + edge, exists := l.root.inputs[name] + if !exists { + return registryLockedInput{}, false, nil + } + if _, direct := edge.(string); !direct { + return registryLockedInput{}, true, nil // Validated follows; not a declaration. + } + node, err := l.resolve(l.root, name, nil) + if err != nil { + return registryLockedInput{}, true, err + } + n := node.input + n.name = name + return n, true, nil +} + +type registryLockEdge struct { + from *registryLockNode + name string +} + +// A follows edge contains an input-name path starting at the lock root, not +// a list of node keys. Memoize expansions; a pending edge is a follows cycle. +func (l *registryLock) resolve( + from *registryLockNode, + name string, + seen map[registryLockEdge]*registryLockNode, +) (*registryLockNode, error) { + switch edge := from.inputs[name].(type) { + case string: + n := l.nodes[edge] + if n == nil || n == l.root { + return nil, fmt.Errorf( + "flake.lock: input %q points to invalid node %q", + name, + edge, + ) + } + return n, nil + case []any: + key := registryLockEdge{from, name} + if n, ok := seen[key]; ok { + if n == nil { + return nil, fmt.Errorf("flake.lock: follows cycle at input %q", name) + } + return n, nil + } + if seen == nil { + seen = make(map[registryLockEdge]*registryLockNode) + } + seen[key] = nil + n := l.root + for _, part := range edge { + s, ok := part.(string) + if !ok || s == "" { + return nil, fmt.Errorf("flake.lock: malformed follows path for %q", name) + } + var err error + n, err = l.resolve(n, s, seen) + if err != nil { + return nil, err + } + } + seen[key] = n + return n, nil + default: + return nil, fmt.Errorf("flake.lock: missing or invalid input binding %q", name) + } +} + +// registryAttrs recognizes only fetchers and source fields whose meaning we +// know. Additional fetcher options can change the tree (e.g. submodules or +// lfs); their presence makes a binding unmatchable, not available to install. +func registryAttrs(root string, raw any, locked bool) (registryReference, error) { + a, _ := raw.(map[string]any) + kind, _ := a["type"].(string) + if kind == "" { + return registryReference{}, errors.New("missing source type") + } + str := func(key string) string { + s, _ := a[key].(string) + return s + } + supported := true + for key, val := range a { + s, isString := val.(string) + switch key { + case "type": + continue + case "host", "owner", "repo": + supported = supported && registryForge(kind) + case "url": + supported = supported && (kind == "git" || kind == "tarball") + case "path": + supported = supported && kind == "path" + case "ref", "rev", "dir": + // Projected below, after checking their types. + case "lastModified", "revCount": + n, ok := val.(float64) + if !ok || n < 0 || n != float64(uint64(n)) { + return registryReference{}, fmt.Errorf("invalid %s attribute", key) + } + supported = supported && locked + continue + case "narHash", "treeHash": + // Locked result metadata isn't a different repository. On the + // original input, however, these are explicit constraints. + supported = supported && locked + default: + supported = false + continue + } + if !isString || s == "" { + return registryReference{}, fmt.Errorf("invalid %s attribute", key) + } + } + r := registryReference{ + source: registrySource{kind: kind, dir: str("dir")}, + ref: str("ref"), + rev: strings.ToLower(str("rev")), + } + if registryForge(kind) || kind == "git" { + if r.rev != "" && !registryCommit(r.rev) { + return registryReference{}, errors.New("invalid commit hash") + } + if locked && r.rev == "" && str("narHash") == "" { + return registryReference{}, errors.New( + "locked repository has neither rev nor narHash", + ) + } + } + switch kind { + case "github", "gitlab", "sourcehut": + if r.ref != "" && r.rev != "" { + return registryReference{}, errors.New("forge input has both ref and rev") + } + r.source.owner, r.source.repo = str("owner"), str("repo") + if r.source.owner == "" || r.source.repo == "" { + return registryReference{}, errors.New("missing forge owner or repo") + } + r.source.location = registryForgeHost(kind, str("host")) + if strings.Trim(r.source.location, "abcdefghijklmnopqrstuvwxyz0123456789.-") != "" { + return registryReference{}, errors.New("invalid forge host") + } + case "path": + address := str("path") + if address == "" { + return registryReference{}, errors.New("missing path") + } + if locked && filepath.IsAbs(address) && str("narHash") == "" { + return registryReference{}, errors.New("locked absolute path has no narHash") + } + r.source.location = registryLocalPath(root, address) + case "git", "tarball": + address := str("url") + if address == "" { + return registryReference{}, errors.New("missing URL") + } + if kind == "tarball" && locked && str("narHash") == "" { + return registryReference{}, errors.New("locked tarball has no narHash") + } + u, err := url.Parse(address) + if err != nil { + return registryReference{}, errors.New("malformed source URL") + } + r.source.location = registryTransport(root, kind, u) + default: + supported = false + } + if !supported || r.source.location == "" { + return registryReference{}, nil + } + return r, nil +} + +func registryForge(kind string) bool { + return kind == "github" || kind == "gitlab" || kind == "sourcehut" +} + +func registryForgeHost(kind, host string) string { + if host != "" { + return strings.ToLower(host) + } + if kind == "sourcehut" { + return "git.sr.ht" + } + return kind + ".com" +} + +func registryLocalPath(root, p string) string { + if p == "" || strings.ContainsRune(p, 0) { + return "" + } + if !filepath.IsAbs(p) { + return filepath.Join(root, p) + } + return filepath.Clean(p) +} + +func registryURLPath(u *url.URL) string { + if u.Host != "" || u.User != nil { + return "" + } + // Nix filesystem URL segments cannot contain an encoded separator. + if strings.Contains(strings.ToLower(u.RawPath), "%2f") || + strings.Contains(strings.ToLower(u.Opaque), "%2f") { + return "" + } + if u.Opaque != "" { + p, err := url.PathUnescape(u.Opaque) + if err != nil { + return "" + } + return p + } + return u.Path +} + +func registryTransport(root, kind string, u *url.URL) string { + if u.Fragment != "" || u.RawQuery != "" || u.ForceQuery { + return "" + } + if kind == "git" { + // Nix lock attributes can omit the git+ fetcher prefix. + u.Scheme = strings.TrimPrefix(u.Scheme, "git+") + if u.Scheme == "file" { + if p := registryLocalPath(root, registryURLPath(u)); p != "" { + return "file:" + p + } + return "" + } + if u.Scheme != "ssh" && u.Scheme != "https" && u.Scheme != "http" && + u.Scheme != "git" { + return "" + } + } else if u.Scheme != "https" { + return "" + } + if u.Hostname() == "" || u.Path == "" || u.Path == "/" { + return "" + } + // Preserve the entire remote address, including user, port, and escaped + // repository path. Two remotes on the same host need not be related. + return u.String() +} + +func (n registryLockedInput) catalogRef( + flakeURL, ref, rev string, +) (registryReference, bool) { + if n.original.source.kind == "" { + return registryReference{}, false + } + // Use the editor's effective pin: forge fetchers take only a rev when + // both selectors are specified, while a git fetcher can take both. + input := flakeedit.FlakeInput{Name: n.name, URL: flakeURL, Ref: ref, Rev: rev} + pinned, err := input.PinnedURL() + if err != nil { + return registryReference{}, false + } + u, err := url.Parse(pinned) + if err != nil || u.Fragment != "" { + return registryReference{}, false + } + // Nix query strings percent-decode but do not translate '+' to a space. + q, err := url.ParseQuery(strings.ReplaceAll(u.RawQuery, "+", "%2B")) + if err != nil { + return registryReference{}, false + } + r := registryReference{source: registrySource{kind: u.Scheme}} + for key, values := range q { + if len(values) != 1 || values[0] == "" { + return registryReference{}, false + } + value := values[0] + switch key { + case "dir": + if !fs.ValidPath(value) || strings.ContainsAny(value, "\\\x00") { + return registryReference{}, false + } + r.source.dir = value + case "host": + if !registryForge(u.Scheme) { + return registryReference{}, false + } + r.source.location = value + case "ref", "rev": + if !strings.HasPrefix(u.Scheme, "git+") && u.Scheme != "git" { + return registryReference{}, false + } + if key == "ref" { + r.ref = value + } else { + r.rev = strings.ToLower(value) + } + default: + return registryReference{}, false + } + } + u.RawQuery, u.ForceQuery = "", false + switch u.Scheme { + case "github", "gitlab", "sourcehut": + parts := strings.SplitN(u.Opaque, "/", 3) + if len(parts) < 2 || parts[0] == "" || parts[1] == "" { + return registryReference{}, false + } + r.source.owner, r.source.repo = parts[0], parts[1] + r.source.location = registryForgeHost(u.Scheme, r.source.location) + if len(parts) == 3 { + if registryCommit(parts[2]) { + r.rev = strings.ToLower(parts[2]) + } else { + r.ref = parts[2] + } + } + case "git+file", "git+http", "git+https", "git+ssh", "git": + r.source.kind = "git" + r.source.location = registryTransport(n.root, "git", u) + case "https": + r.source.kind = "tarball" + r.source.location = registryTransport(n.root, "tarball", u) + case "path": + r.source.location = registryLocalPath(n.root, registryURLPath(u)) + case "": + // Bare identifiers are indirect flake registry references, not paths. + p, _, _ := strings.Cut(pinned, "?") + if !filepath.IsAbs(p) && p != "." && p != ".." && !strings.HasPrefix(p, "./") && + !strings.HasPrefix(p, "../") { + return registryReference{}, false + } + r.source.kind = "path" + r.source.location = registryLocalPath(n.root, p) + default: + return registryReference{}, false + } + return r, r.source == n.original.source +} + +func registryCommit(s string) bool { + return len(s) == 40 && strings.Trim(s, "0123456789abcdefABCDEF") == "" +} + +func (n registryLockedInput) matchesSource(flakeURL string) bool { + _, ok := n.catalogRef(flakeURL, "", "") + return ok +} + +func (n registryLockedInput) matchesPin(flakeURL, ref, rev string) bool { + want, ok := n.catalogRef(flakeURL, ref, rev) + return ok && want.ref == n.original.ref && want.rev == n.original.rev && + (want.rev == "" || want.rev == n.lockedRev) +} diff --git a/apps/stackpanel-go/internal/agent/server/registry_lock_test.go b/apps/stackpanel-go/internal/agent/server/registry_lock_test.go new file mode 100644 index 00000000..567c2ec5 --- /dev/null +++ b/apps/stackpanel-go/internal/agent/server/registry_lock_test.go @@ -0,0 +1,136 @@ +package server + +import ( + "fmt" + "os" + "path/filepath" + "testing" +) + +func writeRegistryLockFixture(t *testing.T, root, nodes string) { + t.Helper() + data := `{"version":7,"root":"consumer","nodes":` + nodes + `}` + if err := os.WriteFile( + filepath.Join(root, "flake.lock"), + []byte(data), + 0o600, + ); err != nil { + t.Fatal(err) + } +} + +func TestRegistryLockRootBindings(t *testing.T) { + root := t.TempDir() + lock, err := readRegistryLock(root) + if err != nil { + t.Fatal(err) + } + if _, exists, err := lock.input("rust"); exists || err != nil { + t.Fatalf("missing lock: exists=%v err=%v", exists, err) + } + writeRegistryLockFixture(t, root, `{ + "consumer":{"inputs":{"rust":"registry_2","tools":"registry_2","alias":["tools","module"]}}, + "registry_2":{ + "inputs":{"module":["rust"]}, + "original":{"type":"github","owner":"org","repo":"registry","dir":"modules/rust","ref":"release"}, + "locked":{"type":"github","owner":"org","repo":"registry","dir":"modules/rust","rev":"1111111111111111111111111111111111111111"} + } + }`) + lock, err = readRegistryLock(root) + if err != nil { + t.Fatal(err) + } + const source = "github:org/registry?dir=modules/rust" + rust, exists, err := lock.input("rust") + if !exists || err != nil || !rust.matchesPin(source, "release", "") { + t.Fatalf("direct root input did not match: exists=%v err=%v", exists, err) + } + for _, other := range []string{"github:org/registry", "github:org/registry?dir=modules/go", source + "&host=other.example", source + "&futureOption=1"} { + if rust.matchesSource(other) { + t.Errorf("matched distinct source %q", other) + } + } + alias, exists, err := lock.input("alias") + if !exists || err != nil || alias.matchesSource(source) || + alias.matchesPin(source, "release", "") { + t.Fatalf( + "follows must occupy the name without owning the source: exists=%v err=%v", + exists, + err, + ) + } + if _, exists, err := lock.input("registry_2"); exists || err != nil { + t.Fatalf("node key leaked into root inputs: exists=%v err=%v", exists, err) + } +} + +func TestRegistryLockRejectsBrokenGraph(t *testing.T) { + for _, tc := range []struct{ name, nodes string }{ + {"no root", `{"not-consumer":{}}`}, + {"null inputs", `{"consumer":{"inputs":null}}`}, + {"missing node", `{"consumer":{"inputs":{"slug":"absent"}}}`}, + {"missing locked", `{"consumer":{"inputs":{"slug":"x"}},"x":{"original":{"type":"path","path":"./mod"}}}`}, + {"incomplete repository", `{"consumer":{"inputs":{"slug":"x"}},"x":{"original":{"type":"github","owner":"org"},"locked":{"type":"github","owner":"org"}}}`}, + {"broken follows", `{"consumer":{"inputs":{"slug":["not-bound"]}}}`}, + {"malformed follows", `{"consumer":{"inputs":{"slug":[null]}}}`}, + {"cyclic follows", `{"consumer":{"inputs":{"slug":["alias"],"alias":["slug"]}}}`}, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + writeRegistryLockFixture(t, root, tc.nodes) + lock, err := readRegistryLock(root) + if err == nil { + _, exists, lookupErr := lock.input("slug") + if !exists || lookupErr == nil { + t.Fatalf("broken graph reported exists=%v err=%v", exists, lookupErr) + } + } + }) + } +} + +func TestRegistryLockPolicyAndTransport(t *testing.T) { + const rev = "0123456789abcdef0123456789abcdef01234567" + const otherRev = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + const forge = `"type":"gitlab","host":"forge.example","owner":"o","repo":"r"` + const ssh = `"type":"git","url":"ssh://alice@git.example:2222/team/r.git"` + root := t.TempDir() + local := filepath.Join(root, "vendor", "module") + for _, tc := range []struct { + name, original, locked, url, ref, rev string + sourceMatch, pinMatch bool + }{ + {"forge rev wins over ref", forge + `,"rev":"` + rev + `"`, forge + `,"rev":"` + rev + `"`, "gitlab:o/r?host=forge.example", "release", rev, true, true}, + {"locked commit alone is not a declared pin", forge + `,"ref":"release"`, forge + `,"rev":"` + rev + `"`, "gitlab:o/r?host=forge.example", "release", rev, true, false}, + {"declared commit alone is not a locked pin", forge + `,"rev":"` + rev + `"`, forge + `,"rev":"` + otherRev + `"`, "gitlab:o/r/" + rev + "?host=forge.example", "", "", true, false}, + {"git retains both selectors", ssh + `,"ref":"releases/v1","rev":"` + rev + `"`, ssh + `,"rev":"` + rev + `"`, "git+ssh://alice@git.example:2222/team/r.git", "releases/v1", rev, true, true}, + {"locked ref is not the declaration", ssh, ssh + `,"ref":"main","rev":"` + rev + `"`, "git+ssh://alice@git.example:2222/team/r.git", "main", "", true, false}, + {"same host different repository", ssh, ssh + `,"rev":"` + rev + `"`, "git+ssh://alice@git.example:2222/team/s.git", "", "", false, false}, + {"overridden locked URL", ssh, `"type":"git","url":"file:///different","rev":"` + rev + `"`, "git+ssh://alice@git.example:2222/team/r.git", "", "", false, false}, + {"different git tree options", ssh + `,"submodules":true`, ssh + `,"submodules":true,"rev":"` + rev + `"`, "git+ssh://alice@git.example:2222/team/r.git", "", "", false, false}, + {"path relative to lock root", `"type":"path","path":"./vendor/module","dir":"nested"`, fmt.Sprintf(`"type":"path","path":%q,"dir":"nested","narHash":"sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="`, local), "path:vendor/module?dir=nested", "", "", true, true}, + {"git file resolves relative to project", `"type":"git","url":"file:./vendor/module"`, fmt.Sprintf(`"type":"git","url":"file://%s","rev":"%s"`, local, rev), "git+file://" + local, "", "", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + writeRegistryLockFixture( + t, + root, + `{"consumer":{"inputs":{"mod":"node"}},"node":{"original":{`+tc.original+`},"locked":{`+tc.locked+`}}}`, + ) + lock, err := readRegistryLock(root) + if err != nil { + t.Fatal(err) + } + n, exists, err := lock.input("mod") + if !exists || err != nil { + t.Fatalf("exists=%v err=%v", exists, err) + } + if got := n.matchesSource(tc.url); got != tc.sourceMatch { + t.Errorf("source match = %v, want %v", got, tc.sourceMatch) + } + if got := n.matchesPin(tc.url, tc.ref, tc.rev); got != tc.pinMatch { + t.Errorf("pin match = %v, want %v", got, tc.pinMatch) + } + }) + } +} diff --git a/apps/stackpanel-go/internal/agent/server/runtime.go b/apps/stackpanel-go/internal/agent/server/runtime.go index b95aa729..76160357 100644 --- a/apps/stackpanel-go/internal/agent/server/runtime.go +++ b/apps/stackpanel-go/internal/agent/server/runtime.go @@ -1,6 +1,7 @@ package server import ( + "context" "fmt" "path/filepath" "sync" @@ -25,10 +26,12 @@ const runtimeIdleTimeout = 10 * time.Minute // handlers and the v1 per-request handlers share the same instances instead // of racing each other with duplicates (ADR 0005). type projectRuntime struct { - root string - exec *sharedexec.Executor - store *nixdata.Store - shell *ShellManager + root string + exec *sharedexec.Executor + store *nixdata.Store + shell *ShellManager + moduleMu sync.Mutex // Serialize module config and registry lifecycle mutations. + evalModuleState func(context.Context, string) ([]byte, error) // nil uses the pure project flake // Watchers run only while the server is serving; see startWatching. flake *FlakeWatcher @@ -143,19 +146,27 @@ func (s *Server) createRuntime(root string) (*projectRuntime, error) { Bool("in_devshell", exec.InDevshell()). Bool("has_devshell_env", exec.HasDevshellEnv()). Msg("Executor initialized with devshell support") + return s.newProjectRuntime(root, exec), nil +} +func (s *Server) newProjectRuntime( + root string, + exec *sharedexec.Executor, +) *projectRuntime { return &projectRuntime{ root: root, exec: exec, store: nixdata.NewStore(root, exec), shell: NewShellManager(root, s), - }, nil + } } // watchRuntime starts live evaluation of the project's flake and the // config-file watcher that drives config.changed events. func (s *Server) watchRuntime(rt *projectRuntime) error { - fw, err := NewFlakeWatcher(FlakeWatcherConfig{ProjectRoot: rt.root, Server: s}) + fw, err := NewFlakeWatcher( + FlakeWatcherConfig{ProjectRoot: rt.root, Server: s, Shell: rt.shell}, + ) if err != nil { return fmt.Errorf("create flake watcher: %w", err) } @@ -194,7 +205,10 @@ func watchConfigFiles(w *fsnotify.Watcher, root string, broadcast func(SSEEvent) for _, dir := range []string{"profile", "state", "gen", "data"} { path := filepath.Join(root, ".stack", dir) if err := w.Add(path); err != nil { - log.Debug().Err(err).Str("path", path).Msg("not watching config directory (may not exist yet)") + log.Debug(). + Err(err). + Str("path", path). + Msg("not watching config directory (may not exist yet)") } } @@ -216,8 +230,9 @@ func watchConfigFiles(w *fsnotify.Watcher, root string, broadcast func(SSEEvent) timer = time.AfterFunc(debounce, func() { log.Debug().Str("file", name).Msg("config file changed, broadcasting") broadcast(SSEEvent{ - Event: "config.changed", - Data: map[string]string{"file": name}, + ProjectRoot: root, + Event: "config.changed", + Data: map[string]string{"file": name}, }) }) case err, ok := <-w.Errors: diff --git a/apps/stackpanel-go/internal/agent/server/secrets_integration_test.go b/apps/stackpanel-go/internal/agent/server/secrets_integration_test.go index ce7952ff..d6102099 100644 --- a/apps/stackpanel-go/internal/agent/server/secrets_integration_test.go +++ b/apps/stackpanel-go/internal/agent/server/secrets_integration_test.go @@ -83,7 +83,7 @@ func writeFakeNixFixture(t *testing.T, workingDir string) { script := `#!/usr/bin/env bash set -euo pipefail -if [[ "$1" == "eval" && "$2" == "--impure" && "$3" == "--json" && "$4" == ".#stackpanelFullConfig.serializable.secrets" ]]; then +if [[ "$1" == "eval" && "$2" == "--json" && "$3" == ".#stackpanelFullConfig.serializable.secrets" && "$4" == "--no-write-lock-file" ]]; then cat <<'JSON' ` + fakeSerializableSecretsJSON + ` JSON diff --git a/apps/stackpanel-go/internal/agent/server/server.go b/apps/stackpanel-go/internal/agent/server/server.go index 59ce6c24..cd1292bb 100644 --- a/apps/stackpanel-go/internal/agent/server/server.go +++ b/apps/stackpanel-go/internal/agent/server/server.go @@ -39,10 +39,11 @@ type Server struct { jwtManager *JWTManager pairTemplate *template.Template // HTML page served at /pair for the browser popup auth flow + pairReturns pairReturnStore // sseSubscribers tracks all active SSE connections. Each subscriber gets a // buffered channel; slow consumers are dropped (non-blocking send). - sseSubscribers map[chan SSEEvent]struct{} + sseSubscribers map[chan SSEEvent]sseScope sseSubscribersMu sync.RWMutex // runtimes owns every project's executor, store, shell manager and file @@ -139,7 +140,7 @@ func New(cfg *config.Config) (*Server, error) { projectMgr: projectMgr, jwtManager: jwtMgr, pairTemplate: pairTmpl, - sseSubscribers: make(map[chan SSEEvent]struct{}), + sseSubscribers: make(map[chan SSEEvent]sseScope), done: make(chan struct{}), } s.runtimes = newRuntimeRegistry(s) @@ -164,6 +165,7 @@ func New(cfg *config.Config) (*Server, error) { "/pair", s.handlePair, ) // No CORS — served as a standalone page in a popup + mux.HandleFunc("/pair/redeem", s.withCORS(s.handlePairRedeem)) mux.HandleFunc("/studio", s.handleStudio) mux.HandleFunc("/api/setup/ready", s.withCORS(s.requireAuth(s.handleSetupReady))) @@ -414,20 +416,6 @@ func New(cfg *config.Config) (*Server, error) { s.withCORS(s.requireAuth(s.requireProject(s.handleHealthchecks))), ) - // Modules endpoint for the module browser - mux.HandleFunc( - "/api/modules", - s.withCORS(s.requireAuth(s.requireProject(s.handleModules))), - ) - mux.HandleFunc( - "/api/modules/", - s.withCORS(s.requireAuth(s.requireProject(s.handleModules))), - ) - - // Module registry endpoint for browsing and installing external modules - mux.HandleFunc("/api/registry", s.withCORS(s.requireAuth(s.handleRegistry))) - mux.HandleFunc("/api/registry/", s.withCORS(s.requireAuth(s.handleRegistry))) - // Connect-RPC: proto-generated typed API that runs alongside the REST endpoints. // The web UI uses this via @connectrpc/connect-web for type-safe RPC calls. agentService := NewAgentServiceServer(s) @@ -437,13 +425,14 @@ func New(cfg *config.Config) (*Server, error) { // v1 Connect services (ADR 0004). They replace the REST endpoints and the // AgentService above one domain at a time. s.mountV1(mux) + s.mountModuleCapabilities(mux) // SSE endpoint for real-time config updates mux.HandleFunc("/api/events", s.withCORS(s.requireAuth(s.handleSSE))) s.httpServer = &http.Server{ Addr: fmt.Sprintf("%s:%d", cfg.BindAddress, cfg.Port), - Handler: s.withLogging(mux.ServeHTTP), + Handler: s.withLogging(guardModuleCapabilityPaths(mux.ServeHTTP)), } projectInfo := cfg.ProjectRoot diff --git a/apps/stackpanel-go/internal/agent/server/server_test.go b/apps/stackpanel-go/internal/agent/server/server_test.go index 6d9a8991..42c9509a 100644 --- a/apps/stackpanel-go/internal/agent/server/server_test.go +++ b/apps/stackpanel-go/internal/agent/server/server_test.go @@ -3,6 +3,7 @@ package server import ( "net/http" "net/http/httptest" + "net/url" "strings" "testing" @@ -36,6 +37,23 @@ func TestHandleHealth(t *testing.T) { } } +func TestModulesAreNotADataEntity(t *testing.T) { + s := &Server{} + for _, tc := range []struct{ method, query, body string }{ + {"GET", "?entity=modules", ""}, + {"GET", "?entity=external-modules", ""}, + {"POST", "", `{"entity":"modules","data":{}}`}, + {"POST", "", `{"entity":"modules","key":"db","delete":true}`}, + {"DELETE", "?entity=modules", ""}, + } { + w := httptest.NewRecorder() + s.handleNixData(w, httptest.NewRequest(tc.method, "/api/nix/data"+tc.query, strings.NewReader(tc.body))) + if w.Code != http.StatusBadRequest { + t.Errorf("%s %s: expected unsupported entity, got %d", tc.method, tc.query, w.Code) + } + } +} + func TestHandlePairIncludesNoOpenerRedirectFallback(t *testing.T) { tempDir := t.TempDir() cfg := &config.Config{ @@ -50,7 +68,20 @@ func TestHandlePairIncludesNoOpenerRedirectFallback(t *testing.T) { } rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/pair?origin=http://localhost:3001", nil) + state := strings.Repeat("ab", 32) + verifier := strings.Repeat("cd", 32) + form := url.Values{ + "state": {state}, + "verifier": {verifier}, + "return_to": {"http://localhost:3001/studio/m/demo?project=p&token=secret#private"}, + } + req := httptest.NewRequest( + http.MethodPost, + "/pair?origin=https://elsewhere.example", + strings.NewReader(form.Encode()), + ) + req.Header.Set("Origin", "http://localhost:3001") + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") srv.handlePair(rec, req) if rec.Code != http.StatusOK { @@ -59,12 +90,82 @@ func TestHandlePairIncludesNoOpenerRedirectFallback(t *testing.T) { body := rec.Body.String() for _, want := range []string{ - "stackpanel_agent_token", + "stackpanel_pair_code: code", "window.location.replace", - "targetOrigin", + "const targetOrigin = \"http://localhost:3001\"", + "const returnUrl = \"http://localhost:3001/studio/m/demo?project=p\"", + "const state = \"" + state + "\"", + "stackpanel_pair_state: state", + "window.opener.postMessage", } { if !strings.Contains(body, want) { - t.Fatalf("expected pair page to contain %q fallback, got: %s", want, body) + t.Fatalf("expected pair page to contain %q", want) + } + } + if strings.Contains(body, "stackpanel_agent_token") || + strings.Contains(body, verifier) || + strings.Contains(body, "secret") || + strings.Contains(body, "#private") || + strings.Contains(body, "elsewhere.example") { + t.Fatal("approval page propagated untrusted recipient or legacy URL credential") + } +} + +func TestPairRequiresBrowserOriginAndPostedState(t *testing.T) { + s := &Server{config: &config.Config{}} + state := strings.Repeat("ab", 32) + for _, tc := range []struct { + name, method, origin, form string + want int + }{ + {"GET", "GET", "http://localhost:3001", "", 403}, + {"missing Origin", "POST", "", "state=" + state, 403}, + {"opaque Origin", "POST", "null", "state=" + state, 403}, + {"disallowed Origin", "POST", "https://other.example", "state=" + state, 403}, + {"path is not an origin", "POST", "http://localhost:3001/path", "state=" + state, 403}, + {"receiving agent origin (canonical host and effective port)", "POST", "http://localhost", "state=" + state, 403}, + {"no posted state", "POST", "http://localhost:3001", "", 400}, + {"invalid state", "POST", "http://localhost:3001", "state=invalid", 400}, + } { + r := httptest.NewRequest( + tc.method, + "/pair?origin=http://localhost:3001&state="+state, + strings.NewReader(tc.form), + ) + r.Host = "LOCALHOST:80" + r.Header.Set("Origin", tc.origin) + r.Header.Set("Referer", "http://localhost:3001/studio") + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + s.handlePair(w, r) + if w.Code != tc.want { + t.Errorf("%s: got %d, want %d", tc.name, w.Code, tc.want) + } + } +} + +func TestPairRejectsAgentAsItsOwnPeer(t *testing.T) { + const agent = "http://localhost:9876" + r := httptest.NewRequest( + http.MethodPost, + agent+"/pair", + strings.NewReader("state="+strings.Repeat("a", 64)), + ) + r.Header.Set("Origin", agent) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r.Header.Set("Sec-Fetch-Site", "same-origin") + w := httptest.NewRecorder() + (&Server{}).handlePair(w, r) + if w.Code != http.StatusForbidden { + t.Fatal("agent must not be its own pairing peer") + } +} + +func TestPairReturnURLCannotChangeRecipients(t *testing.T) { + const origin = "http://localhost:3001" + for _, invalid := range []string{"//other.example/studio", "http://127.0.0.1:3001/studio", origin + "0/studio", "http://user@localhost:3001/studio", origin + "/outside"} { + if got := pairReturnURL(invalid, origin); got != origin+"/studio" { + t.Errorf("invalid return address %q accepted", invalid) } } } diff --git a/apps/stackpanel-go/internal/agent/server/setup_session.go b/apps/stackpanel-go/internal/agent/server/setup_session.go index 8365ac30..9a78d806 100644 --- a/apps/stackpanel-go/internal/agent/server/setup_session.go +++ b/apps/stackpanel-go/internal/agent/server/setup_session.go @@ -11,15 +11,24 @@ import ( "time" "github.com/darkmatter/stackpanel/stackpanel-go/internal/setupsession" + "github.com/darkmatter/stackpanel/stackpanel-go/pkg/nixeval" "github.com/darkmatter/stackpanel/stackpanel-go/pkg/userconfig" ) -func (s *Server) validateSetupRequest(r *http.Request, id string) (setupsession.Session, error) { +func (s *Server) validateSetupRequest( + r *http.Request, + id string, +) (setupsession.Session, error) { session, err := setupsession.Load(id) if err != nil { return session, err } - if err := setupsession.ValidateBrowser(session, s.jwtManager.GetAgentID(), r.Header.Get("Origin"), r.URL.Query().Get("project")); err != nil { + if err := setupsession.ValidateBrowser( + session, + s.jwtManager.GetAgentID(), + r.Header.Get("Origin"), + r.URL.Query().Get("project"), + ); err != nil { return session, err } if filepath.Clean(s.config.ProjectRoot) != session.Root { @@ -48,13 +57,19 @@ func (s *Server) handleSetupReady(w http.ResponseWriter, r *http.Request) { var body struct { Session string `json:"session"` } - if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&body); err != nil { + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)). + Decode(&body); err != nil { s.writeAPIError(w, http.StatusBadRequest, "invalid setup acknowledgement") return } session, err := s.validateSetupRequest(r, body.Session) if err == nil { - err = setupsession.RecordReady(body.Session, s.jwtManager.GetAgentID(), r.Header.Get("Origin"), session.ProjectID) + err = setupsession.RecordReady( + body.Session, + s.jwtManager.GetAgentID(), + r.Header.Get("Origin"), + session.ProjectID, + ) } if err != nil { s.writeAPIError(w, http.StatusConflict, err.Error()) @@ -64,15 +79,39 @@ func (s *Server) handleSetupReady(w http.ResponseWriter, r *http.Request) { } func (s *Server) handleStudio(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + w.WriteHeader(http.StatusMethodNotAllowed) + return + } u, _ := url.Parse(setupsession.DefaultStudioURL) - q := u.Query() - for _, key := range []string{"project", "setup", "agent"} { - if value := r.URL.Query().Get(key); value != "" { + u.RawQuery = studioHandoff(r.URL.Query()).Encode() + // Without an explicit fragment, browsers inherit the source fragment + // across redirects (including an unsolicited legacy pairing payload). + w.Header().Set("Referrer-Policy", "no-referrer") + http.Redirect(w, r, u.String()+"#", http.StatusTemporaryRedirect) +} + +// Forward routing hints, never a caller-supplied credential or arbitrary URL. +// CLI setup and module preview links select a loopback HTTP agent. +func studioHandoff(params url.Values) url.Values { + q := url.Values{} + for _, key := range []string{"project", "setup"} { + if value := params.Get(key); value != "" { q.Set(key, value) } } - u.RawQuery = q.Encode() - http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect) + if agent, err := url.Parse( + params.Get("agent"), + ); err == nil && agent.Scheme == "http" && agent.User == nil && + (agent.Path == "" || agent.Path == "/") && agent.RawQuery == "" && + agent.Fragment == "" { + switch agent.Hostname() { + case "localhost", "127.0.0.1", "::1": + q.Set("agent", agent.Scheme+"://"+agent.Host) + } + } + return q } // handleSetupConfig evaluates the session's repository directly. It deliberately @@ -86,7 +125,19 @@ func (s *Server) handleSetupConfig(w http.ResponseWriter, r *http.Request) { } ctx, cancel := context.WithTimeout(r.Context(), 90*time.Second) defer cancel() - cmd := exec.CommandContext(ctx, "nix", "eval", "--json", "--no-update-lock-file", "--no-write-lock-file", ".#legacyPackages."+getCurrentSystem()+".stackpanelConfig") + flags, err := nixeval.SetupFlakeArgs(session.Root) + if err != nil { + s.writeAPIError(w, http.StatusInternalServerError, err.Error()) + return + } + args := append( + []string{ + "eval", + "--json", + ".#legacyPackages." + getCurrentSystem() + ".stackpanelConfig", + }, + flags...) + cmd := exec.CommandContext(ctx, "nix", args...) cmd.Dir = session.Root cmd.WaitDelay = time.Second data, err := cmd.Output() @@ -95,12 +146,23 @@ func (s *Server) handleSetupConfig(w http.ResponseWriter, r *http.Request) { err = json.Unmarshal(data, &config) } if err != nil || len(config) == 0 { - s.writeAPIError(w, http.StatusInternalServerError, fmt.Sprintf("could not evaluate setup repository configuration: %v", err)) + s.writeAPIError( + w, + http.StatusInternalServerError, + fmt.Sprintf("could not evaluate setup repository configuration: %v", err), + ) return } - if err := setupsession.Update(id, func(session *setupsession.Session) error { session.ConfigLoadedAt = time.Now(); return nil }); err != nil { + if err := setupsession.Update( + id, + func(session *setupsession.Session) error { session.ConfigLoadedAt = time.Now(); return nil }, + ); err != nil { s.writeAPIError(w, http.StatusConflict, err.Error()) return } - s.writeAPI(w, http.StatusOK, map[string]any{"config": config, "source": "setup_pure_eval"}) + s.writeAPI( + w, + http.StatusOK, + map[string]any{"config": config, "source": "setup_pure_eval"}, + ) } diff --git a/apps/stackpanel-go/internal/agent/server/setup_session_test.go b/apps/stackpanel-go/internal/agent/server/setup_session_test.go index 4ae0331c..6756bf3e 100644 --- a/apps/stackpanel-go/internal/agent/server/setup_session_test.go +++ b/apps/stackpanel-go/internal/agent/server/setup_session_test.go @@ -26,7 +26,9 @@ func TestSetupAcknowledgementRequiresAuthAndProjectEvidence(t *testing.T) { if err != nil { t.Fatal(err) } - jwt, err := NewJWTManagerWithOptions(JWTManagerOptions{TestPairingToken: "setup-test"}) + jwt, err := NewJWTManagerWithOptions( + JWTManagerOptions{TestPairingToken: "setup-test"}, + ) if err != nil { t.Fatal(err) } @@ -35,12 +37,24 @@ func TestSetupAcknowledgementRequiresAuthAndProjectEvidence(t *testing.T) { t.Fatal(err) } s := &Server{config: &config.Config{ProjectRoot: root}, jwtManager: jwt} - session, err := setupsession.Create(setupsession.Session{Root: root, AgentID: jwt.GetAgentID(), ProjectID: project.ID, Origin: origin, RequireBrowser: true}) + session, err := setupsession.Create( + setupsession.Session{ + Root: root, + AgentID: jwt.GetAgentID(), + ProjectID: project.ID, + Origin: origin, + RequireBrowser: true, + }, + ) if err != nil { t.Fatal(err) } request := func(auth, projectID string) int { - r := httptest.NewRequest("POST", "/api/setup/ready?project="+projectID, strings.NewReader(`{"session":"`+session.ID+`"}`)) + r := httptest.NewRequest( + "POST", + "/api/setup/ready?project="+projectID, + strings.NewReader(`{"session":"`+session.ID+`"}`), + ) r.Header.Set("Origin", origin) r.Header.Set("X-Stackpanel-Token", auth) w := httptest.NewRecorder() @@ -74,14 +88,53 @@ func TestSetupAcknowledgementRequiresAuthAndProjectEvidence(t *testing.T) { } func TestStudioRedirectPreservesHandoff(t *testing.T) { - r := httptest.NewRequest("GET", "/studio?project=repo&setup=session&agent=http%3A%2F%2Flocalhost%3A9876&redirect=https://other", nil) + r := httptest.NewRequest( + "GET", + "/studio?project=repo&setup=session&agent=http%3A%2F%2Flocalhost%3A9876&redirect=https://other&token=secret&stackpanel_pair_state=stale", + nil, + ) w := httptest.NewRecorder() (&Server{}).handleStudio(w, r) - u, err := url.Parse(w.Header().Get("Location")) + location := w.Header().Get("Location") + if w.Code != http.StatusTemporaryRedirect || !strings.HasSuffix(location, "#") || + w.Header().Get("Referrer-Policy") != "no-referrer" { + t.Fatal("redirect must not inherit or disclose the source URL") + } + u, err := url.Parse(location) if err != nil { t.Fatal(err) } - if u.Host != "local.stackpanel.com" || u.Query().Get("project") != "repo" || u.Query().Get("setup") != "session" || u.Query().Get("redirect") != "" { + if u.Host != "local.stackpanel.com" || u.Query().Get("project") != "repo" || + u.Query().Get("setup") != "session" || + u.Query().Get("agent") != "http://localhost:9876" || + len(u.Query()) != 3 { t.Fatal(u) } } + +func TestStudioRejectsPostedCredentials(t *testing.T) { + w := httptest.NewRecorder() + (&Server{}).handleStudio( + w, + httptest.NewRequest("POST", "/studio", strings.NewReader("token=secret")), + ) + if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Location") != "" { + t.Fatal("must not redirect a request body to Studio") + } +} + +func TestStudioHandoffDoesNotForwardCredentialURLs(t *testing.T) { + for _, endpoint := range []string{"http://user:secret@localhost:9876", "http://localhost:9876/?token=secret", "http://localhost:9876/#secret", "https://unrelated.example"} { + q := studioHandoff( + url.Values{ + "project": {"p"}, + "agent": {endpoint}, + "origin": {endpoint}, + "token": {"secret"}, + }, + ) + if q.Encode() != "project=p" { + t.Error("unexpected handoff fields") + } + } +} diff --git a/apps/stackpanel-go/internal/agent/server/shell_manager.go b/apps/stackpanel-go/internal/agent/server/shell_manager.go index 89072cda..122abdca 100644 --- a/apps/stackpanel-go/internal/agent/server/shell_manager.go +++ b/apps/stackpanel-go/internal/agent/server/shell_manager.go @@ -89,7 +89,8 @@ func (sm *ShellManager) MarkNixFileChanged(filename string) { // Broadcast SSE event if sm.server != nil { sm.server.broadcastSSE(SSEEvent{ - Event: "shell.stale", + ProjectRoot: sm.projectRoot, + Event: "shell.stale", Data: map[string]any{ "file": relPath, "timestamp": sm.lastNixChange.Format(time.RFC3339), diff --git a/apps/stackpanel-go/internal/agent/server/sse.go b/apps/stackpanel-go/internal/agent/server/sse.go index 270e4089..790c5d1b 100644 --- a/apps/stackpanel-go/internal/agent/server/sse.go +++ b/apps/stackpanel-go/internal/agent/server/sse.go @@ -6,23 +6,45 @@ import ( "encoding/json" "fmt" "net/http" + "path/filepath" "time" "github.com/darkmatter/stackpanel/stackpanel-go/internal/setupsession" "github.com/rs/zerolog/log" ) +const moduleDevDiagnosticsEvent = "module.dev.diagnostics" + +// LinkedModuleStatus deliberately omits filesystem paths and full launch URLs. +// uiDevUrl is a display origin only (scheme and host, including port). +type LinkedModuleStatus struct { + UIDevURL string `json:"uiDevUrl,omitempty"` +} + +// ModuleDevDiagnostics is a replacement snapshot, not a delta. A pending +// evaluation has no timing; a successful config eval clears any previous error. +// Error is selected from fixed public summaries; it is never Nix stderr. +type ModuleDevDiagnostics struct { + ProjectID string `json:"projectId"` + LinkedModules map[string]LinkedModuleStatus `json:"linkedModules"` + EvaluatedAt string `json:"evaluatedAt,omitempty"` + DurationMs *int64 `json:"durationMs,omitempty"` + Error string `json:"error,omitempty"` +} + // SSEEvent represents a server-sent event. Event types include: // - "connected": initial event with project info (sent on SSE connect) // - "config.changed": a file in .stack/ was modified on disk (fsnotify) // - "flake.config.updated": stackpanelConfig re-evaluated after nix file change // - "flake.packages.updated": stackpanelPackages re-evaluated +// - "module.dev.diagnostics": linked inputs and latest config evaluation result // - "shell.stale": nix files changed, devshell may need rebuild // - "shell.rebuilding" / "shell.rebuilt": rebuild lifecycle // - "ping": keepalive heartbeat (every 5s) type SSEEvent struct { - Event string `json:"event"` - Data any `json:"data"` + Event string `json:"event"` + Data any `json:"data"` + ProjectRoot string `json:"-"` // stream routing only; empty for existing agent-wide events } // handleSSE handles Server-Sent Events connections for real-time updates. @@ -30,12 +52,16 @@ type SSEEvent struct { // using received events to invalidate TanStack Query caches and trigger refetches. func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) { setupID := r.URL.Query().Get("setup") + projectID := r.URL.Query().Get("project") connectionID := "" + root := s.config.ProjectRoot if setupID != "" { - if _, err := s.validateSetupRequest(r, setupID); err != nil { + session, err := s.validateSetupRequest(r, setupID) + if err != nil { s.writeAPIError(w, http.StatusConflict, err.Error()) return } + root = session.Root var nonce [16]byte if _, err := rand.Read(nonce[:]); err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -60,18 +86,42 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) { }) }() } + // Legacy connections bind to the current project's non-sensitive updates. + // Diagnostics additionally require an explicitly selected project/setup. + if setupID == "" && projectID != "" { + var err error + root, err = s.resolveProjectRoot(projectID) + if err != nil { + s.writeAPIError(w, http.StatusBadRequest, err.Error()) + return + } + } + var rt *projectRuntime + var fw *FlakeWatcher + if root != "" { + var err error + rt, err = s.runtimes.get(root) + if err != nil { + s.writeAPIError(w, http.StatusInternalServerError, err.Error()) + return + } + s.runtimes.mu.Lock() + fw = rt.flake + s.runtimes.mu.Unlock() + root, err = filepath.Abs(root) + if err != nil { + s.writeAPIError(w, http.StatusInternalServerError, err.Error()) + return + } + } // Set SSE headers w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") - // Create channel for this subscriber - eventChan := make(chan SSEEvent, 10) - - // Register subscriber - s.sseSubscribersMu.Lock() - s.sseSubscribers[eventChan] = struct{}{} - s.sseSubscribersMu.Unlock() + // requireAuth has already validated the token (including for localhost). + scope := sseScope{root: root, diagnostics: setupID != "" || projectID != ""} + eventChan := s.subscribeSSE(scope, fw) // Cleanup on disconnect defer func() { @@ -90,11 +140,11 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) { // Send initial "connected" event with project info so the UI can immediately // render project state without a separate health poll round-trip. - hasProject := s.config.ProjectRoot != "" + hasProject := root != "" connectedData := map[string]any{ "status": "ok", "hasProject": hasProject, - "projectRoot": s.config.ProjectRoot, + "projectRoot": root, "agentId": s.jwtManager.GetAgentID(), } connectedJSON, _ := json.Marshal(connectedData) @@ -108,9 +158,18 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) { // Stream events for { select { + case <-s.done: + return case <-r.Context().Done(): return case <-heartbeatTicker.C: + // An open non-current project in Studio is an active consumer even + // when no RPCs have been made since the last edit. + if rt != nil { + s.runtimes.mu.Lock() + rt.lastUsed = s.runtimes.now() + s.runtimes.mu.Unlock() + } if setupID != "" { _ = setupsession.Update(setupID, func(session *setupsession.Session) error { if session.Connection == connectionID { @@ -134,6 +193,44 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) { } } +type sseScope struct { + root string + diagnostics bool // explicitly selected, validated project/setup; never an implicit current project +} + +func (scope sseScope) accepts(event SSEEvent) bool { + if event.Event == moduleDevDiagnosticsEvent && + (!scope.diagnostics || event.ProjectRoot == "") { + return false + } + return event.ProjectRoot == "" || event.ProjectRoot == scope.root +} + +func (s *Server) subscribeSSE(scope sseScope, fw *FlakeWatcher) chan SSEEvent { + ch := make(chan SSEEvent, 10) + // Publish takes these locks in this order. Queue the snapshot atomically + // with subscription, so a fast initial eval neither disappears nor replays + // an older error over a newer result. No filesystem reads here. + if scope.diagnostics && fw != nil { + fw.mu.RLock() + defer fw.mu.RUnlock() + } + s.sseSubscribersMu.Lock() + defer s.sseSubscribersMu.Unlock() + s.sseSubscribers[ch] = scope + if scope.diagnostics && fw != nil { + event := SSEEvent{ + Event: moduleDevDiagnosticsEvent, + ProjectRoot: fw.projectRoot, + Data: fw.diagnostics, + } + if scope.accepts(event) { + ch <- event + } + } + return ch +} + // broadcastSSE fans out an event to all connected SSE subscribers. // Uses non-blocking sends — if a subscriber's channel is full (buffer=10), // the event is dropped for that subscriber rather than blocking all others. @@ -141,7 +238,10 @@ func (s *Server) broadcastSSE(event SSEEvent) { s.sseSubscribersMu.RLock() defer s.sseSubscribersMu.RUnlock() - for ch := range s.sseSubscribers { + for ch, scope := range s.sseSubscribers { + if !scope.accepts(event) { + continue + } select { case ch <- event: default: diff --git a/apps/stackpanel-go/internal/agent/server/templates/pair.html b/apps/stackpanel-go/internal/agent/server/templates/pair.html index 80be52da..f2e0cccc 100644 --- a/apps/stackpanel-go/internal/agent/server/templates/pair.html +++ b/apps/stackpanel-go/internal/agent/server/templates/pair.html @@ -177,8 +177,8 @@

Pair Agent

- Grant the Stackpanel web UI permission to manage files and run local - commands in this project: + Grant {{.TargetOrigin}} permission to manage files and run + local commands in this project:

{{.ProjectRoot}}
@@ -186,23 +186,34 @@

Pair Agent

', + }), + ); + await page.route( + (url) => url.pathname === `${ticket}/panel.js`, + (route) => route.fulfill({ contentType: "text/javascript", body: bundle }), + ); + return state; +} diff --git a/apps/web/e2e/support/status-panel.ts b/apps/web/e2e/support/status-panel.ts new file mode 100644 index 00000000..a9289003 --- /dev/null +++ b/apps/web/e2e/support/status-panel.ts @@ -0,0 +1,50 @@ +// Browser entry point; the test bundles this exactly as an external panel author would. +import { getConfig, getContext, patchModuleConfig, proxyFetch } from "@stackpanel/extension-sdk"; +import { registerPanelElements } from "@stackpanel/extension-sdk/elements"; + +async function renderStatus() { + registerPanelElements(); + const context = await getContext(); + const status = document.createElement("p"); + const metric = document.createElement("sp-metric"); + metric.setAttribute("label", "Module"); + metric.setAttribute("value", context.moduleId); + document.body.append(metric); + const read = document.createElement("button"); + read.textContent = "Read greeting"; + read.onclick = async () => { + try { + const config = await getConfig(); + if (typeof config.greeting !== "string") throw new Error("Greeting is not configured."); + status.textContent = `${context.moduleId}/${context.panelId}: ${config.greeting}`; + } catch (error) { + status.textContent = error instanceof Error ? error.message : String(error); + } + }; + document.body.append(read, status); + const save = document.createElement("button"); + save.textContent = "Try changing greeting"; + save.onclick = async () => { + try { + await patchModuleConfig({ greeting: "changed by panel" }); + status.textContent = "Settings changed"; + } catch (error) { + status.textContent = error instanceof Error ? error.message : String(error); + } + }; + document.body.append(save); + const service = document.createElement("button"); + service.textContent = "Read local service"; + service.onclick = async () => { + try { + status.textContent = (await proxyFetch("health", "/status")).body; + } catch (error) { + status.textContent = error instanceof Error ? error.message : String(error); + } + }; + document.body.append(service); +} + +void renderStatus().catch((error: unknown) => { + document.body.textContent = String(error); +}); diff --git a/apps/web/package.json b/apps/web/package.json index 2e0925d3..663eb754 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -31,10 +31,13 @@ "test:coverage": "vitest run --coverage --exclude 'src/test/integration/**'", "test:integration": "vitest run --include 'src/test/integration/**' --testTimeout=120000", "test:watch": "vitest --exclude 'src/test/integration/**'", - "web:dev": "vite --host" + "web:dev": "vite --host", + "widgets:check": "bun src/components/studio/panels/shared/spec/generate-widget-catalog.ts --check", + "widgets:generate": "bun src/components/studio/panels/shared/spec/generate-widget-catalog.ts" }, "dependencies": { "@ai-sdk/react": "^3.0.178", + "@alchemy.run/cloudflare": "catalog:", "@base-ui/react": "^1.1.0", "@bufbuild/protobuf": "^2.10.2", "@connectrpc/connect": "^2.1.1", @@ -47,6 +50,8 @@ "@fontsource-variable/source-code-pro": "^5.2.7", "@gen/featureflags": "workspace:*", "@hookform/resolvers": "^5.2.2", + "@json-render/core": "catalog:", + "@json-render/react": "catalog:", "@monaco-editor/react": "^4.7.0", "@radix-ui/react-accordion": "^1.2.12", "@radix-ui/react-alert-dialog": "^1.1.15", @@ -76,6 +81,7 @@ "@stackpanel/api": "workspace:*", "@stackpanel/auth": "workspace:*", "@stackpanel/docs-content": "workspace:*", + "@stackpanel/extension-sdk": "workspace:*", "@stackpanel/proto": "workspace:*", "@stackpanel/ui-core": "workspace:*", "@stackpanel/ui-web": "workspace:*", @@ -98,6 +104,7 @@ "effect": "catalog:", "effect-query": "^1.0.0", "embla-carousel-react": "^8.6.0", + "eventsource-parser": "^3.0.8", "idb": "^8.0.2", "immer": "^11.1.7", "input-otp": "^1.4.2", @@ -124,6 +131,7 @@ "zustand": "^5.0.13" }, "devDependencies": { + "@alchemy.run/frontend-frameworks": "catalog:", "@cloudflare/workers-types": "4.20260508.1", "@effect/platform-bun": "catalog:", "@effect/platform-node": "catalog:", diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts index 3de6aba7..97e27c2a 100644 --- a/apps/web/playwright.config.ts +++ b/apps/web/playwright.config.ts @@ -6,7 +6,7 @@ import { PLAYWRIGHT_PAIRING_SECRET, PLAYWRIGHT_WEB_HOST, PLAYWRIGHT_WEB_PORT, - REPO_ROOT, + PLAYWRIGHT_PROJECT_ROOT, STACKPANEL_GO_DIR, WEB_APP_DIR, } from "./e2e/support/constants"; @@ -44,10 +44,11 @@ export default defineConfig({ webServer: [ { name: "agent", - command: `go run . agent --port ${PLAYWRIGHT_AGENT_PORT} --project-root "${REPO_ROOT}"`, + command: `go run . agent --port ${PLAYWRIGHT_AGENT_PORT} --project-root "$STACKPANEL_PROJECT_ROOT"`, cwd: STACKPANEL_GO_DIR, env: { ...process.env, + STACKPANEL_PROJECT_ROOT: PLAYWRIGHT_PROJECT_ROOT, STACKPANEL_TEST_PAIRING_TOKEN: PLAYWRIGHT_PAIRING_SECRET, }, url: `http://${PLAYWRIGHT_WEB_HOST}:${PLAYWRIGHT_AGENT_PORT}/health`, diff --git a/apps/web/scripts/demo-smoke.ts b/apps/web/scripts/demo-smoke.ts index 265c4725..ba6c5c24 100644 --- a/apps/web/scripts/demo-smoke.ts +++ b/apps/web/scripts/demo-smoke.ts @@ -2,15 +2,15 @@ /** * Standalone smoke test for the demo agent. * - * Runs without the vitest harness so it can be invoked from any environment - * that has bun installed (no `bun install` required for this single script — - * msw is the only runtime dependency the handlers use, and it's already - * pulled in by apps/web). + * Exercises the MSW handlers without starting a browser or a live agent. * * Run: bun apps/web/scripts/demo-smoke.ts */ -import { DEMO_BASE_URL, demoEntities, demoStateJson } from "../src/demo/fixture"; +import { Code, ConnectError, createClient } from "@connectrpc/connect"; +import { createConnectTransport } from "@connectrpc/connect-web"; +import { ModuleService } from "@stackpanel/proto/agent/v1/module"; +import { DEMO_BASE_URL, demoEntities, demoProject, demoStateJson } from "../src/demo/fixture"; import { demoHandlers } from "../src/demo/handlers"; type AnyHandler = (typeof demoHandlers)[number]; @@ -18,180 +18,279 @@ type AnyHandler = (typeof demoHandlers)[number]; let failures = 0; function assert(cond: unknown, label: string): void { - if (cond) { - console.log(` ok ${label}`); - } else { - failures++; - console.error(` FAIL ${label}`); - } + if (cond) { + console.log(` ok ${label}`); + } else { + failures++; + console.error(` FAIL ${label}`); + } } async function run(handler: AnyHandler, request: Request): Promise { - const result = await ( - handler as unknown as { - run: (args: { request: Request }) => Promise<{ response: Response } | null>; - } - ).run({ request }); - if (!result) throw new Error(`handler did not match: ${request.url}`); - return result.response; + const result = await ( + handler as unknown as { + run: (args: { request: Request }) => Promise<{ response: Response } | null>; + } + ).run({ request }); + if (!result) throw new Error(`handler did not match: ${request.url}`); + return result.response; } function findHandler(method: string, path: string): AnyHandler { - const target = `${DEMO_BASE_URL}${path}`; - for (const h of demoHandlers) { - const info = (h as unknown as { info: { method: string; path: string } }) - .info; - if (info.method !== method) continue; - if (info.path === target || info.path === path) return h; - } - throw new Error(`no handler for ${method} ${path}`); + const target = `${DEMO_BASE_URL}${path}`; + for (const h of demoHandlers) { + const info = (h as unknown as { info: { method: string; path: string } }).info; + if (info.method !== method) continue; + if (info.path === target || info.path === path) return h; + } + throw new Error(`no handler for ${method} ${path}`); } async function main() { - console.log("# demo agent smoke test"); - - { - console.log("GET /health"); - const res = await run( - findHandler("GET", "/health"), - new Request(`${DEMO_BASE_URL}/health`), - ); - const body = (await res.json()) as { status: string; agentId: string }; - assert(body.status === "ok", `status === "ok" (got ${body.status})`); - assert( - body.agentId === "demo-agent", - `agentId === "demo-agent" (got ${body.agentId})`, - ); - } - - { - console.log("GET /api/state"); - const res = await run( - findHandler("GET", "/api/state"), - new Request(`${DEMO_BASE_URL}/api/state`), - ); - const body = (await res.json()) as typeof demoStateJson; - assert( - body.projectName === demoStateJson.projectName, - `projectName === "${demoStateJson.projectName}"`, - ); - assert( - body.basePort === demoStateJson.basePort, - `basePort === ${demoStateJson.basePort}`, - ); - assert(Object.keys(body.apps).includes("web"), "apps include `web`"); - } - - { - console.log("GET /api/nix/data?entity=apps"); - const res = await run( - findHandler("GET", "/api/nix/data"), - new Request(`${DEMO_BASE_URL}/api/nix/data?entity=apps`), - ); - const body = (await res.json()) as { - success: boolean; - data: { entity: string; exists: boolean; data: unknown }; - }; - assert(body.success === true, "success === true"); - assert(body.data.entity === "apps", `entity === "apps"`); - assert(body.data.exists === true, "exists === true"); - assert( - JSON.stringify(body.data.data) === JSON.stringify(demoEntities.apps), - "data matches demoEntities.apps", - ); - } - - { - console.log("GET /api/process-compose/processes"); - const res = await run( - findHandler("GET", "/api/process-compose/processes"), - new Request(`${DEMO_BASE_URL}/api/process-compose/processes`), - ); - const body = (await res.json()) as { - success: boolean; - data: { processes: { name: string }[] }; - }; - assert(body.success === true, "success === true"); - assert(body.data.processes.length > 0, "processes.length > 0"); - assert( - body.data.processes.some((p) => p.name === "web"), - "processes include `web`", - ); - } - - { - console.log("POST Connect GetNixConfig"); - const res = await run( - findHandler("POST", "/:service/:method"), - new Request( - `${DEMO_BASE_URL}/stackpanel.agent.AgentService/GetNixConfig`, - { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ refresh: false }), - }, - ), - ); - const body = (await res.json()) as { configJson?: string }; - assert(typeof body.configJson === "string", "configJson is a string"); - const config = JSON.parse(body.configJson ?? "{}") as { - projectName?: string; - panels?: Record; - ui?: { panels?: Record }; - }; - assert( - config.projectName === "stackpanel-demo", - `projectName === stackpanel-demo (got ${config.projectName})`, - ); - assert( - config.panels !== undefined && Object.keys(config.panels).length > 0, - "top-level panels are populated", - ); - assert( - config.ui?.panels !== undefined && - Object.keys(config.ui.panels).length > 0, - "ui.panels are populated", - ); - } - - { - console.log("GET /api/modules"); - const res = await run( - findHandler("GET", "/api/modules"), - new Request(`${DEMO_BASE_URL}/api/modules`), - ); - const body = (await res.json()) as { - success: boolean; - data: { modules: { id: string }[]; enabled: number }; - }; - assert(body.success === true, "success === true"); - assert(body.data.modules.length > 0, "modules.length > 0"); - assert(body.data.enabled > 0, "enabled > 0"); - } - - { - console.log("GET /api/healthchecks"); - const res = await run( - findHandler("GET", "/api/healthchecks"), - new Request(`${DEMO_BASE_URL}/api/healthchecks`), - ); - const body = (await res.json()) as { - success: boolean; - data: { overallStatus: string; totalHealthy: number }; - }; - assert(body.success === true, "success === true"); - assert( - body.data.overallStatus === "HEALTH_STATUS_HEALTHY", - `overallStatus healthy (got ${body.data.overallStatus})`, - ); - assert(body.data.totalHealthy > 0, "totalHealthy > 0"); - } - - if (failures > 0) { - console.error(`\n${failures} assertion(s) failed`); - process.exit(1); - } - console.log("\nall demo agent assertions passed"); + console.log("# demo agent smoke test"); + + { + console.log("GET /health"); + const res = await run(findHandler("GET", "/health"), new Request(`${DEMO_BASE_URL}/health`)); + const body = (await res.json()) as { status: string; agentId: string }; + assert(body.status === "ok", `status === "ok" (got ${body.status})`); + assert(body.agentId === "demo-agent", `agentId === "demo-agent" (got ${body.agentId})`); + } + + { + console.log("GET /api/state"); + const res = await run( + findHandler("GET", "/api/state"), + new Request(`${DEMO_BASE_URL}/api/state`), + ); + const body = (await res.json()) as typeof demoStateJson; + assert( + body.projectName === demoStateJson.projectName, + `projectName === "${demoStateJson.projectName}"`, + ); + assert(body.basePort === demoStateJson.basePort, `basePort === ${demoStateJson.basePort}`); + assert(Object.keys(body.apps).includes("web"), "apps include `web`"); + } + + { + console.log("GET /api/nix/data?entity=apps"); + const res = await run( + findHandler("GET", "/api/nix/data"), + new Request(`${DEMO_BASE_URL}/api/nix/data?entity=apps`), + ); + const body = (await res.json()) as { + success: boolean; + data: { entity: string; exists: boolean; data: unknown }; + }; + assert(body.success === true, "success === true"); + assert(body.data.entity === "apps", `entity === "apps"`); + assert(body.data.exists === true, "exists === true"); + assert( + JSON.stringify(body.data.data) === JSON.stringify(demoEntities.apps), + "data matches demoEntities.apps", + ); + const oldRead = await run(findHandler("GET", "/api/nix/data"), + new Request(`${DEMO_BASE_URL}/api/nix/data?entity=modules`)); + const oldWrite = await run(findHandler("POST", "/api/nix/data"), + new Request(`${DEMO_BASE_URL}/api/nix/data`, { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ entity: "modules", key: "fly", data: {} }), + })); + assert(oldRead.status === 400 && oldWrite.status === 400, "modules are not a generic Nix data entity"); + } + + { + console.log("GET /api/process-compose/processes"); + const res = await run( + findHandler("GET", "/api/process-compose/processes"), + new Request(`${DEMO_BASE_URL}/api/process-compose/processes`), + ); + const body = (await res.json()) as { + success: boolean; + data: { processes: { name: string }[] }; + }; + assert(body.success === true, "success === true"); + assert(body.data.processes.length > 0, "processes.length > 0"); + assert( + body.data.processes.some((p) => p.name === "web"), + "processes include `web`", + ); + } + + { + console.log("POST Connect GetNixConfig"); + const res = await run( + findHandler("POST", "/:service/:method"), + new Request(`${DEMO_BASE_URL}/stackpanel.agent.AgentService/GetNixConfig`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ refresh: false }), + }), + ); + const body = (await res.json()) as { configJson?: string }; + assert(typeof body.configJson === "string", "configJson is a string"); + const config = JSON.parse(body.configJson ?? "{}") as { + projectName: string; + modulesListAll: { id: string; enabled: boolean }[]; + panelsList: { id: string; module: string; slot: string }[]; + }; + assert( + config.projectName === "stackpanel-demo", + `projectName === stackpanel-demo (got ${config.projectName})`, + ); + const enabled = new Set(config.modulesListAll.filter((mod) => mod.enabled).map((mod) => mod.id)); + assert(config.panelsList.every((panel) => panel.slot && enabled.has(panel.module)), + "every mounted panel declares its slot and an enabled owner"); + assert(config.panelsList.some((panel) => panel.module === "fly" && panel.slot === "app:deployment"), + "Fly.io app settings belong to the installed Fly module"); + assert(!["panels", "panelModules", "panelsComputed", "ui"].some((key) => key in config), + "evaluated config does not publish duplicate panel or module catalogs"); + } + + { + console.log("Connect module lifecycle"); + const transport = createConnectTransport({ + baseUrl: DEMO_BASE_URL, + useBinaryFormat: false, + interceptors: [(next) => (request) => { + request.header.set("X-Stackpanel-Project", demoProject.id); + return next(request); + }], + fetch: Object.assign( + (...args: Parameters) => { + const request = new Request(...args); + return run(findHandler(request.method, new URL(request.url).pathname), request); + }, + { preconnect: fetch.preconnect }, + ), + }); + const client = createClient(ModuleService, transport); + assert( + (await client.listModules({})).modules.some((mod) => mod.enabled), + "lists enabled modules", + ); + const { modules } = await client.listRegistryModules({ query: "playwright", tag: "browser" }); + const entry = modules[0]; + if (!entry || !entry.versions[1]) throw new Error("Missing versioned Playwright demo fixture"); + const moduleId = entry.slug; + await client.installModule({ moduleId, version: entry.versions[1].version }); + assert( + (await client.getModule({ moduleId })).module?.enabled === false, + "install does not enable", + ); + assert((await client.getRegistryModule({ moduleId })).module?.installedVersion === entry.versions[1].version, + "the registry reports the selected catalog pin independently of enablement"); + const { preview } = await client.previewModuleEnable({ moduleId }); + const offer = preview?.offers[0]; + if (!offer || preview?.files?.added.includes("playwright.config.ts")) + throw new Error("Optional file must need an explicit choice"); + const choice = { + id: offer.id, + revision: offer.revision, + answer: { kind: { case: "boolValue" as const, value: true } }, + }; + const answers = [choice]; + const reviewed = await client.previewModuleEnable({ moduleId, answers }); + assert( + reviewed.preview?.files?.added.includes("playwright.config.ts"), + "selected plan includes the optional file", + ); + try { + await client.enableModule({ moduleId, answers: [{ ...choice, revision: "stale" }] }); + assert(false, "rejects a stale adoption revision"); + } catch (error) { + assert(error instanceof ConnectError && error.code === Code.FailedPrecondition, + "rejects a stale adoption revision"); + } + await client.enableModule({ moduleId, answers }); + await client.updateModuleConfig({ + moduleId, + settings: { "demo.key": "literal", runner: { workers: 2 } }, + }); + await client.updateModuleConfig({ moduleId, settings: { runner: { retries: 1 } } }); + await client.updateModule({ moduleId, version: entry.latestVersion, ref: "demo-branch" }); + const detail = await client.getModule({ moduleId }); + assert( + detail.module?.settings?.["demo.key"] === "literal", + "update preserves literal setting keys", + ); + const runner = detail.module?.settings?.runner; + assert( + runner && + typeof runner === "object" && + !Array.isArray(runner) && + runner.workers === 2 && + runner.retries === 1, + "settings patches preserve nested siblings", + ); + assert(detail.module?.source?.ref === "demo-branch", "update persists the ref override"); + const updated = (await client.getRegistryModule({ moduleId })).module; + assert(updated?.installed && updated.installedVersion === undefined, + "a custom ref remains installed without inventing a catalog version"); + assert( + (await client.getModuleOutputs({ moduleId })).outputs?.files.some( + (file) => file.path === "playwright.config.ts", + ), + "enabled module contributes outputs", + ); + try { + const bound = client.runModuleAction({ moduleId, actionId: "inspect" }, { + headers: { "X-Stackpanel-UI-Grant": "unissued-demo-grant" }, + }); + await bound[Symbol.asyncIterator]().next(); + assert(false, "rejects unissued panel grants"); + } catch (error) { + assert(error instanceof ConnectError && error.code === Code.PermissionDenied, + "rejects unissued panel grants instead of running as the host"); + } + const events = []; + for await (const response of client.runModuleAction({ moduleId, actionId: "inspect" })) + events.push(response.event); + assert(events.some((event) => event.case === "stdout" && event.value.includes('"workers": 2')) && + events.some((event) => event.case === "exitCode" && event.value === 0), + "the declared inspect action streams this module's current settings and exits"); + await client.disableModule({ moduleId }); + assert((await client.getModuleOutputs({ moduleId })).outputs?.files.length === 0, + "disable removes the contribution without uninstalling the module"); + await client.uninstallModule({ moduleId }); + assert( + (await client.getRegistryModule({ moduleId })).module?.installed === false, + "uninstall clears registry state", + ); + try { + await client.getModule({ moduleId }); + assert(false, "uninstalled module is absent"); + } catch (error) { + assert( + error instanceof ConnectError && error.code === Code.NotFound, + "uninstalled module is absent", + ); + } + } + + { + console.log("GET /api/healthchecks"); + const res = await run( + findHandler("GET", "/api/healthchecks"), + new Request(`${DEMO_BASE_URL}/api/healthchecks`), + ); + const body = (await res.json()) as { + success: boolean; + data: { overallStatus: string; totalHealthy: number }; + }; + assert(body.success === true, "success === true"); + assert( + body.data.overallStatus === "HEALTH_STATUS_HEALTHY", + `overallStatus healthy (got ${body.data.overallStatus})`, + ); + assert(body.data.totalHealthy > 0, "totalHealthy > 0"); + } + + if (failures > 0) { + console.error(`\n${failures} assertion(s) failed`); + process.exit(1); + } + console.log("\nall demo agent assertions passed"); } await main(); diff --git a/apps/web/src/components/agent-connect.tsx b/apps/web/src/components/agent-connect.tsx index 41e38a6b..797c5de0 100644 --- a/apps/web/src/components/agent-connect.tsx +++ b/apps/web/src/components/agent-connect.tsx @@ -8,6 +8,7 @@ import { Loader2, Settings, Unplug, Wifi } from "lucide-react"; import { useEffect, useState } from "react"; import { useAgentEndpoint } from "@/lib/agent-endpoint"; import { useAgentContext } from "@/lib/agent-provider"; +import { canonicalAgentOrigin } from "@/lib/agent-identity"; export function AgentConnect({ onConnected }: { onConnected?: () => void; overlay?: boolean }) { const { @@ -25,6 +26,7 @@ export function AgentConnect({ onConnected }: { onConnected?: () => void; overla const [settings, setSettings] = useState(false); const [nextHost, setNextHost] = useState(host); const [nextPort, setNextPort] = useState(String(port)); + const [endpointError, setEndpointError] = useState(null); useEffect(() => { if (isConnected) onConnected?.(); }, [isConnected, onConnected]); @@ -75,10 +77,15 @@ export function AgentConnect({ onConnected }: { onConnected?: () => void; overla onSubmit={(event) => { event.preventDefault(); const parsed = Number(nextPort); - if (!nextHost.trim() || !Number.isInteger(parsed) || parsed < 1 || parsed > 65535) + const host = nextHost.trim(); + try { + canonicalAgentOrigin(host, parsed); + } catch { + setEndpointError("Enter a hostname and a port between 1 and 65535."); return; - clearPairing(); - useLocal({ host: nextHost.trim(), port: parsed }); + } + setEndpointError(null); + useLocal({ host, port: parsed }); setSettings(false); }} > @@ -93,6 +100,7 @@ export function AgentConnect({ onConnected }: { onConnected?: () => void; overla value={nextPort} onChange={(e) => setNextPort(e.target.value)} /> + {endpointError &&

{endpointError}

} ) : null} diff --git a/apps/web/src/components/demo/demo-banner.tsx b/apps/web/src/components/demo/demo-banner.tsx index 65790534..37bcf998 100644 --- a/apps/web/src/components/demo/demo-banner.tsx +++ b/apps/web/src/components/demo/demo-banner.tsx @@ -22,8 +22,8 @@ export function DemoBanner() { Demo mode.{" "} - You're running the real Studio against fixture data. Writes are - no-ops; install the CLI to use a live local agent. + Module changes stay in this tab and reset on reload. Nothing is + written to your project.
diff --git a/apps/web/src/components/studio/command-runner.test.tsx b/apps/web/src/components/studio/command-runner.test.tsx new file mode 100644 index 00000000..93b26e2f --- /dev/null +++ b/apps/web/src/components/studio/command-runner.test.tsx @@ -0,0 +1,223 @@ +/// +import { EventEmitter, once } from "node:events"; +import { fromJson, type MessageInitShape } from "@bufbuild/protobuf"; +import { ValueSchema } from "@bufbuild/protobuf/wkt"; +import { + Code, + ConnectError, + createClient, + createRouterTransport, + type ServiceImpl, +} from "@connectrpc/connect"; +import { + ModuleService, + type RunModuleActionResponseSchema, +} from "@stackpanel/proto/agent/v1/module"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { StrictMode, useState } from "react"; +import * as agentProvider from "@/lib/agent-provider"; +import { agentQueryKeys } from "@/lib/use-agent"; +import { + ModuleActionRunnerDialog, + type ModuleActionRunnerDialogProps, + useModuleActionRunner, +} from "./command-runner"; + +type ActionEvent = MessageInitShape; +const scope = ["agent", "modules", "localhost", 9876, "first-project", "t0", true] as const; +const request = { + moduleId: "deploy", + actionId: "inspect", + args: { app: "web app", verbose: true }, +}; + +const pairedIdentity = { + selectedProjectId: "first-project", + token: "test-token", + isAuthenticated: true, +}; +let identity: { selectedProjectId: string | null; token: string | null; isAuthenticated: boolean }; +vi.mock("@/lib/agent-provider", async (importOriginal) => ({ + ...(await importOriginal()), + useAgentContext: () => identity, +})); +vi.mock("./panels/modules/use-modules", () => ({ useModuleQueryScope: () => scope })); + +function SubmitAction({ onSuccess }: Pick) { + const { start } = useModuleActionRunner(); + const [run, setRun] = useState(null); + function submit() { + setRun( + start({ + ...request, + label: "Inspect app", + invalidates: ["apps"], + onClose: () => setRun(null), + onSuccess, + }), + ); + } + return ( + <> + + {run && } + + ); +} + +function setup( + runModuleAction: ServiceImpl["runModuleAction"], + unavailable?: "project" | "credential", +) { + identity = { ...pairedIdentity }; + if (unavailable === "project") identity.selectedProjectId = null; + if (unavailable === "credential") { + identity.token = null; + identity.isAuthenticated = false; + } + const transport = createRouterTransport((router) => + router.service(ModuleService, { runModuleAction }), + ); + vi.spyOn(agentProvider, "useModuleServiceClient").mockReturnValue( + createClient(ModuleService, transport), + ); + const cache = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const onSuccess = vi.fn(); + render( + + + + + , + ); + return { + cache, + onSuccess, + submit: () => fireEvent.click(screen.getByRole("button", { name: "Submit" })), + }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("submitted module actions", () => { + it.each(["project", "credential"] as const)( + "never starts a module process without a %s", + async (missing) => { + const requests: string[] = []; + const { submit } = setup(async function* (request): AsyncGenerator { + requests.push(request.actionId); + yield { event: { case: "exitCode", value: 0 } }; + }, missing); + submit(); + expect(await screen.findByRole("alert")).toBeTruthy(); + expect(requests).toEqual([]); + }, + ); + + it("streams ordered, labeled output before exit; delivers JSON and refreshes this project's data once", async () => { + const action = new EventEmitter(); + const gate = once(action, "finish"); + const requests: unknown[] = []; + const result = { rows: [{ healthy: true }] }; + const { cache, onSuccess, submit } = setup(async function* (req): AsyncGenerator { + requests.push(req); + yield { event: { case: "stdout", value: "Inspecting app" } }; + yield { event: { case: "stderr", value: "Version mismatch" } }; + yield { event: { case: "json", value: fromJson(ValueSchema, result) } }; + await gate; + yield { event: { case: "exitCode", value: 0 } }; + }); + const refreshed = [ + [...scope, "catalog"], + agentQueryKeys.nixConfig(), + agentQueryKeys.apps(), + ]; + const unrelated = [ + "agent", + "modules", + "localhost", + 9876, + "other-project", + "t1", + true, + "catalog", + ]; + for (const key of [...refreshed, unrelated]) cache.setQueryData(key, true); + + expect(requests).toHaveLength(0); + submit(); + const dialog = within(await screen.findByRole("dialog", { name: "Inspect app" })); + const output = dialog.getByRole("log", { name: "Action output" }); + try { + await within(output).findByText(/"healthy": true/); + expect(output.textContent).toMatch(/stdoutInspecting appstderrVersion mismatchjson/); + expect(dialog.getByRole("status").textContent).toBe("Running"); + expect(onSuccess).not.toHaveBeenCalled(); + expect(cache.getQueryState(agentQueryKeys.apps())?.isInvalidated).toBe(false); + } finally { + action.emit("finish"); + } + await dialog.findByText("Exit code 0"); + await waitFor(() => expect(onSuccess.mock.calls).toEqual([[result]])); + expect(requests).toEqual([expect.objectContaining(request)]); + for (const key of refreshed) expect(cache.getQueryState(key)?.isInvalidated).toBe(true); + expect(cache.getQueryState(unrelated)?.isInvalidated).toBe(false); + }); + + it("cancels the RPC when the user closes a running action", async () => { + const action = new EventEmitter(); + const gate = once(action, "finish"); + let signal: AbortSignal | undefined; + const { submit, onSuccess } = setup( + async function* (_request, context): AsyncGenerator { + signal = context.signal; + yield { event: { case: "stdout", value: "Waiting for app" } }; + await gate; + yield { event: { case: "exitCode", value: 0 } }; + }, + ); + submit(); + try { + await screen.findByText("Waiting for app"); + fireEvent.click(screen.getByRole("button", { name: "Close" })); + await waitFor(() => expect(signal?.aborted).toBe(true)); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(onSuccess).not.toHaveBeenCalled(); + } finally { + action.emit("finish"); + } + }); + + it("keeps the transcript and the process exit code when an action fails", async () => { + const { submit, onSuccess } = setup(async function* (): AsyncGenerator { + yield { event: { case: "stderr", value: "No deployment selected" } }; + yield { event: { case: "exitCode", value: 17 } }; + }); + submit(); + await screen.findByText("Exit code 17"); + expect(screen.getByRole("log").textContent).toContain("No deployment selected"); + expect(onSuccess).not.toHaveBeenCalled(); + }); + + it.each([ + ["truncated", "ended without an exit code"], + ["disconnected", "connection lost"], + ])("does not report success on a %s stream", async (kind, reason) => { + const { submit, onSuccess } = setup(async function* (): AsyncGenerator { + yield { event: { case: "stdout", value: "Started" } }; + if (kind === "disconnected") { + yield { event: { case: "exitCode", value: 0 } }; + throw new ConnectError("connection lost", Code.Unavailable); + } + }); + submit(); + expect((await screen.findByRole("alert")).textContent).toContain(reason); + expect(screen.getByRole("log").textContent).toContain("Started"); + expect(onSuccess).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/studio/command-runner.tsx b/apps/web/src/components/studio/command-runner.tsx index 852a442d..c9629be9 100644 --- a/apps/web/src/components/studio/command-runner.tsx +++ b/apps/web/src/components/studio/command-runner.tsx @@ -1,30 +1,25 @@ "use client"; import React, { useState, useCallback, useRef, useEffect } from "react"; +import type { JsonValue } from "@bufbuild/protobuf"; +import { hashKey, useQueryClient } from "@tanstack/react-query"; +import { useStore } from "zustand"; import { Button } from "@ui/button"; import { ButtonGroup, ButtonGroupSeparator } from "@ui/button-group"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, -} from "@ui/dialog"; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@ui/dialog"; import { Badge } from "@ui/badge"; import { Popover, PopoverContent, PopoverTrigger } from "@ui/popover"; -import { - Check, - ChevronDown, - Copy, - Info, - Loader2, - Play, - Terminal, - X, -} from "lucide-react"; +import { Check, ChevronDown, Copy, Info, Loader2, Play, Terminal, X } from "lucide-react"; import { cn } from "@/lib/utils"; import { toast } from "sonner"; -import { useExec } from "@/lib/use-agent"; +import { useAgentContext, useModuleServiceClient } from "@/lib/agent-provider"; +import { agentQueryKeys, useExec } from "@/lib/use-agent"; +import { useModuleQueryScope } from "./panels/modules/use-modules"; +import { + startModuleActionStream, + type ModuleActionOutput, + type ModuleActionRequest, +} from "./module-action-stream"; // ============================================================================= // Types @@ -48,11 +43,7 @@ export interface CommandRunnerProps { /** Variant for buttons */ variant?: "default" | "outline" | "secondary" | "ghost"; /** Called when execution completes */ - onComplete?: (result: { - exitCode: number; - stdout: string; - stderr: string; - }) => void; + onComplete?: (result: { exitCode: number; stdout: string; stderr: string }) => void; /** Called when execution fails */ onError?: (error: Error) => void; /** Whether to show the command text in a code block */ @@ -74,14 +65,175 @@ export interface CommandRunnerDialogProps { description?: string; /** Auto-run the command when dialog opens */ autoRun?: boolean; - onComplete?: (result: { - exitCode: number; - stdout: string; - stderr: string; - }) => void; + onComplete?: (result: { exitCode: number; stdout: string; stderr: string }) => void; onError?: (error: Error) => void; } +interface ModuleActionSubmission extends ModuleActionRequest { + label: string; + onClose: () => void; + onSuccess?: (json: JsonValue | undefined) => void; + invalidates?: string[]; +} + +export interface ModuleActionRunnerDialogProps extends ModuleActionSubmission { + output: ModuleActionOutput; +} + +/** Call the returned function in the submit handler, never during render or in an effect. */ +export function useModuleActionRunner() { + const client = useModuleServiceClient(); + const { selectedProjectId, token, isAuthenticated } = useAgentContext(); + let unavailable: string | undefined; + if (!selectedProjectId?.trim()) unavailable = "Select a project to run module actions."; + else if (!isAuthenticated || !token) unavailable = "Pair this agent to run module actions."; + const cache = useQueryClient(); + const scope = useModuleQueryScope(); + const scopeKey = hashKey(scope); + const active = useRef(new Set()); + + // Legacy Nix keys describe the currently selected project. Don't refresh those + // keys or deliver an old result to the parent after switching projects. + React.useLayoutEffect(() => { + const controllers = active.current; + return () => { + for (const controller of controllers) controller.abort(); + controllers.clear(); + }; + }, [client, scopeKey, unavailable]); + + function start(options: ModuleActionSubmission): ModuleActionRunnerDialogProps { + const { moduleId, actionId, args, invalidates, onSuccess } = options; + const controller = new AbortController(); + active.current.add(controller); + const run = startModuleActionStream( + unavailable ? null : client, + { moduleId, actionId, args }, + controller.signal, + ); + void run.finished.then((result) => { + active.current.delete(controller); + if (!result || controller.signal.aborted) return; + + // Nonzero exits can also leave the module's evaluated state changed. + void cache.invalidateQueries({ queryKey: scope }); + void cache.invalidateQueries({ queryKey: agentQueryKeys.nixConfig() }); + if (result.exitCode !== 0) return; + const targets = new Set(invalidates); + for (const entity of targets) { + void cache.invalidateQueries({ queryKey: [...agentQueryKeys.all, "entity", entity] }); + void cache.invalidateQueries({ queryKey: [...agentQueryKeys.all, "mapEntity", entity] }); + } + for (const [name, key] of Object.entries(agentQueryKeys)) { + if (targets.has(name) && name !== "nixConfig" && typeof key === "function") { + void cache.invalidateQueries({ queryKey: key() }); + } + } + onSuccess?.(result.json); + }); + return { + ...options, + output: run.output, + onClose: () => { + controller.abort(); + options.onClose(); + }, + }; + } + return { start, unavailable }; +} + +/** Read-only terminal for one submitted module action; mounting it never starts an RPC. */ +export function ModuleActionRunnerDialog({ + moduleId, + actionId, + label, + onClose, + output, +}: ModuleActionRunnerDialogProps) { + const { chunks, status } = useStore(output); + const log = useRef(null); + const follow = useRef(true); + useEffect(() => { + if (follow.current && log.current) log.current.scrollTop = log.current.scrollHeight; + }, [chunks]); + + return ( + !open && onClose()}> + + + + + + {moduleId} / {actionId} + + +
{ + follow.current = + currentTarget.scrollHeight - currentTarget.scrollTop - currentTarget.clientHeight < + 16; + }} + ref={log} + role="log" + tabIndex={0} + > + {(chunks[0]?.id ?? 0) > 0 && ( +

Earlier output omitted.

+ )} + {chunks.length === 0 && ( +

+ {status.kind === "running" ? "No output yet." : "No output."} +

+ )} + {chunks.map(({ id, channel, text }) => ( +
+ {channel} +
+                {text}
+              
+
+ ))} +
+ {status.kind === "failed" ? ( +

+ Action stream failed: {status.reason} +

+ ) : ( +

+ {status.kind === "running" ? ( + <> +

+ )} + {status.kind === "running" && ( +

Closing this dialog cancels the stream.

+ )} +
+
+ ); +} + // ============================================================================= // Utilities // ============================================================================= @@ -120,9 +272,7 @@ export function CommandRunnerDialog({ onError, }: CommandRunnerDialogProps) { const outputRef = useRef(null); - const [status, setStatus] = useState< - "idle" | "running" | "success" | "error" - >("idle"); + const [status, setStatus] = useState<"idle" | "running" | "success" | "error">("idle"); const [output, setOutput] = useState([]); const [exitCode, setExitCode] = useState(null); const hasRun = useRef(false); @@ -222,10 +372,7 @@ export function CommandRunnerDialog({ {label || "Run Command"} {status === "running" && ( - + Running @@ -240,10 +387,7 @@ export function CommandRunnerDialog({ )} {status === "error" && ( - + Failed{exitCode !== null && ` (${exitCode})`} @@ -278,12 +422,7 @@ export function CommandRunnerDialog({

Ready to execute

- @@ -320,9 +459,7 @@ export function CommandRunnerDialog({ {/* Footer actions */}
-
- {cwd && cwd: {cwd}} -
+
{cwd && cwd: {cwd}}
{output.length > 0 && ( - @@ -451,9 +578,7 @@ export function CommandRunner({
{/* Command preview */}
-
- Command -
+
Command
$ {fullCommand} @@ -461,9 +586,7 @@ export function CommandRunner({
{/* Description if provided */} - {description && ( -

{description}

- )} + {description &&

{description}

} {/* Actions */}
@@ -498,8 +621,8 @@ export function CommandRunner({

- For best results, copy and run in your terminal. UI execution - may not handle all interactive commands reliably. + For best results, copy and run in your terminal. UI execution may not handle all + interactive commands reliably.

@@ -571,9 +694,7 @@ export function CommandRunnerDropdown({ disabled = false, }: CommandRunnerDropdownProps) { const [dialogOpen, setDialogOpen] = useState(false); - const [selectedCommand, setSelectedCommand] = useState( - null, - ); + const [selectedCommand, setSelectedCommand] = useState(null); const [menuOpen, setMenuOpen] = useState(false); const handleSelect = useCallback((cmd: CommandOption) => { @@ -600,10 +721,7 @@ export function CommandRunnerDropdown({ {menuOpen && ( <> {/* Backdrop to close menu */} -
setMenuOpen(false)} - /> +
setMenuOpen(false)} /> {/* Menu */}
diff --git a/apps/web/src/components/studio/dashboard-header.tsx b/apps/web/src/components/studio/dashboard-header.tsx index 62844263..a2f0e65a 100644 --- a/apps/web/src/components/studio/dashboard-header.tsx +++ b/apps/web/src/components/studio/dashboard-header.tsx @@ -1,6 +1,6 @@ "use client"; -import { useRouterState } from "@tanstack/react-router"; +import { useMatch, useRouterState } from "@tanstack/react-router"; import { Avatar, AvatarFallback } from "@ui/avatar"; import { Button } from "@ui/button"; import { @@ -16,11 +16,11 @@ import { useAgentContext } from "@/lib/agent-provider"; import { ShellStatus } from "./shell-status"; import { AgentConsoleDialog } from "./agent-console-dialog"; import type { PanelType } from "./dashboard-sidebar"; +import { useStudioPanels } from "./panels/shared/use-studio-panels"; import { SidebarTrigger } from "../ui/sidebar"; const panelTitles: Record = { overview: "Overview", - dashboard: "Dashboard", setup: "Setup", services: "Services", devshells: "Dev Shells", @@ -33,7 +33,6 @@ const panelTitles: Record = { configuration: "Configuration", "local-config": "Local Config", network: "Network", - extensions: "Extensions", modules: "Modules", panels: "Panels", files: "Generated Files", @@ -48,7 +47,6 @@ const panelTitles: Record = { const pathToPanelMap: Record = { "/studio": "overview", "/studio/": "overview", - "/studio/dashboard": "dashboard", "/studio/setup": "setup", "/studio/apps": "apps", "/studio/tasks": "tasks", @@ -61,8 +59,9 @@ const pathToPanelMap: Record = { "/studio/packages": "packages", "/studio/team": "team", "/studio/network": "network", - "/studio/extensions": "extensions", "/studio/modules": "modules", + "/studio/panels": "panels", + "/studio/infra": "infra", "/studio/files": "files", "/studio/terminal": "terminal", "/studio/roadmap": "roadmap", @@ -76,6 +75,9 @@ export function DashboardHeader() { const routerState = useRouterState(); const pathname = routerState.location.pathname; const activePanel = pathToPanelMap[pathname] ?? "overview"; + const modulePage = useMatch({ from: "/studio/m/$moduleId", shouldThrow: false }); + const { modules } = useStudioPanels(); + const title = modulePage ? (modules.get(modulePage.params.moduleId)?.name ?? "Module") : panelTitles[activePanel]; return (
@@ -90,7 +92,7 @@ export function DashboardHeader() { */} {/*
*/} -

{panelTitles[activePanel]}

+

{title}

diff --git a/apps/web/src/components/studio/dashboard-sidebar.tsx b/apps/web/src/components/studio/dashboard-sidebar.tsx index da02cae4..6da0c0d2 100644 --- a/apps/web/src/components/studio/dashboard-sidebar.tsx +++ b/apps/web/src/components/studio/dashboard-sidebar.tsx @@ -1,13 +1,9 @@ "use client"; import { Logo } from "@stackpanel/ui-core/logo"; -import { Link, useRouterState } from "@tanstack/react-router"; +import { Link, useRouterState, useSearch } from "@tanstack/react-router"; import { Badge } from "@ui/badge"; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from "@ui/collapsible"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@ui/collapsible"; import { CircularProgress } from "@ui/circular-progress"; import { Sidebar, @@ -34,11 +30,9 @@ import { CheckCircle2, ChevronRight, ChevronUp, - Cloud, FileCode, Home, - LayoutDashboard, - Map, + Map as MapIcon, Network, Package, Play, @@ -65,16 +59,16 @@ import { DropdownMenuTrigger, } from "@ui/dropdown-menu"; import { - CONFIGURATION_SECTIONS, + getConfigurationSections, type ConfigurationSection, -} from "./panels/configuration"; +} from "./panels/configuration/sections"; import { useSopsConfigStatus } from "./panels/variables/use-sops-config-status"; -import { useAllPanelsGroupedByModule } from "./panels/panels-panel"; -import { getModuleIconById } from "./panels/shared"; +import { getModuleIconByName } from "./panels/shared/module-icons"; +import { studioPanelKey, useStudioPanels } from "./panels/shared/use-studio-panels"; +import { getSetupPanelSteps } from "./panels/setup/panel-steps"; export type PanelType = | "overview" - | "dashboard" | "setup" | "apps" | "packages" @@ -88,7 +82,6 @@ export type PanelType = | "network" | "infra" | "deploy" - | "extensions" | "modules" | "panels" | "files" @@ -107,7 +100,6 @@ interface NavItem { const navItems: NavItem[] = [ { id: "overview", label: "Overview", icon: Home }, - { id: "dashboard", label: "Dashboard", icon: LayoutDashboard }, { id: "checks", label: "Checks", icon: Activity }, ]; @@ -118,14 +110,10 @@ const mainNavItems: NavItem[] = [ { id: "packages", label: "Packages", icon: Package }, { id: "processes", label: "Processes", icon: Server }, { id: "network", label: "Network", icon: Network }, - { id: "deploy", label: "Deploy", icon: Rocket }, ]; const toolsNavItems: NavItem[] = [ { id: "modules", label: "Explore Modules", icon: Search }, - // { id: "panels", label: "Configure", icon: Puzzle }, - // { id: "panels", label: "Panels", icon: Activity }, - { id: "infra", label: "Infrastructure", icon: Cloud }, { id: "devshells", label: "Dev Shells", icon: Terminal }, { id: "team", label: "Team", icon: Users }, { id: "inspector", label: "Inspector", icon: Search }, @@ -133,14 +121,13 @@ const toolsNavItems: NavItem[] = [ const otherNavItems: NavItem[] = [ { id: "feature-flags", label: "Feature Flags", icon: SlidersHorizontal }, - { id: "roadmap", label: "Roadmap", icon: Map }, + { id: "roadmap", label: "Roadmap", icon: MapIcon }, { id: "docs", label: "Docs", icon: BookOpen }, ]; const coceptsNavItems: NavItem[] = [ { id: "tasks", label: "Tasks", icon: Play }, { id: "services", label: "Services", icon: Server }, - { id: "extensions", label: "Extensions", icon: Puzzle }, // { id: "files", label: "Generated Files", icon: FileCode }, { id: "local-config", label: "Local Config", icon: FileCode }, { id: "terminal", label: "Terminal", icon: SquareTerminal }, @@ -215,27 +202,21 @@ function ConfigurationSectionItem({ function ConfigurationMenuItem() { const routerState = useRouterState(); const pathname = routerState.location.pathname; - const search = routerState.location.search; - const activeSectionId = search - ? new URLSearchParams(search).get("section") - : null; + const { section: activeSectionId } = useSearch({ strict: false }); + const { panels } = useStudioPanels(); + const sections = getConfigurationSections(panels); const { state } = useSidebar(); const isCollapsed = state === "collapsed"; const isActive = - pathname === "/studio/configuration" || - pathname.startsWith("/studio/configuration/"); + pathname === "/studio/configuration" || pathname.startsWith("/studio/configuration/"); // When collapsed, just show a simple button if (isCollapsed) { return ( - + @@ -255,14 +236,14 @@ function ConfigurationMenuItem() { - {CONFIGURATION_SECTIONS.map((section) => ( + {sections.map((section) => ( @@ -274,47 +255,28 @@ function ConfigurationMenuItem() { ); } -const coreModules = [ - "process-compose", - "app-commands", - "configuration", - "local-config", - "terminal" -]; -// Filter out core stackpanel modules -function moduleFilter(mod: { id: string }) { - return !coreModules.includes(mod.id); -} - -// Configuration menu item with collapsible sections function ModulePanelsMenuItem() { const routerState = useRouterState(); const pathname = routerState.location.pathname; - const search = routerState.location.search; - const activeModuleId = search - ? new URLSearchParams(search).get("module") - : null; + const { module: activeModuleId } = useSearch({ strict: false }); const { state } = useSidebar(); const isCollapsed = state === "collapsed"; const isActive = pathname === "/studio/panels" || pathname.startsWith("/studio/panels/"); - const { modules, byModule } = useAllPanelsGroupedByModule(); - const activeModule = activeModuleId ?? modules[0]?.id ?? null; - const panelCount = (moduleId: string) => { - const data = byModule[moduleId]; - if (!data) return 0; - return data.infoPanels.length + data.appConfigPanels.length; - }; + const { panels, modules } = useStudioPanels(); + const counts = new Map(); + for (const panel of panels) { + if (panel.slot === "module") { + counts.set(panel.module, (counts.get(panel.module) ?? 0) + 1); + } + } + const activeModule = activeModuleId ?? counts.keys().next().value; // When collapsed, just show a simple button if (isCollapsed) { return ( - + @@ -328,17 +290,16 @@ function ModulePanelsMenuItem() { - Modules + Module panels - {modules.filter(moduleFilter).map((mod) => { + {Array.from(counts, ([moduleId, count]) => { + const mod = modules.get(moduleId)!; const isModActive = mod.id === activeModule; - const Icon = getModuleIconById(mod.id); - const count = panelCount(mod.id); - const hasAppConfig = (byModule[mod.id]?.appConfigPanels.length ?? 0) > 0; + const Icon = getModuleIconByName(mod.icon); return ( @@ -347,20 +308,15 @@ function ModulePanelsMenuItem() { isActive={isActive && isModActive} className="bg-transparent data-active:border-l-accent data-[active=true]:border-l-2 -ml-2 pl-4 data-[active=true]:bg-secondary rounded-l-none!" > - + {mod.name}
- {hasAppConfig && ( -
- )} - + {count}
@@ -381,15 +337,15 @@ function SetupMenuItem() { const routerState = useRouterState(); const pathname = routerState.location.pathname; const progress = useSetupProgress(); + const { panels } = useStudioPanels(); + const steps = getSetupPanelSteps(panels); + const { step: activeStep } = useSearch({ strict: false }); const { state } = useSidebar(); const isCollapsed = state === "collapsed"; - const isActive = - pathname === "/studio/setup" || pathname.startsWith("/studio/setup/"); + const isActive = pathname === "/studio/setup" || pathname.startsWith("/studio/setup/"); const isComplete = progress?.isComplete ?? false; - const progressPercent = progress - ? (progress.requiredComplete / progress.requiredTotal) * 100 - : 0; + const progressPercent = progress ? (progress.requiredComplete / progress.requiredTotal) * 100 : 0; // When collapsed, just show a simple button if (isCollapsed) { @@ -401,8 +357,7 @@ function SetupMenuItem() { tooltip="Setup" className={cn( "rounded-lg", - !isComplete && - "bg-amber-500/10 text-amber-600 dark:text-amber-400", + !isComplete && "bg-amber-500/10 text-amber-600 dark:text-amber-400", isComplete && "text-accent dark:text-accent", )} > @@ -427,11 +382,9 @@ function SetupMenuItem() { className={cn( "rounded-lg ", !isComplete && - !isActive && - "bg-sidebar-accent/10 text-sidebar-accent-foreground dark:text-sidebar-accent-foreground hover:bg-sidebar-accent/20", - isComplete && - !isActive && - "text-accent dark:text-accent-foreground", + !isActive && + "bg-sidebar-accent/10 text-sidebar-accent-foreground dark:text-sidebar-accent-foreground hover:bg-sidebar-accent/20", + isComplete && !isActive && "text-accent dark:text-accent-foreground", )} > {isComplete ? ( @@ -455,16 +408,57 @@ function SetupMenuItem() { + + {steps.map((step) => ( + + + + + {step.label} + + + + ))} + ); } +function SidebarSlotItems({ section }: { section: string }) { + const { panels, modules } = useStudioPanels(); + return panels + .filter((p) => p.slot === "sidebar" && p.nav?.section === section) + .map((panel) => { + const label = panel.nav?.label ?? panel.title; + const Icon = getModuleIconByName( + panel.nav?.icon ?? modules.get(panel.module)?.icon ?? panel.icon, + ); + return ( + + + + + {label} + + + + ); + }); +} + export function DashboardSidebar() { const { state } = useSidebar(); const isCollapsed = state === "collapsed"; const sopsConfigStatus = useSopsConfigStatus(); + const { panels } = useStudioPanels(); return ( @@ -472,10 +466,7 @@ export function DashboardSidebar() {
{!isCollapsed ? ( - + Beta @@ -486,9 +477,7 @@ export function DashboardSidebar() { to="/studio" className="flex h-8 w-8 items-center justify-center rounded-lg bg-accent relative" > - - S - + S )} @@ -522,26 +511,49 @@ export function DashboardSidebar() { {mainNavItems.map((item) => ( - + ))} + {/* Tools */} - Modules + Workspace {toolsNavItems.map((item) => ( ))} + + {(["Cloud", "Extensions"] as const).map( + (section) => + panels.some( + (panel) => + panel.slot === "sidebar" && panel.nav?.section === section, + ) && ( + + {section} + + + + + + + ), + )} + {/* Other */} Other @@ -568,18 +580,6 @@ export function DashboardSidebar() { {/* Footer */} - - {!isCollapsed && ( -
-

- Demo Mode -

-

- This is a preview of your StackPanel dashboard. -

-
- )} -
@@ -590,22 +590,19 @@ export function DashboardSidebar() { - + {otherNavItems.map((item) => ( + ? "/docs" + : item.id === "feature-flags" + ? "/studio/feature-flags" + : "/studio/roadmap" + } + className="flex items-center" + > {item.label} diff --git a/apps/web/src/components/studio/extension-dev-toolbar.test.tsx b/apps/web/src/components/studio/extension-dev-toolbar.test.tsx new file mode 100644 index 00000000..b3a72eba --- /dev/null +++ b/apps/web/src/components/studio/extension-dev-toolbar.test.tsx @@ -0,0 +1,90 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { expect, it, vi } from "vite-plus/test"; +import { ExtensionDevToolsProvider, useExtensionDevTools } from "./extension-dev-toolbar"; + +const fixture = vi.hoisted(() => ({ + onDiagnostics: undefined as ((event: { data: unknown }) => void) | undefined, + scope: ["agent", "modules", "localhost", 9876, "shop", null], + catalog: { + modules: [{ id: "sample", linked: true, uiDevUrl: "http://localhost:5173/private-path" }], + }, +})); +vi.mock("@/lib/agent-provider", () => ({ + useAgentContext: () => ({ + selectedProjectId: "shop", + host: "localhost", + port: 9876, + isAuthenticated: true, + }), +})); +vi.mock("@/lib/agent-sse-provider", () => ({ + useAgentSSEOptional: () => ({ + addEventListener: (_event: string, listener: typeof fixture.onDiagnostics) => { + fixture.onDiagnostics = listener; + return () => { + fixture.onDiagnostics = undefined; + }; + }, + }), +})); +vi.mock("./panels/modules/use-modules", () => ({ + useModuleCatalog: () => ({ data: fixture.catalog }), + useModuleQueryScope: () => fixture.scope, +})); + +function PanelProbe() { + const dev = useExtensionDevTools(); + return ( + + ); +} + +it("shows current-project eval latency and errors, logs permission decisions, and reopens linked panels", async () => { + const cache = new QueryClient(); + const refresh = vi.spyOn(cache, "invalidateQueries"); + render( + + + + + , + ); + fireEvent.click(screen.getByText("Extension development · sample")); + expect(screen.getByText("HMR: http://localhost:5173")).toBeTruthy(); + expect(screen.queryByText(/private-path/)).toBeNull(); + const data = { + linkedModules: { sample: { uiDevUrl: "http://localhost:5173/" } }, + durationMs: 81, + }; + act(() => + fixture.onDiagnostics?.({ data: { ...data, projectId: "other", error: "foreign error" } }), + ); + expect(screen.queryByText("foreign error")).toBeNull(); + act(() => + fixture.onDiagnostics?.({ data: { ...data, projectId: "shop", error: "Evaluation failed" } }), + ); + expect(screen.getByText("Nix evaluation: 81 ms")).toBeTruthy(); + expect(screen.getByText("Evaluation failed")).toBeTruthy(); + fireEvent.click(screen.getByText("Probe 0")); + fireEvent.click(screen.getByText("SDK permission log")); + expect(screen.getByText("custom: proxyFetch — denied")).toBeTruthy(); + fireEvent.click(screen.getByText("Reload Module")); + await waitFor(() => expect(screen.getByText("Probe 1")).toBeTruthy()); + expect(refresh).toHaveBeenCalledWith({ queryKey: fixture.scope }, { throwOnError: true }); + act(() => fixture.onDiagnostics?.({ data: { ...data, projectId: "shop", linkedModules: {} } })); + expect(screen.queryByLabelText("Extension development")).toBeNull(); +}); diff --git a/apps/web/src/components/studio/extension-dev-toolbar.tsx b/apps/web/src/components/studio/extension-dev-toolbar.tsx new file mode 100644 index 00000000..0cd6da54 --- /dev/null +++ b/apps/web/src/components/studio/extension-dev-toolbar.tsx @@ -0,0 +1,169 @@ +"use client"; + +import { Button } from "@stackpanel/ui-web/button"; +import { useQueryClient } from "@tanstack/react-query"; +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, + type ReactNode, +} from "react"; +import { z } from "zod"; +import { useAgentContext } from "@/lib/agent-provider"; +import { useAgentSSEOptional } from "@/lib/agent-sse-provider"; +import { useModuleCatalog, useModuleQueryScope } from "./panels/modules/use-modules"; +import { localDevUrl } from "./panels/shared/extension-url"; +import type { PermissionLog } from "./panels/shared/extension-session"; + +const diagnosticsSchema = z.object({ + projectId: z.string(), + linkedModules: z.record(z.string(), z.object({ uiDevUrl: z.string().optional() })), + durationMs: z.number().nonnegative().optional(), + error: z.string().optional(), +}); +type Diagnostics = z.infer; +type Audit = PermissionLog & { moduleId: string; panelId: string }; +interface DevTools { + revision: ReadonlyMap; + links: ReadonlyMap; + audit: (entry: Audit) => void; +} +const DevContext = createContext(null); +export const useExtensionDevTools = () => useContext(DevContext); + +/** Keep diagnostics, log history, and reload generations scoped to this tab's project. */ +export function ExtensionDevToolsProvider({ children }: { children: ReactNode }) { + const { host, port, selectedProjectId, isAuthenticated } = useAgentContext(); + const id = isAuthenticated ? selectedProjectId : null; + return ( + + {children} + + ); +} + +function ProjectDevTools({ + projectId, + children, +}: { + projectId: string | null; + children: ReactNode; +}) { + const catalog = useModuleCatalog(Boolean(projectId)); + const scope = useModuleQueryScope(); + const cache = useQueryClient(); + const subscribe = useAgentSSEOptional()?.addEventListener; + const [diagnostics, setDiagnostics] = useState(null); + const [logs, setLogs] = useState([]); + const [revision, setRevision] = useState(new Map()); + const [selected, setSelected] = useState(""); + const [reloadError, setReloadError] = useState(""); + const [reloading, setReloading] = useState(false); + useEffect( + () => + subscribe?.("module.dev.diagnostics", ({ data }) => { + const info = diagnosticsSchema.safeParse(data); + if (projectId && info.success && info.data.projectId === projectId) + setDiagnostics(info.data); + }), + [projectId, subscribe], + ); + const links = useMemo(() => { + if (diagnostics) + return new Map( + Object.entries(diagnostics.linkedModules).map(([id, link]) => [id, link.uiDevUrl ?? ""]), + ); + return new Map( + catalog.data?.modules.filter((mod) => mod.linked).map((mod) => [mod.id, mod.uiDevUrl ?? ""]), + ); + }, [catalog.data, diagnostics]); + const active = links.has(selected) ? selected : links.keys().next().value; + const audit = useCallback( + (entry: Audit) => { + if (links.has(entry.moduleId)) setLogs((prev) => [...prev.slice(-63), entry]); + }, + [links], + ); + const context = useMemo(() => ({ revision, links, audit }), [revision, links, audit]); + async function reload() { + if (!projectId || !active || reloading) return; + setReloading(true); + setReloadError(""); + // A fresh frame means a fresh server-issued launch grant, even with Vite HMR. + setRevision((old) => new Map(old).set(active, (old.get(active) ?? 0) + 1)); + try { + await cache.invalidateQueries({ queryKey: scope }, { throwOnError: true }); + } catch (error) { + setReloadError(error instanceof Error ? error.message : "Module reload failed"); + } finally { + setReloading(false); + } + } + return ( + + {children} + {projectId && active && ( + + )} + + ); +} diff --git a/apps/web/src/components/studio/module-action-stream.ts b/apps/web/src/components/studio/module-action-stream.ts new file mode 100644 index 00000000..8e477dcb --- /dev/null +++ b/apps/web/src/components/studio/module-action-stream.ts @@ -0,0 +1,91 @@ +import { toJson, type JsonObject, type JsonValue } from "@bufbuild/protobuf"; +import { ValueSchema } from "@bufbuild/protobuf/wkt"; +import { ConnectError, type Client } from "@connectrpc/connect"; +import type { ModuleService } from "@stackpanel/proto/agent/v1/module"; +import { createStore, type StoreApi } from "zustand/vanilla"; + +export interface ModuleActionRequest { + moduleId: string; + actionId: string; + args: JsonObject; +} + +interface Chunk { + id: number; + channel: "stdout" | "stderr" | "json"; + text: string; +} + +type Status = + | { kind: "running" } + | { kind: "exited"; exitCode: number } + | { kind: "failed"; reason: string }; + +interface Transcript { + chunks: Chunk[]; + status: Status; +} + +export type ModuleActionOutput = Pick< + StoreApi, + "getState" | "getInitialState" | "subscribe" +>; + +// Keep a bounded scrollback even if the executable continuously emits output. +const SCROLLBACK_CHUNKS = 1000; + +/** Starts exactly one RPC. Observers of `output` may mount, unmount or subscribe late. */ +export function startModuleActionStream( + client: Client | null, + request: ModuleActionRequest, + signal: AbortSignal, +) { + const output = createStore(() => ({ chunks: [], status: { kind: "running" } })); + let nextId = 0; + function append(channel: Chunk["channel"], text: string) { + const chunks = output.getState().chunks.slice(1 - SCROLLBACK_CHUNKS); + chunks.push({ id: nextId++, channel, text }); + output.setState({ chunks }); + } + + async function consume() { + let exitCode: number | undefined; + let json: JsonValue | undefined; + try { + if (!client) + throw new Error("Module actions are unavailable. Pair an agent and select a project."); + for await (const { event } of client.runModuleAction(request, { signal })) { + signal.throwIfAborted(); + if (exitCode !== undefined) throw new Error("Action sent output after its exit code."); + switch (event.case) { + case "stdout": + case "stderr": + append(event.case, event.value); + break; + case "json": + json = toJson(ValueSchema, event.value); + append("json", JSON.stringify(json, null, 2)); + break; + case "exitCode": + exitCode = event.value; + break; + default: + throw new Error("Unrecognized action stream event."); + } + } + // EOF alone isn't success, nor is an exit code followed by a transport error. + signal.throwIfAborted(); + if (exitCode === undefined) throw new Error("Action stream ended without an exit code."); + output.setState({ status: { kind: "exited", exitCode } }); + return { exitCode, json }; + } catch (error) { + const reason = signal.aborted + ? "Action stream canceled." + : ConnectError.from(error).rawMessage; + output.setState({ status: { kind: "failed", reason } }); + return undefined; + } + } + + return { output, finished: consume() }; +} diff --git a/apps/web/src/components/studio/overview/services-status-card.tsx b/apps/web/src/components/studio/overview/services-status-card.tsx index b90d99e7..d3d3aacd 100644 --- a/apps/web/src/components/studio/overview/services-status-card.tsx +++ b/apps/web/src/components/studio/overview/services-status-card.tsx @@ -1,278 +1,198 @@ "use client"; -import { Card, CardContent, CardHeader, CardTitle } from "@ui/card"; import { Button } from "@ui/button"; -import { - CheckCircle2, - Circle, - Database, - HardDrive, - Loader2, - RefreshCw, - Server, - XCircle, -} from "lucide-react"; -import { useMemo } from "react"; -import { useProcesses, useNixConfigQuery } from "@/lib/use-agent"; +import { Card, CardContent, CardHeader, CardTitle } from "@ui/card"; +import { CheckCircle2, Circle, Loader2, RefreshCw, Server, XCircle } from "lucide-react"; +import { z } from "zod"; import { useAgentContext } from "@/lib/agent-provider"; +import { useNixConfigQuery, useProcesses } from "@/lib/use-agent"; import { cn } from "@/lib/utils"; -interface ServiceInfo { - name: string; - displayName: string; - icon: React.ComponentType<{ className?: string }>; - enabled: boolean; - running: boolean; +type ServiceStatus = "running" | "stopped" | "unknown"; + +interface Service { + id: string; + label: string; port?: number; - status: "running" | "stopped" | "unknown"; + status: ServiceStatus; } -/** - * Card showing the status of infrastructure services (Postgres, Redis, Minio, Caddy). - * Uses nix config to determine which services are enabled, and process-compose to check if running. - */ -export function ServicesStatusCard() { - const { isConnected } = useAgentContext(); - const { data: nixConfig, isLoading: configLoading } = useNixConfigQuery(); - const { data: processes, isLoading: processesLoading, refetch } = useProcesses(); - - const services = useMemo((): ServiceInfo[] => { - const config = nixConfig?.config as Record | null; - const processList = processes?.processes ?? []; - - // Helper to check if a process is running (by exact name or substring match) - const isRunning = (names: string[]): boolean => { - return processList.some(p => - names.some(name => p.name.toLowerCase().includes(name.toLowerCase())) && p.isRunning - ); - }; - - const result: ServiceInfo[] = []; - - // Read from stackpanel.services (new canonical format) - const stackpanelServices = (config?.services ?? {}) as Record>; - for (const [name, svc] of Object.entries(stackpanelServices)) { - if (svc && svc.enable === true) { - const displayName = (svc.displayName as string) ?? name; - const icon = name.includes("postgres") ? Database - : name.includes("minio") ? HardDrive - : Server; - result.push({ - name, - displayName, - icon, - enabled: true, - running: isRunning([name]), - port: svc.port as number | undefined, - status: isRunning([name]) ? "running" : "stopped", - }); - } - } - - // Fallback: also check globalServices for backward compatibility - if (result.length === 0) { - const globalServices = (config?.globalServices ?? {}) as Record; - const getServiceConfig = (svcName: string) => - (globalServices[svcName] ?? {}) as Record; - - const postgresConfig = getServiceConfig("postgres"); - const redisConfig = getServiceConfig("redis"); - const minioConfig = getServiceConfig("minio"); - const caddyConfig = getServiceConfig("caddy"); +interface ProcessObservation { + name: string; + namespace: string; + isRunning: boolean; +} - if (postgresConfig.enable === true) { - result.push({ - name: "postgres", displayName: "PostgreSQL", icon: Database, - enabled: true, running: isRunning(["postgres", "postgresql"]), - port: postgresConfig.port as number | undefined, - status: isRunning(["postgres", "postgresql"]) ? "running" : "stopped", - }); - } - if (redisConfig.enable === true) { - result.push({ - name: "redis", displayName: "Redis", icon: Server, - enabled: true, running: isRunning(["redis"]), - port: redisConfig.port as number | undefined, - status: isRunning(["redis"]) ? "running" : "stopped", - }); - } - if (minioConfig.enable === true) { - result.push({ - name: "minio", displayName: "Minio", icon: HardDrive, - enabled: true, running: isRunning(["minio"]), - port: minioConfig.port as number | undefined, - status: isRunning(["minio"]) ? "running" : "stopped", - }); - } - if (caddyConfig.enable === true) { - result.push({ - name: "caddy", displayName: "Caddy", icon: Server, - enabled: true, running: isRunning(["caddy"]), - status: isRunning(["caddy"]) ? "running" : "stopped", - }); - } +const serviceDefinition = z.object({ + enable: z.boolean(), + displayName: z.string().nullish(), + port: z.number().nullish(), + "process-compose": z + .object({ enable: z.boolean().optional(), namespace: z.string().optional() }) + .optional(), +}); + +const serviceConfig = z.object({ + services: z.record(z.string(), serviceDefinition), +}); + +function configuredServices( + config: Record, + observations: readonly ProcessObservation[], +): Service[] | null { + const root = serviceConfig.safeParse(config); + if (!root.success) return null; + + // Process-compose uses the Nix service key as its process name. Do not + // match display names or substrings (e.g. a service's migration worker). + const byName = new Map(observations.map((process) => [process.name, process])); + const services: Service[] = []; + for (const [id, definition] of Object.entries(root.data.services)) { + if (!definition.enable) continue; + const pc = definition["process-compose"]; + const namespace = pc?.namespace ?? "services"; + const observation = byName.get(id); + let status: ServiceStatus = "unknown"; + if ( + observation && + pc?.enable !== false && + (!observation.namespace || observation.namespace === namespace) + ) { + status = observation.isRunning ? "running" : "stopped"; } + services.push({ + id, + label: definition.displayName ?? id, + port: definition.port ?? undefined, + status, + }); + } + return services; +} - return result; - }, [nixConfig, processes]); +const badges = { + running: { Icon: CheckCircle2, label: "Running", style: "bg-emerald-500/10 text-emerald-500" }, + stopped: { Icon: XCircle, label: "Stopped", style: "bg-muted text-muted-foreground" }, + unknown: { Icon: Circle, label: "Unknown", style: "bg-muted text-muted-foreground" }, +}; - const enabledServices = services.filter(s => s.enabled); - const runningCount = enabledServices.filter(s => s.running).length; - const isLoading = configLoading || processesLoading; +function ServiceList({ services }: { services: Service[] }) { + return ( +
    + {services.map((service) => { + const { Icon, label, style } = badges[service.status]; + return ( +
  • +
    +

    {service.label}

    + {service.port != null && ( +

    Port {service.port}

    + )} +
    + + + {label} + +
  • + ); + })} +
+ ); +} - if (!isConnected) { - return ( - - - - - Services - - - -

Connect to agent to view services

-
-
- ); - } +export function ServicesStatusCard() { + const { isConnected, selectedProjectId } = useAgentContext(); + const config = useNixConfigQuery(); + const processes = useProcesses(); + // GetProcesses observes the agent's local process-compose instance, not + // an explicitly selected project's instance. Never join the two by ID. + const processError = selectedProjectId + ? "the process monitor is agent-wide, not scoped to the selected project" + : processes.error?.message || processes.data?.error; + const live = !processError && processes.data?.available; + const services = + isConnected && !config.error && config.data?.config + ? configuredServices(config.data.config, live ? (processes.data?.processes ?? []) : []) + : null; + const refreshing = config.isFetching || (!selectedProjectId && processes.isFetching); + const running = services?.filter((service) => service.status === "running").length ?? 0; + const allObserved = + !!services?.length && services.every((service) => service.status !== "unknown"); return ( - - Services - {!isLoading && enabledServices.length > 0 && ( + Services + {allObserved && ( - ({runningCount}/{enabledServices.length} running) + ({running}/{services?.length} running) )} - - {isLoading ? ( -
- -
- ) : enabledServices.length === 0 ? ( -
-

No services configured

-

- Enable services in your Nix configuration -

-
+ + {!isConnected ? ( +

Connect to the agent to view services.

+ ) : config.isLoading ? ( +

+ Loading services… +

+ ) : !services ? ( +

+ Service configuration is unavailable{config.error ? `: ${config.error.message}` : "."} +

+ ) : services.length === 0 ? ( +

+ No enabled services. Enable services in your Nix configuration. +

) : ( -
- {services.map((service) => { - const Icon = service.icon; - - if (!service.enabled) { - return null; - } - - return ( -
-
-
- -
-
-

- {service.displayName} -

- {service.port && ( -

- Port {service.port} -

- )} -
-
-
- -
-
- ); - })} -
- )} - - {/* Summary footer */} - {!isLoading && enabledServices.length > 0 && ( -
-
- {runningCount === enabledServices.length ? ( - <> - - - All services running - - - ) : runningCount > 0 ? ( - <> - - - {enabledServices.length - runningCount} service(s) stopped - - - ) : ( - <> - - - No services running - - - )} + <> + {!selectedProjectId && processes.isLoading ? ( +

+ Loading live service status… +

+ ) : ( + !live && ( +

+ Live service status is unavailable{processError ? `: ${processError}` : "."} +

+ ) + )} + +
+

+ {!allObserved + ? "Some service statuses could not be confirmed" + : running === services.length + ? "All services running" + : `${services.length - running} stopped`} +

+

+ Run dev to start process-compose. +

-

- Run dev to start all services with process-compose -

-
+ )} ); } - -function ServiceStatusBadge({ status }: { status: "running" | "stopped" | "unknown" }) { - switch (status) { - case "running": - return ( -
- - Running -
- ); - case "stopped": - return ( -
- - Stopped -
- ); - default: - return ( -
- - Disabled -
- ); - } -} diff --git a/apps/web/src/components/studio/panels/apps-panel-alt.tsx b/apps/web/src/components/studio/panels/apps-panel-alt.tsx index 13208770..90b77f01 100644 --- a/apps/web/src/components/studio/panels/apps-panel-alt.tsx +++ b/apps/web/src/components/studio/panels/apps-panel-alt.tsx @@ -3,12 +3,7 @@ import { Badge } from "@ui/badge"; import { Button } from "@ui/button"; import { useQuery } from "@tanstack/react-query"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@ui/tooltip"; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@ui/tooltip"; import { AlertTriangle, ChevronDown, @@ -19,10 +14,7 @@ import { Trash2, } from "lucide-react"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { - type ProcessComposeStatusResponse, - type TurboPackage, -} from "@/lib/agent"; +import { type ProcessComposeStatusResponse, type TurboPackage } from "@/lib/agent"; import { DEFAULT_APP_ENVIRONMENT_IDS, flattenConfiguredAppVariables, @@ -31,18 +23,11 @@ import { import { useAgentContext, useAgentClient } from "@/lib/agent-provider"; import { useAgentSSEEvent } from "@/lib/agent-sse-provider"; import { cn } from "@/lib/utils"; -import { - useAppVariableLinks, - useApps, - useNixConfig, - useVariables, -} from "@/lib/use-agent"; +import { useAppVariableLinks, useApps, useVariables } from "@/lib/use-agent"; import { AddAppDialog } from "./apps/add-app-dialog"; -import { - AppExpandedContent, - type AppFramework, -} from "./apps/app-expanded-content"; -import type { AppModulePanel } from "./shared/panel-types"; +import { AppExpandedContent } from "./apps/app-expanded-content"; +import { type AppProviders, getAppProviders } from "./apps/app-providers"; +import { useStudioPanels } from "./shared/use-studio-panels"; import { useAppMutations } from "./apps/hooks"; import type { DisplayVariable, TaskWithCommand } from "./apps/types"; import type { AvailableVariable } from "./apps/app-variables-section/types"; @@ -116,15 +101,11 @@ function groupAppWarnings(warnings: CodegenWarning[]): GroupedEnvWarning[] { severity: "error" | "warning"; fix: string; order: string[]; - byKey: Map< - string, - { envKey: string; description?: string; environments: string[] } - >; + byKey: Map; } >(); for (const w of warnings) { - const severity: "error" | "warning" = - w.severity === "error" ? "error" : "warning"; + const severity: "error" | "warning" = w.severity === "error" ? "error" : "warning"; const fix = envWarningFix(w); const bucketKey = `${severity}|${fix}`; let bucket = buckets.get(bucketKey); @@ -165,16 +146,14 @@ export function AppsPanelAlt() { const { token, readFile } = useAgentContext(); const agentClient = useAgentClient(); const { data: rawApps, isLoading, error, refetch } = useApps(); - const { data: nixConfig } = useNixConfig(); + const { config: nixConfig, modules } = useStudioPanels(); const { data: rawVariables } = useVariables(); const { data: appVariableLinks } = useAppVariableLinks(); const { data: codegenWarnings } = useQuery({ queryKey: ["agent", "codegenWarnings", "appsPanel"], enabled: !!token, queryFn: async () => { - const result = (await readFile( - ".stack/gen/codegen/env-warnings.json", - )) as { + const result = (await readFile(".stack/gen/codegen/env-warnings.json")) as { exists?: boolean; content?: string; }; @@ -191,50 +170,7 @@ export function AppsPanelAlt() { // Get project name from config, fallback to "stackpanel" const projectName = - (typeof nixConfig?.projectName === "string" - ? nixConfig.projectName - : null) ?? "stackpanel"; - - // Extract PANEL_TYPE_APP_CONFIG panels from panelsComputed - // Panels come from nix eval: config.panelsComputed (flake path) or config.ui.panels (CLI path) - const appConfigPanels = useMemo((): AppModulePanel[] => { - const cfg = nixConfig as Record | null | undefined; - if (!cfg) return []; - - // Try flake eval path first (panelsComputed), then CLI config path (ui.panels) - const panels = - cfg.panelsComputed ?? - (cfg.ui as Record | undefined)?.panels; - if (!panels || typeof panels !== "object") return []; - - type RawPanel = AppModulePanel & { type?: string }; - return Object.values(panels as Record).filter( - (p): p is RawPanel => p.type === "PANEL_TYPE_APP_CONFIG", - ); - }, [nixConfig]); - - // Separate panels by category: - // - Container panels go to the Docker tab - // - Deployment panels (fly, cloudflare) go to the Deployment tab - // - Other panels go to the Modules tab - const containerPanels = useMemo(() => { - return appConfigPanels.filter((p) => p.module === "containers"); - }, [appConfigPanels]); - - const deploymentPanels = useMemo(() => { - return appConfigPanels.filter( - (p) => p.module === "deployment-fly" || p.module === "deployment-cloudflare", - ); - }, [appConfigPanels]); - - const modulePanels = useMemo(() => { - return appConfigPanels.filter( - (p) => - p.module !== "containers" && - p.module !== "deployment-fly" && - p.module !== "deployment-cloudflare", - ); - }, [appConfigPanels]); + (typeof nixConfig?.projectName === "string" ? nixConfig.projectName : null) ?? "stackpanel"; // Transform apps data to include id, stablePort, and isRunning fields const resolvedApps = useMemo(() => { @@ -242,18 +178,24 @@ export function AppsPanelAlt() { type RawApp = NonNullable[string]; const result: Record< string, - RawApp & { id: string; stablePort: number; isRunning: boolean } + RawApp & { + id: string; + stablePort: number; + isRunning: boolean; + providers: AppProviders | null; + } > = {}; for (const [id, app] of Object.entries(rawApps)) { result[id] = { ...app, id, + providers: getAppProviders(nixConfig, id, modules), stablePort: app.port ?? 3000, isRunning: false, // Will be updated from process-compose status }; } return result; - }, [rawApps]); + }, [rawApps, nixConfig, modules]); // Turbo package graph state - source of truth for available tasks const [packageGraph, setPackageGraph] = useState([]); @@ -277,7 +219,6 @@ export function AppsPanelAlt() { handleUpdateVariableInApp, handleUpdateEnvironmentsForApp, handleDeleteVariableFromApp, - handleUpdateFramework, handleDeleteApp, } = useAppMutations({ token, @@ -307,8 +248,7 @@ export function AppsPanelAlt() { if (!rawVariables) return []; return Object.entries(rawVariables).map(([id, variable]) => { // Variable is now an object with { value: string } - const value = - typeof variable === "string" ? variable : (variable?.value ?? ""); + const value = typeof variable === "string" ? variable : (variable?.value ?? ""); // Use the full ID as the display name (e.g., "/dev/DATABASE_URL") // This avoids confusion when multiple vars have the same last segment (e.g., "port") const name = id; @@ -383,17 +323,15 @@ export function AppsPanelAlt() { // Get all tasks for an app from turbo (simplified - tasks come from turbo, not app config) const getTasksForApp = useCallback( - (app: App): TaskWithCommand[] => { + (app: { path: string }): TaskWithCommand[] => { const turboTasks = getTurboTasksForApp(app.path); // Tasks come from turbo package graph only - const tasks: TaskWithCommand[] = Array.from(turboTasks.entries()).map( - ([name, command]) => ({ - name, - command, - isOverridden: false, - }), - ); + const tasks: TaskWithCommand[] = Array.from(turboTasks.entries()).map(([name, command]) => ({ + name, + command, + isOverridden: false, + })); return tasks; }, @@ -405,11 +343,7 @@ export function AppsPanelAlt() { if (!processComposeStatus?.running || !processComposeStatus.processes) { return new Set(); } - return new Set( - processComposeStatus.processes - .filter((p) => p.is_running) - .map((p) => p.name), - ); + return new Set(processComposeStatus.processes.filter((p) => p.is_running).map((p) => p.name)); }, [processComposeStatus]); // Convert resolved apps to display format @@ -427,15 +361,10 @@ export function AppsPanelAlt() { const linkedVariableId = mapping.environments .map((envName) => appVariableLinks?.[appId]?.[envName]?.[mapping.envKey]) - .find(Boolean) ?? - parseVariableLinkReference(mapping.value); - const linkedVariable = linkedVariableId - ? rawVariables?.[linkedVariableId] - : undefined; + .find(Boolean) ?? parseVariableLinkReference(mapping.value); + const linkedVariable = linkedVariableId ? rawVariables?.[linkedVariableId] : undefined; const linkedValue = - typeof linkedVariable === "string" - ? linkedVariable - : (linkedVariable?.value ?? ""); + typeof linkedVariable === "string" ? linkedVariable : (linkedVariable?.value ?? ""); const typeName = linkedVariableId ? getVariableType(linkedVariableId, linkedValue) : mapping.isSecret @@ -444,9 +373,7 @@ export function AppsPanelAlt() { const isSecret = mapping.isSecret || typeName === "secret"; return { envKey: mapping.envKey, - value: linkedVariableId - ? buildVariableLinkReference(linkedVariableId) - : mapping.value, + value: linkedVariableId ? buildVariableLinkReference(linkedVariableId) : mapping.value, environments: mapping.environments, isSecret, typeName, @@ -467,7 +394,7 @@ export function AppsPanelAlt() { name: app.name, path: app.path, domain: app.domain ?? "", - type: app.type, + providers: app.providers, port: app.port ?? stablePort, stablePort, description: app.description, @@ -481,12 +408,6 @@ export function AppsPanelAlt() { }); }, [appVariableLinks, resolvedApps, getTasksForApp, projectName, rawVariables, runningProcesses]); - // Derive the active framework from the app's type field - const getFrameworkForApp = (appType?: string): AppFramework => { - if (appType === "go" || appType === "bun") return appType; - return null; - }; - // Auto-expand first app if none expanded useEffect(() => { if (apps.length > 0 && !expandedApp) { @@ -538,9 +459,7 @@ export function AppsPanelAlt() { if (error) { return (
-

- Error loading apps: {error.message} -

+

Error loading apps: {error.message}

); } @@ -559,12 +478,8 @@ export function AppsPanelAlt() { {apps.length === 0 ? (
-

- No apps configured yet. -

-

- Add your first app to get started. -

+

No apps configured yet.

+

Add your first app to get started.

) : (
@@ -612,14 +527,14 @@ export function AppsPanelAlt() { : "fill-muted text-muted" }`} /> - - {app.name} - - {app.type && ( - - {app.type} - - )} + {app.name} + {app.providers?.runtime + .filter((runtime) => runtime.enabled) + .map((runtime) => ( + + {runtime.label} + + ))} {hasWarnings && ( @@ -634,9 +549,7 @@ export function AppsPanelAlt() {
{appWarnings.map((warning, index) => ( -
- {warning.message} -
+
{warning.message}
))}
@@ -661,9 +574,7 @@ export function AppsPanelAlt() { :{app.port}
- - Stable port for this app - + Stable port for this app
@@ -690,7 +601,7 @@ export function AppsPanelAlt() { {/* Expanded Content with subnav */} {isExpanded && ( <> - {hasWarnings && ( + {hasWarnings && (() => { const groups = groupAppWarnings(appWarnings); return ( @@ -703,8 +614,7 @@ export function AppsPanelAlt() { const iconColor = isError ? "text-red-600 dark:text-red-400" : "text-amber-600 dark:text-amber-400"; - const noun = - group.keys.length === 1 ? "env var" : "env vars"; + const noun = group.keys.length === 1 ? "env var" : "env vars"; const heading = isError ? `Required ${noun} missing (${group.keys.length})` : `Env ${noun} warning (${group.keys.length})`; @@ -717,9 +627,7 @@ export function AppsPanelAlt() { {heading} → - - {group.fix} - + {group.fix}
    {group.keys.map((entry) => ( @@ -748,23 +656,12 @@ export function AppsPanelAlt() { })}
); - })() - )} + })()} p.apps[app.id] != null, - )} - containerPanels={containerPanels.filter( - (p) => p.apps[app.id] != null, - )} - deploymentPanels={deploymentPanels.filter( - (p) => p.apps[app.id] != null, - )} editingTask={editingTask} taskCommandOverride={taskCommandOverride} onTaskEdit={handleTaskEdit} @@ -772,19 +669,9 @@ export function AppsPanelAlt() { onTaskCancel={handleTaskCancel} onTaskCommandChange={setTaskCommandOverride} onAddVariable={(envKey, value, environments) => - handleAddVariableToApp( - app.id, - envKey, - value, - environments, - ) + handleAddVariableToApp(app.id, envKey, value, environments) } - onUpdateVariable={( - oldEnvKey, - newEnvKey, - value, - environments, - ) => + onUpdateVariable={(oldEnvKey, newEnvKey, value, environments) => handleUpdateVariableInApp( app.id, oldEnvKey, @@ -793,15 +680,10 @@ export function AppsPanelAlt() { environments, ) } - onDeleteVariable={(envKey) => - handleDeleteVariableFromApp(app.id, envKey) - } + onDeleteVariable={(envKey) => handleDeleteVariableFromApp(app.id, envKey)} onUpdateEnvironments={(environments) => handleUpdateEnvironmentsForApp(app.id, environments) } - onFrameworkChange={(fw) => - handleUpdateFramework(app.id, fw) - } /> )} diff --git a/apps/web/src/components/studio/panels/apps/add-app-dialog.tsx b/apps/web/src/components/studio/panels/apps/add-app-dialog.tsx index ca072093..8900a651 100644 --- a/apps/web/src/components/studio/panels/apps/add-app-dialog.tsx +++ b/apps/web/src/components/studio/panels/apps/add-app-dialog.tsx @@ -2,157 +2,156 @@ import { Button } from "@ui/button"; import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, } from "@ui/dialog"; import { Loader2, Plus } from "lucide-react"; import { useCallback, useState } from "react"; import { toast } from "sonner"; -import { useAgentContext, useAgentClient } from "@/lib/agent-provider"; -import type { AppEntity } from "@/lib/types"; -import { usePatchNixData } from "@/lib/use-agent"; +import { useAgentRpcClient, usePatchNixData } from "@/lib/use-agent"; +import { useStudioPanels } from "../shared/use-studio-panels"; +import { appPathSegment, getAppProviders } from "./app-providers"; -import { - type AppForm, - AppFormFields, - type AppFormValues, - parsePortValue, -} from "./app-form-fields"; +import { type AppForm, AppFormFields, type AppFormValues, parsePortValue } from "./app-form-fields"; interface AddAppDialogProps { - onSuccess: () => void; + onSuccess: () => void; } export function AddAppDialog({ onSuccess }: AddAppDialogProps) { - const { token } = useAgentContext(); - const client = useAgentClient(); - const patchNixData = usePatchNixData(); - const [dialogOpen, setDialogOpen] = useState(false); - const [isSaving, setIsSaving] = useState(false); - const [formRef, setFormRef] = useState(null); - const [isFormValid, setIsFormValid] = useState(false); - - const handleFormReady = useCallback((form: AppForm) => { - setFormRef(form); - }, []); - - const handleValuesChange = useCallback((values: AppFormValues) => { - const hasId = values.id?.trim().length > 0; - const hasPath = values.path?.trim().length > 0; - setIsFormValid(hasId && hasPath); - }, []); - - const handleOpenChange = (open: boolean) => { - setDialogOpen(open); - if (!open) { - // Reset form and validity when closing - formRef?.reset(); - setIsFormValid(false); - } - }; - - const handleSubmit = async () => { - if (!formRef || !token) { - toast.error("Not connected to agent"); - return; - } - - // Trigger validation - const isValid = await formRef.trigger(); - if (!isValid) return; - - const values = formRef.getValues(); - - if (!values.id.trim()) { - toast.error("Please enter an app ID"); - return; - } - - setIsSaving(true); - try { - const appsClient = client.nix.mapEntity("apps"); - - const existingApp = await appsClient.get(values.id); - if (existingApp) { - toast.error(`App "${values.id}" already exists`); - setIsSaving(false); - return; - } - - // With simplified schema: environments is Record - // Start with default "dev" environment - const newApp: AppEntity = { - id: values.id, - name: values.name || values.id, - description: values.description || undefined, - path: values.path || `apps/${values.id}`, - type: values.type || "bun", - port: parsePortValue(values.port), - domain: values.domain || undefined, - environments: { - dev: { name: "dev", env: {} }, - }, - }; - - await patchNixData.mutateAsync({ - entity: "apps", - key: "_root", - path: values.id, - value: JSON.stringify(newApp), - valueType: "object", - }); - toast.success( - `Created app "${values.id}". You can now configure tasks and variables.`, - ); - handleOpenChange(false); - onSuccess(); - } catch (err) { - toast.error(err instanceof Error ? err.message : "Failed to create app"); - } finally { - setIsSaving(false); - } - }; - - return ( - - - - - Add New App - - Create a new app. You can configure tasks and variables after - creation. - - -
- -
- - - - -
-
- ); + const client = useAgentRpcClient(); + const { config, modules, error, isLoading } = useStudioPanels(); + const runtimes = getAppProviders(config, null, modules)?.runtime ?? []; + const patchNixData = usePatchNixData(); + const [dialogOpen, setDialogOpen] = useState(false); + const [isSaving, setIsSaving] = useState(false); + const [formRef, setFormRef] = useState(null); + const [isFormValid, setIsFormValid] = useState(false); + + const handleFormReady = useCallback((form: AppForm) => { + setFormRef(form); + }, []); + + const handleValuesChange = useCallback((values: AppFormValues) => { + const hasId = values.id?.trim().length > 0; + const hasPath = values.path?.trim().length > 0; + setIsFormValid(hasId && hasPath); + }, []); + + const handleOpenChange = (open: boolean) => { + setDialogOpen(open); + if (!open) { + // Reset form and validity when closing + formRef?.reset(); + setIsFormValid(false); + } + }; + + const handleSubmit = async () => { + if (!formRef || !client) { + toast.error("Not connected to agent"); + return; + } + + // Trigger validation + const isValid = await formRef.trigger(); + if (!isValid) return; + + const values = formRef.getValues(); + + if (!values.id.trim()) { + toast.error("Please enter an app ID"); + return; + } + + setIsSaving(true); + try { + const { apps } = await client.getApps({}); + if (Object.hasOwn(apps, values.id)) { + toast.error(`App "${values.id}" already exists`); + setIsSaving(false); + return; + } + + // With simplified schema: environments is Record + // Start with default "dev" environment + if (values.runtime && (error || !runtimes.some(({ id }) => id === values.runtime))) { + throw new Error("The selected runtime is no longer available in this project"); + } + const newApp = { + name: values.name || values.id, + description: values.description || undefined, + path: values.path || `apps/${values.id}`, + ...(values.runtime ? { [values.runtime]: { enable: true } } : {}), + port: parsePortValue(values.port), + domain: values.domain || undefined, + environments: { + dev: { name: "dev", env: {} }, + }, + }; + + await patchNixData.mutateAsync({ + entity: "apps", + key: "_root", + path: appPathSegment(values.id), + value: JSON.stringify(newApp), + valueType: "object", + }); + toast.success(`Created app "${values.id}". You can now configure tasks and variables.`); + handleOpenChange(false); + onSuccess(); + } catch (err) { + toast.error(err instanceof Error ? err.message : "Failed to create app"); + } finally { + setIsSaving(false); + } + }; + + return ( + + + + + Add New App + + Create a new app. You can configure tasks and variables after creation. + + +
+ {error && ( +

+ Could not load runtimes: {error.message} +

+ )} + {isLoading && ( +

+ Loading runtimes… +

+ )} + +
+ + + + +
+
+ ); } diff --git a/apps/web/src/components/studio/panels/apps/app-expanded-content.tsx b/apps/web/src/components/studio/panels/apps/app-expanded-content.tsx index 0d1b3fd0..96b11cc3 100644 --- a/apps/web/src/components/studio/panels/apps/app-expanded-content.tsx +++ b/apps/web/src/components/studio/panels/apps/app-expanded-content.tsx @@ -1,23 +1,13 @@ "use client"; -import { useMemo, useState } from "react"; +import { type ElementType, type ReactNode, useMemo, useState } from "react"; import { Button } from "@ui/button"; import { Input } from "@ui/input"; import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@ui/select"; -import { - Boxes, - Container, FolderOpen, ListChecks, Pencil, Plus, - Rocket, Settings, ShieldCheck, Variable, @@ -26,12 +16,11 @@ import { AppVariablesSection } from "./app-variables-section"; import type { DisplayVariable, TaskWithCommand } from "./types"; import type { AvailableVariable } from "./app-variables-section/types"; import { CardContent } from "@/components/ui/card"; -import type { AppModulePanel, ModuleGroup } from "../shared/panel-types"; -import { - AppConfigFormRenderer, - getModuleIconByName, - formatModuleName, -} from "../shared"; +import { getModuleIconByName } from "../shared/module-icons"; +import { StudioPanel } from "../shared/studio-panel"; +import { studioPanelKey, useStudioPanels } from "../shared/use-studio-panels"; +import { AppProviderSelectors } from "./app-provider-selectors"; +import { type AppProviders, getAppPanelMounts } from "./app-providers"; // --------------------------------------------------------------------------- // Types @@ -41,22 +30,16 @@ import { interface NavItem { id: string; label: string; - icon: React.ComponentType<{ className?: string }>; + icon: ElementType; } -const navItems: NavItem[] = [ +const coreNavItems: NavItem[] = [ { id: "overview", label: "Overview", icon: Settings }, { id: "tasks", label: "Tasks", icon: ListChecks }, { id: "variables", label: "Variables", icon: Variable }, - { id: "docker", label: "Docker", icon: Container }, - { id: "deployment", label: "Deployment", icon: Rocket }, { id: "checks", label: "Checks", icon: ShieldCheck }, - { id: "modules", label: "Modules", icon: Boxes }, ]; -/** The currently active framework for an app, or null for none */ -export type AppFramework = "go" | "bun" | null; - /** Props for the expanded content area within an app item */ export interface AppExpandedContentProps { app: { @@ -64,7 +47,7 @@ export interface AppExpandedContentProps { name: string; path: string; domain: string; - type?: string; + providers: AppProviders | null; port: number; stablePort: number; description?: string; @@ -74,16 +57,9 @@ export interface AppExpandedContentProps { variables: DisplayVariable[]; isRunning: boolean; }; - framework: AppFramework; environmentOptions: string[]; availableVariables: AvailableVariable[]; disabled?: boolean; - /** Module config panels for this app (PANEL_TYPE_APP_CONFIG) */ - modulePanels?: AppModulePanel[]; - /** Container config panels for this app */ - containerPanels?: AppModulePanel[]; - /** Deployment config panels for this app */ - deploymentPanels?: AppModulePanel[]; // Task editing editingTask: { appId: string; taskName: string } | null; taskCommandOverride: string; @@ -92,11 +68,7 @@ export interface AppExpandedContentProps { onTaskCancel: () => void; onTaskCommandChange: (value: string) => void; // Variable mutations - onAddVariable: ( - envKey: string, - value: string, - environments: string[], - ) => void; + onAddVariable: (envKey: string, value: string, environments: string[]) => void; onUpdateVariable: ( oldEnvKey: string, newEnvKey: string, @@ -105,8 +77,6 @@ export interface AppExpandedContentProps { ) => void; onDeleteVariable: (envKey: string) => void; onUpdateEnvironments: (environments: string[]) => void; - // Framework mutation - onFrameworkChange: (framework: AppFramework) => void; } // --------------------------------------------------------------------------- @@ -115,13 +85,9 @@ export interface AppExpandedContentProps { export function AppExpandedContent({ app, - framework, environmentOptions, availableVariables, disabled, - modulePanels, - containerPanels, - deploymentPanels, editingTask, taskCommandOverride, onTaskEdit, @@ -132,14 +98,34 @@ export function AppExpandedContent({ onUpdateVariable, onDeleteVariable, onUpdateEnvironments, - onFrameworkChange, }: AppExpandedContentProps) { - const [activeSection, setActiveSection] = useState("overview"); + const [requestedSection, setActiveSection] = useState("overview"); + const { catalog, isLoading, error } = useStudioPanels(); + const { providers } = app; + const mounts = useMemo( + () => getAppPanelMounts(catalog, app.id, providers), + [catalog, app.id, providers], + ); + const navItems = coreNavItems.concat( + mounts.tabs.map((panel) => ({ + id: studioPanelKey(panel), + label: panel.nav?.label || panel.title, + icon: getModuleIconByName(panel.nav?.icon || panel.icon), + })), + ); + // If a module is removed or stops applying, don't strand the app on a missing tab. + const activeSection = navItems.some((item) => item.id === requestedSection) + ? requestedSection + : "overview"; + const activePanel = mounts.tabs.find((panel) => studioPanelKey(panel) === activeSection); return ( {/* Horizontal tab bar */} -
+
+ {/* Content area */}
{activeSection === "overview" && ( - + + {error ? ( +

+ Could not load app extensions: {error.message} +

+ ) : isLoading ? ( +

+ Loading app extensions… +

+ ) : providers ? ( + <> + + {[...mounts.runtime, ...mounts.framework].map((panel) => ( + + ))} + + ) : ( +

+ Evaluated provider data is unavailable for this app. +

+ )} +
)} {activeSection === "tasks" && ( )} - {activeSection === "modules" && ( - - )} - {activeSection === "docker" && ( - - )} - {activeSection === "deployment" && ( - - )} + {activePanel && } {activeSection === "checks" && }
@@ -228,36 +209,14 @@ export function AppExpandedContent({ // Overview Tab // --------------------------------------------------------------------------- -const FRAMEWORK_OPTIONS: Array<{ - value: string; - label: string; - description: string; -}> = [ - { value: "none", label: "None", description: "No framework module" }, - { - value: "go", - label: "Go", - description: "Go toolchain, air live reload, and binary packaging", - }, - { - value: "bun", - label: "Bun", - description: "Bun runtime, build scripts, and packaging", - }, - ]; - function OverviewTab({ app, - framework, - disabled, onNavigate, - onFrameworkChange, + children, }: { app: AppExpandedContentProps["app"]; - framework: AppFramework; - disabled?: boolean; onNavigate: (section: string) => void; - onFrameworkChange: (framework: AppFramework) => void; + children: ReactNode; }) { return (
@@ -279,37 +238,16 @@ function OverviewTab({
Port
{app.port}
-
-
Framework
- -
{app.description && (
-
- Description -
+
Description
{app.description}
)}
+ {children} + {/* Summary cards */}
-
@@ -442,109 +371,6 @@ function TasksTab({ ); } -// --------------------------------------------------------------------------- -// Docker Tab - Container configuration -// --------------------------------------------------------------------------- - -function DockerTab({ - appId, - panels, - disabled, -}: { - appId: string; - panels: AppModulePanel[]; - disabled?: boolean; -}) { - if (panels.length === 0) { - return ( -
-

- Container building is not enabled for this app. -

-

- Enable container support in your Nix configuration: -

-
-          {`stackpanel.apps.${appId}.container.enable = true;`}
-        
- -
- ); - } - - return ( -
- {panels.map((panel) => ( - - ))} -
- ); -} - -// --------------------------------------------------------------------------- -// Deployment Tab - Fly.io / Cloudflare configuration -// --------------------------------------------------------------------------- - -function DeploymentTab({ - appId, - panels, - disabled, -}: { - appId: string; - panels: AppModulePanel[]; - disabled?: boolean; -}) { - if (panels.length === 0) { - return ( -
-

- Deployment is not enabled for this app. -

-

- Enable deployment in your Nix configuration: -

-
-          {`stackpanel.apps.${appId}.deployment = {
-  enable = true;
-  provider = "fly"; # or "cloudflare"
-};`}
-        
- -
- ); - } - - return ( -
- {panels.map((panel) => ( - - ))} -
- ); -} - // --------------------------------------------------------------------------- // Checks Tab - Shows app-specific healthchecks // --------------------------------------------------------------------------- @@ -580,8 +406,8 @@ function ChecksTab({ appId }: { appId: string }) { }); }, [summary, appId]); - const hasChecks = appRelatedModules.length > 0 && - appRelatedModules.some(([_, mod]) => mod.checks?.length > 0); + const hasChecks = + appRelatedModules.length > 0 && appRelatedModules.some(([_, mod]) => mod.checks?.length > 0); return (
@@ -597,9 +423,7 @@ function ChecksTab({ appId }: { appId: string }) { disabled={isLoading || isRefreshing} className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs bg-secondary hover:bg-secondary/80 transition-colors disabled:opacity-50" > - + Run Checks
@@ -626,11 +450,9 @@ function ChecksTab({ appId }: { appId: string }) {

No healthchecks configured for this app

-

- Add checks in your Nix config: -

+

Add checks in your Nix config:

-{`stackpanel.apps.${appId}.commands.check = {
+            {`stackpanel.apps.${appId}.commands.check = {
   exec = "bun run typecheck";
 };`}
           
@@ -641,10 +463,7 @@ function ChecksTab({ appId }: { appId: string }) { {hasChecks && (
{appRelatedModules.map(([moduleName, moduleHealth]) => ( - + ))}
)} @@ -661,11 +480,7 @@ function ChecksTab({ appId }: { appId: string }) { ); } -function AppHealthModule({ - moduleHealth, -}: { - moduleHealth: ModuleHealth; -}) { +function AppHealthModule({ moduleHealth }: { moduleHealth: ModuleHealth }) { const status = moduleHealth.status || "HEALTH_STATUS_UNKNOWN"; const checks = moduleHealth.checks || []; @@ -708,20 +523,14 @@ function AppHealthcheckItem({ result }: { result: HealthcheckResult }) {
{checkName} {result.durationMs > 0 && ( - - {result.durationMs}ms - + {result.durationMs}ms )}
{check?.description && ( -

- {check.description} -

+

{check.description}

)} {result.error && ( -

- {result.error} -

+

{result.error}

)} {result.output && status === "HEALTH_STATUS_HEALTHY" && (

@@ -732,96 +541,3 @@ function AppHealthcheckItem({ result }: { result: HealthcheckResult }) {

); } - -// --------------------------------------------------------------------------- -// Modules Tab - Vertical subnav per module + panel content -// --------------------------------------------------------------------------- - -function ModulesTab({ - appId, - panels, - disabled, -}: { - appId: string; - panels: AppModulePanel[]; - disabled?: boolean; -}) { - const [activeModule, setActiveModule] = useState(null); - - // Group panels by module (preserves order) - const moduleGroups: ModuleGroup[] = useMemo(() => { - const groups: ModuleGroup[] = []; - const seen = new Set(); - - for (const panel of panels) { - if (!seen.has(panel.module)) { - seen.add(panel.module); - groups.push({ - id: panel.module, - label: formatModuleName(panel.module), - icon: panel.icon, - panels: [], - }); - } - groups.find((g) => g.id === panel.module)?.panels.push(panel); - } - return groups; - }, [panels]); - - // Resolve active module (default to first) - const selected = activeModule ?? moduleGroups[0]?.id ?? null; - const selectedGroup = moduleGroups.find((g) => g.id === selected); - - if (panels.length === 0) { - return ( -
-

- No module configuration panels available for this app. -

-

- Module panels appear when a language module (Go, Bun, etc.) or - tool module (OxLint, etc.) is enabled for this app. -

-
- ); - } - - return ( -
- {/* Vertical subnav */} - - - {/* Panel content */} -
- {selectedGroup?.panels.map((panel) => ( - - ))} -
-
- ); -} diff --git a/apps/web/src/components/studio/panels/apps/app-form-fields.tsx b/apps/web/src/components/studio/panels/apps/app-form-fields.tsx index 83aa180a..01216df2 100644 --- a/apps/web/src/components/studio/panels/apps/app-form-fields.tsx +++ b/apps/web/src/components/studio/panels/apps/app-form-fields.tsx @@ -2,34 +2,23 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { - Form, - FormControl, - FormDescription, - FormField, - FormItem, - FormLabel, - FormMessage, + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, } from "@ui/form"; import { Input } from "@ui/input"; -import { - InputGroup, - InputGroupAddon, - InputGroupInput, - InputGroupText, -} from "@ui/input-group"; +import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from "@ui/input-group"; import { Label } from "@ui/label"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@ui/select"; import { Globe } from "lucide-react"; import { useEffect } from "react"; import { useForm } from "react-hook-form"; import { z } from "zod"; -import { APP_TYPES } from "./constants"; +import { ProviderSelect } from "./app-provider-selectors"; +import type { AppProvider } from "./app-providers"; /** * App form schema - simplified for the new schema. @@ -37,13 +26,13 @@ import { APP_TYPES } from "./constants"; * not through this form. */ export const appFormSchema = z.object({ - id: z.string().min(1, "App ID is required").max(36), - name: z.string().max(100).optional(), - description: z.string().max(500).optional(), - path: z.string().min(1, "Path is required").max(200), - type: z.string().min(1), - port: z.string().optional(), - domain: z.string().max(100).optional(), + id: z.string().min(1, "App ID is required").max(36), + name: z.string().max(100).optional(), + description: z.string().max(500).optional(), + path: z.string().min(1, "Path is required").max(200), + runtime: z.string(), + port: z.string().optional(), + domain: z.string().max(100).optional(), }); export type AppFormValues = z.infer; @@ -52,215 +41,191 @@ export type AppForm = ReturnType>; /** Convert form values port string to number for API submission */ export function parsePortValue(port: string | undefined): number | undefined { - if (!port) return undefined; - const parsed = Number.parseInt(port, 10); - return Number.isNaN(parsed) ? undefined : parsed; + if (!port) return undefined; + const parsed = Number.parseInt(port, 10); + return Number.isNaN(parsed) ? undefined : parsed; } interface AppFormFieldsProps { - /** Optional ID field for "add" mode - not shown in edit mode */ - showIdField?: boolean; - /** Hide tasks and variables sections (used in Add App form) - deprecated, always hidden now */ - hideTasksAndVariables?: boolean; - /** Default values to populate the form */ - defaultValues?: Partial; - /** Callback when form values change */ - onValuesChange?: (values: AppFormValues) => void; - /** Expose form instance to parent */ - onFormReady?: (form: AppForm) => void; + runtimes: AppProvider[]; + /** Optional ID field for "add" mode - not shown in edit mode */ + showIdField?: boolean; + /** Default values to populate the form */ + defaultValues?: Partial; + /** Callback when form values change */ + onValuesChange?: (values: AppFormValues) => void; + /** Expose form instance to parent */ + onFormReady?: (form: AppForm) => void; } export function AppFormFields({ - showIdField = false, - defaultValues, - onValuesChange, - onFormReady, + runtimes, + showIdField = false, + defaultValues, + onValuesChange, + onFormReady, }: AppFormFieldsProps) { - const form = useForm({ - // @ts-expect-error - zodResolver type mismatch between zod versions - resolver: zodResolver(appFormSchema), - defaultValues: { - id: "", - name: "", - description: "", - path: "", - type: "bun", - port: "", - domain: "", - ...defaultValues, - }, - }); + const form = useForm({ + resolver: zodResolver(appFormSchema), + defaultValues: { + id: "", + name: "", + description: "", + path: "", + runtime: "", + port: "", + domain: "", + ...defaultValues, + }, + }); - // Expose form to parent - useEffect(() => { - onFormReady?.(form); - }, [form, onFormReady]); + // Expose form to parent + useEffect(() => { + onFormReady?.(form); + }, [form, onFormReady]); - // Watch for changes and notify parent - useEffect(() => { - if (!onValuesChange) return; + // Watch for changes and notify parent + useEffect(() => { + if (!onValuesChange) return; - const subscription = form.watch((values) => { - onValuesChange(values as AppFormValues); - }); + const subscription = form.watch((values) => { + onValuesChange(values as AppFormValues); + }); - return () => subscription.unsubscribe(); - }, [form, onValuesChange]); + return () => subscription.unsubscribe(); + }, [form, onValuesChange]); - return ( -
-
- {showIdField && ( - ( - - App ID * - - - - - Unique identifier for this app - - - - )} - /> - )} -
- ( - - Display Name - - - - - - )} - /> + return ( + +
+ {showIdField && ( + ( + + App ID * + + + + Unique identifier for this app + + + )} + /> + )} +
+ ( + + Display Name + + + + + + )} + /> - ( - - Type - - - - )} - /> -
- ( - - Description - - - - - - )} - /> - ( - - Path {showIdField && "*"} - - - - - Relative path to the app directory - - - - )} - /> -
- ( - - Dev Port - - - - Port for local development - - - )} - /> + ( + id === field.value)} + disabled={runtimes.length === 0} + onChange={(id) => field.onChange(id ?? "")} + /> + )} + /> +
+ ( + + Description + + + + + + )} + /> + ( + + Path {showIdField && "*"} + + + + Relative path to the app directory + + + )} + /> +
+ ( + + Dev Port + + + + Port for local development + + + )} + /> - ( - - Local Domain - - - - - - - - .internal - - - - Custom local domain - - - )} - /> -
-
- - ); + ( + + Local Domain + + + + + + + + .internal + + + + Custom local domain + + + )} + /> +
+
+ + ); } diff --git a/apps/web/src/components/studio/panels/apps/app-provider-selectors.tsx b/apps/web/src/components/studio/panels/apps/app-provider-selectors.tsx new file mode 100644 index 00000000..413621f5 --- /dev/null +++ b/apps/web/src/components/studio/panels/apps/app-provider-selectors.tsx @@ -0,0 +1,149 @@ +import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ui/select"; +import { useAgentContext } from "@/lib/agent-provider"; +import { agentQueryKeys, useAgentRpcClient, useNixConfigKey } from "@/lib/use-agent"; +import { + type AppProvider, + type AppProviders, + appPathSegment, + compatibleFrameworks, + planProviderChange, + type ProviderKind, +} from "./app-providers"; + +export function ProviderSelect({ + label, + options, + enabled, + disabled, + onChange, +}: { + label: string; + options: AppProvider[]; + enabled: AppProvider[]; + disabled: boolean; + onChange: (id: string | null) => void; +}) { + const current = enabled.length === 1 ? enabled[0] : undefined; + const currentAvailable = current && options.some(({ id }) => id === current.id); + // Prefix option values so an externally registered provider named "none" is selectable. + const value = enabled.length === 0 ? "none" : currentAvailable ? `id:${current.id}` : ""; + return ( +
+
{label}
+ + {enabled.length > 1 && ( +

+ Multiple enabled; choose one to replace them. +

+ )} + {current && !currentAvailable && ( +

Incompatible with the current runtime.

+ )} +
+ ); +} + +export function AppProviderSelectors({ + appId, + providers, + disabled = false, +}: { + appId: string; + providers: AppProviders; + disabled?: boolean; +}) { + const client = useAgentRpcClient(); + const queryClient = useQueryClient(); + const configKey = useNixConfigKey(); + const { host, port, selectedProjectId, projectRoot } = useAgentContext(); + const scope = [host, port, selectedProjectId ?? projectRoot] as const; + const mutationKey = ["app-provider-selection", ...scope, appId]; + const pending = useIsMutating({ mutationKey, exact: true }) > 0; + const save = useMutation({ + mutationKey, + mutationFn: async ({ kind, id }: { kind: ProviderKind; id: string | null }) => { + if (!client) throw new Error("Not connected to agent"); + const patches = planProviderChange(providers, kind, id); + let applied = 0; + try { + for (const { path, enabled } of patches) { + const response = await client.patchNixData({ + entity: "apps", + key: "_root", + path: `${appPathSegment(appId)}.${path}`, + valueType: "bool", + value: JSON.stringify(enabled), + }); + if (!response.success) throw new Error(response.error || `Could not update ${path}`); + applied++; + } + } catch (cause) { + if (!applied) throw cause; + throw new Error( + `Some changes were saved. ${cause instanceof Error ? cause.message : String(cause)}`, + ); + } finally { + // Scope and transport are captured at the start of the save, even if Studio changes projects. + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: configKey, + exact: true, + }), + queryClient.invalidateQueries({ + queryKey: [...agentQueryKeys.apps(), ...scope], + exact: true, + }), + ]); + } + }, + }); + + const locked = disabled || !client || pending; + return ( +
+
+ p.enabled)} + disabled={locked} + onChange={(id) => save.mutate({ kind: "runtime", id })} + /> + p.enabled)} + disabled={locked} + onChange={(id) => save.mutate({ kind: "framework", id })} + /> +
+ {pending && ( +

+ Saving provider selection… +

+ )} + {save.error && ( +

+ Could not save provider selection: {save.error.message} +

+ )} +
+ ); +} diff --git a/apps/web/src/components/studio/panels/apps/app-providers.test.ts b/apps/web/src/components/studio/panels/apps/app-providers.test.ts new file mode 100644 index 00000000..8fc51408 --- /dev/null +++ b/apps/web/src/components/studio/panels/apps/app-providers.test.ts @@ -0,0 +1,117 @@ +import { expect, it } from "vite-plus/test"; +import type { NixPanel } from "../shared/panel-types"; +import { + compatibleFrameworks, + getAppPanelMounts, + getAppProviders, + planProviderChange, +} from "./app-providers"; + +const modules = new Map(["js-tools", "native", "web-tools", "portable"].map((id) => [id, {}])); +const config = { + apps: { + web: { type: "native", js: { enable: true }, framework: { site: { enable: true } } }, + api: { native: { enable: true } }, + script: {}, + }, + appRuntimes: { js: { module: "js-tools" }, native: { module: "native" }, disabled: { module: "disabled" } }, + appFrameworks: { + site: { module: "web-tools", label: "Site", compatibleRuntimes: ["js"] }, + "native.web": { module: "native", compatibleRuntimes: ["native"] }, + portable: { module: "portable", compatibleRuntimes: [] }, + }, +}; + +function providersFor(appId: string) { + const providers = getAppProviders(config, appId, modules); + if (!providers) throw new Error(`Missing app ${appId}`); + return providers; +} + +it("reads enabled owners and per-app flags, not legacy app type or another app's choices", () => { + const web = providersFor("web"); + expect(web.runtime.map(({ id, enabled }) => [id, enabled])).toEqual([ + ["js", true], + ["native", false], + ]); + expect(compatibleFrameworks(web).map((p) => p.id)).toEqual(["site", "portable"]); + expect(compatibleFrameworks(providersFor("api")).map((p) => p.id)).toEqual([ + "native.web", + "portable", + ]); + expect(compatibleFrameworks(providersFor("script"))).toHaveLength(3); + expect(getAppProviders(config, "missing", modules)).toBeNull(); +}); + +it("does not infer an owner or grant unrestricted compatibility from incomplete metadata", () => { + expect(getAppProviders({ ...config, appRuntimes: { native: {} } }, "web", modules)).toBeNull(); + expect(getAppProviders({ ...config, appFrameworks: { site: { module: "web-tools" } } }, "web", modules)).toBeNull(); +}); + +it("switches only canonical enable flags, clearing conflicts before enabling their replacement", () => { + const web = providersFor("web"); + expect(planProviderChange(web, "runtime", "native")).toEqual([ + { path: "framework.site.enable", enabled: false }, + { path: "js.enable", enabled: false }, + { path: "native.enable", enabled: true }, + ]); + expect(planProviderChange(web, "framework", "portable")).toEqual([ + { path: "framework.site.enable", enabled: false }, + { path: "framework.portable.enable", enabled: true }, + ]); + expect(planProviderChange(web, "framework", null)).toEqual([ + { path: "framework.site.enable", enabled: false }, + ]); + expect(() => planProviderChange(web, "framework", "native.web")).toThrow("Unavailable framework"); + expect(planProviderChange(providersFor("api"), "framework", "native.web")).toEqual([ + { path: "framework.native\\.web.enable", enabled: true }, + ]); +}); + +function panel(module: string, id: string, slot: string, props?: Partial): NixPanel { + return { + module, + id, + title: id, + slot, + order: 0, + enabled: true, + fields: [], + type: "PANEL_TYPE_APP_CONFIG", + apps: { web: { enabled: true, config: {} } }, + ...props, + }; +} + +it("mounts selected owners' cards and distinct eligible app tabs exactly once", () => { + const js = panel("js-tools", "settings", "app:runtime"); + const site = panel("web-tools", "settings", "app:framework"); + const image = panel("image-tools", "build", "app:container"); + const deploy = panel("cloud-tools", "build", "app:deployment"); + const lint = panel("quality", "lint", "app:tab", { type: "PANEL_TYPE_STATUS", apps: {} }); + const group = panel("quality", "checks", "app:tab", { type: "PANEL_TYPE_TABS", tabs: ["lint"] }); + const panels = [ + js, + site, + image, + deploy, + lint, + lint, + group, + panel("native", "options", "app:runtime"), + panel("portable", "options", "app:framework"), + panel("web-tools", "global", "module"), + panel("quality", "disabled", "app:tab", { apps: { web: { enabled: false, config: {} } } }), + panel("quality", "no-app-data", "app:tab", { apps: {} }), + ]; + expect(getAppPanelMounts(panels, "web", providersFor("web"))).toEqual({ + runtime: [js], + framework: [site], + tabs: [image, deploy, group], + }); + expect(getAppPanelMounts(panels, "api", providersFor("api"))).toEqual({ + runtime: [], + framework: [], + tabs: [lint], + }); +}); diff --git a/apps/web/src/components/studio/panels/apps/app-providers.ts b/apps/web/src/components/studio/panels/apps/app-providers.ts new file mode 100644 index 00000000..d8f223b9 --- /dev/null +++ b/apps/web/src/components/studio/panels/apps/app-providers.ts @@ -0,0 +1,168 @@ +import type { NixPanel } from "../shared/panel-types"; +import { + getRootStudioPanels, + studioPanelKey, + studioPanelMatchesApp, +} from "../shared/use-studio-panels"; + +export type ProviderKind = "runtime" | "framework"; + +export interface AppProvider { + id: string; + module: string; + label: string; + enabled: boolean; + compatibleRuntimes: string[]; +} + +export type AppProviders = Record; + +// PatchNixData accepts dotted paths with backslash-escaped literal segments. +export function appPathSegment(id: string): string { + return id.replaceAll("\\", "\\\\").replaceAll(".", "\\."); +} + +function record(value: unknown): Record | undefined { + if (typeof value === "object" && value !== null && !Array.isArray(value)) { + return value as Record; + } + return undefined; +} + +/** Provider registries describe choices; the evaluated app, not its display type, owns selection. */ +export function getAppProviders( + config: Record | null, + appId: string | null, + enabledModules: ReadonlyMap, +): AppProviders | null { + // A new app has no enabled providers yet. A missing existing app is not the same thing. + const app: Record | undefined = + appId === null ? {} : record(record(config?.apps)?.[appId]); + const runtimes = record(config?.appRuntimes); + const frameworks = record(config?.appFrameworks); + if (!app || !runtimes || !frameworks) return null; + + function choices( + registry: Record, + options: Record | undefined, + kind: ProviderKind, + ): AppProvider[] | null { + const choices: AppProvider[] = []; + for (const [id, value] of Object.entries(registry)) { + const provider = record(value); + if (!provider || typeof provider.module !== "string" || !provider.module) return null; + if (!enabledModules.has(provider.module)) continue; + const compatible = kind === "framework" ? provider.compatibleRuntimes : []; + if (!Array.isArray(compatible) || !compatible.every((id) => typeof id === "string")) return null; + choices.push( + { + id, + module: provider.module, + label: typeof provider?.label === "string" ? provider.label : id, + enabled: record(options?.[id])?.enable === true, + compatibleRuntimes: compatible, + }, + ); + } + return choices; + } + + const runtime = choices(runtimes, app, "runtime"); + const framework = choices(frameworks, record(app.framework), "framework"); + return runtime && framework ? { runtime, framework } : null; +} + +function supportsRuntime(framework: AppProvider, runtimeIds: string[]): boolean { + return ( + runtimeIds.length === 0 || + framework.compatibleRuntimes.length === 0 || + runtimeIds.some((id) => framework.compatibleRuntimes.includes(id)) + ); +} + +export function compatibleFrameworks(providers: AppProviders): AppProvider[] { + const runtimeIds = providers.runtime.filter((p) => p.enabled).map((p) => p.id); + return providers.framework.filter((framework) => supportsRuntime(framework, runtimeIds)); +} + +interface EnablePatch { + path: string; + enabled: boolean; +} + +/** Only touch enable flags, never replace the provider's app-specific options. */ +export function planProviderChange( + providers: AppProviders, + kind: ProviderKind, + next: string | null, +): EnablePatch[] { + const choices = kind === "framework" ? compatibleFrameworks(providers) : providers.runtime; + if (next !== null && !choices.some((p) => p.id === next)) { + throw new Error(`Unavailable ${kind}: ${next}`); + } + + const patches: EnablePatch[] = []; + function patch(target: ProviderKind, id: string, enabled: boolean) { + const segment = appPathSegment(id); + patches.push({ + path: `${target === "framework" ? "framework." : ""}${segment}.enable`, + enabled, + }); + } + + // Keep intermediate states valid as PatchNixData commits one field at a time. + if (kind === "runtime" && next !== null) { + for (const framework of providers.framework) { + if (framework.enabled && !supportsRuntime(framework, [next])) + patch("framework", framework.id, false); + } + } + for (const provider of providers[kind]) { + if (provider.enabled && provider.id !== next) patch(kind, provider.id, false); + } + if (next !== null && !providers[kind].some((p) => p.id === next && p.enabled)) + patch(kind, next, true); + return patches; +} + +export interface AppPanelMounts { + runtime: NixPanel[]; + framework: NixPanel[]; + tabs: NixPanel[]; +} + +export function getAppPanelMounts( + panels: NixPanel[], + appId: string, + providers: AppProviders | null, +): AppPanelMounts { + const mounts: AppPanelMounts = { runtime: [], framework: [], tabs: [] }; + const frameworks = providers ? compatibleFrameworks(providers) : []; + const seen = new Set(); + // Resolve nested-tab ownership only after applying this app's eligibility: + // a group exclusive to app A must not hide its child in app B. + const roots = getRootStudioPanels( + panels.filter((panel) => panel.enabled && studioPanelMatchesApp(panel, appId)), + ); + for (const panel of roots) { + const key = studioPanelKey(panel); + if (seen.has(key)) continue; + switch (panel.slot) { + case "app:runtime": + if (providers?.runtime.some((p) => p.enabled && p.module === panel.module)) + mounts.runtime.push(panel); + break; + case "app:framework": + if (frameworks.some((p) => p.enabled && p.module === panel.module)) + mounts.framework.push(panel); + break; + case "app:container": + case "app:deployment": + case "app:tab": + mounts.tabs.push(panel); + break; + } + seen.add(key); + } + return mounts; +} diff --git a/apps/web/src/components/studio/panels/apps/constants.ts b/apps/web/src/components/studio/panels/apps/constants.ts deleted file mode 100644 index b890068d..00000000 --- a/apps/web/src/components/studio/panels/apps/constants.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * App type configuration and helper functions - */ - -export const APP_TYPES = [ - { value: "bun", label: "Bun", color: "bg-yellow-500/20 text-yellow-400" }, - { value: "node", label: "Node.js", color: "bg-green-500/20 text-green-400" }, - { value: "go", label: "Go", color: "bg-cyan-500/20 text-cyan-400" }, - { value: "python", label: "Python", color: "bg-blue-500/20 text-blue-400" }, - { value: "rust", label: "Rust", color: "bg-orange-500/20 text-orange-400" }, - { value: "other", label: "Other", color: "bg-gray-500/20 text-gray-400" }, -] as const; - -export type AppType = (typeof APP_TYPES)[number]["value"]; - -export function getTypeColor(type: string): string { - return ( - APP_TYPES.find((t) => t.value === type)?.color ?? - "bg-gray-500/20 text-gray-400" - ); -} - -export function getTypeLabel(type: string): string { - return APP_TYPES.find((t) => t.value === type)?.label ?? type; -} diff --git a/apps/web/src/components/studio/panels/apps/hooks/use-app-mutations.ts b/apps/web/src/components/studio/panels/apps/hooks/use-app-mutations.ts index 1019d044..3dc8c554 100644 --- a/apps/web/src/components/studio/panels/apps/hooks/use-app-mutations.ts +++ b/apps/web/src/components/studio/panels/apps/hooks/use-app-mutations.ts @@ -2,267 +2,190 @@ import { useCallback } from "react"; import { toast } from "sonner"; import { usePatchNixData } from "@/lib/use-agent"; import { - buildVariableConfigExpression, - isVariableLinkReference, - parseVariableLinkReference, + buildVariableConfigExpression, + isVariableLinkReference, + parseVariableLinkReference, } from "../../variables/constants"; interface UseAppMutationsOptions { - token: string | null; - refetch: () => void; + token: string | null; + refetch: () => void; } -export function useAppMutations({ - token, - refetch, -}: UseAppMutationsOptions) { - const patchNixData = usePatchNixData(); - - const toPatchPayload = useCallback((value: string) => { - if (isVariableLinkReference(value)) { - const variableId = parseVariableLinkReference(value); - if (variableId) { - const nextValue = buildVariableConfigExpression(variableId); - return { - value: nextValue, - valueType: nextValue.startsWith("var://") ? "string" : "nix_expr", - } as const; - } - } - return { - value: JSON.stringify(value), - valueType: "string", - } as const; - }, []); - - const patchAppPath = useCallback( - async (appId: string, path: string, value: string, valueType: string) => { - await patchNixData.mutateAsync({ - entity: "apps", - key: appId, - path, - value, - valueType, - }); - }, - [patchNixData], - ); - - const deleteAppPath = useCallback( - async (appId: string, path: string) => { - await patchAppPath(appId, path, "", "delete"); - }, - [patchAppPath], - ); - - const handleAddVariableToApp = useCallback( - async ( - appId: string, - envKey: string, - value: string, - _environments: string[], - ) => { - if (!token) { - toast.error("Not connected to agent"); - return; - } - - try { - const patchPayload = toPatchPayload(value); - await patchAppPath( - appId, - `env.${envKey}.value`, - patchPayload.value, - patchPayload.valueType, - ); - toast.success(`Added ${envKey} to app`); - refetch(); - } catch (err) { - toast.error( - err instanceof Error ? err.message : "Failed to add variable", - ); - } - }, - [patchAppPath, refetch, toPatchPayload, token], - ); - - const handleUpdateVariableInApp = useCallback( - async ( - appId: string, - oldEnvKey: string, - newEnvKey: string, - value: string, - _environments: string[], - ) => { - if (!token) { - toast.error("Not connected to agent"); - return; - } - - try { - const patchPayload = toPatchPayload(value); - - if (oldEnvKey !== newEnvKey) { - await deleteAppPath(appId, `env.${oldEnvKey}`); - } - - await patchAppPath( - appId, - `env.${newEnvKey}.value`, - patchPayload.value, - patchPayload.valueType, - ); - - toast.success(`Updated ${newEnvKey}`); - refetch(); - } catch (err) { - toast.error( - err instanceof Error ? err.message : "Failed to update variable", - ); - } - }, - [ - deleteAppPath, - patchAppPath, - refetch, - toPatchPayload, - token, - ], - ); - - const handleUpdateEnvironmentsForApp = useCallback( - async (appId: string, newEnvNames: string[]) => { - if (!token) { - toast.error("Not connected to agent"); - return; - } - - try { - const nextEnvNames = Array.from( - new Set(newEnvNames.map((name) => name.trim()).filter(Boolean)), - ); - await patchAppPath( - appId, - "environmentIds", - JSON.stringify(nextEnvNames), - "list", - ); - - toast.success("Updated environments"); - refetch(); - } catch (err) { - toast.error( - err instanceof Error - ? err.message - : "Failed to update environments", - ); - } - }, - [patchAppPath, refetch, token], - ); - - const handleDeleteVariableFromApp = useCallback( - async (appId: string, envKey: string) => { - if (!token) { - toast.error("Not connected to agent"); - return; - } - - try { - await deleteAppPath(appId, `env.${envKey}`); - - toast.success(`Removed ${envKey}`); - refetch(); - } catch (err) { - toast.error( - err instanceof Error ? err.message : "Failed to delete variable", - ); - } - }, - [deleteAppPath, refetch, token], - ); - - const handleUpdateFramework = useCallback( - async (appId: string, framework: "go" | "bun" | null) => { - if (!token) { - toast.error("Not connected to agent"); - return; - } - - try { - if (framework == null) { - await deleteAppPath(appId, "type"); - } else { - await patchAppPath(appId, "type", JSON.stringify(framework), "string"); - } - await patchAppPath( - appId, - "go.enable", - JSON.stringify(framework === "go"), - "bool", - ); - await patchAppPath( - appId, - "bun.enable", - JSON.stringify(framework === "bun"), - "bool", - ); - - const label = - framework === "go" - ? "Go" - : framework === "bun" - ? "Bun" - : "None"; - toast.success(`Set framework to ${label} for ${appId}`); - refetch(); - } catch (err) { - toast.error( - err instanceof Error - ? err.message - : "Failed to update framework setting", - ); - } - }, - [deleteAppPath, patchAppPath, refetch, token], - ); - - const handleDeleteApp = useCallback( - async (appId: string) => { - if (!token) { - toast.error("Not connected to agent"); - return; - } - - if (!confirm(`Are you sure you want to delete "${appId}"?`)) { - return; - } - - try { - await patchNixData.mutateAsync({ - entity: "apps", - key: "_root", - path: appId, - value: "", - valueType: "delete", - }); - toast.success(`Deleted app "${appId}"`); - refetch(); - } catch (err) { - toast.error( - err instanceof Error ? err.message : "Failed to delete app", - ); - } - }, - [patchNixData, refetch, token], - ); - - return { - handleAddVariableToApp, - handleUpdateVariableInApp, - handleUpdateEnvironmentsForApp, - handleDeleteVariableFromApp, - handleUpdateFramework, - handleDeleteApp, - }; +export function useAppMutations({ token, refetch }: UseAppMutationsOptions) { + const patchNixData = usePatchNixData(); + + const toPatchPayload = useCallback((value: string) => { + if (isVariableLinkReference(value)) { + const variableId = parseVariableLinkReference(value); + if (variableId) { + const nextValue = buildVariableConfigExpression(variableId); + return { + value: nextValue, + valueType: nextValue.startsWith("var://") ? "string" : "nix_expr", + } as const; + } + } + return { + value: JSON.stringify(value), + valueType: "string", + } as const; + }, []); + + const patchAppPath = useCallback( + async (appId: string, path: string, value: string, valueType: string) => { + await patchNixData.mutateAsync({ + entity: "apps", + key: appId, + path, + value, + valueType, + }); + }, + [patchNixData], + ); + + const deleteAppPath = useCallback( + async (appId: string, path: string) => { + await patchAppPath(appId, path, "", "delete"); + }, + [patchAppPath], + ); + + const handleAddVariableToApp = useCallback( + async (appId: string, envKey: string, value: string, _environments: string[]) => { + if (!token) { + toast.error("Not connected to agent"); + return; + } + + try { + const patchPayload = toPatchPayload(value); + await patchAppPath( + appId, + `env.${envKey}.value`, + patchPayload.value, + patchPayload.valueType, + ); + toast.success(`Added ${envKey} to app`); + refetch(); + } catch (err) { + toast.error(err instanceof Error ? err.message : "Failed to add variable"); + } + }, + [patchAppPath, refetch, toPatchPayload, token], + ); + + const handleUpdateVariableInApp = useCallback( + async ( + appId: string, + oldEnvKey: string, + newEnvKey: string, + value: string, + _environments: string[], + ) => { + if (!token) { + toast.error("Not connected to agent"); + return; + } + + try { + const patchPayload = toPatchPayload(value); + + if (oldEnvKey !== newEnvKey) { + await deleteAppPath(appId, `env.${oldEnvKey}`); + } + + await patchAppPath( + appId, + `env.${newEnvKey}.value`, + patchPayload.value, + patchPayload.valueType, + ); + + toast.success(`Updated ${newEnvKey}`); + refetch(); + } catch (err) { + toast.error(err instanceof Error ? err.message : "Failed to update variable"); + } + }, + [deleteAppPath, patchAppPath, refetch, toPatchPayload, token], + ); + + const handleUpdateEnvironmentsForApp = useCallback( + async (appId: string, newEnvNames: string[]) => { + if (!token) { + toast.error("Not connected to agent"); + return; + } + + try { + const nextEnvNames = Array.from( + new Set(newEnvNames.map((name) => name.trim()).filter(Boolean)), + ); + await patchAppPath(appId, "environmentIds", JSON.stringify(nextEnvNames), "list"); + + toast.success("Updated environments"); + refetch(); + } catch (err) { + toast.error(err instanceof Error ? err.message : "Failed to update environments"); + } + }, + [patchAppPath, refetch, token], + ); + + const handleDeleteVariableFromApp = useCallback( + async (appId: string, envKey: string) => { + if (!token) { + toast.error("Not connected to agent"); + return; + } + + try { + await deleteAppPath(appId, `env.${envKey}`); + + toast.success(`Removed ${envKey}`); + refetch(); + } catch (err) { + toast.error(err instanceof Error ? err.message : "Failed to delete variable"); + } + }, + [deleteAppPath, refetch, token], + ); + + const handleDeleteApp = useCallback( + async (appId: string) => { + if (!token) { + toast.error("Not connected to agent"); + return; + } + + if (!confirm(`Are you sure you want to delete "${appId}"?`)) { + return; + } + + try { + await patchNixData.mutateAsync({ + entity: "apps", + key: "_root", + path: appId, + value: "", + valueType: "delete", + }); + toast.success(`Deleted app "${appId}"`); + refetch(); + } catch (err) { + toast.error(err instanceof Error ? err.message : "Failed to delete app"); + } + }, + [patchNixData, refetch, token], + ); + + return { + handleAddVariableToApp, + handleUpdateVariableInApp, + handleUpdateEnvironmentsForApp, + handleDeleteVariableFromApp, + handleDeleteApp, + }; } diff --git a/apps/web/src/components/studio/panels/apps/index.ts b/apps/web/src/components/studio/panels/apps/index.ts index de205641..2ba7ad16 100644 --- a/apps/web/src/components/studio/panels/apps/index.ts +++ b/apps/web/src/components/studio/panels/apps/index.ts @@ -8,12 +8,6 @@ export { } from "./app-form-fields"; export { AppTasks } from "./app-tasks"; export { AppVariablesSection } from "./app-variables-section"; -export { - APP_TYPES, - type AppType, - getTypeColor, - getTypeLabel, -} from "./constants"; // Hooks export { useAppMutations } from "./hooks"; export { diff --git a/apps/web/src/components/studio/panels/apps/types.ts b/apps/web/src/components/studio/panels/apps/types.ts index 2bed91e1..94badc19 100644 --- a/apps/web/src/components/studio/panels/apps/types.ts +++ b/apps/web/src/components/studio/panels/apps/types.ts @@ -15,7 +15,7 @@ export const defaultFormState: AppFormState = { name: "", description: "", path: "", - type: "bun", + type: "", commands: [], variables: [], }; diff --git a/apps/web/src/components/studio/panels/configuration-panel.tsx b/apps/web/src/components/studio/panels/configuration-panel.tsx index c8e331d2..3ca73bc9 100644 --- a/apps/web/src/components/studio/panels/configuration-panel.tsx +++ b/apps/web/src/components/studio/panels/configuration-panel.tsx @@ -2,12 +2,7 @@ import { TooltipProvider } from "@ui/tooltip"; import { useSearch } from "@tanstack/react-router"; -import { - CONFIGURATION_SECTIONS, - getDefaultSectionId, - useConfiguration, -} from "./configuration"; -import { PanelHeader } from "./shared/panel-header"; +import { useAgentContext } from "@/lib/agent-provider"; import { AwsSection, CacheSection, @@ -15,52 +10,65 @@ import { IdeSection, StarshipSection, StepCaSection, + getConfigurationSections, + getDefaultSectionId, + useConfiguration, } from "./configuration"; +import { PanelHeader } from "./shared/panel-header"; +import { StudioPanel } from "./shared/studio-panel"; +import { useStudioPanels } from "./shared/use-studio-panels"; -export function ConfigurationPanel() { +function BuiltInSection({ id }: { id: string }) { const config = useConfiguration(); - const search = useSearch({ from: "/studio/configuration" }); - const activeSection = - (search as { section?: string }).section ?? getDefaultSectionId(); - - // Find the current section metadata - const currentSection = CONFIGURATION_SECTIONS.find( - (section) => section.id === activeSection, - ); - - // Render the active section - function renderSection() { - switch (activeSection) { - case "github": - return ; - case "step-ca": - return ; - case "aws": - return ; - case "starship": - return ; - case "ide": - case "vscode": // backward compatibility - return ; - case "cache": - return ; - default: - return ; - } + switch (id) { + case "github": + return ; + case "step-ca": + return ; + case "aws": + return ; + case "starship": + return ; + case "ide": + return ; + case "cache": + return ; } + return null; +} + +export function ConfigurationPanel() { + const { section } = useSearch({ from: "/studio/configuration" }); + const { isConnected } = useAgentContext(); + const { panels, config, isLoading, error } = useStudioPanels(); + const activeId = section === "vscode" ? "ide" : (section ?? getDefaultSectionId()); + const current = getConfigurationSections(panels).find(({ id }) => id === activeId); + let notice: string | undefined; + if (!isConnected) notice = "Connect to the agent to view configuration."; + else if (error) notice = `Could not load configuration: ${error.message}`; + else if (isLoading) notice = "Loading configuration sections…"; + else if (!config) notice = "Project configuration is unavailable."; + else if (!current) notice = "This configuration section is not available."; return (
- -
{renderSection()}
+ {notice ? ( +

+ {notice} +

+ ) : current?.panel ? ( + + ) : current ? ( +
+ +
+ ) : null}
); diff --git a/apps/web/src/components/studio/panels/configuration/sections.ts b/apps/web/src/components/studio/panels/configuration/sections.ts index 66fd3c3e..c510440d 100644 --- a/apps/web/src/components/studio/panels/configuration/sections.ts +++ b/apps/web/src/components/studio/panels/configuration/sections.ts @@ -3,20 +3,18 @@ * Each section represents a collapsible form panel in the configuration page. */ -import type { LucideIcon } from "lucide-react"; -import { - GitBranch as Github, - Lock, - Settings, - Shield, - Terminal, -} from "lucide-react"; +import type { ElementType } from "react"; +import { getModuleIconByName } from "../shared/module-icons"; +import type { NixPanel } from "../shared/panel-types"; +import { studioPanelKey } from "../shared/use-studio-panels"; +import { GitBranch as Github, Lock, Settings, Shield, Terminal } from "lucide-react"; export interface ConfigurationSection { id: string; label: string; - icon: LucideIcon; + icon: ElementType; description: string; + panel?: NixPanel; } export const CONFIGURATION_SECTIONS: ConfigurationSection[] = [ @@ -60,11 +58,20 @@ export const CONFIGURATION_SECTIONS: ConfigurationSection[] = [ export type ConfigurationSectionId = (typeof CONFIGURATION_SECTIONS)[number]["id"]; -/** - * Get a section by its ID - */ -export function getConfigurationSection(id: string): ConfigurationSection | undefined { - return CONFIGURATION_SECTIONS.find((section) => section.id === id); +/** The sidebar and the content area must resolve exactly the same section IDs. */ +export function getConfigurationSections(panels: readonly NixPanel[]): ConfigurationSection[] { + return [ + ...CONFIGURATION_SECTIONS, + ...panels + .filter((panel) => panel.enabled && panel.slot === "configuration") + .map((panel) => ({ + id: studioPanelKey(panel), + label: panel.nav?.label ?? panel.title, + icon: getModuleIconByName(panel.nav?.icon ?? panel.icon), + description: panel.description ?? "", + panel, + })), + ]; } /** diff --git a/apps/web/src/components/studio/panels/extensions-panel.tsx b/apps/web/src/components/studio/panels/extensions-panel.tsx deleted file mode 100644 index 2651ff48..00000000 --- a/apps/web/src/components/studio/panels/extensions-panel.tsx +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Extensions Panel - * - * Displays extension panels from the Nix configuration. - * Uses nix eval to get live config with extensions and their panels. - */ - -import { Loader2, Puzzle } from "lucide-react"; -import { - type AppData, - type Extension, - renderExtensionPanels, -} from "@/lib/extension-panels"; -import { useNixConfig } from "@/lib/use-agent"; - -export function ExtensionsPanel() { - const { data: config, isLoading, isError, error, refetch } = useNixConfig(); - - if (isLoading) { - return ( -
- -
- ); - } - - if (isError) { - return ( -
-
-

- Failed to load extensions: {error?.message || "Unknown error"} -

-
- -
- ); - } - - // Extract extensions from config - const extensions = (config as Record)?.extensions as - | Record - | undefined; - const apps = (config as Record)?.apps as - | Record - | undefined; - - if (!extensions || Object.keys(extensions).length === 0) { - return ; - } - - // Sort extensions by priority - const sortedExtensions = Object.entries(extensions).sort( - ([, a], [, b]) => (a.priority ?? 100) - (b.priority ?? 100), - ); - - return ( -
-
-

- - Extensions -

-

- Extension panels from your Nix configuration -

-
- -
- {sortedExtensions.map(([key, extension]) => ( - - ))} -
-
- ); -} - -/** - * Section for a single extension with its panels - */ -function ExtensionSection({ - extensionKey: _extensionKey, - extension, - allApps, -}: { - extensionKey: string; - extension: Extension; - allApps: Record; -}) { - const panels = renderExtensionPanels(extension, allApps); - - if (panels.length === 0) { - return null; - } - - return ( -
-
-

{extension.name}

- {extension.tags && extension.tags.length > 0 && ( -
- {extension.tags.map((tag) => ( - - {tag} - - ))} -
- )} -
-
{panels}
-
- ); -} - -/** - * Empty state when no extensions are configured - */ -function EmptyState() { - return ( -
- -
-

No Extensions

-

- Extensions with UI panels will appear here. -

-

- Enable extensions in your Nix modules by setting{" "} - - stackpanel.extensions.<name> - -

-
-
- ); -} diff --git a/apps/web/src/components/studio/panels/inspector-panel.tsx b/apps/web/src/components/studio/panels/inspector-panel.tsx index 4d112014..d68d24ca 100644 --- a/apps/web/src/components/studio/panels/inspector-panel.tsx +++ b/apps/web/src/components/studio/panels/inspector-panel.tsx @@ -2,7 +2,7 @@ * Inspector Panel * * Provides a comprehensive view of the Stackpanel environment for debugging - * and inspection purposes. Shows generated files, integrations, scripts, + * and inspection purposes. Shows generated files, scripts, * state files, and configuration data in organized tabs. */ @@ -32,7 +32,6 @@ import { Loader2, Pencil, Play, - Puzzle, RefreshCw, Search, Terminal, @@ -53,7 +52,7 @@ import { type InspectorDataFile, type InspectorData, type InspectorGeneratedFile, - type InspectorIntegration, + inspectorContributors, type InspectorScript, type InspectorStateFile, useInspectorData, @@ -61,6 +60,7 @@ import { import { useAgentContext } from "@/lib/agent-provider"; import { buildLocalConfigJsonSchema, + CONFIG_FILE_PATHS, CONFIG_FILE_PROJECTION_EVALS, renderNixFile, STACKPANEL_OPTIONS_DOC_EVAL, @@ -72,6 +72,7 @@ import { import { cn } from "@/lib/utils"; import { JsonSchemaEditor } from "./shared/json-schema-editor"; import { PanelHeader } from "./shared/panel-header"; +import { useStudioPanels } from "./shared/use-studio-panels"; // ============================================================================= // Generated Files Tab @@ -498,80 +499,6 @@ function GeneratedFilesTab({ ); } -// ============================================================================= -// Integrations Tab -// ============================================================================= - -function IntegrationItem({ integration }: { integration: InspectorIntegration }) { - return ( -
-
-
- -
-
-

{integration.displayName}

-

{integration.name}

-
-
-
- {integration.tags?.map((tag) => ( - - {tag} - - ))} - - {integration.enabled ? "Enabled" : "Disabled"} - -
-
- ); -} - -function IntegrationsTab({ integrations }: { integrations: InspectorIntegration[] }) { - const enabledCount = integrations.filter((i) => i.enabled).length; - - return ( -
-
- - {enabledCount} of {integrations.length} integrations enabled - -
- - {integrations.length === 0 ? ( -
- -

No integrations configured

-
- ) : ( -
- {integrations.map((integration) => ( - - ))} -
- )} -
- ); -} - // ============================================================================= // Scripts Tab // ============================================================================= @@ -783,7 +710,7 @@ function StateFilesTab({ files }: { files: InspectorStateFile[] }) { return (
- {files.length} state files in .stackpanel/state/ + {files.length} state files in .stack/state/
{files.length === 0 ? ( @@ -840,7 +767,7 @@ function DataFilesTab({ files }: { files: InspectorDataFile[] }) { return (
- {files.length} data entities in .stackpanel/data/ + {files.length} data entities in .stack/data/
{files.length === 0 ? ( @@ -872,7 +799,6 @@ type ConfigViewMode = "evaluated" | ConfigFileTarget; interface ConfigFileState { status: "idle" | "loading" | "ready"; - path: string; exists: boolean; isFunction: boolean; rawMode: boolean; @@ -886,11 +812,6 @@ interface ConfigFileState { const EMPTY_JSON_TEXT = JSON.stringify({}, null, 2); -const CONFIG_FILE_DEFAULT_PATHS: Record = { - config: ".stack/config.nix", - local: ".stack/config.local.nix", -}; - const CONFIG_FILE_LABELS: Record = { config: "Config", local: "Local Overrides", @@ -906,10 +827,9 @@ const CONFIG_FILE_DEFAULT_HEADERS: Record = { local: null, }; -function createEmptyConfigFileState(target: ConfigFileTarget): ConfigFileState { +function createEmptyConfigFileState(): ConfigFileState { return { status: "idle", - path: CONFIG_FILE_DEFAULT_PATHS[target], exists: false, isFunction: false, rawMode: false, @@ -923,8 +843,8 @@ function createEmptyConfigFileState(target: ConfigFileTarget): ConfigFileState { } const EMPTY_CONFIG_FILE_STATES: Record = { - config: createEmptyConfigFileState("config"), - local: createEmptyConfigFileState("local"), + config: createEmptyConfigFileState(), + local: createEmptyConfigFileState(), }; function ConfigSourceBadge({ source }: { source: string | null }) { @@ -1070,11 +990,11 @@ function ConfigTab({ error: null, })); + const path = CONFIG_FILE_PATHS[target]; try { const projection = await nixEval( CONFIG_FILE_PROJECTION_EVALS[target], ); - const path = projection.path || CONFIG_FILE_DEFAULT_PATHS[target]; const rawFile = (await readFile(path)) as FileReadResult; const nextConfig = isRecord(projection.config) ? projection.config : {}; const jsonText = JSON.stringify(nextConfig, null, 2); @@ -1084,7 +1004,6 @@ function ConfigTab({ ...prev, [target]: { status: "ready", - path, exists: Boolean(projection.exists), isFunction: Boolean(projection.isFunction), rawMode: false, @@ -1097,20 +1016,20 @@ function ConfigTab({ }, })); } catch (error) { - const fallback = await readConfigFileFallback(target, readFile); + const rawFile = (await readFile(path)) as FileReadResult; + const content = rawFile.content ?? ""; setFileStates((prev) => ({ ...prev, [target]: { status: "ready", - path: fallback.path, - exists: fallback.exists, - isFunction: detectFunctionWrapper(fallback.content), + exists: Boolean(rawFile.exists), + isFunction: detectFunctionWrapper(content), rawMode: true, config: null, jsonText: EMPTY_JSON_TEXT, savedJsonText: EMPTY_JSON_TEXT, - rawContent: fallback.content, - savedRawContent: fallback.content, + rawContent: content, + savedRawContent: content, error: error instanceof Error ? error.message @@ -1147,7 +1066,7 @@ function ConfigTab({ const isEditing = currentTarget !== null && editingTarget === currentTarget; const currentFileLabel = currentTarget ? CONFIG_FILE_LABELS[currentTarget] : null; const currentFileDescription = currentTarget ? CONFIG_FILE_DESCRIPTIONS[currentTarget] : null; - const currentFileDefaultPath = currentTarget ? CONFIG_FILE_DEFAULT_PATHS[currentTarget] : null; + const currentFilePath = currentTarget ? CONFIG_FILE_PATHS[currentTarget] : null; const currentModelPath = currentTarget ? `file:///stackpanel/${currentTarget === "config" ? "config" : "config.local"}.json` : "file:///stackpanel/config.json"; @@ -1302,12 +1221,13 @@ function ConfigTab({ }); } - await writeFile(currentFileState.path, nextContent); + const path = CONFIG_FILE_PATHS[currentTarget]; + await writeFile(path, nextContent); await Promise.all([loadConfigFile(currentTarget), refreshConfig()]); setEditingTarget(null); setEditorMarkers([]); toast.success(`${CONFIG_FILE_LABELS[currentTarget]} saved`, { - description: `Updated ${currentFileState.path}`, + description: `Updated ${path}`, }); } catch (error) { toast.error(`Failed to save ${currentFileLabel?.toLowerCase() ?? "config"}`, { @@ -1330,7 +1250,7 @@ function ConfigTab({ ) : ( <> - {currentFileState?.path ?? currentFileDefaultPath} + {currentFilePath} {currentFileState && !currentFileState.exists && ( @@ -1418,7 +1338,7 @@ function ConfigTab({
- This file currently falls back to raw Nix because {currentFileState.path}{" "} + This file currently falls back to raw Nix because {currentFilePath}{" "} could not be projected to JSON. Schema hints apply once it evaluates to plain JSON-compatible data again. @@ -1432,7 +1352,7 @@ function ConfigTab({

- Editing the JSON projection of {currentFileState?.path}. + Editing the JSON projection of {currentFilePath}.

Save converts the edited object back into Nix so{" "} @@ -1538,54 +1458,6 @@ function ConfigTab({ ); } -async function readConfigFileFallback( - target: ConfigFileTarget, - readFile: (path: string) => Promise, -): Promise<{ path: string; exists: boolean; content: string }> { - const stackPath = target === "config" ? ".stack/config.nix" : ".stack/config.local.nix"; - const legacyPath = - target === "config" ? ".stackpanel/config.nix" : ".stackpanel/config.local.nix"; - const [stackFile, legacyFile] = await Promise.all([ - readFile(stackPath) as Promise, - readFile(legacyPath) as Promise, - ]); - - if (stackFile.exists) { - return { - path: stackPath, - exists: true, - content: stackFile.content ?? "", - }; - } - - if (legacyFile.exists) { - return { - path: legacyPath, - exists: true, - content: legacyFile.content ?? "", - }; - } - - if (target === "config") { - return { - path: stackPath, - exists: false, - content: "", - }; - } - - const [stackConfig, legacyConfig] = await Promise.all([ - readFile(".stack/config.nix") as Promise, - readFile(".stackpanel/config.nix") as Promise, - ]); - - return { - path: legacyConfig.exists && !stackConfig.exists ? legacyPath : stackPath, - exists: false, - content: "", - }; -} - function getConfigFileName(target: ConfigFileTarget): string { return target === "config" ? "config.nix" : "config.local.nix"; } @@ -1634,14 +1506,6 @@ function filterInspectorDataByContributor(data: InspectorData, contributor: stri textContainsContributor(file.description, contributor), ); - const integrations = data.integrations.filter( - (integration) => - matchesContributor(integration.name, contributor) || - matchesContributor(integration.displayName, contributor) || - matchesContributor(integration.source?.path, contributor) || - textContainsContributor(integration.tags?.join(" "), contributor), - ); - const scripts = data.scripts.filter( (script) => matchesContributor(script.source, contributor) || @@ -1674,7 +1538,6 @@ function filterInspectorDataByContributor(data: InspectorData, contributor: stri enabledCount, staleCount, }, - integrations, scripts, dataFiles, stateFiles, @@ -1693,7 +1556,11 @@ interface InspectorPanelProps { export function InspectorPanel({ initialContributor }: InspectorPanelProps = {}) { const { data, isLoading, isError, error, refetch, refreshConfig } = useInspectorData(); - const contributors = data?.contributors ?? []; + const { modules } = useStudioPanels(); + const contributors = useMemo( + () => inspectorContributors(modules.values(), data?.generatedFiles.files ?? []), + [modules, data?.generatedFiles.files], + ); const [selectedContributor, setSelectedContributor] = useState( initialContributor ?? null, ); @@ -1761,12 +1628,7 @@ export function InspectorPanel({ initialContributor }: InspectorPanelProps = {}) {contributors.map((contributor) => ( -

- {contributor.label} - - {contributor.type === "extension" ? "Extension" : "Module"} - -
+ {contributor.label} ))} @@ -1895,14 +1757,6 @@ export function InspectorPanel({ initialContributor }: InspectorPanelProps = {}) - - - - - - - - diff --git a/apps/web/src/components/studio/panels/modules/adoption-choices.tsx b/apps/web/src/components/studio/panels/modules/adoption-choices.tsx new file mode 100644 index 00000000..4b761a0c --- /dev/null +++ b/apps/web/src/components/studio/panels/modules/adoption-choices.tsx @@ -0,0 +1,53 @@ +import type { ModuleAdoptionOffer } from "@stackpanel/proto/agent/v1/module"; +import { Button } from "@ui/button"; + +export interface AdoptionDecision { + id: string; + revision: string; + answer: boolean | string | string[]; +} + +export function AdoptionChoices({ offers, decisions, onChange, disabled }: { + offers: ModuleAdoptionOffer[]; + decisions: AdoptionDecision[]; + onChange: (next: AdoptionDecision[]) => void; + disabled: boolean; +}) { + if (!offers.length) return null; + function decide(offer: ModuleAdoptionOffer, answer?: AdoptionDecision["answer"]) { + const rest = decisions.filter((item) => item.id !== offer.id); + onChange(answer === undefined ? rest : [...rest, { id: offer.id, revision: offer.revision, answer }]); + } + return
+

Adoption offers

+

Optional. Leave an offer undecided to skip it. Changing an answer evaluates a new plan; nothing is saved until you enable the module.

+ {offers.map((offer) => { + const answer = decisions.find((item) => item.id === offer.id && item.revision === offer.revision)?.answer; + const label = offer.label || offer.id; + return
+ {label} + {offer.description &&

{offer.description}

} + {offer.reason &&

{offer.reason}

} + {offer.type === "bool" && } + {offer.type === "select" && } + {offer.type === "multiselect" &&
+ {offer.choices.map((choice) => )} +

{answer === undefined ? "Undecided" : Array.isArray(answer) && !answer.length ? "Declined" : "Choices selected"}

+ {" "} + +
} + {!offer.revision || !["bool", "select", "multiselect"].includes(offer.type) ?

This agent cannot accept an answer for this offer.

: null} +
; + })} +
; +} diff --git a/apps/web/src/components/studio/panels/modules/adoption-preview-dialog.tsx b/apps/web/src/components/studio/panels/modules/adoption-preview-dialog.tsx new file mode 100644 index 00000000..9f2c7f72 --- /dev/null +++ b/apps/web/src/components/studio/panels/modules/adoption-preview-dialog.tsx @@ -0,0 +1,167 @@ +import type { ModulePreviewDiff } from "@stackpanel/proto/agent/v1/module"; +import { Button } from "@ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@ui/dialog"; +import { useState } from "react"; +import { AdoptionChoices, type AdoptionDecision } from "./adoption-choices"; +import { useEnableModule, useModule, useModulePreview } from "./use-modules"; + +function PlanSection({ label, diff }: { label: string; diff?: ModulePreviewDiff }) { + if (!diff) return null; + const groups = [ + { label: "Add", items: diff.added }, + { label: "Change", items: diff.changed }, + { label: "Remove", items: diff.removed }, + ]; + return ( +
+

{label}

+ {groups.every(({ items }) => !items.length) && ( +

No changes

+ )} + {groups.map( + ({ label: operation, items }) => + items.length > 0 && ( +
    + {items.map((item) => ( +
  • + {operation}: {item} +
  • + ))} +
+ ), + )} +
+ ); +} + +/** Mount only while reviewing so reopening always evaluates a fresh plan. */ +export function AdoptionPreviewDialog({ + moduleId, + onClose, + onEnabled, +}: { + moduleId: string; + onClose: () => void; + onEnabled: (message: string) => void; +}) { + const detail = useModule(moduleId); + const enable = useEnableModule(moduleId); + const needsEnable = detail.data?.module.enabled === false && !detail.error; + const [decisions, setDecisions] = useState([]); + const baseline = useModulePreview(moduleId, needsEnable && !enable.isPending); + const selected = useModulePreview( + moduleId, + needsEnable && !enable.isPending && decisions.length > 0, + decisions, + ); + const preview = decisions.length ? selected : baseline; + const offers = preview.data?.offers ?? baseline.data?.offers ?? []; + const reviewed = decisions.every(({ id, revision }) => + preview.data?.offers.some((offer) => offer.id === id && offer.revision === revision), + ); + return ( + { + if (!open && !enable.isPending) onClose(); + }} + > + + + Enable module? + + Review the changes evaluated for {moduleId} in this project before enabling it. + + + {detail.error && ( +

+ Could not verify module state: {detail.error.message} +

+ )} + {detail.data?.module.enabled && !enable.isPending &&

This module is already enabled.

} + {preview.isFetching &&

Evaluating enable plan…

} + {preview.error && ( +
+

Could not preview changes: {preview.error.message}

+ +
+ )} + {needsEnable && preview.data && !preview.error && ( +
+ + + + {!reviewed && ( +

+ An adoption offer changed. Discard your answers and review the current offers. +

+ )} +
+ )} + {needsEnable && ( + { + enable.reset(); + setDecisions(next); + }} + /> + )} + {decisions.length > 0 && (preview.error || !reviewed) && !preview.isFetching && ( + + )} + {enable.error && ( +

+ Enable failed: {enable.error.message} +

+ )} + + + + +
+
+ ); +} diff --git a/apps/web/src/components/studio/panels/modules/manual-flake-setup.tsx b/apps/web/src/components/studio/panels/modules/manual-flake-setup.tsx new file mode 100644 index 00000000..85ab8444 --- /dev/null +++ b/apps/web/src/components/studio/panels/modules/manual-flake-setup.tsx @@ -0,0 +1,99 @@ +import type { RegistryModuleVersion } from "@stackpanel/proto/agent/v1/module"; +import { Textarea } from "@ui/textarea"; + +const forge = /^(github|gitlab|sourcehut):([~\w.-]+\/[~\w.-]+)(?:\/(.+))?$/; +const git = /^(?:git\+(?:http|https|file|ssh)|git):/; +const validRef = /^[A-Za-z0-9_][A-Za-z0-9./_+-]*$/; +const revision = /^[a-f\d]{40}$/i; + +// Keep non-selector query parameters (notably dir and host) verbatim. On forges +// an immutable rev wins; git URLs can carry both the ref to fetch and its rev. +function inputUrl(raw: string, ref: string, rev: string): string { + if (!ref && !rev) return raw; + if (ref && (!validRef.test(ref) || ref.includes("..") || ref.endsWith("/"))) + throw new Error("Invalid Git ref."); + if (rev && !revision.test(rev)) throw new Error("Invalid Git revision."); + const split = raw.indexOf("?"); + const base = split < 0 ? raw : raw.slice(0, split); + const options: string[] = []; + const hosted = forge.exec(base); + let originalRef = hosted?.[3] ?? ""; + if (revision.test(originalRef)) originalRef = ""; + if (!hosted && !git.test(base)) throw new Error("A ref override requires a Git source."); + for (const field of split < 0 ? [] : raw.slice(split + 1).split("&")) { + if (field.startsWith("ref=")) originalRef = decodeURIComponent(field.slice(4)); + else if (!field.startsWith("rev=")) options.push(field); + } + let source = base; + if (hosted) source = `${hosted[1]}:${hosted[2]}/${rev || ref || originalRef}`; + else { + if (ref || originalRef) options.push(`ref=${encodeURIComponent(ref || originalRef)}`); + if (rev) options.push(`rev=${rev}`); + } + return options.length ? `${source}?${options.join("&")}` : source; +} + +function nixString(value: string) { + if (/\p{Cc}/u.test(value)) throw new Error("The input contains invalid characters."); + return JSON.stringify(value).replaceAll("${", "\\${"); +} + +function inputLines(name: string, url: string, follows: boolean) { + const prefix = `inputs.${nixString(name)}`; + return ( + `${prefix}.url = ${nixString(url)};` + + (follows ? `\n${prefix}.inputs.nixpkgs.follows = "nixpkgs";` : "") + ); +} + +export function ManualFlakeSetup({ + slug, + release, + override, +}: { + slug: string; + release: RegistryModuleVersion; + override: string; +}) { + let snippet: string | undefined; + let error: string | undefined; + try { + const rev = override && override !== release.ref ? "" : release.rev; + snippet = [ + inputLines( + slug, + inputUrl(release.flakeUrl, override || release.ref, rev), + release.followsNixpkgs, + ), + ...release.flakeInputs.map((dep) => + inputLines(dep.name, inputUrl(dep.url, dep.ref || "", ""), dep.followsNixpkgs), + ), + ].join("\n"); + } catch (cause) { + error = cause instanceof Error ? cause.message : "Invalid registry input."; + } + return ( +
+ Manual setup · flake.nix +

+ Merge these input declarations into the top-level attribute set of your flake.nix, then lock + the inputs. Editing this example does not change your project or the Install button. +

+ {snippet ? ( +