feat: add canvas marketplace distribution and sharing (#3603)

This commit is contained in:
Carlos Florêncio
2026-09-14 09:31:20 +01:00
committed by GitHub
parent 5c6434d7d8
commit ba960f9732
121 changed files with 10732 additions and 121 deletions
@@ -34,6 +34,13 @@ Apply larger hit areas through a phone or coarse-pointer condition.
Use the canonical 768px phone boundary for new shared sizing rules.
Preserve existing overlay boundaries unless the task changes their composition.
Feature callers must not use a desktop repair class such as
`min-h-11 md:min-h-9`: it produces a 36px desktop control and bypasses the
28px standard. Leave Button, Input, and SelectTrigger defaults in place when
only layout or width needs changing, or use the shared sizing helper. If a
caller needs a custom touch target, scope it to the phone or coarse-pointer
condition instead of overriding the desktop base.
Do not add a global CSS rule that assigns one height to every HTML button.
Do not change existing compact or large variant meanings to repair individual callers.
Use the standard variant at ordinary action call sites.
+11 -3
View File
@@ -1206,8 +1206,12 @@ async function loadCoverageContents({ client, changedFiles, headSha }) {
continue;
}
let system;
let designRequirements = [];
try {
parseFrontmatter(designContent);
const design = parseFrontmatter(designContent);
designRequirements = Array.isArray(design.data.requirements)
? design.data.requirements
: [];
const match = /^docs\/specs\/([^/]+)\/system-design\/[^/]+\.md$/.exec(designPath);
if (!match) {
continue;
@@ -1225,8 +1229,12 @@ async function loadCoverageContents({ client, changedFiles, headSha }) {
}
}
const unresolvedRequirementIds = [];
const workOrderRequirements = new Set(workOrder.requirements ?? []);
const referencedRequirementIds = designRequirements.filter(requirementId =>
workOrderRequirements.has(requirementId)
);
if (typeof client.searchCode === 'function') {
for (const requirementId of workOrder.requirements ?? []) {
for (const requirementId of referencedRequirementIds) {
const searchKey = JSON.stringify([requirementDirectory, requirementId]);
if (!requirementSearches.has(searchKey)) {
requirementSearches.set(
@@ -1243,7 +1251,7 @@ async function loadCoverageContents({ client, changedFiles, headSha }) {
}
}
} else {
unresolvedRequirementIds.push(...(workOrder.requirements ?? []));
unresolvedRequirementIds.push(...referencedRequirementIds);
}
if (unresolvedRequirementIds.length > 0 && typeof client.listDirectory === 'function') {
if (!requirementDirectories.has(requirementDirectory)) {
+42
View File
@@ -407,6 +407,48 @@ test('multi-design work orders validate each requirement against its owning desi
assert.deepEqual(result.errors, []);
});
// @covers AC-CI-PR-DOCS-001.4
test('coverage loading searches only requirements declared by each design', async () => {
const contents = multiDesignFixtureContents();
const changed = runtimeAndWorkOrderDiff();
const searches = [];
const client = {
async getPullRequest() {
return pullRequest(42, SHA_B, [], changed.length);
},
async listFiles() {
return changed;
},
async getFile(pathname, ref) {
assert.equal(ref, SHA_B);
if (!Object.hasOwn(contents, pathname)) {
throw new Error('GitHub API request failed with HTTP 404: Not Found');
}
return contents[pathname];
},
async searchCode(requirementId, directory) {
searches.push({ requirementId, directory });
return [directory.includes('/platform/')
? 'docs/specs/platform/requirements/diagnostic-logging.md'
: 'docs/specs/web/requirements/browser-retention.md'];
},
};
const result = await validator.evaluatePullRequest({ client, pullNumber: 42 });
assert.equal(result.status, 'covered', result.errors.join('; '));
assert.deepEqual(searches, [
{
requirementId: 'REQ-PLATFORM-DIAGNOSTIC-LOGGING-001',
directory: 'docs/specs/platform/requirements',
},
{
requirementId: 'REQ-WEB-BROWSER-RETENTION-001',
directory: 'docs/specs/web/requirements',
},
]);
});
test('multi-design work orders fail when a requirement has no owning design', () => {
const contents = multiDesignFixtureContents();
contents['docs/specs/web/system-design/retention.md'] = contents[
@@ -57,7 +57,13 @@ jobs:
with:
node-version: "22"
- name: Build canvas package inspector
working-directory: apps/backend
run: go build -o bin/canvas-package ./cmd/canvas-package
- name: Test build script
env:
KANDEV_CANVAS_PACKAGE_INSPECTOR: apps/backend/bin/canvas-package
run: node --test plugin-registry/build-index.test.mjs
- name: Build index.json
@@ -68,6 +74,7 @@ jobs:
# this secret instead.
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
KANDEV_CANVAS_PACKAGE_INSPECTOR: apps/backend/bin/canvas-package
run: node plugin-registry/build-index.mjs
- name: Stage Pages site
+118
View File
@@ -0,0 +1,118 @@
// Command canvas-package inspects a portable canvas bundle without executing
// or extracting any package content. Registry tooling uses its JSON output as
// the trusted package descriptor.
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"sort"
"github.com/kandev/kandev/internal/plugins/webapp"
)
type packageDescriptor struct {
ID string `json:"id"`
Version string `json:"version"`
Kind string `json:"kind"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Author string `json:"author"`
License string `json:"license"`
SourceMode string `json:"source_mode"`
MinKandevVersion string `json:"min_kandev_version"`
RepoURL string `json:"repo_url,omitempty"`
Digest string `json:"sha256"`
CompressedBytes int64 `json:"compressed_bytes"`
ExpandedBytes int64 `json:"expanded_bytes"`
Files []string `json:"files"`
APIRead []string `json:"api_read,omitempty"`
APIWrite []string `json:"api_write,omitempty"`
Events []string `json:"events,omitempty"`
State bool `json:"state,omitempty"`
Secrets bool `json:"secrets,omitempty"`
NetworkOrigins []string `json:"network_origins,omitempty"`
}
func main() {
os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
}
func run(args []string, input io.Reader, output, errorOutput io.Writer) int {
flags := flag.NewFlagSet("canvas-package", flag.ContinueOnError)
flags.SetOutput(errorOutput)
fileName := flags.String("file", "-", "bundle path, or - for stdin")
if err := flags.Parse(args); err != nil {
return 2
}
if flags.NArg() != 0 {
_, _ = fmt.Fprintln(errorOutput, "canvas-package: unexpected argument")
return 2
}
reader := input
var file *os.File
if *fileName != "-" {
var err error
file, err = os.Open(*fileName)
if err != nil {
_, _ = fmt.Fprintln(errorOutput, "canvas-package: unable to read package")
return 1
}
defer func() { _ = file.Close() }()
reader = file
}
pkg, err := webapp.ValidateDistributionPackage(reader)
if err != nil {
// Package paths and parser details are deliberately not returned to
// registry callers. The inspector is an admission boundary.
_, _ = fmt.Fprintln(errorOutput, "canvas-package: invalid distribution package")
return 1
}
descriptor := describePackage(pkg)
encoder := json.NewEncoder(output)
encoder.SetEscapeHTML(true)
if err := encoder.Encode(descriptor); err != nil {
_, _ = fmt.Fprintln(errorOutput, "canvas-package: unable to write descriptor")
return 1
}
return 0
}
func describePackage(pkg *webapp.Package) packageDescriptor {
manifest := pkg.Manifest
files := make([]string, 0, len(pkg.Files))
for name := range pkg.Files {
files = append(files, name)
}
sort.Strings(files)
networkOrigins := make([]string, 0)
if len(manifest.UI.WebApps) == 1 {
networkOrigins = append(networkOrigins, manifest.UI.WebApps[0].NetworkOrigins...)
}
return packageDescriptor{
ID: manifest.ID,
Version: manifest.Version,
Kind: manifest.Distribution.Kind,
DisplayName: manifest.DisplayName,
Description: manifest.Description,
Author: manifest.Author,
License: manifest.Distribution.License,
SourceMode: manifest.Distribution.SourceMode,
MinKandevVersion: manifest.MinKandevVersion,
RepoURL: manifest.RepoURL,
Digest: pkg.Digest,
CompressedBytes: pkg.CompressedBytes,
ExpandedBytes: pkg.ExpandedBytes,
Files: files,
APIRead: append([]string(nil), manifest.Capabilities.APIRead...),
APIWrite: append([]string(nil), manifest.Capabilities.APIWrite...),
Events: append([]string(nil), manifest.Capabilities.Events...),
State: manifest.Capabilities.State,
Secrets: manifest.Capabilities.Secrets,
NetworkOrigins: networkOrigins,
}
}
@@ -0,0 +1,113 @@
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"sort"
"testing"
)
func TestRunInspectsDistributionPackageAsSafeJSON(t *testing.T) {
archive := testDistributionArchive(t)
var output bytes.Buffer
code := run([]string{"--file", "-"}, bytes.NewReader(archive), &output, &bytes.Buffer{})
if code != 0 {
t.Fatalf("run() exit code = %d", code)
}
var descriptor packageDescriptor
if err := json.Unmarshal(output.Bytes(), &descriptor); err != nil {
t.Fatalf("decode descriptor: %v", err)
}
if descriptor.ID != "canvas-board" || descriptor.Version != "1.2.3" || descriptor.Kind != "canvas" {
t.Fatalf("descriptor = %+v", descriptor)
}
if descriptor.Digest == "" || len(descriptor.Files) == 0 {
t.Fatalf("descriptor lacks package metadata: %+v", descriptor)
}
}
func TestRunRejectsInvalidDistributionWithoutLeakingDetails(t *testing.T) {
var output, errorOutput bytes.Buffer
code := run([]string{"--file", "-"}, bytes.NewReader([]byte("not an archive")), &output, &errorOutput)
if code == 0 || output.Len() != 0 {
t.Fatalf("run() code=%d output=%q", code, output.String())
}
if bytes.Contains(errorOutput.Bytes(), []byte("/")) {
t.Fatalf("error output contains a path: %q", errorOutput.String())
}
}
func testDistributionArchive(t *testing.T) []byte {
t.Helper()
files := map[string]string{
"manifest.yaml": `id: canvas-board
api_version: 2
version: 1.2.3
display_name: Canvas Board
description: A board
author: Kandev
categories: [canvas]
min_kandev_version: 1.0.0
distribution:
schema_version: 1
kind: canvas
license: MIT
source_mode: static
ui:
web_apps:
- key: main
title: Board
entry: ui/index.html
placements: [workspace-canvas]
`,
"README.md": "A board.\n",
"ui/index.html": "<html></html>",
"checksums.txt": "",
}
files["checksums.txt"] = checksumFile(files)
var compressed bytes.Buffer
zw := gzip.NewWriter(&compressed)
tw := tar.NewWriter(zw)
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
data := []byte(files[name])
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(data)), Typeflag: tar.TypeReg}); err != nil {
t.Fatalf("tar header: %v", err)
}
if _, err := io.Copy(tw, bytes.NewReader(data)); err != nil {
t.Fatalf("tar data: %v", err)
}
}
if err := tw.Close(); err != nil {
t.Fatalf("tar close: %v", err)
}
if err := zw.Close(); err != nil {
t.Fatalf("gzip close: %v", err)
}
return compressed.Bytes()
}
func checksumFile(files map[string]string) string {
names := make([]string, 0, len(files))
for name := range files {
if name != "checksums.txt" {
names = append(names, name)
}
}
sort.Strings(names)
var output string
for _, name := range names {
sum := sha256.Sum256([]byte(files[name]))
output += fmt.Sprintf("%x %s\n", sum, name)
}
return output
}
@@ -16,6 +16,7 @@ import (
"github.com/gin-gonic/gin"
agentctltypes "github.com/kandev/kandev/internal/agentctl/types"
"github.com/kandev/kandev/internal/plugins/webapp"
"go.uber.org/zap"
)
@@ -185,6 +186,13 @@ func (c *canvasSourceCollector) visit(currentPath string, entry fs.DirEntry, wal
if relativePath == ".canvas-root" {
return nil
}
if err := webapp.ValidateCanvasSourcePath(relativePath, info.IsDir()); err != nil {
code := "source_contains_unsupported_file"
if errors.Is(err, webapp.ErrUnsafeSource) {
code = "source_contains_excluded_file"
}
return newCanvasSourceError(code, "canvas source contains an excluded or unsupported file", err)
}
if len([]byte(relativePath)) > 240 {
return newCanvasSourceLimitError(errors.New("source path is too long"))
}
@@ -87,6 +87,24 @@ func TestCanvasSourceTransfer_StreamsWorkspaceRelativeRoot(t *testing.T) {
}, readCanvasTar(t, response.Body.Bytes()))
}
func TestCanvasSourceTransfer_RetainsRuntimeAssets(t *testing.T) {
server, workDir := newCanvasSourceTestServer(t)
root := filepath.Join(workDir, "source")
require.NoError(t, os.MkdirAll(filepath.Join(root, "assets"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(root, "index.html"), []byte("<main>ok</main>"), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(root, "assets", "logo.svg"), []byte("<svg></svg>"), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(root, "assets", "body.woff2"), []byte("font-bytes"), 0o644))
response := canvasSourceRequest(t, server, "source", true)
require.Equal(t, http.StatusOK, response.Code, response.Body.String())
require.Equal(t, map[string]string{
"index.html": "<main>ok</main>",
"assets/": "",
"assets/logo.svg": "<svg></svg>",
"assets/body.woff2": "font-bytes",
}, readCanvasTar(t, response.Body.Bytes()))
}
func TestCanvasSourceTransfer_RejectsTraversalAndSymlinks(t *testing.T) {
server, workDir := newCanvasSourceTestServer(t)
require.NoError(t, os.Mkdir(filepath.Join(workDir, "source"), 0o755))
@@ -121,7 +139,7 @@ func TestCanvasSourceTransfer_RejectsFileDataLimit(t *testing.T) {
server, workDir := newCanvasSourceTestServer(t)
root := filepath.Join(workDir, "source")
require.NoError(t, os.Mkdir(root, 0o755))
file, err := os.Create(filepath.Join(root, "large.bin"))
file, err := os.Create(filepath.Join(root, "large.txt"))
require.NoError(t, err)
require.NoError(t, file.Truncate(int64(agentctltypes.MaxCanvasSourceFileData+1)))
require.NoError(t, file.Close())
@@ -129,3 +147,26 @@ func TestCanvasSourceTransfer_RejectsFileDataLimit(t *testing.T) {
response := canvasSourceRequest(t, server, "source", true)
require.Equal(t, http.StatusRequestEntityTooLarge, response.Code)
}
func TestCanvasSourceTransfer_RejectsExcludedProjectSource(t *testing.T) {
server, workDir := newCanvasSourceTestServer(t)
root := filepath.Join(workDir, "source", "distribution", "source")
require.NoError(t, os.MkdirAll(root, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(root, ".env"), []byte("TOKEN=secret"), 0o600))
response := canvasSourceRequest(t, server, "source", true)
require.Equal(t, http.StatusBadRequest, response.Code)
require.NotContains(t, response.Body.String(), "secret")
}
func TestCanvasSourceTransfer_RejectsExcludedWorkspaceSourceFiles(t *testing.T) {
server, workDir := newCanvasSourceTestServer(t)
root := filepath.Join(workDir, "source")
require.NoError(t, os.MkdirAll(filepath.Join(root, "node_modules", "pkg"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(root, ".env"), []byte("TOKEN=secret"), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(root, "node_modules", "pkg", "index.js"), []byte("secret"), 0o600))
response := canvasSourceRequest(t, server, "source", true)
require.Equal(t, http.StatusBadRequest, response.Code)
require.NotContains(t, response.Body.String(), "secret")
}
@@ -0,0 +1,288 @@
package backendapp
import (
"errors"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
canvasservice "github.com/kandev/kandev/internal/canvas"
plugininstances "github.com/kandev/kandev/internal/plugins/instances"
"github.com/kandev/kandev/internal/plugins/webapp"
)
func registerCanvasDistributionRoutes(router *gin.Engine, handler *canvasHTTPHandler) {
if router == nil || handler == nil || handler.distribution == nil {
return
}
router.POST("/api/v1/canvases/:canvasID/exports", handler.prepareCanvasExport)
router.GET("/api/v1/canvases/exports/:preparationID", handler.getCanvasExport)
router.GET("/api/v1/canvases/exports/:preparationID/bundle", handler.downloadCanvasBundle)
router.GET("/api/v1/canvases/exports/:preparationID/source", handler.downloadCanvasSource)
router.DELETE("/api/v1/canvases/exports/:preparationID", handler.cancelCanvasExport)
router.POST("/api/v1/canvases/install-preparations", handler.prepareCanvasInstall)
router.GET("/api/v1/canvases/install-preparations/:preparationID", handler.getCanvasInstall)
router.POST("/api/v1/canvases/install-preparations/:preparationID/confirm", handler.confirmCanvasInstall)
router.DELETE("/api/v1/canvases/install-preparations/:preparationID", handler.cancelCanvasInstall)
}
type canvasExportRequest struct {
WorkspaceID string `json:"workspace_id"`
ExpectedReleaseID string `json:"expected_release_id"`
Metadata canvasservice.ExportMetadata `json:"metadata"`
PackageID string `json:"package_id,omitempty"`
Version string `json:"version,omitempty"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
License string `json:"license,omitempty"`
SourceMode string `json:"source_mode,omitempty"`
MinKandevVersion string `json:"min_kandev_version,omitempty"`
RepoURL string `json:"repo_url,omitempty"`
}
type canvasInstallRequest struct {
WorkspaceID string `json:"workspace_id"`
OriginKind string `json:"origin_kind,omitempty"`
SourceID string `json:"source_id,omitempty"`
RepositoryURL string `json:"repository_url,omitempty"`
PackageID string `json:"package_id,omitempty"`
ExpectedVersion string `json:"expected_version,omitempty"`
ExpectedDigest string `json:"expected_sha256,omitempty"`
BundleURL string `json:"bundle_url,omitempty"`
}
func (r canvasInstallRequest) serviceRequest(userID string, bundle []byte) canvasservice.InstallRequest {
return canvasservice.InstallRequest{
UserID: userID, WorkspaceID: strings.TrimSpace(r.WorkspaceID), OriginKind: strings.TrimSpace(r.OriginKind),
SourceID: strings.TrimSpace(r.SourceID), RepositoryURL: strings.TrimSpace(r.RepositoryURL),
PackageID: strings.TrimSpace(r.PackageID), ExpectedVersion: strings.TrimSpace(r.ExpectedVersion),
ExpectedArchiveDigest: strings.TrimSpace(r.ExpectedDigest), Bundle: bundle,
}
}
type canvasInstallConfirmationRequest struct {
canvasservice.InstallConfirmation
}
func (r canvasExportRequest) metadata() canvasservice.ExportMetadata {
metadata := r.Metadata
if metadata.PackageID == "" {
metadata = canvasservice.ExportMetadata{
PackageID: r.PackageID, Version: r.Version, DisplayName: r.DisplayName,
Description: r.Description, Author: r.Author, License: r.License,
SourceMode: r.SourceMode, MinKandevVersion: r.MinKandevVersion, RepoURL: r.RepoURL,
}
}
return metadata
}
func (h *canvasHTTPHandler) prepareCanvasExport(c *gin.Context) {
var request canvasExportRequest
if err := c.ShouldBindJSON(&request); err != nil {
writeCanvasError(c, http.StatusBadRequest, "invalid_request", nil)
return
}
request.WorkspaceID = strings.TrimSpace(request.WorkspaceID)
if request.WorkspaceID == "" || strings.TrimSpace(request.ExpectedReleaseID) == "" {
writeCanvasError(c, http.StatusBadRequest, "invalid_request", nil)
return
}
review, err := h.distribution.PrepareExport(c.Request.Context(), canvasservice.ExportRequest{
UserID: canvasRuntimeUser(c), WorkspaceID: request.WorkspaceID, CanvasID: c.Param("canvasID"),
ExpectedReleaseID: request.ExpectedReleaseID, Metadata: request.metadata(),
})
if err != nil {
writeCanvasDistributionError(c, err)
return
}
writeCanvasJSON(c, http.StatusOK, review)
}
func (h *canvasHTTPHandler) getCanvasExport(c *gin.Context) {
review, err := h.distribution.GetExport(c.Request.Context(), canvasRuntimeUser(c), c.Param("preparationID"))
if err != nil {
writeCanvasDistributionError(c, err)
return
}
writeCanvasJSON(c, http.StatusOK, review)
}
func (h *canvasHTTPHandler) downloadCanvasBundle(c *gin.Context) {
h.downloadCanvasExport(c, canvasservice.ExportBundle)
}
func (h *canvasHTTPHandler) downloadCanvasSource(c *gin.Context) {
h.downloadCanvasExport(c, canvasservice.ExportSource)
}
func (h *canvasHTTPHandler) downloadCanvasExport(c *gin.Context, kind canvasservice.ExportKind) {
download, err := h.distribution.DownloadExport(c.Request.Context(), canvasRuntimeUser(c), c.Param("preparationID"), kind)
if err != nil {
writeCanvasDistributionError(c, err)
return
}
c.Header("Cache-Control", "private, no-store")
c.Header("X-Content-Type-Options", "nosniff")
c.Header("Content-Disposition", `attachment; filename="`+download.Filename+`"`)
c.Data(http.StatusOK, download.ContentType, download.Data)
}
func (h *canvasHTTPHandler) cancelCanvasExport(c *gin.Context) {
if err := h.distribution.CancelExport(c.Request.Context(), canvasRuntimeUser(c), c.Param("preparationID")); err != nil {
writeCanvasDistributionError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *canvasHTTPHandler) prepareCanvasInstall(c *gin.Context) {
if strings.HasPrefix(c.ContentType(), "multipart/form-data") {
h.prepareCanvasInstallUpload(c)
return
}
var request canvasInstallRequest
if err := c.ShouldBindJSON(&request); err != nil || (strings.TrimSpace(request.BundleURL) == "" && (strings.TrimSpace(request.SourceID) == "" || strings.TrimSpace(request.PackageID) == "" || strings.TrimSpace(request.ExpectedVersion) == "" || strings.TrimSpace(request.ExpectedDigest) == "")) {
writeCanvasError(c, http.StatusBadRequest, "invalid_request", nil)
return
}
if strings.TrimSpace(request.WorkspaceID) == "" {
writeCanvasError(c, http.StatusBadRequest, "invalid_request", nil)
return
}
serviceRequest := request.serviceRequest(canvasRuntimeUser(c), nil)
var review canvasservice.InstallReview
var err error
if strings.TrimSpace(request.BundleURL) != "" {
review, err = h.distribution.PrepareInstallFromURL(c.Request.Context(), serviceRequest, request.BundleURL)
} else {
review, err = h.distribution.PrepareInstallFromCatalog(c.Request.Context(), serviceRequest)
}
if err != nil {
writeCanvasDistributionError(c, err)
return
}
writeCanvasJSON(c, http.StatusOK, review)
}
func (h *canvasHTTPHandler) prepareCanvasInstallUpload(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, webapp.MaxCompressedBytes+1<<20)
fileHeader, err := c.FormFile("package")
if err != nil || fileHeader.Size > webapp.MaxCompressedBytes {
writeCanvasDistributionError(c, webapp.ErrCompressedTooLarge)
return
}
file, err := fileHeader.Open()
if err != nil {
writeCanvasDistributionError(c, canvasservice.ErrInstallInvalid)
return
}
defer func() { _ = file.Close() }()
bundle, err := io.ReadAll(io.LimitReader(file, webapp.MaxCompressedBytes+1))
if err != nil || int64(len(bundle)) > webapp.MaxCompressedBytes {
writeCanvasDistributionError(c, webapp.ErrCompressedTooLarge)
return
}
request := canvasInstallRequest{
WorkspaceID: c.PostForm("workspace_id"), OriginKind: "upload", SourceID: c.PostForm("source_id"),
RepositoryURL: c.PostForm("repository_url"), PackageID: c.PostForm("package_id"),
ExpectedVersion: c.PostForm("expected_version"), ExpectedDigest: c.PostForm("expected_sha256"),
}
if strings.TrimSpace(request.WorkspaceID) == "" {
writeCanvasError(c, http.StatusBadRequest, "invalid_request", nil)
return
}
review, err := h.distribution.PrepareInstall(c.Request.Context(), request.serviceRequest(canvasRuntimeUser(c), bundle))
if err != nil {
writeCanvasDistributionError(c, err)
return
}
writeCanvasJSON(c, http.StatusOK, review)
}
func (h *canvasHTTPHandler) getCanvasInstall(c *gin.Context) {
review, err := h.distribution.GetInstallReview(c.Request.Context(), canvasRuntimeUser(c), c.Param("preparationID"))
if err != nil {
writeCanvasDistributionError(c, err)
return
}
writeCanvasJSON(c, http.StatusOK, review)
}
func (h *canvasHTTPHandler) confirmCanvasInstall(c *gin.Context) {
var request canvasInstallConfirmationRequest
if err := c.ShouldBindJSON(&request); err != nil {
writeCanvasError(c, http.StatusBadRequest, "invalid_request", nil)
return
}
result, err := h.distribution.ConfirmInstall(c.Request.Context(), canvasRuntimeUser(c), c.Param("preparationID"), request.InstallConfirmation)
if err != nil {
writeCanvasDistributionError(c, err)
return
}
writeCanvasJSON(c, http.StatusOK, result)
}
func (h *canvasHTTPHandler) cancelCanvasInstall(c *gin.Context) {
if err := h.distribution.CancelInstall(c.Request.Context(), canvasRuntimeUser(c), c.Param("preparationID")); err != nil {
writeCanvasDistributionError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func writeCanvasDistributionError(c *gin.Context, err error) {
status, code := canvasDistributionErrorStatus(err)
writeCanvasError(c, status, code, nil)
}
func canvasDistributionErrorStatus(err error) (int, string) {
switch {
case errors.Is(err, canvasservice.ErrCanvasNotFound):
return http.StatusNotFound, "canvas_not_found"
case errors.Is(err, canvasservice.ErrPreparationNotFound):
return http.StatusNotFound, "review_not_found"
case errors.Is(err, canvasservice.ErrPreparationExpired):
return http.StatusConflict, "review_expired"
case errors.Is(err, canvasservice.ErrExportStale):
return http.StatusConflict, "review_stale"
case errors.Is(err, canvasservice.ErrExportInvalid):
return http.StatusBadRequest, "invalid_request"
case isCanvasInvalidInstallError(err):
return http.StatusBadRequest, "invalid_install"
case errors.Is(err, canvasservice.ErrInstallIncompatible):
return http.StatusConflict, "incompatible_install"
case errors.Is(err, canvasservice.ErrInstallURLBlocked):
return http.StatusBadRequest, "install_url_blocked"
case errors.Is(err, webapp.ErrCompressedTooLarge):
return http.StatusRequestEntityTooLarge, "package_too_large"
case errors.Is(err, canvasservice.ErrInstallUnavailable):
return http.StatusServiceUnavailable, "install_unavailable"
case errors.Is(err, canvasservice.ErrInstallReceiptNotFound):
return http.StatusNotFound, "install_not_found"
case errors.Is(err, canvasservice.ErrPreparationLimit), isCanvasStorageLimitError(err):
return http.StatusConflict, "storage_limit_reached"
case isCanvasSourceUnavailableError(err):
return http.StatusConflict, "source_unavailable"
default:
return http.StatusInternalServerError, "internal_error"
}
}
func isCanvasStorageLimitError(err error) bool {
return errors.Is(err, plugininstances.ErrWorkspaceStorageLimit) ||
errors.Is(err, plugininstances.ErrInstallationStorageLimit)
}
func isCanvasInvalidInstallError(err error) bool {
return errors.Is(err, canvasservice.ErrInstallInvalid) ||
errors.Is(err, canvasservice.ErrInstallNotApproved) ||
errors.Is(err, canvasservice.ErrPackageDigestMismatch) ||
errors.Is(err, canvasservice.ErrInstallURLInvalid)
}
func isCanvasSourceUnavailableError(err error) bool {
return errors.Is(err, webapp.ErrSourceUnavailable) || errors.Is(err, webapp.ErrArtifactUnavailable)
}
@@ -0,0 +1,23 @@
package backendapp
import (
"errors"
"net/http"
"testing"
canvasservice "github.com/kandev/kandev/internal/canvas"
)
func TestCanvasDistributionErrorStatusUsesInternalErrorForUnexpectedFailures(t *testing.T) {
status, code := canvasDistributionErrorStatus(errors.New("database unavailable"))
if status != http.StatusInternalServerError || code != "internal_error" {
t.Fatalf("status = %d %q, want 500 internal_error", status, code)
}
}
func TestCanvasDistributionErrorStatusMapsIncompatibleInstall(t *testing.T) {
status, code := canvasDistributionErrorStatus(canvasservice.ErrInstallIncompatible)
if status != http.StatusConflict || code != "incompatible_install" {
t.Fatalf("status = %d %q, want 409 incompatible_install", status, code)
}
}
@@ -30,10 +30,11 @@ import (
// and host operations. Source transfer and publishing stay on the agent MCP
// path; browsers receive only metadata and short-lived runtime capabilities.
type canvasHTTPHandler struct {
canvases *canvasservice.Service
plugins *plugins.Service
tasks *taskservice.Service
editor *canvasEditService
canvases *canvasservice.Service
plugins *plugins.Service
tasks *taskservice.Service
editor *canvasEditService
distribution *canvasservice.DistributionService
}
type canvasEditTaskStore interface {
@@ -337,9 +338,10 @@ func registerCanvasRoutes(p routeParams) {
return
}
h := &canvasHTTPHandler{
canvases: p.services.Canvas,
plugins: p.services.Plugins,
tasks: p.taskSvc,
canvases: p.services.Canvas,
plugins: p.services.Plugins,
tasks: p.taskSvc,
distribution: p.services.CanvasDistribution,
}
if p.taskSvc != nil && p.taskRepo != nil && p.orchestratorSvc != nil && p.lifecycleMgr != nil {
instanceStore := p.services.Plugins.Instances()
@@ -361,6 +363,7 @@ func registerCanvasRoutes(p routeParams) {
p.router.GET("/api/v1/workspaces/:id/canvases", h.listWorkspace)
p.router.GET("/api/v1/canvases/workspace/:workspaceID", h.listWorkspace)
p.router.GET("/api/v1/canvases/workspaces/:workspaceID", h.listWorkspace)
registerCanvasDistributionRoutes(p.router, h)
p.router.GET("/api/v1/canvases/:canvasID", h.get)
p.router.GET("/api/v1/canvases/:canvasID/releases", h.releases)
p.router.GET("/api/v1/canvases/:canvasID/promotion-preview", h.promotionPreview)
@@ -323,6 +323,26 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories
if err != nil {
return nil, nil, fmt.Errorf("initialize canvas service: %w", err)
}
var canvasDistributionSvc *canvasservice.DistributionService
if cfg.Features.Canvases {
preparations, prepErr := canvasservice.NewPreparationStore(filepath.Join(cfg.ResolvedHomeDir(), "canvas-preparations"))
if prepErr != nil {
return nil, nil, fmt.Errorf("initialize canvas preparations: %w", prepErr)
}
canvasDistributionSvc = canvasservice.NewDistributionService(
canvasSvc,
pluginsSvc.Instances(),
pluginsSvc.WebArtifacts(),
taskSvc.AuthorizeWorkspaceAccess,
preparations,
)
canvasDistributionSvc.SetKandevVersion(version)
canvasDistributionSvc.SetInstallReceiptStore(canvasRepo)
canvasDistributionSvc.SetArtifactQuota(pluginsSvc.Instances())
if pluginsSvc != nil {
canvasDistributionSvc.SetCatalogResolver(pluginsSvc.Marketplace())
}
}
gitCredentialBroker := newGitCredentialBroker(githubSvc, pluginsSvc, repos.Task, cfg.GitHubCredentialBroker.ReissueSigningKey)
if pluginsSvc != nil {
pluginsSvc.SetGitCredentialLeaseRevoker(gitCredentialBroker.RevokeProvider)
@@ -415,6 +435,7 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories
Automation: automationComponents,
Plugins: pluginsSvc,
Canvas: canvasSvc,
CanvasDistribution: canvasDistributionSvc,
GitCredentials: gitCredentialBroker,
// Office is constructed later in initOfficeServices once all
// of its dependencies (config loader, task integrations, etc.) are available.
@@ -135,6 +135,9 @@ type Services struct {
// Canvas is the gated lifecycle service for agent-authored plugin web
// applications. It is nil while features.canvases is disabled.
Canvas *canvasservice.Service
// CanvasDistribution owns bounded, user-bound export and installation
// preparations. It is nil while features.canvases is disabled.
CanvasDistribution *canvasservice.DistributionService
// GitCredentials is the shared provider-neutral lease broker used by the
// GitHub HTTP endpoint and task executor helper leases.
GitCredentials *gitcredentials.Broker
+129
View File
@@ -95,9 +95,11 @@ type authoringInstanceStore interface {
type transactionalAuthoringStore interface {
authoringInstanceStore
WithTransaction(context.Context, func(*sqlx.Tx) error) error
CreateTx(context.Context, *sqlx.Tx, plugininstances.Instance) error
CreateReleaseTx(context.Context, *sqlx.Tx, plugininstances.Release) error
SetPluginIDTx(context.Context, *sqlx.Tx, string, string) error
ActivateReleaseTx(context.Context, *sqlx.Tx, string, string) error
ApproveReleaseTx(context.Context, *sqlx.Tx, string, string, string, []plugininstances.Grant) error
}
type reviewedPromotionStore interface {
@@ -174,6 +176,104 @@ func (s *Service) PublishPackage(ctx context.Context, request PublishRequest) (*
return result, nil
}
// InstallCanvasPackage commits the canvas instance, its first release, and
// the durable installation receipt in the same lifecycle transaction. The
// artifact is written before entering the transaction and is owned by the
// release row only after this method commits.
func (s *Service) InstallCanvasPackage(ctx context.Context, request InstallCanvasPackageRequest) (*InstallResult, error) {
if err := s.ready(); err != nil {
return nil, err
}
store, createRequest, err := s.prepareCanvasInstall(request)
if err != nil {
return nil, err
}
s.mu.Lock()
result, event, err := s.installCanvasPackageLocked(ctx, store, createRequest, request)
publisher := s.publisher
s.mu.Unlock()
if err != nil {
return result, err
}
publishEvent(ctx, publisher, event)
return result, nil
}
func (s *Service) prepareCanvasInstall(request InstallCanvasPackageRequest) (transactionalAuthoringStore, CreateCanvasRequest, error) {
if request.Package == nil || request.Package.Manifest == nil || request.Artifact.Digest == "" || s.repo == nil {
return nil, CreateCanvasRequest{}, fmt.Errorf("%w: package and artifact are required", ErrInvalidCanvas)
}
if !request.Approved || strings.TrimSpace(request.Receipt.UserID) == "" {
return nil, CreateCanvasRequest{}, ErrInstallNotApproved
}
store, ok := s.instances.(transactionalAuthoringStore)
if !ok {
return nil, CreateCanvasRequest{}, ErrCanvasNotConfigured
}
createRequest, err := normalizeCreateRequest(CreateCanvasRequest{WorkspaceID: request.WorkspaceID, Title: request.Title, PluginID: CanvasPluginID})
if err != nil {
return nil, CreateCanvasRequest{}, err
}
return store, createRequest, nil
}
func (s *Service) installCanvasPackageLocked(ctx context.Context, store transactionalAuthoringStore, createRequest CreateCanvasRequest, request InstallCanvasPackageRequest) (*InstallResult, LifecycleEvent, error) {
now := s.nowUTC()
metadata := CanvasMetadata{ID: uuid.NewString(), PluginInstanceID: uuid.NewString(), WorkspaceID: createRequest.WorkspaceID, Title: createRequest.Title, CreatedAt: now, UpdatedAt: now}
instance := plugininstances.Instance{ID: metadata.PluginInstanceID, PluginID: createRequest.PluginID, SourceKind: plugininstances.SourceLocalCanvas, ScopeKind: ScopeWorkspace, WorkspaceID: createRequest.WorkspaceID, Status: plugininstances.StatusPending, CreatedAt: now, UpdatedAt: now}
publishRequest := PublishRequest{CanvasID: metadata.ID, Package: request.Package, Artifact: request.Artifact, SourceActorKind: request.SourceActorKind, SourceUserID: request.SourceUserID}
preparedInstance, release, activated, err := s.preparePublishedReleaseForInstance(ctx, store, instance, publishRequest)
if err != nil {
return nil, LifecycleEvent{}, err
}
if preparedInstance.ID != instance.ID {
return nil, LifecycleEvent{}, ErrInvalidCanvas
}
receipt := request.Receipt
receipt.CanvasID = metadata.ID
receipt.WorkspaceID = metadata.WorkspaceID
if receipt.CreatedAt.IsZero() {
receipt.CreatedAt = now
}
if err := s.commitCanvasInstallation(ctx, store, instance, metadata, release, activated, receipt, request.Package.Manifest); err != nil {
return nil, LifecycleEvent{}, err
}
installed, err := s.Get(ctx, metadata.ID)
if err != nil {
return &InstallResult{Receipt: receipt}, LifecycleEvent{}, err
}
return &InstallResult{Canvas: installed, Receipt: receipt}, lifecycleEvent(EventReleaseActivated, *installed), nil
}
func (s *Service) commitCanvasInstallation(ctx context.Context, store transactionalAuthoringStore, instance plugininstances.Instance, metadata CanvasMetadata, release plugininstances.Release, activated bool, receipt InstallReceipt, canvasManifest *manifest.Manifest) error {
return store.WithTransaction(ctx, func(tx *sqlx.Tx) error {
if err := store.CreateTx(ctx, tx, instance); err != nil {
return err
}
if err := s.repo.CreateTx(ctx, tx, metadata); err != nil {
return err
}
if err := store.CreateReleaseTx(ctx, tx, release); err != nil {
return err
}
if err := activateOrApproveCanvasRelease(ctx, store, tx, instance.ID, release, activated, receipt.UserID, canvasManifest); err != nil {
return err
}
return s.repo.CreateInstallReceiptTx(ctx, tx, receipt)
})
}
func activateOrApproveCanvasRelease(ctx context.Context, store transactionalAuthoringStore, tx *sqlx.Tx, instanceID string, release plugininstances.Release, activated bool, userID string, canvasManifest *manifest.Manifest) error {
if !activated {
return store.ApproveReleaseTx(ctx, tx, instanceID, release.ID, userID, grantsForManifest(ManifestPermissions(canvasManifest), userID, ScopeWorkspace))
}
if err := store.SetPluginIDTx(ctx, tx, instanceID, release.PluginID); err != nil {
return err
}
return store.ActivateReleaseTx(ctx, tx, instanceID, release.ID)
}
func (s *Service) preparePublishedRelease(ctx context.Context, store authoringInstanceStore, request PublishRequest) (plugininstances.Instance, plugininstances.Release, bool, CreationAuthority, []plugininstances.Grant, error) {
if err := validatePublishRequest(request); err != nil {
return plugininstances.Instance{}, plugininstances.Release{}, false, CreationAuthority{}, nil, err
@@ -205,6 +305,35 @@ func (s *Service) preparePublishedRelease(ctx context.Context, store authoringIn
return instance, release, activated, creationAuthority, initialGrants, nil
}
func (s *Service) preparePublishedReleaseForInstance(ctx context.Context, store authoringInstanceStore, instance plugininstances.Instance, request PublishRequest) (plugininstances.Instance, plugininstances.Release, bool, error) {
if request.Package == nil || request.Package.Manifest == nil || request.Artifact.Digest == "" {
return plugininstances.Instance{}, plugininstances.Release{}, false, fmt.Errorf("%w: package and artifact are required", ErrInvalidCanvas)
}
if instance.Status == StatusRemoved || instance.Status == StatusArchived {
return plugininstances.Instance{}, plugininstances.Release{}, false, fmt.Errorf("%w: canvas is %s", ErrInvalidCanvasState, instance.Status)
}
if !request.ExpectedAuthority.IsZero() && request.ExpectedAuthority != instance.PublishAuthority() {
return plugininstances.Instance{}, plugininstances.Release{}, false, ErrStaleCanvasPublish
}
if request.Artifact.Digest != request.Package.Digest {
return plugininstances.Instance{}, plugininstances.Release{}, false, fmt.Errorf("%w: artifact digest does not match package", ErrInvalidCanvas)
}
if err := request.Package.Manifest.Validate(); err != nil {
return plugininstances.Instance{}, plugininstances.Release{}, false, fmt.Errorf("%w: invalid manifest: %v", ErrInvalidCanvas, err)
}
permissions := ManifestPermissions(request.Package.Manifest)
grants, err := store.ListGrants(ctx, instance.ID)
if err != nil {
return plugininstances.Instance{}, plugininstances.Release{}, false, err
}
activated := permissionsFit(permissions, instance.ScopeKind, grants)
release, err := s.buildPublishedRelease(request, instance.ID, permissions, activated)
if err != nil {
return plugininstances.Instance{}, plugininstances.Release{}, false, err
}
return instance, release, activated, nil
}
func validatePublishRequest(request PublishRequest) error {
if request.Package == nil || request.Package.Manifest == nil || request.Artifact.Digest == "" {
return fmt.Errorf("%w: package and artifact are required", ErrInvalidCanvas)
@@ -419,6 +419,48 @@ func TestCanvasCreationAuthorityRollsBackOnActivationFailure(t *testing.T) {
}
}
func TestInstallCanvasPackageCommitsReceiptWithCanvasLifecycle(t *testing.T) {
service, instanceStore, _ := newCanvasService(t)
ctx := context.Background()
result, err := service.InstallCanvasPackage(ctx, InstallCanvasPackageRequest{
WorkspaceID: "workspace-install",
Title: "Installed board",
Package: testCanvasPackage("atomic-install", nil),
Artifact: webapp.Artifact{Digest: "atomic-install", RelativePath: "releases/atomic-install", Bytes: 1},
SourceActorKind: "canvas-install:upload",
SourceUserID: "user-1",
Approved: true,
Receipt: InstallReceipt{
PreparationID: "preparation-atomic",
UserID: "user-1",
PackageID: "canvas-board",
Version: "atomic-install",
Digest: "atomic-install",
OriginKind: "upload",
},
})
if err != nil {
t.Fatalf("InstallCanvasPackage() error = %v", err)
}
if result == nil || result.Canvas == nil || result.Receipt.CanvasID != result.Canvas.ID {
t.Fatalf("install result = %+v", result)
}
receipt, err := service.repo.GetInstallReceipt(ctx, "preparation-atomic", "user-1")
if err != nil {
t.Fatalf("GetInstallReceipt() error = %v", err)
}
if receipt.CanvasID != result.Canvas.ID || receipt.WorkspaceID != "workspace-install" {
t.Fatalf("receipt = %+v", receipt)
}
releases, err := instanceStore.ListReleases(ctx, result.Canvas.PluginInstanceID)
if err != nil {
t.Fatalf("ListReleases() error = %v", err)
}
if len(releases) != 1 || releases[0].PackageDigest != "atomic-install" {
t.Fatalf("releases = %+v", releases)
}
}
func TestFirstTaskReleaseCanBeReviewedAndApproved(t *testing.T) {
service, instanceStore, _ := newCanvasService(t)
canvas := createCanvas(t, service, CreateCanvasRequest{
@@ -0,0 +1,169 @@
package canvas
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"time"
"github.com/kandev/kandev/internal/plugins/webapp"
)
func archiveDigest(data []byte) string {
digest := sha256.Sum256(data)
return hex.EncodeToString(digest[:])
}
var (
ErrInstallURLInvalid = errors.New("invalid canvas install URL")
ErrInstallURLBlocked = errors.New("canvas install URL destination is not public")
ErrInstallDownload = errors.New("canvas install download failed")
)
const (
installDownloadTimeout = 2 * time.Minute
installMaxRedirects = 5
)
func newDistributionHTTPClient() *http.Client {
transport := &http.Transport{
Proxy: nil,
DialContext: publicDistributionDialContext,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 20 * time.Second,
IdleConnTimeout: 30 * time.Second,
ForceAttemptHTTP2: true,
MaxIdleConnsPerHost: 2,
DisableCompression: false,
}
return &http.Client{
Transport: transport,
Timeout: installDownloadTimeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= installMaxRedirects {
return ErrInstallURLInvalid
}
if _, err := validateInstallURL(req.URL.String()); err != nil {
return err
}
return nil
},
}
}
func (s *DistributionService) downloadInstallBundle(ctx context.Context, rawURL string) ([]byte, error) {
parsed, err := validateInstallURL(rawURL)
if err != nil {
return nil, err
}
s.installMu.Lock()
client := s.httpClient
s.installMu.Unlock()
if client == nil {
return nil, ErrInstallDownload
}
requestContext, cancel := context.WithTimeout(ctx, installDownloadTimeout)
defer cancel()
req, err := http.NewRequestWithContext(requestContext, http.MethodGet, parsed.String(), nil)
if err != nil {
return nil, fmt.Errorf("%w: request could not be created", ErrInstallURLInvalid)
}
req.Header.Set("Accept", "application/gzip, application/octet-stream")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrInstallDownload, safeDownloadError(err))
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return nil, fmt.Errorf("%w: server returned %s", ErrInstallDownload, resp.Status)
}
if resp.ContentLength > webapp.MaxCompressedBytes {
return nil, webapp.ErrCompressedTooLarge
}
data, err := io.ReadAll(io.LimitReader(resp.Body, webapp.MaxCompressedBytes+1))
if err != nil {
return nil, fmt.Errorf("%w: response could not be read", ErrInstallDownload)
}
if int64(len(data)) > webapp.MaxCompressedBytes {
return nil, webapp.ErrCompressedTooLarge
}
return data, nil
}
func validateInstallURL(raw string) (*url.URL, error) {
parsed, err := url.ParseRequestURI(strings.TrimSpace(raw))
if err != nil || parsed == nil {
return nil, ErrInstallURLInvalid
}
if parsed.Scheme != "https" || parsed.Hostname() == "" || parsed.User != nil || parsed.Fragment != "" || parsed.Opaque != "" {
return nil, ErrInstallURLInvalid
}
if ip := net.ParseIP(parsed.Hostname()); ip != nil && !isPublicInstallIP(ip) {
return nil, ErrInstallURLBlocked
}
return parsed, nil
}
func publicDistributionDialContext(ctx context.Context, network, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, ErrInstallURLBlocked
}
if ip := net.ParseIP(host); ip != nil {
if !isPublicInstallIP(ip) {
return nil, ErrInstallURLBlocked
}
return (&net.Dialer{}).DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
}
ips, err := net.LookupIP(host)
if err != nil || len(ips) == 0 {
return nil, ErrInstallURLBlocked
}
var lastErr error
for _, ip := range ips {
if !isPublicInstallIP(ip) {
continue
}
connection, dialErr := (&net.Dialer{}).DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
if dialErr == nil {
return connection, nil
}
lastErr = dialErr
}
if lastErr != nil {
return nil, lastErr
}
return nil, ErrInstallURLBlocked
}
func isPublicInstallIP(value net.IP) bool {
parsed, err := netip.ParseAddr(value.String())
if err != nil {
return false
}
if parsed.IsLoopback() || parsed.IsPrivate() || parsed.IsLinkLocalUnicast() || parsed.IsLinkLocalMulticast() || parsed.IsUnspecified() || parsed.IsMulticast() {
return false
}
if parsed.Is4() {
value4 := parsed.As4()
if value4[0] == 100 && value4[1] >= 64 && value4[1] <= 127 {
return false
}
}
return true
}
func safeDownloadError(err error) error {
if err == nil {
return nil
}
return errors.New("remote download request failed")
}
@@ -0,0 +1,60 @@
package canvas
import (
"context"
"errors"
"io"
"net/http"
"testing"
"time"
"github.com/kandev/kandev/internal/plugins/webapp"
)
type blockingDownloadBody struct {
closed chan struct{}
}
func (b *blockingDownloadBody) Read([]byte) (int, error) {
<-b.closed
return 0, io.EOF
}
func (b *blockingDownloadBody) Close() error {
select {
case <-b.closed:
default:
close(b.closed)
}
return nil
}
func TestDownloadInstallBundleClosesOversizedResponseWithoutDrainingIt(t *testing.T) {
body := &blockingDownloadBody{closed: make(chan struct{})}
service := NewDistributionService(nil, nil, nil, func(context.Context, string) error { return nil }, nil)
service.SetInstallHTTPClient(&http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusOK, ContentLength: webapp.MaxCompressedBytes + 1, Body: body}, nil
})})
result := make(chan error, 1)
go func() {
_, err := service.downloadInstallBundle(context.Background(), "https://example.test/too-large.tar.gz")
result <- err
}()
select {
case err := <-result:
if !errors.Is(err, webapp.ErrCompressedTooLarge) {
t.Fatalf("download error = %v, want ErrCompressedTooLarge", err)
}
case <-time.After(2 * time.Second):
_ = body.Close()
t.Fatal("oversized response was drained instead of closed")
}
}
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return f(request)
}
@@ -0,0 +1,413 @@
package canvas
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"strings"
"sync"
plugininstances "github.com/kandev/kandev/internal/plugins/instances"
"github.com/kandev/kandev/internal/plugins/manifest"
"github.com/kandev/kandev/internal/plugins/webapp"
)
var (
ErrExportInvalid = errors.New("invalid canvas export")
ErrExportStale = errors.New("canvas export is stale")
)
type CanvasReader interface {
Get(context.Context, string) (*Canvas, error)
}
type ReleaseReader interface {
GetRelease(context.Context, string) (plugininstances.Release, error)
}
type ArtifactReader interface {
ReadFiles(webapp.Artifact) (map[string][]byte, error)
}
type WorkspaceAuthorizer func(context.Context, string) error
// CatalogResolver resolves a server-selected catalog entry. It returns only
// trusted server metadata; the browser never supplies a package URL for this
// path.
type CatalogResolver interface {
ResolveCanvasPackage(context.Context, string, string, string, string) (string, string, error)
}
type ExportMetadata struct {
PackageID string `json:"package_id"`
Version string `json:"version"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Author string `json:"author"`
License string `json:"license"`
SourceMode string `json:"source_mode"`
MinKandevVersion string `json:"min_kandev_version"`
RepoURL string `json:"repo_url,omitempty"`
}
type ExportRequest struct {
UserID string
WorkspaceID string
CanvasID string
ExpectedReleaseID string
Metadata ExportMetadata
}
type ExportReview struct {
PreparationID string `json:"preparation_id"`
CanvasID string `json:"canvas_id"`
WorkspaceID string `json:"workspace_id"`
ReleaseID string `json:"release_id"`
Metadata ExportMetadata `json:"metadata"`
Digest string `json:"sha256"`
Files []ExportFile `json:"files"`
BundleBytes int64 `json:"bundle_bytes"`
SourceBytes int64 `json:"source_bytes"`
ExpiresAt string `json:"expires_at"`
BundleDownload string `json:"bundle_download"`
SourceDownload string `json:"source_download"`
}
type ExportDownload struct {
Data []byte
Filename string
ContentType string
}
type DistributionService struct {
canvases CanvasReader
releases ReleaseReader
artifacts ArtifactReader
authorize WorkspaceAuthorizer
preparations *PreparationStore
installMu sync.Mutex
artifactQuota ArtifactQuota
receipts map[string]InstallReceipt
receiptStore InstallReceiptStore
httpClient *http.Client
catalog CatalogResolver
kandevVersion string
}
// SetArtifactQuota wires the durable storage admission store used by
// marketplace installs. Production composition supplies the same instance
// store used by canvas authoring.
func (s *DistributionService) SetArtifactQuota(quota ArtifactQuota) {
if s == nil {
return
}
s.installMu.Lock()
s.artifactQuota = quota
s.installMu.Unlock()
}
func NewDistributionService(canvases CanvasReader, releases ReleaseReader, artifacts ArtifactReader, authorize WorkspaceAuthorizer, preparations *PreparationStore) *DistributionService {
return &DistributionService{canvases: canvases, releases: releases, artifacts: artifacts, authorize: authorize, preparations: preparations, receipts: make(map[string]InstallReceipt), httpClient: newDistributionHTTPClient()}
}
func (s *DistributionService) SetInstallReceiptStore(store InstallReceiptStore) {
if s == nil {
return
}
s.installMu.Lock()
s.receiptStore = store
s.installMu.Unlock()
}
// SetKandevVersion supplies the stamped server version used by the same
// compatibility gate as native plugin installation.
func (s *DistributionService) SetKandevVersion(version string) {
if s == nil {
return
}
s.installMu.Lock()
s.kandevVersion = version
s.installMu.Unlock()
}
// SetInstallHTTPClient is intended for deterministic local transport tests.
// Production composition leaves the destination-validating client installed.
func (s *DistributionService) SetInstallHTTPClient(client *http.Client) {
if s == nil || client == nil {
return
}
s.installMu.Lock()
s.httpClient = client
s.installMu.Unlock()
}
func (s *DistributionService) SetCatalogResolver(resolver CatalogResolver) {
if s == nil {
return
}
s.installMu.Lock()
s.catalog = resolver
s.installMu.Unlock()
}
func (s *DistributionService) PrepareExport(ctx context.Context, request ExportRequest) (ExportReview, error) {
if err := s.validateReady(request.UserID, request.WorkspaceID, request.CanvasID); err != nil {
return ExportReview{}, err
}
if err := s.authorizeWorkspace(ctx, request.WorkspaceID); err != nil {
return ExportReview{}, err
}
item, release, files, err := s.loadExportSnapshot(ctx, request)
if err != nil {
return ExportReview{}, err
}
metadata, err := normalizeExportMetadata(request.Metadata, releaseManifest(release))
if err != nil {
return ExportReview{}, err
}
manifestValue, err := exportManifest(release.ManifestJSON, metadata)
if err != nil {
return ExportReview{}, err
}
if _, ok := files["README.md"]; !ok {
files["README.md"] = []byte(fmt.Sprintf("# %s\n\n%s\n\nBuild and publish the retained canvas files.\n", metadata.DisplayName, metadata.Description))
}
pkg, err := webapp.BuildDistributionPackage(manifestValue, files)
if err != nil {
if errors.Is(err, webapp.ErrSourceUnavailable) {
return ExportReview{}, err
}
return ExportReview{}, fmt.Errorf("%w: %v", ErrExportInvalid, err)
}
archives, err := webapp.BuildDistributionArchives(pkg)
if err != nil {
return ExportReview{}, fmt.Errorf("%w: %v", ErrExportInvalid, err)
}
preparation, err := s.preparations.Create(ctx, Preparation{
UserID: request.UserID, WorkspaceID: item.WorkspaceID, CanvasID: item.ID, ReleaseID: release.ID,
PackageID: metadata.PackageID, PackageVersion: metadata.Version, PackageDigest: pkg.Digest,
Metadata: metadata,
OriginKind: "export", Bundle: archives.Bundle, Source: archives.Source,
Files: distributionInventory(pkg.Files),
})
if err != nil {
return ExportReview{}, err
}
return exportReview(preparation, metadata, pkg, len(archives.Bundle), len(archives.Source)), nil
}
func (s *DistributionService) GetExport(ctx context.Context, userID, preparationID string) (ExportReview, error) {
preparation, err := s.preparations.Get(ctx, userID, preparationID)
if err != nil {
return ExportReview{}, err
}
if err := s.verifyCurrentRelease(ctx, preparation); err != nil {
return ExportReview{}, err
}
return preparationReview(preparation), nil
}
func (s *DistributionService) DownloadExport(ctx context.Context, userID, preparationID string, kind ExportKind) (ExportDownload, error) {
preparation, err := s.preparations.Get(ctx, userID, preparationID)
if err != nil {
return ExportDownload{}, err
}
if err := s.verifyCurrentRelease(ctx, preparation); err != nil {
return ExportDownload{}, err
}
data, err := s.preparations.Open(ctx, userID, preparationID, kind)
if err != nil {
return ExportDownload{}, err
}
extension, contentType := ".tar.gz", "application/gzip"
if kind == ExportSource {
extension, contentType = ".zip", "application/zip"
} else if kind != ExportBundle {
return ExportDownload{}, ErrExportInvalid
}
return ExportDownload{Data: data, Filename: preparation.PackageID + "-" + preparation.PackageVersion + extension, ContentType: contentType}, nil
}
func (s *DistributionService) CancelExport(ctx context.Context, userID, preparationID string) error {
return s.preparations.Delete(ctx, userID, preparationID)
}
func (s *DistributionService) validateReady(userID, workspaceID, canvasID string) error {
if s == nil || s.canvases == nil || s.releases == nil || s.artifacts == nil || s.preparations == nil ||
strings.TrimSpace(userID) == "" || strings.TrimSpace(workspaceID) == "" || strings.TrimSpace(canvasID) == "" {
return ErrExportInvalid
}
return nil
}
func (s *DistributionService) authorizeWorkspace(ctx context.Context, workspaceID string) error {
if s.authorize == nil {
return nil
}
return s.authorize(ctx, workspaceID)
}
func (s *DistributionService) loadExportSnapshot(ctx context.Context, request ExportRequest) (*Canvas, plugininstances.Release, map[string][]byte, error) {
item, err := s.canvases.Get(ctx, request.CanvasID)
if err != nil || !validExportCanvas(item, request) {
return nil, plugininstances.Release{}, nil, ErrCanvasNotFound
}
if !matchesExpectedRelease(item, request.ExpectedReleaseID) {
return nil, plugininstances.Release{}, nil, ErrExportStale
}
release, err := s.releases.GetRelease(ctx, item.ActiveReleaseID)
if err != nil || !validExportRelease(item, release, request.ExpectedReleaseID) {
return nil, plugininstances.Release{}, nil, ErrExportStale
}
files, err := s.artifacts.ReadFiles(webapp.Artifact{Digest: release.PackageDigest, RelativePath: release.ArtifactPath, Bytes: release.ArtifactBytes, Available: true})
if err != nil {
return nil, plugininstances.Release{}, nil, webapp.ErrArtifactUnavailable
}
return item, release, cloneFiles(files), nil
}
func validExportCanvas(item *Canvas, request ExportRequest) bool {
return item != nil && item.WorkspaceID == request.WorkspaceID &&
(item.ScopeKind == ScopeWorkspace || item.ScopeKind == ScopeTask) && item.Status == StatusActive &&
item.ActiveReleaseID != "" && item.ActiveReleaseStatus == ValidationValid
}
func matchesExpectedRelease(item *Canvas, expectedReleaseID string) bool {
return expectedReleaseID != "" && item != nil && expectedReleaseID == item.ActiveReleaseID
}
func validExportRelease(item *Canvas, release plugininstances.Release, expectedReleaseID string) bool {
if release.ID != expectedReleaseID {
return false
}
return release.InstanceID == "" || item.PluginInstanceID == "" || release.InstanceID == item.PluginInstanceID
}
func (s *DistributionService) verifyCurrentRelease(ctx context.Context, preparation Preparation) error {
if err := s.authorizeWorkspace(ctx, preparation.WorkspaceID); err != nil {
return err
}
item, err := s.canvases.Get(ctx, preparation.CanvasID)
if err != nil || item == nil || item.WorkspaceID != preparation.WorkspaceID || item.ActiveReleaseID != preparation.ReleaseID || item.ActiveReleaseStatus != ValidationValid || item.Status != StatusActive {
return ErrExportStale
}
return nil
}
func releaseManifest(release plugininstances.Release) manifest.Manifest {
var value manifest.Manifest
_ = json.Unmarshal(release.ManifestJSON, &value)
return value
}
func normalizeExportMetadata(input ExportMetadata, current manifest.Manifest) (ExportMetadata, error) {
input = fillExportMetadata(input, current)
if exportMetadataIncomplete(input) {
return ExportMetadata{}, fmt.Errorf("%w: package identity, description, author, license, and compatibility are required", ErrExportInvalid)
}
return input, nil
}
func fillExportMetadata(input ExportMetadata, current manifest.Manifest) ExportMetadata {
if input.PackageID == "" {
input.PackageID = current.ID
}
if input.Version == "" {
input.Version = current.Version
}
if input.DisplayName == "" {
input.DisplayName = current.DisplayName
}
if input.Description == "" {
input.Description = current.Description
}
if input.Author == "" {
input.Author = current.Author
}
if input.License == "" && current.Distribution != nil {
input.License = current.Distribution.License
}
if input.SourceMode == "" {
input.SourceMode = manifest.SourceModeStatic
if current.Distribution != nil {
input.SourceMode = current.Distribution.SourceMode
}
}
if input.MinKandevVersion == "" {
input.MinKandevVersion = current.MinKandevVersion
}
if input.RepoURL == "" {
input.RepoURL = current.RepoURL
}
return input
}
func exportMetadataIncomplete(input ExportMetadata) bool {
return input.PackageID == "" || input.Version == "" || input.DisplayName == "" ||
input.Description == "" || input.Author == "" || input.License == "" || input.MinKandevVersion == ""
}
func exportManifest(data json.RawMessage, metadata ExportMetadata) (*manifest.Manifest, error) {
var value manifest.Manifest
if err := json.Unmarshal(data, &value); err != nil {
return nil, fmt.Errorf("%w: release manifest is invalid", ErrExportInvalid)
}
value.ID, value.Version = metadata.PackageID, metadata.Version
value.DisplayName, value.Description, value.Author = metadata.DisplayName, metadata.Description, metadata.Author
value.MinKandevVersion, value.RepoURL = metadata.MinKandevVersion, metadata.RepoURL
if len(value.UI.WebApps) > 0 && !containsString(value.UI.WebApps[0].Placements, manifest.WebAppPlacementWorkspace) {
value.UI.WebApps[0].Placements = append(value.UI.WebApps[0].Placements, manifest.WebAppPlacementWorkspace)
}
value.Distribution = &manifest.Distribution{SchemaVersion: manifest.DistributionSchemaVersion, Kind: manifest.DistributionKindCanvas, License: metadata.License, SourceMode: metadata.SourceMode}
return &value, nil
}
func cloneFiles(input map[string][]byte) map[string][]byte {
output := make(map[string][]byte, len(input))
for name, data := range input {
output[name] = append([]byte(nil), data...)
}
return output
}
func distributionInventory(files map[string][]byte) []ExportFile {
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
sort.Strings(names)
result := make([]ExportFile, 0, len(names))
for _, name := range names {
result = append(result, ExportFile{Path: name, Bytes: int64(len(files[name]))})
}
return result
}
func exportReview(preparation Preparation, metadata ExportMetadata, pkg *webapp.Package, bundleBytes, sourceBytes int) ExportReview {
review := preparationReview(preparation)
review.Metadata, review.Digest, review.Files = metadata, pkg.Digest, distributionInventory(pkg.Files)
review.BundleBytes, review.SourceBytes = int64(bundleBytes), int64(sourceBytes)
review.BundleDownload = "/api/v1/canvases/exports/" + preparation.ID + "/bundle"
review.SourceDownload = "/api/v1/canvases/exports/" + preparation.ID + "/source"
return review
}
func preparationReview(preparation Preparation) ExportReview {
metadata := preparation.Metadata
if metadata.PackageID == "" {
metadata.PackageID, metadata.Version = preparation.PackageID, preparation.PackageVersion
}
return ExportReview{PreparationID: preparation.ID, CanvasID: preparation.CanvasID, WorkspaceID: preparation.WorkspaceID, ReleaseID: preparation.ReleaseID, Metadata: metadata, Digest: preparation.PackageDigest, Files: append([]ExportFile(nil), preparation.Files...), ExpiresAt: preparation.ExpiresAt.UTC().Format("2006-01-02T15:04:05.000Z07:00")}
}
func (s *DistributionService) preparationsCount() int {
if s == nil || s.preparations == nil {
return 0
}
s.preparations.mu.Lock()
defer s.preparations.mu.Unlock()
return len(s.preparations.items)
}
@@ -0,0 +1,393 @@
package canvas
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"errors"
"testing"
"time"
plugininstances "github.com/kandev/kandev/internal/plugins/instances"
"github.com/kandev/kandev/internal/plugins/manifest"
"github.com/kandev/kandev/internal/plugins/webapp"
)
func TestPrepareExportBuildsOneReleaseBoundBundleAndSource(t *testing.T) {
service, releases, _ := newDistributionExportTestService(t)
review, err := service.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
if review.PreparationID == "" || review.Digest == "" || review.BundleBytes == 0 || review.SourceBytes == 0 {
t.Fatalf("review = %+v", review)
}
if review.Metadata.SourceMode != manifest.SourceModeStatic {
t.Fatalf("metadata = %+v", review.Metadata)
}
if !hasExportFile(review.Files, "ui/logo.svg") || !hasExportFile(review.Files, "ui/body.woff2") {
t.Fatalf("runtime assets missing from export inventory: %+v", review.Files)
}
if releases.lastID != "release-1" {
t.Fatalf("release lookup = %q, want release-1", releases.lastID)
}
bundle, err := service.DownloadExport(context.Background(), "user-1", review.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport(bundle) error = %v", err)
}
if _, err := webapp.ValidateDistributionPackage(bytes.NewReader(bundle.Data)); err != nil {
t.Fatalf("downloaded bundle validation error = %v", err)
}
source, err := service.DownloadExport(context.Background(), "user-1", review.PreparationID, ExportSource)
if err != nil {
t.Fatalf("DownloadExport(source) error = %v", err)
}
if _, err := zip.NewReader(bytes.NewReader(source.Data), int64(len(source.Data))); err != nil {
t.Fatalf("downloaded source validation error = %v", err)
}
if !sameReleaseID(review, "release-1") {
t.Fatal("review is not bound to the expected release")
}
}
func TestPrepareExportAllowsTaskCanvasWithPortableWorkspacePlacement(t *testing.T) {
service, releases, canvases := newDistributionExportTestService(t)
var sourceManifest manifest.Manifest
if err := json.Unmarshal(releases.release.ManifestJSON, &sourceManifest); err != nil {
t.Fatalf("unmarshal source manifest: %v", err)
}
sourceManifest.UI.WebApps[0].Placements = []string{manifest.WebAppPlacementTask}
if err := sourceManifest.Validate(); err != nil {
t.Fatalf("task source manifest should remain locally valid: %v", err)
}
releases.release.ManifestJSON, _ = json.Marshal(sourceManifest)
canvases.canvas.ScopeKind = ScopeTask
review, err := service.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
if canvases.canvas.ScopeKind != ScopeTask {
t.Fatalf("task canvas scope changed to %q during export", canvases.canvas.ScopeKind)
}
bundle, err := service.DownloadExport(context.Background(), "user-1", review.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport() error = %v", err)
}
pkg, err := webapp.ValidateDistributionPackage(bytes.NewReader(bundle.Data))
if err != nil {
t.Fatalf("downloaded task bundle validation error = %v", err)
}
placements := pkg.Manifest.UI.WebApps[0].Placements
if !containsString(placements, manifest.WebAppPlacementWorkspace) {
t.Fatalf("exported placements = %v, want workspace-canvas", placements)
}
}
func TestPrepareExportRejectsStaleReleaseWithoutCreatingPreparation(t *testing.T) {
service, _, canvases := newDistributionExportTestService(t)
canvases.canvas.ActiveReleaseID = "release-new"
_, err := service.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if !errors.Is(err, ErrExportStale) {
t.Fatalf("PrepareExport() error = %v, want ErrExportStale", err)
}
if service.preparationsCount() != 0 {
t.Fatal("stale export created a preparation")
}
}
func TestPrepareInstallInspectsExactBundleAndReturnsPermissions(t *testing.T) {
service, _, _ := newDistributionExportTestService(t)
export, err := service.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
bundle, err := service.DownloadExport(context.Background(), "user-1", export.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport() error = %v", err)
}
review, err := service.PrepareInstall(context.Background(), InstallRequest{
UserID: "user-1", WorkspaceID: "workspace-1", OriginKind: "upload", Bundle: bundle.Data,
})
if err != nil {
t.Fatalf("PrepareInstall() error = %v", err)
}
if review.Metadata.PackageID != "canvas-board" || review.Metadata.License != "MIT" || review.PermissionSummary.Reads == nil {
t.Fatalf("install review = %+v", review)
}
}
func TestPrepareInstallRejectsExpectedDigestMismatch(t *testing.T) {
service, _, _ := newDistributionExportTestService(t)
export, err := service.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
bundle, err := service.DownloadExport(context.Background(), "user-1", export.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport() error = %v", err)
}
_, err = service.PrepareInstall(context.Background(), InstallRequest{UserID: "user-1", WorkspaceID: "workspace-1", OriginKind: "upload", ExpectedDigest: "wrong", Bundle: bundle.Data})
if !errors.Is(err, ErrPackageDigestMismatch) {
t.Fatalf("PrepareInstall() error = %v, want ErrPackageDigestMismatch", err)
}
}
func TestConfirmInstallChecksDurableArtifactQuotaBeforeWriting(t *testing.T) {
exportService, _, _ := newDistributionExportTestService(t)
export, err := exportService.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
bundle, err := exportService.DownloadExport(context.Background(), "user-1", export.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport() error = %v", err)
}
installer := &fakeDistributionInstaller{}
artifactWriter := &fakeDistributionArtifactWriter{}
quota := &fakeDistributionQuota{reserveErr: plugininstances.ErrWorkspaceStorageLimit}
service := NewDistributionService(installer, &fakeDistributionReleaseReader{}, artifactWriter, func(context.Context, string) error { return nil }, exportService.preparations)
service.SetArtifactQuota(quota)
review, err := service.PrepareInstall(context.Background(), InstallRequest{UserID: "user-1", WorkspaceID: "workspace-1", OriginKind: "upload", Bundle: bundle.Data})
if err != nil {
t.Fatalf("PrepareInstall() error = %v", err)
}
_, err = service.ConfirmInstall(context.Background(), "user-1", review.PreparationID, InstallConfirmation{ExpectedDigest: review.Digest, Approved: true})
if !errors.Is(err, plugininstances.ErrWorkspaceStorageLimit) {
t.Fatalf("ConfirmInstall() error = %v, want workspace storage limit", err)
}
if artifactWriter.next != 0 || installer.created != 0 || quota.released != 0 {
t.Fatalf("quota failure left writes behind: artifacts=%d installs=%d releases=%d", artifactWriter.next, installer.created, quota.released)
}
}
func TestConfirmInstallReleasesDurableArtifactReservationAfterInstall(t *testing.T) {
exportService, _, _ := newDistributionExportTestService(t)
export, err := exportService.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
bundle, err := exportService.DownloadExport(context.Background(), "user-1", export.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport() error = %v", err)
}
quota := &fakeDistributionQuota{}
installer := &fakeDistributionInstaller{}
writer := &fakeDistributionArtifactWriter{}
service := NewDistributionService(installer, &fakeDistributionReleaseReader{}, writer, func(context.Context, string) error { return nil }, exportService.preparations)
service.SetArtifactQuota(quota)
review, err := service.PrepareInstall(context.Background(), InstallRequest{UserID: "user-1", WorkspaceID: "workspace-1", OriginKind: "upload", Bundle: bundle.Data})
if err != nil {
t.Fatalf("PrepareInstall() error = %v", err)
}
if _, err := service.ConfirmInstall(context.Background(), "user-1", review.PreparationID, InstallConfirmation{ExpectedDigest: review.Digest, Approved: true}); err != nil {
t.Fatalf("ConfirmInstall() error = %v", err)
}
if quota.released != 1 || writer.next != 1 || installer.created != 1 {
t.Fatalf("reservation cleanup = released %d, artifacts %d, installs %d", quota.released, writer.next, installer.created)
}
}
func TestPrepareInstallRejectsPackageRequiringNewerKandev(t *testing.T) {
service, _, _ := newDistributionExportTestService(t)
service.SetKandevVersion("0.9.0")
export, err := service.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
bundle, err := service.DownloadExport(context.Background(), "user-1", export.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport() error = %v", err)
}
_, err = service.PrepareInstall(context.Background(), InstallRequest{UserID: "user-1", WorkspaceID: "workspace-1", OriginKind: "upload", Bundle: bundle.Data})
if !errors.Is(err, ErrInstallIncompatible) {
t.Fatalf("PrepareInstall() error = %v, want ErrInstallIncompatible", err)
}
}
func TestConfirmInstallIsIdempotentForOnePreparation(t *testing.T) {
exportService, _, _ := newDistributionExportTestService(t)
export, err := exportService.PrepareExport(context.Background(), ExportRequest{
UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1", ExpectedReleaseID: "release-1",
Metadata: ExportMetadata{PackageID: "canvas-board", Version: "1.2.3", DisplayName: "Board", Description: "A board", Author: "Kandev", License: "MIT", SourceMode: manifest.SourceModeStatic, MinKandevVersion: "1.0.0"},
})
if err != nil {
t.Fatalf("PrepareExport() error = %v", err)
}
bundle, err := exportService.DownloadExport(context.Background(), "user-1", export.PreparationID, ExportBundle)
if err != nil {
t.Fatalf("DownloadExport() error = %v", err)
}
installer := &fakeDistributionInstaller{}
artifactWriter := &fakeDistributionArtifactWriter{}
service := NewDistributionService(installer, &fakeDistributionReleaseReader{}, artifactWriter, func(context.Context, string) error { return nil }, exportService.preparations)
review, err := service.PrepareInstall(context.Background(), InstallRequest{UserID: "user-1", WorkspaceID: "workspace-1", OriginKind: "upload", Bundle: bundle.Data})
if err != nil {
t.Fatalf("PrepareInstall() error = %v", err)
}
first, err := service.ConfirmInstall(context.Background(), "user-1", review.PreparationID, InstallConfirmation{ExpectedDigest: review.Digest, Approved: true})
if err != nil {
t.Fatalf("ConfirmInstall(first) error = %v", err)
}
second, err := service.ConfirmInstall(context.Background(), "user-1", review.PreparationID, InstallConfirmation{ExpectedDigest: review.Digest, Approved: true})
if err != nil {
t.Fatalf("ConfirmInstall(retry) error = %v", err)
}
if first.Canvas == nil || second.Canvas == nil || first.Canvas.ID != second.Canvas.ID || installer.created != 1 {
t.Fatalf("first=%+v second=%+v created=%d", first, second, installer.created)
}
}
type fakeDistributionCanvasReader struct{ canvas *Canvas }
func (f *fakeDistributionCanvasReader) Get(context.Context, string) (*Canvas, error) {
return f.canvas, nil
}
type fakeDistributionReleaseReader struct {
release plugininstances.Release
lastID string
}
func (f *fakeDistributionReleaseReader) GetRelease(_ context.Context, id string) (plugininstances.Release, error) {
f.lastID = id
return f.release, nil
}
type fakeDistributionArtifactReader struct{ files map[string][]byte }
func (f *fakeDistributionArtifactReader) ReadFiles(webapp.Artifact) (map[string][]byte, error) {
return f.files, nil
}
type fakeDistributionArtifactWriter struct{ next int }
func (f *fakeDistributionArtifactWriter) ReadFiles(webapp.Artifact) (map[string][]byte, error) {
return nil, nil
}
func (f *fakeDistributionArtifactWriter) Put(pkg *webapp.Package) (webapp.Artifact, error) {
f.next++
return webapp.Artifact{Digest: pkg.Digest, RelativePath: "releases/" + pkg.Digest, Bytes: pkg.ExpandedBytes, Available: true}, nil
}
type fakeDistributionQuota struct {
reserveErr error
released int
}
func (f *fakeDistributionQuota) ReserveBytes(context.Context, string, int64, int64, int64) (plugininstances.Reservation, error) {
if f.reserveErr != nil {
return plugininstances.Reservation{}, f.reserveErr
}
return plugininstances.Reservation{ID: "reservation-1"}, nil
}
func (f *fakeDistributionQuota) ReleaseBytes(context.Context, string) error {
f.released++
return nil
}
type fakeDistributionInstaller struct {
created int
canvas *Canvas
}
func (f *fakeDistributionInstaller) InstallCanvasPackage(_ context.Context, request InstallCanvasPackageRequest) (*InstallResult, error) {
f.created++
f.canvas = &Canvas{ID: "installed-canvas", PluginInstanceID: "installed-instance", WorkspaceID: request.WorkspaceID, ScopeKind: ScopeWorkspace, Status: StatusActive, Title: request.Title}
receipt := request.Receipt
receipt.CanvasID = f.canvas.ID
return &InstallResult{Canvas: f.canvas, Receipt: receipt}, nil
}
func (f *fakeDistributionInstaller) Get(context.Context, string) (*Canvas, error) {
if f.canvas == nil {
return nil, ErrCanvasNotFound
}
return f.canvas, nil
}
func (f *fakeDistributionInstaller) CreateCanvas(_ context.Context, request CreateCanvasRequest) (*Canvas, error) {
f.created++
f.canvas = &Canvas{ID: "installed-canvas", PluginInstanceID: "installed-instance", WorkspaceID: request.WorkspaceID, ScopeKind: ScopeWorkspace, Status: StatusActive, Title: request.Title}
return f.canvas, nil
}
func (f *fakeDistributionInstaller) PublishPackage(_ context.Context, request PublishRequest) (*PublishResult, error) {
return &PublishResult{Canvas: f.canvas, Release: plugininstances.Release{ID: "installed-release", InstanceID: f.canvas.PluginInstanceID}, Activated: false}, nil
}
func (f *fakeDistributionInstaller) ApproveRelease(context.Context, string, string, string) (*Canvas, error) {
f.canvas.ActiveReleaseID = "installed-release"
f.canvas.ActiveReleaseStatus = ValidationValid
return f.canvas, nil
}
func newDistributionExportTestService(t *testing.T) (*DistributionService, *fakeDistributionReleaseReader, *fakeDistributionCanvasReader) {
t.Helper()
manifestValue := manifest.Manifest{
ID: "legacy-board", APIVersion: manifest.CurrentAPIVersion, Version: "0.1.0", DisplayName: "Board", Description: "A board", Author: "Author",
UI: manifest.UISection{WebApps: []manifest.WebApp{{Key: "main", Title: "Board", Entry: "ui/index.html", Placements: []string{manifest.WebAppPlacementWorkspace}}}},
Capabilities: manifest.Capabilities{APIRead: []string{"tasks"}},
}
manifestJSON, err := json.Marshal(manifestValue)
if err != nil {
t.Fatalf("marshal manifest: %v", err)
}
releases := &fakeDistributionReleaseReader{release: plugininstances.Release{
ID: "release-1", InstanceID: "instance-1", PackageDigest: "old-digest", ArtifactPath: "releases/old-digest", ArtifactBytes: 10,
ManifestJSON: manifestJSON, ValidationStatus: plugininstances.ValidationValid, CreatedAt: time.Now().UTC(),
}}
canvases := &fakeDistributionCanvasReader{canvas: &Canvas{ID: "canvas-1", WorkspaceID: "workspace-1", ScopeKind: ScopeWorkspace, Status: StatusActive, ActiveReleaseID: "release-1", ActiveReleaseStatus: ValidationValid}}
files := map[string][]byte{
"manifest.yaml": []byte("legacy"),
"ui/index.html": []byte("<html></html>"),
"ui/logo.svg": []byte("<svg></svg>"),
"ui/body.woff2": []byte("font-bytes"),
"ui/theme.css": []byte("body { color: red; }"),
"ui/runtime.json": []byte(`{"ready":true}`),
}
preparations, err := NewPreparationStore(t.TempDir())
if err != nil {
t.Fatalf("NewPreparationStore: %v", err)
}
service := NewDistributionService(canvases, releases, &fakeDistributionArtifactReader{files: files}, func(context.Context, string) error { return nil }, preparations)
return service, releases, canvases
}
func sameReleaseID(review ExportReview, id string) bool { return review.ReleaseID == id }
func hasExportFile(files []ExportFile, path string) bool {
for _, file := range files {
if file.Path == path {
return true
}
}
return false
}
@@ -0,0 +1,511 @@
package canvas
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"time"
plugininstances "github.com/kandev/kandev/internal/plugins/instances"
"github.com/kandev/kandev/internal/plugins/manifest"
"github.com/kandev/kandev/internal/plugins/webapp"
)
var (
ErrInstallInvalid = errors.New("invalid canvas installation")
ErrPackageDigestMismatch = errors.New("canvas package digest mismatch")
ErrInstallNotApproved = errors.New("canvas installation approval is required")
ErrInstallUnavailable = errors.New("canvas installation is unavailable")
ErrInstallReceiptNotFound = errors.New("canvas installation receipt not found")
ErrInstallIncompatible = errors.New("canvas package requires a newer Kandev version")
)
const (
installOriginUpload = "upload"
installOriginURL = "url"
installOriginRegistry = "registry"
)
type ArtifactWriter interface {
Put(*webapp.Package) (webapp.Artifact, error)
}
type artifactWriterWithCreated interface {
PutWithCreated(*webapp.Package) (webapp.Artifact, bool, error)
}
type artifactRemover interface {
Remove(webapp.Artifact) error
}
// ArtifactQuota is the shared durable admission mechanism used by both
// authoring and marketplace installation. Reservations are held until the
// install transaction has either committed or failed.
type ArtifactQuota interface {
ReserveBytes(context.Context, string, int64, int64, int64) (plugininstances.Reservation, error)
ReleaseBytes(context.Context, string) error
}
type CanvasInstaller interface {
CanvasReader
InstallCanvasPackage(context.Context, InstallCanvasPackageRequest) (*InstallResult, error)
}
// InstallCanvasPackageRequest is the trusted, already-inspected input for the
// single database transaction used by the production canvas service.
type InstallCanvasPackageRequest struct {
WorkspaceID string
Title string
Package *webapp.Package
Artifact webapp.Artifact
SourceActorKind string
SourceUserID string
Approved bool
Receipt InstallReceipt
}
type InstallReceiptStore interface {
GetInstallReceipt(context.Context, string, string) (InstallReceipt, error)
CreateInstallReceipt(context.Context, InstallReceipt) error
}
type InstallConfirmation struct {
ExpectedDigest string `json:"expected_digest"`
Approved bool `json:"approved"`
}
type InstallReceipt struct {
PreparationID string `json:"preparation_id"`
UserID string `json:"user_id"`
CanvasID string `json:"canvas_id"`
WorkspaceID string `json:"workspace_id"`
PackageID string `json:"package_id"`
Version string `json:"version"`
Digest string `json:"sha256"`
SourceID string `json:"source_id,omitempty"`
RepositoryURL string `json:"repository_url,omitempty"`
OriginKind string `json:"origin_kind"`
CreatedAt time.Time `json:"created_at"`
}
type InstallResult struct {
Canvas *Canvas `json:"canvas"`
Receipt InstallReceipt `json:"receipt"`
}
type InstallRequest struct {
UserID string
WorkspaceID string
OriginKind string
SourceID string
RepositoryURL string
PackageID string
ExpectedVersion string
ExpectedDigest string
ExpectedArchiveDigest string
Bundle []byte
}
// GetInstallReview returns the authoritative inspected metadata for a staged
// install. It reopens the staged bytes so permissions are never reconstructed
// from browser-supplied fields.
func (s *DistributionService) GetInstallReview(ctx context.Context, userID, preparationID string) (InstallReview, error) {
if s == nil || s.preparations == nil || strings.TrimSpace(userID) == "" || strings.TrimSpace(preparationID) == "" {
return InstallReview{}, ErrInstallInvalid
}
preparation, err := s.preparations.Get(ctx, userID, preparationID)
if err != nil {
return InstallReview{}, err
}
if err := s.authorizeWorkspace(ctx, preparation.WorkspaceID); err != nil {
return InstallReview{}, err
}
bundle, err := s.preparations.Open(ctx, userID, preparationID, ExportBundle)
if err != nil {
return InstallReview{}, err
}
pkg, err := webapp.ValidateDistributionPackage(bytes.NewReader(bundle))
if err != nil {
return InstallReview{}, fmt.Errorf("%w: %v", ErrInstallInvalid, err)
}
if pkg.Digest != preparation.PackageDigest {
return InstallReview{}, ErrPackageDigestMismatch
}
return installReview(preparation, pkg), nil
}
// CancelInstall removes an unconfirmed install review.
func (s *DistributionService) CancelInstall(ctx context.Context, userID, preparationID string) error {
if s == nil || s.preparations == nil {
return ErrInstallInvalid
}
return s.preparations.Delete(ctx, userID, preparationID)
}
type InstallReview struct {
PreparationID string `json:"preparation_id"`
WorkspaceID string `json:"workspace_id"`
Metadata InstallMetadata `json:"metadata"`
Digest string `json:"sha256"`
ArchiveDigest string `json:"archive_sha256"`
PermissionSummary PermissionSummary `json:"permissions"`
OriginKind string `json:"origin_kind"`
SourceID string `json:"source_id,omitempty"`
RepositoryURL string `json:"repository_url,omitempty"`
ExpiresAt string `json:"expires_at"`
}
type InstallMetadata struct {
PackageID string `json:"package_id"`
Version string `json:"version"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Author string `json:"author"`
License string `json:"license"`
SourceMode string `json:"source_mode"`
MinKandevVersion string `json:"min_kandev_version"`
RepoURL string `json:"repo_url,omitempty"`
}
func (s *DistributionService) PrepareInstall(ctx context.Context, request InstallRequest) (InstallReview, error) {
if err := s.validateInstallRequest(ctx, request); err != nil {
return InstallReview{}, err
}
origin, err := normalizeInstallOrigin(request.OriginKind)
if err != nil {
return InstallReview{}, err
}
pkg, archive, err := inspectInstallBundle(request, origin)
if err != nil {
return InstallReview{}, err
}
if err := s.validateInstallCompatibility(pkg); err != nil {
return InstallReview{}, err
}
return s.stageInstall(ctx, request, origin, archive, pkg)
}
func (s *DistributionService) validateInstallCompatibility(pkg *webapp.Package) error {
if pkg == nil || pkg.Manifest == nil {
return ErrInstallInvalid
}
s.installMu.Lock()
runningVersion := s.kandevVersion
s.installMu.Unlock()
if err := manifest.CheckMinimumKandevVersion(pkg.Manifest.MinKandevVersion, runningVersion); err != nil {
return fmt.Errorf("%w: %v", ErrInstallIncompatible, err)
}
return nil
}
func (s *DistributionService) validateInstallRequest(ctx context.Context, request InstallRequest) error {
if s == nil || s.preparations == nil || strings.TrimSpace(request.UserID) == "" || strings.TrimSpace(request.WorkspaceID) == "" || len(request.Bundle) == 0 {
return ErrInstallInvalid
}
return s.authorizeWorkspace(ctx, request.WorkspaceID)
}
func normalizeInstallOrigin(origin string) (string, error) {
origin = strings.TrimSpace(origin)
if origin == "" {
return installOriginUpload, nil
}
if origin != installOriginUpload && origin != installOriginURL && origin != installOriginRegistry {
return "", ErrInstallInvalid
}
return origin, nil
}
func inspectInstallBundle(request InstallRequest, origin string) (*webapp.Package, string, error) {
pkg, err := webapp.ValidateDistributionPackage(bytes.NewReader(request.Bundle))
if err != nil {
return nil, "", fmt.Errorf("%w: %v", ErrInstallInvalid, err)
}
archive := archiveDigest(request.Bundle)
if err := validateInstallExpectations(request, origin, pkg, archive); err != nil {
return nil, "", err
}
return pkg, archive, nil
}
func validateInstallExpectations(request InstallRequest, origin string, pkg *webapp.Package, archive string) error {
if request.PackageID != "" && request.PackageID != pkg.Manifest.ID {
return ErrPackageDigestMismatch
}
if request.ExpectedVersion != "" && request.ExpectedVersion != pkg.Manifest.Version {
return ErrPackageDigestMismatch
}
if request.ExpectedDigest != "" && request.ExpectedDigest != pkg.Digest {
return ErrPackageDigestMismatch
}
if request.ExpectedArchiveDigest != "" && request.ExpectedArchiveDigest != archive {
return ErrPackageDigestMismatch
}
return nil
}
func (s *DistributionService) stageInstall(ctx context.Context, request InstallRequest, origin, archive string, pkg *webapp.Package) (InstallReview, error) {
metadata := installMetadata(pkg.Manifest)
repositoryURL := sanitizeRepositoryURL(request.RepositoryURL)
preparation, err := s.preparations.Create(ctx, Preparation{
UserID: request.UserID, WorkspaceID: request.WorkspaceID, PackageID: pkg.Manifest.ID,
PackageVersion: pkg.Manifest.Version, PackageDigest: pkg.Digest, PackageArchiveDigest: archive, OriginKind: origin,
SourceID: request.SourceID, RepositoryURL: repositoryURL,
Metadata: ExportMetadata{PackageID: pkg.Manifest.ID, Version: pkg.Manifest.Version, DisplayName: pkg.Manifest.DisplayName, Description: pkg.Manifest.Description, Author: pkg.Manifest.Author, License: pkg.Manifest.Distribution.License, SourceMode: pkg.Manifest.Distribution.SourceMode, MinKandevVersion: pkg.Manifest.MinKandevVersion, RepoURL: pkg.Manifest.RepoURL},
Bundle: append([]byte(nil), request.Bundle...), Files: distributionInventory(pkg.Files),
})
if err != nil {
return InstallReview{}, err
}
return InstallReview{PreparationID: preparation.ID, WorkspaceID: request.WorkspaceID, Metadata: metadata, Digest: pkg.Digest, ArchiveDigest: archive, PermissionSummary: ManifestPermissions(pkg.Manifest), OriginKind: origin, SourceID: request.SourceID, RepositoryURL: repositoryURL, ExpiresAt: preparation.ExpiresAt.UTC().Format("2006-01-02T15:04:05.000Z07:00")}, nil
}
// PrepareInstallFromURL downloads one bounded HTTPS bundle and routes the
// resulting bytes through the same inspection path as uploads.
func (s *DistributionService) PrepareInstallFromURL(ctx context.Context, request InstallRequest, rawURL string) (InstallReview, error) {
if s == nil || strings.TrimSpace(request.UserID) == "" || strings.TrimSpace(request.WorkspaceID) == "" {
return InstallReview{}, ErrInstallInvalid
}
if err := s.authorizeWorkspace(ctx, request.WorkspaceID); err != nil {
return InstallReview{}, err
}
bundle, err := s.downloadInstallBundle(ctx, rawURL)
if err != nil {
return InstallReview{}, err
}
request.Bundle = bundle
if strings.TrimSpace(request.OriginKind) == "" {
request.OriginKind = installOriginURL
}
if strings.TrimSpace(request.RepositoryURL) == "" {
request.RepositoryURL = sanitizeRepositoryURL(rawURL)
}
return s.PrepareInstall(ctx, request)
}
// PrepareInstallFromCatalog resolves and downloads the exact server-selected
// canvas listing before entering the normal inspected-byte review path.
func (s *DistributionService) PrepareInstallFromCatalog(ctx context.Context, request InstallRequest) (InstallReview, error) {
if s == nil || strings.TrimSpace(request.UserID) == "" || strings.TrimSpace(request.WorkspaceID) == "" || strings.TrimSpace(request.SourceID) == "" || strings.TrimSpace(request.PackageID) == "" || strings.TrimSpace(request.ExpectedVersion) == "" || strings.TrimSpace(request.ExpectedArchiveDigest) == "" {
return InstallReview{}, ErrInstallInvalid
}
if err := s.authorizeWorkspace(ctx, request.WorkspaceID); err != nil {
return InstallReview{}, err
}
s.installMu.Lock()
resolver := s.catalog
s.installMu.Unlock()
if resolver == nil {
return InstallReview{}, ErrInstallUnavailable
}
packageURL, repositoryURL, err := resolver.ResolveCanvasPackage(ctx, request.SourceID, request.PackageID, request.ExpectedVersion, request.ExpectedArchiveDigest)
if err != nil {
return InstallReview{}, err
}
request.OriginKind = installOriginRegistry
request.RepositoryURL = repositoryURL
request.ExpectedDigest = ""
return s.PrepareInstallFromURL(ctx, request, packageURL)
}
func (s *DistributionService) ConfirmInstall(ctx context.Context, userID, preparationID string, confirmation InstallConfirmation) (InstallResult, error) {
if s == nil || s.preparations == nil || strings.TrimSpace(userID) == "" || strings.TrimSpace(preparationID) == "" {
return InstallResult{}, ErrInstallInvalid
}
if !confirmation.Approved {
return InstallResult{}, ErrInstallNotApproved
}
if result, ok, err := s.lookupReceipt(ctx, userID, preparationID); err != nil {
return InstallResult{}, err
} else if ok {
return s.authorizeInstallReceipt(ctx, result)
}
s.installMu.Lock()
defer s.installMu.Unlock()
if result, ok, err := s.lookupReceiptLocked(ctx, userID, preparationID); err != nil {
return InstallResult{}, err
} else if ok {
return s.authorizeInstallReceipt(ctx, result)
}
preparation, err := s.preparations.Get(ctx, userID, preparationID)
if err != nil {
return InstallResult{}, err
}
if err := s.authorizeWorkspace(ctx, preparation.WorkspaceID); err != nil {
return InstallResult{}, err
}
pkg, err := s.openInstallPackage(ctx, userID, preparation, confirmation.ExpectedDigest)
if err != nil {
return InstallResult{}, err
}
receipt := InstallReceipt{PreparationID: preparation.ID, UserID: userID, WorkspaceID: preparation.WorkspaceID, PackageID: preparation.PackageID, Version: preparation.PackageVersion, Digest: preparation.PackageDigest, SourceID: preparation.SourceID, RepositoryURL: sanitizeRepositoryURL(preparation.RepositoryURL), OriginKind: preparation.OriginKind, CreatedAt: time.Now().UTC()}
return s.installPreparedPackage(ctx, userID, preparation, pkg, receipt)
}
func (s *DistributionService) authorizeInstallReceipt(ctx context.Context, result InstallResult) (InstallResult, error) {
if err := s.authorizeWorkspace(ctx, result.Receipt.WorkspaceID); err != nil {
return InstallResult{}, err
}
return result, nil
}
func (s *DistributionService) installPreparedPackage(ctx context.Context, userID string, preparation Preparation, pkg *webapp.Package, receipt InstallReceipt) (InstallResult, error) {
installer, ok := s.canvases.(CanvasInstaller)
if !ok {
return InstallResult{}, ErrInstallUnavailable
}
if err := s.authorizeWorkspace(ctx, preparation.WorkspaceID); err != nil {
return InstallResult{}, err
}
writer, ok := s.artifacts.(ArtifactWriter)
if !ok {
return InstallResult{}, ErrInstallUnavailable
}
quota := s.artifactQuota
var reservation plugininstances.Reservation
if quota != nil {
var err error
reservation, err = quota.ReserveBytes(ctx, preparation.WorkspaceID, pkg.ExpandedBytes, plugininstances.WorkspaceArtifactLimitBytes, plugininstances.InstallationArtifactLimitBytes)
if err != nil {
return InstallResult{}, err
}
defer func() { _ = quota.ReleaseBytes(context.WithoutCancel(ctx), reservation.ID) }()
}
artifact, created, err := putInstallArtifact(writer, pkg)
if err != nil {
return InstallResult{}, err
}
result, err := installer.InstallCanvasPackage(ctx, InstallCanvasPackageRequest{WorkspaceID: preparation.WorkspaceID, Title: pkg.Manifest.DisplayName, Package: pkg, Artifact: artifact, SourceActorKind: "canvas-install:" + preparation.OriginKind, SourceUserID: userID, Approved: true, Receipt: receipt})
if err != nil {
return s.handleInstallFailure(ctx, userID, preparation.ID, writer, artifact, created, result, err)
}
if !validInstallResult(result) {
return InstallResult{}, ErrInstallUnavailable
}
if err := s.cacheInstallReceipt(ctx, userID, preparation.ID, result.Receipt); err != nil {
return InstallResult{}, err
}
return *result, nil
}
func (s *DistributionService) handleInstallFailure(ctx context.Context, userID, preparationID string, writer ArtifactWriter, artifact webapp.Artifact, created bool, result *InstallResult, installErr error) (InstallResult, error) {
existing, found, lookupErr := s.lookupReceiptLocked(ctx, userID, preparationID)
if lookupErr != nil {
return InstallResult{}, errors.Join(installErr, lookupErr)
}
if found {
return s.authorizeInstallReceipt(ctx, existing)
}
if !created || validInstallResult(result) {
return InstallResult{}, installErr
}
remover, ok := writer.(artifactRemover)
if !ok {
return InstallResult{}, installErr
}
if cleanupErr := remover.Remove(artifact); cleanupErr != nil {
return InstallResult{}, errors.Join(installErr, cleanupErr)
}
return InstallResult{}, installErr
}
func validInstallResult(result *InstallResult) bool {
return result != nil && result.Canvas != nil && result.Receipt.CanvasID != ""
}
func (s *DistributionService) openInstallPackage(ctx context.Context, userID string, preparation Preparation, expectedDigest string) (*webapp.Package, error) {
if expectedDigest == "" || (expectedDigest != preparation.PackageDigest && expectedDigest != preparation.PackageArchiveDigest) {
return nil, ErrPackageDigestMismatch
}
bundle, err := s.preparations.Open(ctx, userID, preparation.ID, ExportBundle)
if err != nil {
return nil, err
}
pkg, err := webapp.ValidateDistributionPackage(bytes.NewReader(bundle))
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrInstallInvalid, err)
}
if pkg.Digest != preparation.PackageDigest {
return nil, ErrPackageDigestMismatch
}
return pkg, nil
}
func (s *DistributionService) cacheInstallReceipt(ctx context.Context, userID, preparationID string, receipt InstallReceipt) error {
if s.receipts == nil {
s.receipts = make(map[string]InstallReceipt)
}
s.receipts[preparationID] = receipt
return s.preparations.Delete(ctx, userID, preparationID)
}
func (s *DistributionService) lookupReceipt(ctx context.Context, userID, preparationID string) (InstallResult, bool, error) {
s.installMu.Lock()
defer s.installMu.Unlock()
return s.lookupReceiptLocked(ctx, userID, preparationID)
}
func (s *DistributionService) lookupReceiptLocked(ctx context.Context, userID, preparationID string) (InstallResult, bool, error) {
receipt, ok := s.receipts[preparationID]
if !ok && s.receiptStore != nil {
stored, err := s.receiptStore.GetInstallReceipt(ctx, preparationID, userID)
if err == nil {
receipt, ok = stored, true
s.receipts[preparationID] = stored
} else if !errors.Is(err, ErrInstallReceiptNotFound) {
return InstallResult{}, false, err
}
}
if !ok || receipt.UserID != userID {
return InstallResult{}, false, nil
}
item, err := s.canvases.Get(ctx, receipt.CanvasID)
if errors.Is(err, ErrCanvasNotFound) || item == nil || item.WorkspaceID != receipt.WorkspaceID {
return InstallResult{}, false, nil
}
if err != nil {
return InstallResult{}, false, err
}
return InstallResult{Canvas: item, Receipt: receipt}, true, nil
}
func putInstallArtifact(writer ArtifactWriter, pkg *webapp.Package) (webapp.Artifact, bool, error) {
if withCreated, ok := writer.(artifactWriterWithCreated); ok {
return withCreated.PutWithCreated(pkg)
}
artifact, err := writer.Put(pkg)
return artifact, false, err
}
func installMetadata(m *manifest.Manifest) InstallMetadata {
if m == nil || m.Distribution == nil {
return InstallMetadata{}
}
return InstallMetadata{PackageID: m.ID, Version: m.Version, DisplayName: m.DisplayName, Description: m.Description, Author: m.Author, License: m.Distribution.License, SourceMode: m.Distribution.SourceMode, MinKandevVersion: m.MinKandevVersion, RepoURL: m.RepoURL}
}
func sanitizeRepositoryURL(value string) string {
value = strings.TrimSpace(value)
if value == "" {
return ""
}
// Provenance is public metadata only. Queries and fragments can contain
// signed-download credentials, so they are never persisted.
if index := strings.IndexAny(value, "?#"); index >= 0 {
value = value[:index]
}
return value
}
func installReview(preparation Preparation, pkg *webapp.Package) InstallReview {
metadata := installMetadata(pkg.Manifest)
return InstallReview{
PreparationID: preparation.ID, WorkspaceID: preparation.WorkspaceID,
Metadata: metadata, Digest: pkg.Digest, ArchiveDigest: preparation.PackageArchiveDigest,
PermissionSummary: ManifestPermissions(pkg.Manifest), OriginKind: preparation.OriginKind,
SourceID: preparation.SourceID, RepositoryURL: sanitizeRepositoryURL(preparation.RepositoryURL),
ExpiresAt: preparation.ExpiresAt.UTC().Format("2006-01-02T15:04:05.000Z07:00"),
}
}
@@ -0,0 +1,347 @@
package canvas
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/google/uuid"
)
const (
PreparationTTL = 15 * time.Minute
MaxPreparationsPerUser = 2
MaxStagedBytes = int64(256 << 20)
)
var (
ErrPreparationNotFound = errors.New("canvas preparation not found")
ErrPreparationExpired = errors.New("canvas preparation expired")
ErrPreparationLimit = errors.New("canvas preparation limit reached")
ErrPreparationInvalid = errors.New("invalid canvas preparation")
)
type ExportKind string
const (
ExportBundle ExportKind = "bundle"
ExportSource ExportKind = "source"
)
// Preparation is temporary, user-bound distribution state. Bundle and Source
// are accepted only by Create and are not kept in the store's metadata map.
type Preparation struct {
ID string
UserID string
WorkspaceID string
CanvasID string
ReleaseID string
PackageID string
PackageVersion string
PackageDigest string
PackageArchiveDigest string
Metadata ExportMetadata
SourceID string
OriginKind string
RepositoryURL string
Bundle []byte
Source []byte
Files []ExportFile
CreatedAt time.Time
ExpiresAt time.Time
}
type ExportFile struct {
Path string `json:"path"`
Bytes int64 `json:"bytes"`
}
type preparationRecord struct {
Preparation
BundleBytes int64
SourceBytes int64
leases int
}
// PreparationStore stages files below a dedicated recovery boundary and keeps
// only bounded metadata in memory. It is intentionally process-local: startup
// cleanup invalidates every uncommitted preparation.
type PreparationStore struct {
mu sync.Mutex
root string
clock func() time.Time
items map[string]*preparationRecord
}
func NewPreparationStore(root string) (*PreparationStore, error) {
if strings.TrimSpace(root) == "" {
return nil, ErrPreparationInvalid
}
if err := os.MkdirAll(root, 0o700); err != nil {
return nil, fmt.Errorf("canvas preparations: create root: %w", err)
}
entries, err := os.ReadDir(root)
if err != nil {
return nil, fmt.Errorf("canvas preparations: inspect root: %w", err)
}
for _, entry := range entries {
if err := os.RemoveAll(filepath.Join(root, entry.Name())); err != nil {
return nil, fmt.Errorf("canvas preparations: clear stale staging: %w", err)
}
}
return &PreparationStore{root: root, clock: time.Now, items: make(map[string]*preparationRecord)}, nil
}
func (s *PreparationStore) SetClock(clock func() time.Time) {
if s == nil || clock == nil {
return
}
s.mu.Lock()
s.clock = clock
s.mu.Unlock()
}
func (s *PreparationStore) Create(ctx context.Context, input Preparation) (Preparation, error) {
if err := validatePreparationCreate(ctx, s, input); err != nil {
return Preparation{}, err
}
input, err := preparePreparationIdentity(input)
if err != nil {
return Preparation{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
now := s.nowLocked()
if err := s.removeExpiredLocked(now); err != nil {
return Preparation{}, fmt.Errorf("canvas preparations: remove expired: %w", err)
}
if err := s.validateCreateAdmissionLocked(input); err != nil {
return Preparation{}, err
}
input, err = setPreparationTimes(input, now)
if err != nil {
return Preparation{}, err
}
if err := s.stagePreparation(input); err != nil {
return Preparation{}, err
}
record := &preparationRecord{Preparation: input, BundleBytes: int64(len(input.Bundle)), SourceBytes: int64(len(input.Source))}
record.Bundle = nil
record.Source = nil
s.items[input.ID] = record
return input, nil
}
func validatePreparationCreate(ctx context.Context, store *PreparationStore, input Preparation) error {
if err := ctx.Err(); err != nil {
return err
}
if store == nil || strings.TrimSpace(input.UserID) == "" || strings.TrimSpace(input.WorkspaceID) == "" {
return ErrPreparationInvalid
}
if len(input.Bundle) == 0 && len(input.Source) == 0 {
return ErrPreparationInvalid
}
return nil
}
func preparePreparationIdentity(input Preparation) (Preparation, error) {
if strings.TrimSpace(input.ID) == "" {
input.ID = uuid.NewString()
}
if !safePreparationID(input.ID) {
return Preparation{}, ErrPreparationInvalid
}
return input, nil
}
func (s *PreparationStore) validateCreateAdmissionLocked(input Preparation) error {
if _, exists := s.items[input.ID]; exists {
return ErrPreparationInvalid
}
if s.userCountLocked(input.UserID) >= MaxPreparationsPerUser || s.stagedBytesLocked()+int64(len(input.Bundle))+int64(len(input.Source)) > MaxStagedBytes {
return ErrPreparationLimit
}
return nil
}
func setPreparationTimes(input Preparation, now time.Time) (Preparation, error) {
if input.CreatedAt.IsZero() {
input.CreatedAt = now
}
if input.ExpiresAt.IsZero() {
input.ExpiresAt = now.Add(PreparationTTL)
}
if !input.ExpiresAt.After(now) {
return Preparation{}, ErrPreparationExpired
}
return input, nil
}
func (s *PreparationStore) stagePreparation(input Preparation) error {
directory := filepath.Join(s.root, input.ID)
if err := os.MkdirAll(directory, 0o700); err != nil {
return fmt.Errorf("canvas preparations: create staging directory: %w", err)
}
if err := writePreparationFile(directory, "bundle", input.Bundle); err != nil {
_ = os.RemoveAll(directory)
return err
}
if err := writePreparationFile(directory, "source", input.Source); err != nil {
_ = os.RemoveAll(directory)
return err
}
return nil
}
func writePreparationFile(directory, name string, data []byte) error {
if len(data) == 0 {
return nil
}
path := filepath.Join(directory, name)
if err := os.WriteFile(path, data, 0o600); err != nil {
return fmt.Errorf("canvas preparations: stage %s: %w", name, err)
}
return nil
}
func (s *PreparationStore) Get(ctx context.Context, userID, id string) (Preparation, error) {
if err := ctx.Err(); err != nil {
return Preparation{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
record, err := s.lookupLocked(userID, id)
if err != nil {
return Preparation{}, err
}
return record.Preparation, nil
}
func (s *PreparationStore) Open(ctx context.Context, userID, id string, kind ExportKind) ([]byte, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
record, err := s.lookupLocked(userID, id)
if err != nil {
s.mu.Unlock()
return nil, err
}
record.leases++
root := s.root
s.mu.Unlock()
defer s.releaseLease(id)
name := string(kind)
if kind != ExportBundle && kind != ExportSource {
return nil, ErrPreparationInvalid
}
data, err := os.ReadFile(filepath.Join(root, id, name))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, ErrPreparationNotFound
}
return nil, err
}
return data, nil
}
func (s *PreparationStore) Delete(ctx context.Context, userID, id string) error {
if err := ctx.Err(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
record, exists := s.items[id]
if !exists || record.UserID != userID {
return nil
}
if record.leases > 0 {
return nil
}
delete(s.items, id)
return os.RemoveAll(filepath.Join(s.root, id))
}
func (s *PreparationStore) Cleanup(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
return s.removeExpiredLocked(s.nowLocked())
}
func (s *PreparationStore) releaseLease(id string) {
s.mu.Lock()
defer s.mu.Unlock()
if record, exists := s.items[id]; exists && record.leases > 0 {
record.leases--
}
}
func (s *PreparationStore) lookupLocked(userID, id string) (*preparationRecord, error) {
if !safePreparationID(id) {
return nil, ErrPreparationNotFound
}
record, exists := s.items[id]
if !exists || record.UserID != userID {
return nil, ErrPreparationNotFound
}
if !record.ExpiresAt.After(s.nowLocked()) {
if record.leases == 0 {
delete(s.items, id)
_ = os.RemoveAll(filepath.Join(s.root, id))
}
return nil, ErrPreparationExpired
}
return record, nil
}
func (s *PreparationStore) removeExpiredLocked(now time.Time) error {
var firstErr error
for id, record := range s.items {
if record.leases > 0 || record.ExpiresAt.After(now) {
continue
}
delete(s.items, id)
if err := os.RemoveAll(filepath.Join(s.root, id)); err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
func (s *PreparationStore) userCountLocked(userID string) int {
count := 0
for _, record := range s.items {
if record.UserID == userID {
count++
}
}
return count
}
func (s *PreparationStore) stagedBytesLocked() int64 {
var total int64
for _, record := range s.items {
total += record.BundleBytes + record.SourceBytes
}
return total
}
func (s *PreparationStore) nowLocked() time.Time {
if s.clock == nil {
return time.Now().UTC()
}
return s.clock().UTC()
}
func safePreparationID(id string) bool {
return id != "" && filepath.Base(id) == id && !strings.ContainsAny(id, "/\\\x00")
}
@@ -0,0 +1,59 @@
package canvas
import (
"context"
"errors"
"testing"
"time"
)
func TestPreparationStoreExpiresAndReleasesStagedFiles(t *testing.T) {
store, err := NewPreparationStore(t.TempDir())
if err != nil {
t.Fatalf("NewPreparationStore() error = %v", err)
}
now := time.Date(2026, 9, 10, 12, 0, 0, 0, time.UTC)
store.SetClock(func() time.Time { return now })
created, err := store.Create(context.Background(), Preparation{
ID: "prep-1", UserID: "user-1", WorkspaceID: "workspace-1", CanvasID: "canvas-1",
ReleaseID: "release-1", PackageDigest: "digest-1", Bundle: []byte("bundle"), Source: []byte("source"),
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if created.ExpiresAt.Sub(now) != PreparationTTL {
t.Fatalf("expires in %s, want %s", created.ExpiresAt.Sub(now), PreparationTTL)
}
if got, err := store.Open(context.Background(), "user-1", "prep-1", ExportBundle); err != nil || string(got) != "bundle" {
t.Fatalf("Open(bundle) = %q, %v", got, err)
}
now = now.Add(PreparationTTL + time.Second)
if _, err := store.Get(context.Background(), "user-1", "prep-1"); !errors.Is(err, ErrPreparationExpired) {
t.Fatalf("Get(expired) error = %v, want ErrPreparationExpired", err)
}
if err := store.Cleanup(context.Background()); err != nil {
t.Fatalf("Cleanup() error = %v", err)
}
if _, err := store.Get(context.Background(), "user-1", "prep-1"); !errors.Is(err, ErrPreparationNotFound) {
t.Fatalf("Get(cleaned) error = %v, want ErrPreparationNotFound", err)
}
}
func TestPreparationStoreLimitsPerUserAndStagedBytes(t *testing.T) {
store, err := NewPreparationStore(t.TempDir())
if err != nil {
t.Fatalf("NewPreparationStore() error = %v", err)
}
for i := 0; i < MaxPreparationsPerUser; i++ {
_, err := store.Create(context.Background(), Preparation{
ID: string(rune('a' + i)), UserID: "user-1", WorkspaceID: "workspace-1",
Bundle: []byte("bundle"), Source: []byte("source"),
})
if err != nil {
t.Fatalf("Create(%d) error = %v", i, err)
}
}
if _, err := store.Create(context.Background(), Preparation{ID: "overflow", UserID: "user-1", WorkspaceID: "workspace-1", Bundle: []byte("bundle")}); !errors.Is(err, ErrPreparationLimit) {
t.Fatalf("Create(per-user overflow) error = %v, want ErrPreparationLimit", err)
}
}
@@ -1,15 +1,27 @@
package canvas
import (
"encoding/json"
"sort"
plugininstances "github.com/kandev/kandev/internal/plugins/instances"
"github.com/kandev/kandev/internal/plugins/manifest"
)
func releaseMetadata(release plugininstances.Release, scope string, grants []plugininstances.Grant) *ReleaseMetadata {
permissions := ReleasePermissionSummary(release)
seed := releaseManifestSeed(release.ManifestJSON)
return &ReleaseMetadata{
ID: release.ID,
PackageID: seed.PackageID,
Version: seed.Version,
DisplayName: seed.DisplayName,
Description: seed.Description,
Author: seed.Author,
License: seed.License,
SourceMode: seed.SourceMode,
MinKandevVersion: seed.MinKandevVersion,
RepoURL: seed.RepoURL,
PackageDigest: release.PackageDigest,
ValidationStatus: release.ValidationStatus,
ValidationError: release.ValidationError,
@@ -25,6 +37,39 @@ func releaseMetadata(release plugininstances.Release, scope string, grants []plu
}
}
type manifestSeed struct {
PackageID string
Version string
DisplayName string
Description string
Author string
License string
SourceMode string
MinKandevVersion string
RepoURL string
}
func releaseManifestSeed(data json.RawMessage) manifestSeed {
var value manifest.Manifest
if err := json.Unmarshal(data, &value); err != nil {
return manifestSeed{}
}
seed := manifestSeed{
PackageID: value.ID,
Version: value.Version,
DisplayName: value.DisplayName,
Description: value.Description,
Author: value.Author,
MinKandevVersion: value.MinKandevVersion,
RepoURL: value.RepoURL,
}
if value.Distribution != nil {
seed.License = value.Distribution.License
seed.SourceMode = value.Distribution.SourceMode
}
return seed
}
func effectiveGrantProjection(instance plugininstances.Instance, summary PermissionSummary, grants []plugininstances.Grant) []GrantProjection {
if instance.ActiveReleaseID == "" {
return nil
@@ -0,0 +1,25 @@
package canvas
import (
"encoding/json"
"testing"
"time"
plugininstances "github.com/kandev/kandev/internal/plugins/instances"
"github.com/kandev/kandev/internal/plugins/manifest"
)
func TestReleaseMetadataIncludesPortableManifestSeed(t *testing.T) {
manifestJSON, err := json.Marshal(manifest.Manifest{
ID: "canvas-one", Version: "1.0.0", DisplayName: "Canvas One", Description: "A canvas",
Author: "Author", MinKandevVersion: "0.94.0", RepoURL: "https://example.test/canvas",
Distribution: &manifest.Distribution{License: "MIT", SourceMode: manifest.SourceModeStatic},
})
if err != nil {
t.Fatalf("marshal manifest: %v", err)
}
seed := releaseMetadata(plugininstances.Release{ID: "release-1", ManifestJSON: manifestJSON, CreatedAt: time.Now()}, ScopeWorkspace, nil)
if seed.PackageID != "canvas-one" || seed.Version != "1.0.0" || seed.Author != "Author" || seed.License != "MIT" || seed.SourceMode != manifest.SourceModeStatic {
t.Fatalf("release metadata seed = %+v", seed)
}
}
@@ -57,8 +57,100 @@ CREATE TABLE IF NOT EXISTS canvas_lifecycle_admission (
);
INSERT INTO canvas_lifecycle_admission (id, version)
VALUES (1, 1) ON CONFLICT (id) DO NOTHING;
CREATE TABLE IF NOT EXISTS canvas_install_receipts (
preparation_id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
canvas_id TEXT NOT NULL UNIQUE,
workspace_id TEXT NOT NULL,
package_id TEXT NOT NULL,
package_version TEXT NOT NULL,
package_digest TEXT NOT NULL,
source_id TEXT NOT NULL DEFAULT '',
repository_url TEXT NOT NULL DEFAULT '',
origin_kind TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_canvas_install_receipts_workspace
ON canvas_install_receipts(workspace_id, created_at, preparation_id);
`
func (r *Repository) GetInstallReceipt(ctx context.Context, preparationID, userID string) (InstallReceipt, error) {
if strings.TrimSpace(preparationID) == "" || strings.TrimSpace(userID) == "" {
return InstallReceipt{}, ErrInstallReceiptNotFound
}
var row struct {
PreparationID string `db:"preparation_id"`
UserID string `db:"user_id"`
CanvasID string `db:"canvas_id"`
WorkspaceID string `db:"workspace_id"`
PackageID string `db:"package_id"`
PackageVersion string `db:"package_version"`
PackageDigest string `db:"package_digest"`
SourceID string `db:"source_id"`
RepositoryURL string `db:"repository_url"`
OriginKind string `db:"origin_kind"`
CreatedAt string `db:"created_at"`
}
err := r.ro.GetContext(ctx, &row, r.ro.Rebind(`SELECT preparation_id, user_id, canvas_id, workspace_id, package_id, package_version, package_digest, source_id, repository_url, origin_kind, created_at FROM canvas_install_receipts WHERE preparation_id = ? AND user_id = ?`), preparationID, userID)
if errors.Is(err, sql.ErrNoRows) {
return InstallReceipt{}, ErrInstallReceiptNotFound
}
if err != nil {
return InstallReceipt{}, err
}
createdAt, err := time.Parse(time.RFC3339Nano, row.CreatedAt)
if err != nil {
return InstallReceipt{}, err
}
return InstallReceipt{PreparationID: row.PreparationID, UserID: row.UserID, CanvasID: row.CanvasID, WorkspaceID: row.WorkspaceID, PackageID: row.PackageID, Version: row.PackageVersion, Digest: row.PackageDigest, SourceID: row.SourceID, RepositoryURL: row.RepositoryURL, OriginKind: row.OriginKind, CreatedAt: createdAt}, nil
}
func (r *Repository) CreateInstallReceiptTx(ctx context.Context, tx *sqlx.Tx, receipt InstallReceipt) error {
if strings.TrimSpace(receipt.PreparationID) == "" || strings.TrimSpace(receipt.UserID) == "" || strings.TrimSpace(receipt.CanvasID) == "" || strings.TrimSpace(receipt.WorkspaceID) == "" || strings.TrimSpace(receipt.PackageID) == "" || strings.TrimSpace(receipt.Version) == "" || strings.TrimSpace(receipt.Digest) == "" || strings.TrimSpace(receipt.OriginKind) == "" {
return ErrInstallInvalid
}
createdAt := receipt.CreatedAt.UTC()
if createdAt.IsZero() {
createdAt = time.Now().UTC()
}
_, err := tx.ExecContext(ctx, tx.Rebind(`INSERT INTO canvas_install_receipts (preparation_id, user_id, canvas_id, workspace_id, package_id, package_version, package_digest, source_id, repository_url, origin_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), receipt.PreparationID, receipt.UserID, receipt.CanvasID, receipt.WorkspaceID, receipt.PackageID, receipt.Version, receipt.Digest, receipt.SourceID, receipt.RepositoryURL, receipt.OriginKind, createdAt.Format(time.RFC3339Nano))
return err
}
func (r *Repository) CreateInstallReceipt(ctx context.Context, receipt InstallReceipt) error {
tx, err := r.db.BeginTxx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if err := r.CreateInstallReceiptTx(ctx, tx, receipt); err != nil {
return err
}
return tx.Commit()
}
func (r *Repository) DeleteInstallReceiptTx(ctx context.Context, tx *sqlx.Tx, canvasID string) error {
if strings.TrimSpace(canvasID) == "" {
return ErrInvalidCanvas
}
_, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM canvas_install_receipts WHERE canvas_id = ?`), canvasID)
return err
}
// DeleteInstallReceipt removes the durable retry receipt for a canvas after
// the canvas authority and plugin instance have been removed.
func (r *Repository) DeleteInstallReceipt(ctx context.Context, canvasID string) error {
tx, err := r.db.BeginTxx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if err := r.DeleteInstallReceiptTx(ctx, tx, canvasID); err != nil {
return err
}
return tx.Commit()
}
// NewRepository constructs the canvas metadata repository on an existing
// application database pool. Plugin instance schema initialization remains
// owned by internal/plugins/instances.
+12
View File
@@ -379,6 +379,9 @@ func (s *Service) removeLocked(ctx context.Context, id string) (LifecycleEvent,
func (s *Service) removeAuthority(ctx context.Context, metadata CanvasMetadata, instance plugininstances.Instance) error {
if instance.Status == StatusRemoved {
if err := s.repo.DeleteInstallReceipt(ctx, metadata.ID); err != nil {
return err
}
err := s.repo.Delete(ctx, metadata.ID)
if errors.Is(err, ErrCanvasNotFound) {
return nil
@@ -391,12 +394,18 @@ func (s *Service) removeAuthority(ctx context.Context, metadata CanvasMetadata,
if err := transactional.RemoveInstanceTx(ctx, tx, instance.ID); err != nil {
return err
}
if err := s.repo.DeleteInstallReceiptTx(ctx, tx, metadata.ID); err != nil {
return err
}
return s.repo.DeleteTx(ctx, tx, metadata.ID)
})
}
if err := s.instances.RemoveInstance(ctx, instance.ID); err != nil {
return err
}
if err := s.repo.DeleteInstallReceipt(ctx, metadata.ID); err != nil {
return err
}
return s.repo.Delete(ctx, metadata.ID)
}
@@ -578,6 +587,9 @@ func (s *Service) removeMetadataLocked(ctx context.Context, metadata CanvasMetad
return LifecycleEvent{}, err
}
}
if err := s.repo.DeleteInstallReceipt(ctx, metadata.ID); err != nil {
return LifecycleEvent{}, err
}
if err := s.repo.Delete(ctx, metadata.ID); err != nil && !errors.Is(err, ErrCanvasNotFound) {
return LifecycleEvent{}, err
}
+10 -1
View File
@@ -126,10 +126,19 @@ type Canvas struct {
}
// ReleaseMetadata deliberately omits manifest and artifact contents. The host
// receives only the review-safe declaration, provenance, and current grant
// receives only the review-safe package identity, provenance, and current grant
// diff needed to choose recovery actions.
type ReleaseMetadata struct {
ID string `json:"id"`
PackageID string `json:"package_id,omitempty"`
Version string `json:"version,omitempty"`
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
License string `json:"license,omitempty"`
SourceMode string `json:"source_mode,omitempty"`
MinKandevVersion string `json:"min_kandev_version,omitempty"`
RepoURL string `json:"repo_url,omitempty"`
PackageDigest string `json:"package_digest"`
ValidationStatus string `json:"validation_status"`
ValidationError string `json:"validation_error,omitempty"`
@@ -99,3 +99,25 @@ Read a supporting reference only when its topic is needed:
- `references/events-and-recovery.md` for events, reconnect, and retries.
- `references/security.md` for opaque-origin and source safety rules.
- `references/ui-patterns.md` for responsive and accessible UI patterns.
## Distribution checklist
When the user asks for a portable canvas, keep the distribution boundary
separate from authoring and runtime state:
1. Add `distribution.schema_version: 1`, `distribution.kind: canvas`, a
license, and `source_mode: static` or `source_mode: project`.
2. Keep `README.md`, the manifest, the application entry, and every local asset
in the package. Use project mode only when the retained project is complete
and bounded below `distribution/source/`.
3. Publish a valid release before offering a bundle or source download. The
host prepares both archives from that immutable release and does not include
screenshots.
4. Add screenshots later as ordered `previews` objects in a registry entry.
The first preview is the cover, canvas entries require one to eight images,
and plugin entries may omit images.
The authoring tools do not create repositories, releases, registry entries, or
pull requests. Report those manual follow-up steps to the user. Do not claim
that a local archive or build is published until the Kandev release flow
confirms it.
@@ -15,6 +15,7 @@ version: 1.0.0
display_name: Example canvas
description: A small task canvas.
author: Canvas author
min_kandev_version: "0.94.0"
ui:
web_apps:
- key: main
@@ -35,6 +36,12 @@ capabilities:
events:
- task.updated
state: true
distribution:
schema_version: 1
kind: canvas
license: MIT
source_mode: static
```
The host parses YAML and calls the same manifest validator used for plugin
@@ -74,3 +81,21 @@ authored scripts. It checks document startup and relative context access. Keep
the entry valid HTML so the host can insert the bootstrap without changing the
stored package. The host waits up to 15 seconds for the startup acknowledgement
and exposes retry controls outside the frame when startup fails.
## Portable distribution
Use the `distribution` block when the canvas is intended for bundle, source, or
registry sharing. `kind` must be `canvas`, `schema_version` must be `1`, and
`source_mode` must be `static` or `project`. Include a non-empty license value
and a compatible `min_kandev_version` in the manifest.
The package must include `README.md` and generated `checksums.txt`. A project
source mode package retains the editable project in
`distribution/source/manifest.yaml` and `distribution/source/README.md`.
Static source mode does not include that subtree. Keep source files bounded and
free of secrets. The host rejects native plugin contributions, backend
executables, unsafe paths, and unsupported files in a portable canvas.
Registry screenshots are not package inputs. Add ordered preview objects to the
registry entry later. The first preview is the cover, canvas entries require
one to eight previews, and plugin entries may omit previews.
@@ -70,7 +70,7 @@ var catalog = []Descriptor{
{ID: "plugin-state", OwnerPackage: "internal/plugins/state", RequiredTables: []string{"plugin_state"}, DependsOn: []string{"schema-meta"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict}},
{ID: "plugin-instance-state", OwnerPackage: "internal/plugins/state", RequiredTables: []string{"plugin_instance_state"}, DependsOn: []string{"plugin-instances"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict}},
{ID: "plugin-user-state", OwnerPackage: "internal/plugins/state", RequiredTables: []string{"plugin_user_state"}, DependsOn: []string{"user"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict}},
{ID: "canvas", OwnerPackage: "internal/canvas", RequiredTables: []string{"canvas_lifecycle_metadata", "canvas_creation_authority"}, DependsOn: []string{"plugin-instances"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict, CapabilityTransaction}},
{ID: "canvas", OwnerPackage: "internal/canvas", RequiredTables: []string{"canvas_lifecycle_metadata", "canvas_creation_authority", "canvas_install_receipts"}, DependsOn: []string{"plugin-instances"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict, CapabilityTransaction}},
{ID: "github", OwnerPackage: "internal/github", RequiredTables: []string{"github_pr_watches"}, DependsOn: []string{"task", "user"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict}},
{ID: "gitlab", OwnerPackage: "internal/gitlab", RequiredTables: []string{"gitlab_configs"}, DependsOn: []string{"task", "user"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict}},
{ID: "jira", OwnerPackage: "internal/jira", RequiredTables: []string{"jira_configs"}, DependsOn: []string{"task", "user"}, Capabilities: []Capability{CapabilityBoolean, CapabilityTimestamp, CapabilityConflict}},
@@ -1213,13 +1213,17 @@ func (s *Store) ApproveRelease(ctx context.Context, instanceID, releaseID, appro
if strings.TrimSpace(instanceID) == "" || strings.TrimSpace(releaseID) == "" || strings.TrimSpace(approvedBy) == "" {
return ErrInvalidRelease
}
s.admission.Lock()
defer s.admission.Unlock()
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return err
return s.WithTransaction(ctx, func(tx *sqlx.Tx) error {
return s.ApproveReleaseTx(ctx, tx, instanceID, releaseID, approvedBy, grants)
})
}
// ApproveReleaseTx applies explicit permission grants and activates a pending
// release inside a caller-owned lifecycle transaction.
func (s *Store) ApproveReleaseTx(ctx context.Context, tx *sqlx.Tx, instanceID, releaseID, approvedBy string, grants []Grant) error {
if strings.TrimSpace(instanceID) == "" || strings.TrimSpace(releaseID) == "" || strings.TrimSpace(approvedBy) == "" {
return ErrInvalidRelease
}
defer func() { _ = tx.Rollback() }()
release, err := loadPendingReleaseTx(ctx, tx, instanceID, releaseID)
if err != nil {
return err
@@ -1251,7 +1255,7 @@ func (s *Store) ApproveRelease(ctx context.Context, instanceID, releaseID, appro
if err := activateReleaseTx(ctx, tx, instanceID, releaseID); err != nil {
return err
}
return tx.Commit()
return nil
}
type pendingReleaseRow struct {
@@ -0,0 +1,94 @@
package manifest
import (
"errors"
"fmt"
"strings"
)
const (
DistributionSchemaVersion = 1
DistributionKindCanvas = "canvas"
SourceModeStatic = "static"
SourceModeProject = "project"
)
// Distribution is the package-owned declaration for a portable canvas. It
// intentionally contains no registry preview URLs or publisher metadata.
type Distribution struct {
SchemaVersion int `yaml:"schema_version" json:"schema_version"`
Kind string `yaml:"kind" json:"kind"`
License string `yaml:"license" json:"license"`
SourceMode string `yaml:"source_mode" json:"source_mode"`
}
// IsCanvasDistribution reports whether the manifest asserts the portable
// canvas profile. A nil declaration preserves legacy plugin behavior.
func (m *Manifest) IsCanvasDistribution() bool {
return m != nil && m.Distribution != nil && m.Distribution.Kind == DistributionKindCanvas
}
func (m *Manifest) validateDistribution() []error {
if m.Distribution == nil {
return nil
}
errs := validateDistributionDeclaration(m)
errs = append(errs, validateDistributionApplication(m)...)
errs = append(errs, validateDistributionContributions(m)...)
return errs
}
func validateDistributionDeclaration(m *Manifest) []error {
d := m.Distribution
var errs []error
if d.SchemaVersion != DistributionSchemaVersion {
errs = append(errs, fmt.Errorf("distribution.schema_version must be %d", DistributionSchemaVersion))
}
if d.Kind != DistributionKindCanvas {
errs = append(errs, fmt.Errorf("distribution.kind %q is unsupported", d.Kind))
}
if strings.TrimSpace(d.License) == "" {
errs = append(errs, errors.New("distribution.license must not be empty"))
}
if d.SourceMode != SourceModeStatic && d.SourceMode != SourceModeProject {
errs = append(errs, fmt.Errorf("distribution.source_mode %q is unsupported", d.SourceMode))
}
if _, ok := NormalizeReleaseVersion(m.MinKandevVersion); !ok {
errs = append(errs, errors.New("min_kandev_version is required for a distribution package"))
}
return errs
}
func validateDistributionApplication(m *Manifest) []error {
var errs []error
if !m.IsStaticWebAppOnly() {
errs = append(errs, errors.New("distribution canvas must be a static web application"))
}
if len(m.UI.WebApps) != 1 {
errs = append(errs, errors.New("distribution canvas must declare exactly one web app"))
} else if !distributionContainsString(m.UI.WebApps[0].Placements, WebAppPlacementWorkspace) {
errs = append(errs, errors.New("distribution canvas must support workspace-canvas placement"))
}
if m.UI.Bundle != "" || len(m.UI.Pages) > 0 || len(m.UI.Styles) > 0 || len(m.UI.Keybindings) > 0 {
errs = append(errs, errors.New("distribution canvas cannot declare native UI contributions"))
}
return errs
}
func validateDistributionContributions(m *Manifest) []error {
if len(m.Webhooks) == 0 && len(m.Actions) == 0 && len(m.RepositoryProviders) == 0 &&
len(m.ReferenceSources) == 0 && len(m.AuthProviders) == 0 && len(m.AgentTools) == 0 &&
len(m.ConfigSchema) == 0 && m.Runtime.Type == "" && len(m.Runtime.Executables) == 0 {
return nil
}
return []error{errors.New("distribution canvas cannot declare backend, tool, or other plugin contributions")}
}
func distributionContainsString(values []string, want string) bool {
for _, value := range values {
if value == want {
return true
}
}
return false
}
@@ -0,0 +1,62 @@
package manifest
import (
"strings"
"testing"
)
func TestValidateCanvasDistribution(t *testing.T) {
m := canvasDistributionManifest()
if err := m.Validate(); err != nil {
t.Fatalf("Validate() unexpected error: %v", err)
}
if !m.IsCanvasDistribution() {
t.Fatal("IsCanvasDistribution() = false, want true")
}
if m.Distribution.SourceMode != SourceModeProject {
t.Fatalf("source mode = %q, want %q", m.Distribution.SourceMode, SourceModeProject)
}
}
func TestValidateCanvasDistributionRejectsOtherContributions(t *testing.T) {
cases := []struct {
name string
mutate func(*Manifest)
want string
}{
{name: "missing license", mutate: func(m *Manifest) { m.Distribution.License = "" }, want: "distribution.license"},
{name: "missing compatibility", mutate: func(m *Manifest) { m.MinKandevVersion = "" }, want: "min_kandev_version"},
{name: "managed runtime", mutate: func(m *Manifest) { m.Runtime.Type = "binary" }, want: "runtime.type"},
{name: "native bundle", mutate: func(m *Manifest) { m.UI.Bundle = "/bundle.js" }, want: "native UI"},
{name: "action", mutate: func(m *Manifest) {
m.Actions = []Action{{Key: "run", ResourceScope: ActionScopeWorkspace, MaxBodyBytes: 1}}
}, want: "backend"},
{name: "task only", mutate: func(m *Manifest) { m.UI.WebApps[0].Placements = []string{WebAppPlacementTask} }, want: "workspace-canvas"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
m := canvasDistributionManifest()
tc.mutate(m)
err := m.Validate()
if err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("Validate() error = %v, want text %q", err, tc.want)
}
})
}
}
func canvasDistributionManifest() *Manifest {
return &Manifest{
ID: "canvas-board", APIVersion: CurrentAPIVersion, Version: "1.2.3",
DisplayName: "Canvas Board", Description: "A board", Author: "Kandev",
Categories: []string{"canvas"}, MinKandevVersion: "1.0.0",
Distribution: &Distribution{
SchemaVersion: DistributionSchemaVersion, Kind: DistributionKindCanvas,
License: "MIT", SourceMode: SourceModeProject,
},
UI: UISection{WebApps: []WebApp{{
Key: "main", Title: "Board", Entry: "ui/index.html",
Placements: []string{WebAppPlacementWorkspace},
}}},
}
}
@@ -76,6 +76,11 @@ type Manifest struct {
Runtime Runtime `yaml:"runtime,omitempty" json:"runtime,omitempty"`
MinKandevVersion string `yaml:"min_kandev_version,omitempty" json:"min_kandev_version,omitempty"`
// Distribution declares an optional portable package profile. Legacy
// plugins and locally-authored canvases may omit it; registry-ready canvas
// packages must provide the complete profile.
Distribution *Distribution `yaml:"distribution,omitempty" json:"distribution,omitempty"`
}
const (
@@ -1,10 +1,32 @@
package manifest
import (
"fmt"
"strconv"
"strings"
)
// CheckMinimumKandevVersion enforces a package minimum against a stamped
// release build. Development and git-describe builds deliberately skip the
// check because they do not provide a trustworthy release boundary.
func CheckMinimumKandevVersion(minVersion, runningVersion string) error {
if strings.TrimSpace(minVersion) == "" || strings.TrimSpace(runningVersion) == "" || strings.EqualFold(strings.TrimSpace(runningVersion), "dev") {
return nil
}
running, runningRelease := NormalizeReleaseVersion(runningVersion)
if !runningRelease {
return nil
}
minimum, minimumRelease := NormalizeReleaseVersion(minVersion)
if !minimumRelease {
return fmt.Errorf("plugins: min_kandev_version %q is not a release version", minVersion)
}
if CompareVersions(running, minimum) < 0 {
return fmt.Errorf("plugins: requires kandev >= %s, running %s", minVersion, runningVersion)
}
return nil
}
// NormalizeReleaseVersion returns a dotted numeric release version suitable
// for compatibility comparisons. Kandev release builds are tagged `vX.Y.Z`,
// while plugin manifests use `X.Y.Z`; development and git-describe strings
@@ -30,6 +30,7 @@ var validCategories = map[string]bool{
"automation": true,
"tools": true,
"analytics": true,
"canvas": true,
}
// validUISurfaces are the allowed values for UIPage.Surface.
@@ -144,6 +145,7 @@ func (m *Manifest) Validate() error {
errs = append(errs, m.validateRepositoryProviders()...)
errs = append(errs, m.validateReferenceSources()...)
errs = append(errs, m.validateAgentTools()...)
errs = append(errs, m.validateDistribution()...)
return errors.Join(errs...)
}
@@ -3,13 +3,16 @@ package marketplace
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
"golang.org/x/sync/singleflight"
@@ -17,6 +20,11 @@ import (
"github.com/kandev/kandev/internal/plugins/manifest"
)
var (
ErrCanvasListingNotFound = errors.New("canvas marketplace listing not found")
ErrCanvasListingStale = errors.New("canvas marketplace listing is stale")
)
// maxIndexBytes caps the index.json body read from any source, bounding
// worst-case memory from a hostile or misconfigured source.
const maxIndexBytes = 5 << 20 // 5 MiB
@@ -26,6 +34,11 @@ const maxIndexBytes = 5 << 20 // 5 MiB
// the cache immediately.
const defaultCacheTTL = 5 * time.Minute
const (
marketplaceKindPlugin = "plugin"
marketplaceKindCanvas = "canvas"
)
// Service fetches, caches, and merges catalog documents across the configured
// marketplace sources.
type Service struct {
@@ -114,7 +127,7 @@ func (s *Service) Catalog(ctx context.Context, installed []InstalledPlugin) (*Ca
// Merge sequentially in source order so first-source-wins dedup is stable,
// even though the fetches above ran concurrently.
installedByID := indexInstalled(installed)
result := &CatalogResult{Plugins: []CatalogEntry{}, Sources: []SourceStatus{}}
result := &CatalogResult{Plugins: []CatalogEntry{}, Canvases: []CatalogEntry{}, Sources: []SourceStatus{}}
seen := map[string]bool{}
for i, src := range sources {
status := statusFor(src)
@@ -128,12 +141,53 @@ func (s *Service) Catalog(ctx context.Context, installed []InstalledPlugin) (*Ca
result.Sources = append(result.Sources, status)
continue
}
result.Plugins = append(result.Plugins, mergeEntries(fetched[i].doc, src, installedByID, seen)...)
if fetched[i].doc.warning != "" {
status.Healthy = false
status.Error = fetched[i].doc.warning
}
for _, entry := range mergeEntries(fetched[i].doc, src, installedByID, seen) {
if entry.Kind == marketplaceKindCanvas {
result.Canvases = append(result.Canvases, entry)
continue
}
result.Plugins = append(result.Plugins, entry)
}
result.Sources = append(result.Sources, status)
}
return result, nil
}
// ResolveCanvasPackage resolves an exact canvas listing from the configured
// source. The caller supplies only the source and expected identity/digest;
// the package URL and repository URL come from the freshly validated source
// document.
func (s *Service) ResolveCanvasPackage(ctx context.Context, sourceID, packageID, version, digest string) (string, string, error) {
source, err := s.store.Get(strings.TrimSpace(sourceID))
if err != nil {
return "", "", ErrCanvasListingNotFound
}
if !source.Enabled {
return "", "", ErrCanvasListingNotFound
}
doc, err := s.fetch(ctx, source.URL)
if err != nil {
return "", "", ErrCanvasListingNotFound
}
for _, entry := range doc.Plugins {
if entry.Kind != marketplaceKindCanvas || entry.ID != packageID {
continue
}
if entry.Version != version || !strings.EqualFold(entry.PackageSHA256, digest) {
return "", "", ErrCanvasListingStale
}
if entry.PackageURL == "" {
return "", "", ErrCanvasListingNotFound
}
return entry.PackageURL, entry.RepoURL, nil
}
return "", "", ErrCanvasListingNotFound
}
type fetchOutcome struct {
doc *IndexDocument
err error
@@ -195,6 +249,9 @@ func indexInstalled(installed []InstalledPlugin) map[string]string {
// annotate derives a catalog entry's install state from what is installed.
func annotate(e IndexEntry, src SourceRecord, installed map[string]string) CatalogEntry {
if e.Kind == "" {
e.Kind = marketplaceKindPlugin
}
ce := CatalogEntry{IndexEntry: e, SourceID: src.ID, SourceName: src.Name, InstallState: StateAvailable}
if v, ok := installed[e.ID]; ok {
ce.InstalledVersion = v
@@ -273,9 +330,92 @@ func (s *Service) download(ctx context.Context, url string) (*IndexDocument, err
if err := json.Unmarshal(body, &doc); err != nil {
return nil, fmt.Errorf("parse index: %w", err)
}
if err := validateIndexDocument(&doc); err != nil {
return nil, err
}
return &doc, nil
}
func validateIndexDocument(doc *IndexDocument) error {
if doc.SchemaVersion != 1 {
return fmt.Errorf("unsupported index schema version %d", doc.SchemaVersion)
}
if doc.Plugins == nil {
return fmt.Errorf("index plugins list is missing")
}
seen := make(map[string]struct{}, len(doc.Plugins))
valid := make([]IndexEntry, 0, len(doc.Plugins))
var warnings []string
for _, entry := range doc.Plugins {
kind := strings.TrimSpace(entry.Kind)
if kind == "" {
kind = marketplaceKindPlugin
}
if entry.ID == "" {
warnings = append(warnings, "an entry has no id")
continue
}
if _, exists := seen[entry.ID]; exists {
warnings = append(warnings, "duplicate entry "+entry.ID)
continue
}
seen[entry.ID] = struct{}{}
if kind != marketplaceKindPlugin && kind != marketplaceKindCanvas {
warnings = append(warnings, "entry "+entry.ID+" has an unsupported kind")
continue
}
if err := validatePreviews(entry.Previews, kind == marketplaceKindCanvas); err != nil {
warnings = append(warnings, "entry "+entry.ID+": "+err.Error())
continue
}
if kind == marketplaceKindCanvas && !validSHA256(entry.PackageSHA256) {
warnings = append(warnings, "entry "+entry.ID+": canvas package digest is missing or invalid")
continue
}
entry.Kind = kind
valid = append(valid, entry)
}
doc.Plugins = valid
if len(warnings) > 0 {
doc.warning = strings.Join(warnings, "; ")
}
return nil
}
func validatePreviews(previews []Preview, required bool) error {
if required && len(previews) == 0 {
return fmt.Errorf("canvas listings require at least one preview")
}
if len(previews) > 8 {
return fmt.Errorf("preview limit exceeded")
}
for _, preview := range previews {
if utf8.RuneCountInString(strings.TrimSpace(preview.Alt)) < 1 || utf8.RuneCountInString(strings.TrimSpace(preview.Alt)) > 300 {
return fmt.Errorf("preview alt text is invalid")
}
if len(preview.URL) > 2048 {
return fmt.Errorf("preview URL is too long")
}
parsed, err := url.Parse(preview.URL)
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" || parsed.User != nil || parsed.Fragment != "" || parsed.Opaque != "" {
return fmt.Errorf("preview URL must be an HTTPS URL without credentials or fragments")
}
}
return nil
}
func validSHA256(value string) bool {
if len(value) != 64 {
return false
}
for _, char := range value {
if (char < '0' || char > '9') && (char < 'a' || char > 'f') && (char < 'A' || char > 'F') {
return false
}
}
return true
}
// ApplyQuery filters and sorts a merged catalog per the request. Filtering:
// Text matches id/name/description (case-insensitive substring); Category
// matches any of an entry's categories. Sort: "name" (asc), "recent"
@@ -284,8 +424,13 @@ func ApplyQuery(entries []CatalogEntry, q Query) []CatalogEntry {
out := make([]CatalogEntry, 0, len(entries))
text := strings.ToLower(strings.TrimSpace(q.Text))
category := strings.ToLower(strings.TrimSpace(q.Category))
kind := strings.ToLower(strings.TrimSpace(q.Kind))
for _, e := range entries {
if matchesText(e, text) && matchesCategory(e, category) {
entryKind := strings.ToLower(strings.TrimSpace(e.Kind))
if entryKind == "" {
entryKind = marketplaceKindPlugin
}
if (kind == "" || entryKind == kind) && matchesText(e, text) && matchesCategory(e, category) {
out = append(out, e)
}
}
@@ -119,6 +119,40 @@ func TestCatalogInstallStateAnnotation(t *testing.T) {
assertState(t, result.Plugins, "fresh", StateAvailable)
}
func TestCatalogSeparatesCanvasEntriesAndPreservesPreviews(t *testing.T) {
canvas := `{"id":"board","kind":"canvas","name":"Board","version":"1.0.0","package_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","package_url":"https://ex/board.tar.gz","previews":[{"url":"https://cdn.example/cover.webp","alt":"Board cover"}]}`
s := newTestService(t)
_ = s.store.EnsureBuiltin("Official", serve(t, indexJSON(canvas)).URL)
result, err := s.Catalog(context.Background(), nil)
if err != nil {
t.Fatalf("catalog: %v", err)
}
if len(result.Plugins) != 0 || len(result.Canvases) != 1 {
t.Fatalf("catalog kind split = plugins=%d canvases=%d", len(result.Plugins), len(result.Canvases))
}
if got := result.Canvases[0].Previews[0].URL; got != "https://cdn.example/cover.webp" {
t.Fatalf("preview URL = %q", got)
}
}
func TestCatalogOmitsInvalidCanvasListingButKeepsValidEntries(t *testing.T) {
valid := `{"id":"valid","kind":"canvas","name":"Valid","version":"1.0.0","package_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","package_url":"https://ex/valid.tar.gz","previews":[{"url":"https://cdn.example/cover.webp","alt":"Valid cover"}]}`
invalid := `{"id":"invalid","kind":"canvas","name":"Invalid","version":"1.0.0","package_url":"https://ex/invalid.tar.gz"}`
s := newTestService(t)
_ = s.store.EnsureBuiltin("Official", serve(t, indexJSON(valid+","+invalid)).URL)
result, err := s.Catalog(context.Background(), nil)
if err != nil {
t.Fatalf("catalog: %v", err)
}
if len(result.Canvases) != 1 || result.Canvases[0].ID != "valid" {
t.Fatalf("invalid canvas was not omitted: %+v", result.Canvases)
}
status := findSource(result.Sources, "Official")
if status == nil || status.Healthy || status.Error == "" {
t.Fatalf("source warning missing: %+v", status)
}
}
func TestCatalogDegradedSourceDoesNotAbortMerge(t *testing.T) {
good := serve(t, indexJSON(entryJSON("alpha", "1.0.0", 1)))
s := newTestService(t)
@@ -38,12 +38,28 @@ type IndexSource struct {
URL string `json:"url"`
}
// Preview is registry-owned listing presentation metadata. It never supplies
// package identity, permissions, or install bytes.
type Preview struct {
URL string `json:"url"`
Alt string `json:"alt"`
}
type PermissionSummary struct {
Reads []string `json:"reads,omitempty"`
Writes []string `json:"writes,omitempty"`
Events []string `json:"events,omitempty"`
SharedState bool `json:"shared_state"`
ExternalOrigins []string `json:"external_origins,omitempty"`
}
// IndexEntry is one plugin as published in a source's index.json. This is the
// hard fetch contract shared with the registry's index-build Action
// (plugin-registry/build-index.mjs); additional/corporate sources must serve
// the same shape. Missing/`null` optional fields decode to their zero value.
type IndexEntry struct {
ID string `json:"id"`
Kind string `json:"kind,omitempty"`
Name string `json:"name"`
Description string `json:"description"`
Author string `json:"author"`
@@ -51,12 +67,15 @@ type IndexEntry struct {
// IconURL is an absolute URL to the plugin's icon, resolved by the
// registry index-build from the plugin manifest's `icon` path. Empty
// when the plugin ships no icon; the UI falls back to a letter tile.
IconURL string `json:"icon_url"`
RepoURL string `json:"repo_url"`
Version string `json:"version"`
MinKandevVersion string `json:"min_kandev_version"`
PackageURL string `json:"package_url"`
PackageSHA256 string `json:"package_sha256"`
IconURL string `json:"icon_url"`
RepoURL string `json:"repo_url"`
Version string `json:"version"`
MinKandevVersion string `json:"min_kandev_version"`
License string `json:"license,omitempty"`
PackageURL string `json:"package_url"`
PackageSHA256 string `json:"package_sha256"`
Previews []Preview `json:"previews,omitempty"`
Permissions *PermissionSummary `json:"permissions,omitempty"`
// Stars is a pointer so a `null` in index.json (the registry build emits
// null when a repo's star lookup failed) stays unknown rather than
// decoding to 0 — a known-zero repo and an unknown one must not collapse,
@@ -71,6 +90,7 @@ type IndexDocument struct {
GeneratedAt string `json:"generated_at"`
Source IndexSource `json:"source"`
Plugins []IndexEntry `json:"plugins"`
warning string
}
// CatalogEntry is an IndexEntry annotated with the source it came from and
@@ -98,8 +118,9 @@ type SourceStatus struct {
// CatalogResult is the merged, deduped catalog across all enabled sources.
type CatalogResult struct {
Plugins []CatalogEntry `json:"plugins"`
Sources []SourceStatus `json:"sources"`
Plugins []CatalogEntry `json:"plugins"`
Canvases []CatalogEntry `json:"canvases"`
Sources []SourceStatus `json:"sources"`
}
// InstalledPlugin is the minimal installed-plugin fact the catalog needs to
@@ -125,4 +146,5 @@ type Query struct {
Text string
Category string
Sort string // "stars" (default) | "name" | "recent"
Kind string // "plugin" (default) | "canvas"
}
@@ -64,6 +64,13 @@ func (c *Controller) marketplaceCatalog(ctx *gin.Context) {
Text: ctx.Query("q"),
Category: ctx.Query("category"),
Sort: ctx.Query("sort"),
Kind: ctx.Query("kind"),
})
result.Canvases = marketplace.ApplyQuery(result.Canvases, marketplace.Query{
Text: ctx.Query("q"),
Category: ctx.Query("category"),
Sort: ctx.Query("sort"),
Kind: ctx.Query("kind"),
})
ctx.JSON(http.StatusOK, result)
}
@@ -215,21 +215,7 @@ const DevKandevVersion = "dev"
// not provide a trustworthy release boundary, so they deliberately skip this
// release-only compatibility gate. An invalid manifest minimum is rejected.
func (s *Service) checkMinKandevVersion(minVersion string) error {
if minVersion == "" || s.kandevVersion == "" || s.kandevVersion == DevKandevVersion {
return nil
}
runningVersion, runningRelease := manifest.NormalizeReleaseVersion(s.kandevVersion)
if !runningRelease {
return nil
}
minimumVersion, minimumRelease := manifest.NormalizeReleaseVersion(minVersion)
if !minimumRelease {
return fmt.Errorf("plugins: min_kandev_version %q is not a release version", minVersion)
}
if manifest.CompareVersions(runningVersion, minimumVersion) < 0 {
return fmt.Errorf("plugins: requires kandev >= %s, running %s", minVersion, s.kandevVersion)
}
return nil
return manifest.CheckMinimumKandevVersion(minVersion, s.kandevVersion)
}
// rollbackFailedInstall cleans up after a store.Save failure partway
@@ -0,0 +1,496 @@
package webapp
import (
"archive/tar"
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"path"
"sort"
"strings"
"time"
"github.com/kandev/kandev/internal/plugins/manifest"
"gopkg.in/yaml.v3"
)
const MaxSourceArchiveBytes int64 = 30 << 20
const (
distributionChecksumsFile = "checksums.txt"
sourceEnvExample = ".env.example"
)
var (
ErrChecksumMissing = errors.New("webapp: distribution checksums are missing")
ErrChecksumMismatch = errors.New("webapp: distribution checksum mismatch")
ErrUnsafeSource = errors.New("webapp: unsafe distribution source")
ErrSourceUnavailable = errors.New("webapp: distribution source is unavailable")
ErrInvalidDistribution = errors.New("webapp: invalid distribution package")
)
// DistributionArchives contains the two deterministic artifacts produced
// from one validated immutable package snapshot.
type DistributionArchives struct {
Bundle []byte
Source []byte
}
// BuildDistributionPackage creates a validated package snapshot from a
// manifest and already-retained files. It rewrites only manifest.yaml and the
// generated checksum file; application/source bytes are copied unchanged.
func BuildDistributionPackage(m *manifest.Manifest, input map[string][]byte) (*Package, error) {
if m == nil {
return nil, ErrInvalidDistribution
}
if err := m.Validate(); err != nil {
return nil, fmt.Errorf("%w: manifest: %v", ErrInvalidDistribution, err)
}
manifestData, err := yaml.Marshal(m)
if err != nil {
return nil, fmt.Errorf("%w: marshal manifest: %v", ErrInvalidDistribution, err)
}
if int64(len(manifestData)) > MaxManifestBytes {
return nil, ErrManifestTooLarge
}
files := buildDistributionFiles(input, manifestData)
expanded, err := validateDistributionFiles(files)
if err != nil {
return nil, err
}
files[distributionChecksumsFile] = checksumBytes(files)
checksumBytesCount := int64(len(files[distributionChecksumsFile]))
if expanded > MaxExpandedBytes-checksumBytesCount {
return nil, ErrExpandedTooLarge
}
pkg := &Package{Manifest: m, Files: files, Digest: digestFiles(files), ExpandedBytes: expanded + checksumBytesCount}
if err := ValidateDistribution(pkg); err != nil {
return nil, err
}
return pkg, nil
}
func buildDistributionFiles(input map[string][]byte, manifestData []byte) map[string][]byte {
files := make(map[string][]byte, len(input)+2)
for name, data := range input {
files[name] = append([]byte(nil), data...)
}
files["manifest.yaml"] = manifestData
delete(files, distributionChecksumsFile)
return files
}
func validateDistributionFiles(files map[string][]byte) (int64, error) {
var expanded int64
for name, data := range files {
clean, err := normalizePackagePath(name, MaxPathBytes)
if err != nil || clean != name {
return 0, fmt.Errorf("%w: %s", ErrUnsafePath, name)
}
if strings.HasPrefix(name, "distribution/source/") {
if err := ValidateDistributionSourcePath(name); err != nil {
return 0, err
}
} else if !supportedFile(name) {
return 0, fmt.Errorf("%w: %s", ErrUnsupportedFile, name)
}
if int64(len(data)) > MaxFileBytes || expanded > MaxExpandedBytes-int64(len(data)) {
return 0, ErrFileTooLarge
}
expanded += int64(len(data))
}
return expanded, nil
}
// ValidateDistributionPackage validates a complete installable canvas bundle.
// It is the same entry point used by the offline registry inspector.
func ValidateDistributionPackage(r io.Reader) (*Package, error) {
pkg, err := ValidatePackage(r)
if err != nil {
return nil, err
}
if err := ValidateDistribution(pkg); err != nil {
return nil, err
}
return pkg, nil
}
// ValidateDistribution validates distribution-only requirements after the
// normal web-app package validator has checked archive safety and manifest
// syntax.
func ValidateDistribution(pkg *Package) error {
if pkg == nil || pkg.Manifest == nil || !pkg.Manifest.IsCanvasDistribution() {
return ErrInvalidDistribution
}
if _, ok := pkg.Files["README.md"]; !ok {
return fmt.Errorf("%w: README.md", ErrInvalidDistribution)
}
if _, ok := pkg.Files[distributionChecksumsFile]; !ok {
return ErrChecksumMissing
}
if requiresLicenseFile(pkg.Manifest.Distribution.License) {
if _, ok := pkg.Files["LICENSE.txt"]; !ok {
return fmt.Errorf("%w: LICENSE.txt", ErrInvalidDistribution)
}
}
if err := validateChecksums(pkg.Files); err != nil {
return err
}
if err := validateSourceMode(pkg.Manifest.Distribution.SourceMode, pkg.Files); err != nil {
return err
}
return nil
}
// ValidateCanvasSourcePath applies the authoring-transfer policy to every
// workspace-relative source entry. Directories are allowed after component
// exclusions; regular files must use the retained-source extension allowlist.
func ValidateCanvasSourcePath(name string, isDir bool) error {
clean, err := normalizePackagePath(name, MaxPathBytes)
if err != nil {
return err
}
if sourcePathForbidden(clean) {
return fmt.Errorf("%w: %s", ErrUnsafeSource, clean)
}
if !isDir && !sourceFileExtensionAllowed(clean) {
return fmt.Errorf("%w: %s", ErrUnsupportedFile, clean)
}
return nil
}
// ValidateDistributionSourcePath applies the source subtree policy during
// package validation. It rejects an unsafe path instead of silently dropping
// it, so a retained project cannot appear complete when it is not.
func ValidateDistributionSourcePath(name string) error {
clean, err := normalizePackagePath(name, MaxPathBytes)
if err != nil {
return err
}
if !strings.HasPrefix(clean, "distribution/source/") {
return nil
}
return ValidateCanvasSourcePath(clean, false)
}
func validateSourceMode(sourceMode string, files map[string][]byte) error {
var sourceFiles int
for name := range files {
if strings.HasPrefix(name, "distribution/source/") {
sourceFiles++
}
}
switch sourceMode {
case manifest.SourceModeStatic:
if sourceFiles != 0 {
return fmt.Errorf("%w: static distributions cannot contain distribution/source", ErrInvalidDistribution)
}
case manifest.SourceModeProject:
if sourceFiles == 0 {
return ErrSourceUnavailable
}
for _, required := range []string{"distribution/source/manifest.yaml", "distribution/source/README.md"} {
if _, ok := files[required]; !ok {
return fmt.Errorf("%w: %s", ErrSourceUnavailable, required)
}
}
default:
return fmt.Errorf("%w: unsupported source mode", ErrInvalidDistribution)
}
return nil
}
func validateChecksums(files map[string][]byte) error {
checksums, ok := files[distributionChecksumsFile]
if !ok {
return ErrChecksumMissing
}
want, err := parseChecksums(checksums, len(files)-1)
if err != nil {
return err
}
return validateChecksumCoverage(files, want)
}
func parseChecksums(checksums []byte, fileCount int) (map[string]string, error) {
want := make(map[string]string, fileCount)
scanner := bufio.NewScanner(bytes.NewReader(checksums))
for scanner.Scan() {
rawLine := scanner.Text()
if strings.TrimSpace(rawLine) == "" {
continue
}
digest, rawName, found := strings.Cut(rawLine, " ")
digest = strings.TrimSpace(digest)
rawName = strings.TrimSpace(rawName)
if !found || rawName == "" || len(digest) != sha256.Size*2 {
return nil, fmt.Errorf("%w: malformed %s", ErrChecksumMismatch, distributionChecksumsFile)
}
name, err := normalizePackagePath(rawName, MaxPathBytes)
if err != nil || name == distributionChecksumsFile || !isLowerHex(digest) {
return nil, fmt.Errorf("%w: malformed %s", ErrChecksumMismatch, distributionChecksumsFile)
}
if _, exists := want[name]; exists {
return nil, fmt.Errorf("%w: duplicate %s", ErrChecksumMismatch, name)
}
want[name] = strings.ToLower(digest)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("%w: read %s: %v", ErrChecksumMismatch, distributionChecksumsFile, err)
}
return want, nil
}
func validateChecksumCoverage(files map[string][]byte, want map[string]string) error {
if len(want) != len(files)-1 {
return fmt.Errorf("%w: incomplete file coverage", ErrChecksumMismatch)
}
for name, data := range files {
if name == distributionChecksumsFile {
continue
}
expected, exists := want[name]
if !exists {
return fmt.Errorf("%w: missing %s", ErrChecksumMismatch, name)
}
actual := sha256.Sum256(data)
if expected != hex.EncodeToString(actual[:]) {
return fmt.Errorf("%w: %s", ErrChecksumMismatch, name)
}
}
for name := range want {
if _, exists := files[name]; !exists {
return fmt.Errorf("%w: unknown %s", ErrChecksumMismatch, name)
}
}
return nil
}
func checksumBytes(files map[string][]byte) []byte {
names := sortedFileNames(files)
var output bytes.Buffer
for _, name := range names {
sum := sha256.Sum256(files[name])
_, _ = fmt.Fprintf(&output, "%x %s\n", sum, name)
}
return output.Bytes()
}
func isLowerHex(value string) bool {
for _, char := range value {
if (char < '0' || char > '9') && (char < 'a' || char > 'f') {
return false
}
}
return true
}
func requiresLicenseFile(license string) bool {
switch strings.ToUpper(strings.TrimSpace(license)) {
case "MIT", "ISC", "UNLICENSE", "APACHE-2.0", "BSD-2-CLAUSE", "BSD-3-CLAUSE", "MPL-2.0", "GPL-2.0-ONLY", "GPL-3.0-ONLY", "LGPL-2.1-ONLY", "LGPL-3.0-ONLY":
return false
default:
return true
}
}
func sourcePathForbidden(name string) bool {
for _, component := range strings.Split(name, "/") {
if component == ".git" || component == "node_modules" || component == ".kandev" {
return true
}
if strings.HasPrefix(component, ".env") && component != sourceEnvExample {
return true
}
}
ext := strings.ToLower(path.Ext(name))
switch ext {
case ".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".exe", ".dll", ".so", ".dylib", ".bin", ".wasm":
return true
default:
return false
}
}
func sourceFileExtensionAllowed(name string) bool {
base := path.Base(name)
if base == "Dockerfile" || base == "Makefile" || base == "README" || base == "LICENSE" || base == sourceEnvExample {
return true
}
switch strings.ToLower(path.Ext(name)) {
case ".css", ".html", ".htm", ".js", ".jsx", ".mjs", ".cjs", ".json", ".map", ".md", ".txt", ".ts", ".tsx", ".yaml", ".yml", ".lock", ".toml",
".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".otf", ".eot", sourceEnvExample:
return true
default:
return false
}
}
// BuildDistributionArchives creates a deterministic installable bundle and a
// source zip from the same validated package. The source zip is intentionally
// not accepted by ValidateDistributionPackage.
func BuildDistributionArchives(pkg *Package) (DistributionArchives, error) {
if err := ValidateDistribution(pkg); err != nil {
return DistributionArchives{}, err
}
bundle, err := writeBundle(pkg.Files)
if err != nil {
return DistributionArchives{}, err
}
source, err := writeSourceZip(pkg.Files)
if err != nil {
return DistributionArchives{}, err
}
return DistributionArchives{Bundle: bundle, Source: source}, nil
}
func writeBundle(files map[string][]byte) ([]byte, error) {
names := sortedFileNames(files)
var output bytes.Buffer
zw := gzip.NewWriter(&output)
zw.ModTime = time.Unix(0, 0)
zw.OS = 255
tw := tar.NewWriter(zw)
for _, name := range names {
data := files[name]
header := &tar.Header{Name: name, Mode: 0o600, Size: int64(len(data)), Typeflag: tar.TypeReg}
if err := tw.WriteHeader(header); err != nil {
return nil, fmt.Errorf("webapp: write bundle header: %w", err)
}
if _, err := tw.Write(data); err != nil {
return nil, fmt.Errorf("webapp: write bundle file: %w", err)
}
}
if err := tw.Close(); err != nil {
return nil, fmt.Errorf("webapp: close bundle: %w", err)
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("webapp: close bundle gzip: %w", err)
}
return output.Bytes(), nil
}
func writeSourceZip(files map[string][]byte) ([]byte, error) {
var output bytes.Buffer
zw := zip.NewWriter(&output)
for _, name := range sortedFileNames(files) {
if name == distributionChecksumsFile {
continue
}
header := &zip.FileHeader{Name: name, Method: zip.Deflate}
header.Modified = time.Unix(0, 0)
header.SetMode(0o600)
writer, err := zw.CreateHeader(header)
if err != nil {
return nil, fmt.Errorf("webapp: create source file: %w", err)
}
if _, err := writer.Write(files[name]); err != nil {
return nil, fmt.Errorf("webapp: write source file: %w", err)
}
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("webapp: close source zip: %w", err)
}
return output.Bytes(), nil
}
// ValidateSourceArchive validates the non-installable source zip emitted by
// BuildDistributionArchives without executing or extracting it to disk.
func ValidateSourceArchive(r io.Reader) (*Package, error) {
data, err := io.ReadAll(io.LimitReader(r, MaxSourceArchiveBytes+1))
if err != nil {
return nil, fmt.Errorf("webapp: read source archive: %w", err)
}
if int64(len(data)) > MaxSourceArchiveBytes {
return nil, ErrCompressedTooLarge
}
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, fmt.Errorf("webapp: open source archive: %w", err)
}
files := make(map[string][]byte, len(reader.File))
var expanded int64
for _, entry := range reader.File {
name, content, err := readSourceArchiveEntry(entry, files)
if err != nil {
return nil, err
}
if expanded > MaxExpandedBytes-int64(len(content)) {
return nil, ErrFileTooLarge
}
files[name] = content
expanded += int64(len(content))
}
return validateSourceArchiveFiles(files, expanded, int64(len(data)))
}
func readSourceArchiveEntry(entry *zip.File, files map[string][]byte) (string, []byte, error) {
if entry.FileInfo().IsDir() || entry.Mode()&0o170000 != 0 {
return "", nil, ErrUnsafeEntry
}
name, err := normalizePackagePath(entry.Name, MaxPathBytes)
if err != nil {
return "", nil, err
}
if _, exists := files[name]; exists {
return "", nil, ErrDuplicatePath
}
if name != "manifest.yaml" {
if strings.HasPrefix(name, "distribution/source/") {
if err := ValidateDistributionSourcePath(name); err != nil {
return "", nil, err
}
} else if !supportedFile(name) {
return "", nil, fmt.Errorf("%w: %s", ErrUnsupportedFile, name)
}
}
if entry.UncompressedSize64 > uint64(MaxFileBytes) {
return "", nil, ErrFileTooLarge
}
file, err := entry.Open()
if err != nil {
return "", nil, err
}
content, readErr := io.ReadAll(io.LimitReader(file, MaxFileBytes+1))
_ = file.Close()
if readErr != nil || uint64(len(content)) != entry.UncompressedSize64 {
return "", nil, ErrFileTooLarge
}
return name, content, nil
}
func validateSourceArchiveFiles(files map[string][]byte, expanded, compressed int64) (*Package, error) {
manifestData, ok := files["manifest.yaml"]
if !ok {
return nil, ErrManifestInvalid
}
m, err := manifest.Parse(manifestData)
if err != nil {
return nil, err
}
if err := m.Validate(); err != nil {
return nil, err
}
if !m.IsCanvasDistribution() {
return nil, ErrInvalidDistribution
}
if err := validateSourceMode(m.Distribution.SourceMode, files); err != nil {
return nil, err
}
return &Package{Manifest: m, Files: files, Digest: digestFiles(files), ExpandedBytes: expanded, CompressedBytes: compressed}, nil
}
func sortedFileNames(files map[string][]byte) []string {
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
sort.Strings(names)
return names
}
@@ -0,0 +1,214 @@
package webapp
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"strings"
"testing"
)
func TestValidateDistributionPackageAcceptsProjectSourceAndChecksums(t *testing.T) {
files := distributionFiles()
files["checksums.txt"] = checksumFile(files)
archive := gzipTarFiles(t, files)
pkg, err := ValidateDistributionPackage(bytes.NewReader(archive))
if err != nil {
t.Fatalf("ValidateDistributionPackage() unexpected error: %v", err)
}
if pkg.Manifest.Distribution.SourceMode != "project" {
t.Fatalf("distribution = %+v", pkg.Manifest.Distribution)
}
}
func TestValidateDistributionPackageRejectsChecksumAndSourceViolations(t *testing.T) {
cases := []struct {
name string
edit func(map[string]string)
want error
}{
{name: "missing checksum", edit: func(files map[string]string) { delete(files, "checksums.txt") }, want: ErrChecksumMissing},
{name: "checksum mismatch", edit: func(files map[string]string) { files["ui/app.js"] = "changed" }, want: ErrChecksumMismatch},
{name: "credential file", edit: func(files map[string]string) { files["distribution/source/.env"] = "TOKEN=secret\n" }, want: ErrUnsafeSource},
{name: "nested archive", edit: func(files map[string]string) { files["distribution/source/app.zip"] = "PK\x03\x04" }, want: ErrUnsafeSource},
{name: "missing project source", edit: func(files map[string]string) {
for name := range files {
if strings.HasPrefix(name, "distribution/source/") {
delete(files, name)
}
}
}, want: ErrSourceUnavailable},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
files := distributionFiles()
if tc.name == "checksum mismatch" {
files["checksums.txt"] = checksumFile(files)
}
tc.edit(files)
if tc.name != "missing checksum" && tc.name != "checksum mismatch" {
files["checksums.txt"] = checksumFile(files)
}
_, err := ValidateDistributionPackage(bytes.NewReader(gzipTarFiles(t, files)))
if !errors.Is(err, tc.want) {
t.Fatalf("ValidateDistributionPackage() error = %v, want %v", err, tc.want)
}
})
}
}
func TestParseChecksumsPreservesSpacesInFilenames(t *testing.T) {
data := []byte("" + strings.Repeat("a", sha256.Size*2) + " ui/my app.js\n")
want, err := parseChecksums(data, 1)
if err != nil {
t.Fatalf("parseChecksums() error = %v", err)
}
if want["ui/my app.js"] != strings.Repeat("a", sha256.Size*2) {
t.Fatalf("checksums = %+v", want)
}
}
func TestValidateCanvasSourcePathRejectsWorkspaceSecretsAndDependencies(t *testing.T) {
for _, name := range []string{".env", "node_modules/pkg/index.js", "source/.env"} {
if err := ValidateCanvasSourcePath(name, false); !errors.Is(err, ErrUnsafeSource) {
t.Fatalf("ValidateCanvasSourcePath(%q) error = %v, want ErrUnsafeSource", name, err)
}
}
}
func TestDistributionArchiveWritersRoundTrip(t *testing.T) {
pkg := packageFromFiles(t, distributionFiles())
archives, err := BuildDistributionArchives(pkg)
if err != nil {
t.Fatalf("BuildDistributionArchives() unexpected error: %v", err)
}
if len(archives.Bundle) == 0 || len(archives.Source) == 0 {
t.Fatalf("archives = %+v, want bundle and source bytes", archives)
}
if _, err := ValidateDistributionPackage(bytes.NewReader(archives.Bundle)); err != nil {
t.Fatalf("bundle validation error = %v", err)
}
if _, err := ValidateSourceArchive(bytes.NewReader(archives.Source)); err != nil {
t.Fatalf("source validation error = %v", err)
}
}
func TestRuntimeFilePathRejectsDistributionAliases(t *testing.T) {
for _, requestPath := range []string{
"distribution/source/app.ts",
"distribution%2Fsource/app.ts",
"ui/../distribution/source/app.ts",
"ui/%2e%2e/distribution/source/app.ts",
} {
if _, err := runtimeFilePath(requestPath, "ui/index.html"); !errors.Is(err, ErrUnsafePath) {
t.Errorf("runtimeFilePath(%q) error = %v, want ErrUnsafePath", requestPath, err)
}
}
}
const distributionManifestYAML = `id: canvas-board
api_version: 2
version: 1.2.3
display_name: Canvas Board
description: A board
author: Kandev
categories: [canvas]
min_kandev_version: 1.0.0
distribution:
schema_version: 1
kind: canvas
license: Custom-License
source_mode: project
ui:
web_apps:
- key: main
title: Board
entry: ui/index.html
placements: [workspace-canvas]
`
func distributionFiles() map[string]string {
return map[string]string{
"manifest.yaml": distributionManifestYAML,
"README.md": "Build with pnpm build.\n",
"LICENSE.txt": "Custom license terms.\n",
"ui/index.html": "<html></html>",
"ui/app.js": "console.log('ok');",
"distribution/source/manifest.yaml": "name: canvas-board\n",
"distribution/source/README.md": "Build with pnpm build.\n",
"distribution/source/package.json": "{\"scripts\":{\"build\":\"vite build\"}}\n",
"distribution/source/src/main.tsx": "export default function Main() { return null; }\n",
"distribution/source/pnpm-lock.yaml": "lockfileVersion: '9.0'\n",
}
}
func packageFromFiles(t *testing.T, files map[string]string) *Package {
t.Helper()
files["checksums.txt"] = checksumFile(files)
pkg, err := ValidateDistributionPackage(bytes.NewReader(gzipTarFiles(t, files)))
if err != nil {
t.Fatalf("ValidateDistributionPackage() unexpected error: %v", err)
}
return pkg
}
func checksumFile(files map[string]string) string {
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
for i := 0; i < len(names); i++ {
for j := i + 1; j < len(names); j++ {
if names[j] < names[i] {
names[i], names[j] = names[j], names[i]
}
}
}
var builder strings.Builder
for _, name := range names {
sum := sha256.Sum256([]byte(files[name]))
builder.WriteString(hex.EncodeToString(sum[:]))
builder.WriteString(" ")
builder.WriteString(name)
builder.WriteByte('\n')
}
return builder.String()
}
func gzipTarFiles(t *testing.T, files map[string]string) []byte {
t.Helper()
var compressed bytes.Buffer
zw := gzip.NewWriter(&compressed)
tw := tar.NewWriter(zw)
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
for i := 0; i < len(names); i++ {
for j := i + 1; j < len(names); j++ {
if names[j] < names[i] {
names[i], names[j] = names[j], names[i]
}
}
}
for _, name := range names {
data := []byte(files[name])
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(data)), Typeflag: tar.TypeReg}); err != nil {
t.Fatalf("tar header: %v", err)
}
if _, err := io.Copy(tw, bytes.NewReader(data)); err != nil {
t.Fatalf("tar data: %v", err)
}
}
if err := tw.Close(); err != nil {
t.Fatalf("tar close: %v", err)
}
if err := zw.Close(); err != nil {
t.Fatalf("gzip close: %v", err)
}
return compressed.Bytes()
}
@@ -217,7 +217,11 @@ func readArchiveRegularFile(reader *tar.Reader, header *tar.Header, files map[st
if _, exists := files[name]; exists {
return "", nil, 0, fmt.Errorf("%w: %s", ErrDuplicatePath, name)
}
if !supportedFile(name) {
if strings.HasPrefix(name, "distribution/source/") {
if err := ValidateDistributionSourcePath(name); err != nil {
return "", nil, 0, err
}
} else if !supportedFile(name) {
return "", nil, 0, fmt.Errorf("%w: %s", ErrUnsupportedFile, name)
}
if header.Size < 0 || header.Size > limits.MaxFileBytes {
@@ -197,10 +197,17 @@ func runtimeFilePath(requestPath, entry string) (string, error) {
if err != nil {
return "", err
}
if runtimePathInDistribution(entryName) {
return "", ErrUnsafePath
}
name := strings.TrimPrefix(strings.TrimSpace(requestPath), "/")
if name == "" {
return entryName, nil
}
name, err = url.PathUnescape(name)
if err != nil {
return "", ErrUnsafePath
}
if strings.HasPrefix(name, "_kandev/") || name == "_kandev" {
return "", ErrUnsafePath
}
@@ -216,7 +223,23 @@ func runtimeFilePath(requestPath, entry string) (string, error) {
if entryDir != "." && !strings.HasPrefix(name, entryDir+"/") {
name = path.Join(entryDir, name)
}
return normalizePackagePath(name, MaxPathBytes)
name, err = normalizePackagePath(name, MaxPathBytes)
if err != nil {
return "", err
}
if runtimePathInDistribution(name) {
return "", ErrUnsafePath
}
return name, nil
}
func runtimePathInDistribution(name string) bool {
for _, component := range strings.Split(name, "/") {
if component == "distribution" {
return true
}
}
return false
}
func runtimeProtocolPath(requestPath string) (string, bool) {
@@ -147,6 +147,7 @@ function installedPlugin(overrides: Partial<PluginRecord> = {}): PluginRecord {
function setStoreState(plugins: PluginRecord[]) {
storeState = {
auth: { user: null },
features: { canvases: false },
plugins: { items: plugins, loading: false, loaded: true, error: null },
setPlugins: vi.fn(),
setPluginsLoading: vi.fn(),
@@ -17,6 +17,9 @@ const COPY: Record<string, string> = {
"canvases:archivedCanvasActionHelp":
"This canvas is archived. Restore it from workspace settings before changing it.",
"canvases:disabledCanvasActionHelp": "This canvas is disabled. Enable it before changing it.",
"canvases:shareCanvas": "Share canvas",
"canvases:shareCanvasDescription":
"Prepare a verified bundle or source archive for review and sharing.",
};
vi.mock("react-i18next", () => ({
@@ -64,6 +67,7 @@ describe("canvas host action guidance", () => {
onEdit={vi.fn()}
onPromote={vi.fn()}
onReleases={vi.fn()}
onShare={vi.fn()}
/>,
);
@@ -89,6 +93,7 @@ describe("canvas host action guidance", () => {
onEdit={vi.fn()}
onPromote={vi.fn()}
onReleases={vi.fn()}
onShare={vi.fn()}
onSelectCanvas={vi.fn()}
editing={false}
/>,
@@ -7,6 +7,7 @@ import {
IconExternalLink,
IconLayoutGrid,
IconListDetails,
IconShare3,
IconSparkles,
} from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
@@ -213,12 +214,14 @@ export function CanvasDesktopActions({
onEdit,
onPromote,
onReleases,
onShare,
}: {
canvas: Canvas;
editing: boolean;
onEdit: () => void;
onPromote: () => void;
onReleases: () => void;
onShare: () => void;
}) {
const { t } = useTranslation();
const lifecycleLocked = canvas.status === "archived" || canvas.status === "disabled";
@@ -255,6 +258,16 @@ export function CanvasDesktopActions({
{t("canvases:releasesAndPermissions")}
</Button>
</CanvasDesktopActionTooltip>
<CanvasDesktopActionTooltip
description={t("canvases:shareCanvasDescription")}
disabled={false}
testId="canvas-action-share-tooltip-trigger"
>
<Button variant="outline" size="sm" className="cursor-pointer" onClick={onShare}>
<IconShare3 className="mr-1.5 h-3.5 w-3.5" />
{t("canvases:shareCanvas")}
</Button>
</CanvasDesktopActionTooltip>
{canvas.scope_kind === "task" && (
<CanvasDesktopActionTooltip
description={promoteDescription}
@@ -469,6 +482,30 @@ function MobileCanvasPromoteAction({
);
}
function MobileCanvasShareAction({
onShare,
t,
}: {
onShare: () => void;
t: (key: string) => string;
}) {
return (
<MobileCanvasAction
description={t("canvases:shareCanvasDescription")}
testId="canvas-action-share-help"
>
<Button
variant="ghost"
className="min-h-11 w-full justify-start cursor-pointer"
onClick={onShare}
>
<IconShare3 className="mr-2 h-4 w-4" />
{t("canvases:shareCanvas")}
</Button>
</MobileCanvasAction>
);
}
function MobileCanvasNewTabAction({ canvas, t }: { canvas: Canvas; t: (key: string) => string }) {
return (
<MobileCanvasAction
@@ -493,6 +530,7 @@ export function MobileCanvasActions({
onEdit,
onPromote,
onReleases,
onShare,
onSelectCanvas,
editing,
}: {
@@ -503,6 +541,7 @@ export function MobileCanvasActions({
onEdit: () => void;
onPromote: () => void;
onReleases: () => void;
onShare: () => void;
onSelectCanvas: (canvas: Canvas) => void;
editing: boolean;
}) {
@@ -529,6 +568,7 @@ export function MobileCanvasActions({
<MobileCanvasEditAction canvas={canvas} editing={editing} onEdit={onEdit} t={t} />
)}
<MobileCanvasReleasesAction onReleases={onReleases} t={t} />
{canvas && <MobileCanvasShareAction onShare={onShare} t={t} />}
{canvas?.scope_kind === "task" && (
<MobileCanvasPromoteAction
canvas={canvas}
@@ -23,6 +23,7 @@ import {
MobileCanvasActions,
type CanvasHostState,
} from "./canvas-host-components";
import { CanvasShareDialog } from "./canvas-share-dialog";
function stateForCanvas(canvas: Canvas): CanvasHostState {
if (canvas.status === "archived") return "archived";
@@ -363,6 +364,34 @@ function useCanvasHost(canvasId: string) {
};
}
type CanvasHostEditOptions = {
canvas: Canvas | null;
router: ReturnType<typeof useRouter>;
setEditing: (editing: boolean) => void;
setMenuOpen: (open: boolean) => void;
onError: (reason: unknown) => void;
};
async function editCanvasFromHost(options: CanvasHostEditOptions): Promise<void> {
const { canvas, router, setEditing, setMenuOpen, onError } = options;
if (!canvas) return;
setEditing(true);
try {
const response = await startCanvasEdit(canvas.id);
if (response.task_id) {
const query = response.session_id
? `?sessionId=${encodeURIComponent(response.session_id)}`
: "";
router.push(`/t/${encodeURIComponent(response.task_id)}${query}`);
}
} catch (reason: unknown) {
onError(reason);
} finally {
setEditing(false);
setMenuOpen(false);
}
}
export function CanvasHostRoute({ canvasId }: { canvasId: string }) {
const { t } = useTranslation();
const router = useRouter();
@@ -381,26 +410,17 @@ export function CanvasHostRoute({ canvasId }: { canvasId: string }) {
const [menuOpen, setMenuOpen] = useState(false);
const [promotionOpen, setPromotionOpen] = useState(false);
const [releasesOpen, setReleasesOpen] = useState(false);
const [shareOpen, setShareOpen] = useState(false);
const [editing, setEditing] = useState(false);
const edit = async () => {
if (!canvas) return;
setEditing(true);
try {
const response = await startCanvasEdit(canvas.id);
if (response.task_id) {
const query = response.session_id
? `?sessionId=${encodeURIComponent(response.session_id)}`
: "";
router.push(`/t/${encodeURIComponent(response.task_id)}${query}`);
}
} catch (reason: unknown) {
setHostError(canvasErrorMessage(reason, t, "canvases:actionFailed"));
} finally {
setEditing(false);
setMenuOpen(false);
}
};
const edit = () =>
editCanvasFromHost({
canvas,
router,
setEditing,
setMenuOpen,
onError: (reason) => setHostError(canvasErrorMessage(reason, t, "canvases:actionFailed")),
});
const selectCanvas = useCallback(
(nextCanvas: Canvas) => {
@@ -418,6 +438,7 @@ export function CanvasHostRoute({ canvasId }: { canvasId: string }) {
onEdit={() => void edit()}
onPromote={() => setPromotionOpen(true)}
onReleases={() => setReleasesOpen(true)}
onShare={() => setShareOpen(true)}
/>
) : null;
@@ -451,6 +472,7 @@ export function CanvasHostRoute({ canvasId }: { canvasId: string }) {
onEdit={() => void edit()}
onPromote={() => setPromotionOpen(true)}
onReleases={() => setReleasesOpen(true)}
onShare={() => setShareOpen(true)}
editing={editing}
canvases={hostCanvases}
onSelectCanvas={selectCanvas}
@@ -464,6 +486,7 @@ export function CanvasHostRoute({ canvasId }: { canvasId: string }) {
onPromotionCompleted={() => router.push(canvas ? canvasHref(canvas.id) : "/")}
onChanged={load}
/>
<CanvasShareDialog canvas={canvas} open={shareOpen} onOpenChange={setShareOpen} />
</PageShell>
);
}
@@ -0,0 +1,134 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Canvas } from "@/lib/api/domains/canvas-api";
import type { ExportReview } from "@/lib/api/domains/canvas-distribution-api";
const prepare = vi.fn();
const share = {
review: null as ExportReview | null,
loading: false,
error: null,
prepare,
download: vi.fn(),
cancel: vi.fn(),
reset: vi.fn(),
invalidate: vi.fn(),
};
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: { size?: string | number }) =>
options?.size === undefined ? key : `${key}:${options.size}`,
}),
}));
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
useResponsiveBreakpoint: () => ({ isMobile: false }),
}));
vi.mock("@/hooks/domains/canvas/use-canvas-share", () => ({
useCanvasShare: () => share,
}));
vi.mock("./canvas-share-help", () => ({ CanvasShareHelp: () => null }));
vi.mock("@kandev/ui/dialog", () => ({
Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
open ? <>{children}</> : null,
DialogContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
DialogDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
DialogFooter: ({ children }: { children?: ReactNode }) => <footer>{children}</footer>,
DialogHeader: ({ children }: { children?: ReactNode }) => <header>{children}</header>,
DialogTitle: ({ children }: { children?: ReactNode }) => <h2>{children}</h2>,
}));
vi.mock("@kandev/ui/drawer", () => ({
Drawer: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
open ? <>{children}</> : null,
DrawerContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
DrawerDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
DrawerFooter: ({ children }: { children?: ReactNode }) => <footer>{children}</footer>,
DrawerHeader: ({ children }: { children?: ReactNode }) => <header>{children}</header>,
DrawerTitle: ({ children }: { children?: ReactNode }) => <h2>{children}</h2>,
}));
import { CanvasShareDialog } from "./canvas-share-dialog";
afterEach(() => cleanup());
const canvas: Canvas = {
id: "canvas-1",
plugin_instance_id: "instance-1",
plugin_id: "canvas-1",
workspace_id: "workspace-1",
scope_kind: "workspace",
title: "Canvas One",
status: "active",
active_release_id: "release-1",
active_release_status: "valid",
active_release: {
id: "release-1",
validation_status: "valid",
package_id: "canvas-one",
version: "1.0.0",
display_name: "Canvas One",
description: "A portable canvas",
author: "Author",
source_mode: "static",
min_kandev_version: "0.94.0",
},
} as Canvas;
beforeEach(() => {
prepare.mockReset().mockResolvedValue(null);
share.cancel.mockReset();
share.reset.mockReset();
share.invalidate.mockReset();
share.download.mockReset();
share.review = null;
});
describe("CanvasShareDialog", () => {
it("submits editable distribution metadata, including a user supplied license", () => {
render(<CanvasShareDialog canvas={canvas} open onOpenChange={vi.fn()} />);
fireEvent.change(screen.getByLabelText("canvases:license"), {
target: { value: "MIT" },
});
fireEvent.click(screen.getByRole("button", { name: "canvases:prepareDownloads" }));
expect(prepare).toHaveBeenCalledWith(
expect.objectContaining({
package_id: "canvas-one",
version: "1.0.0",
author: "Author",
license: "MIT",
source_mode: "static",
min_kandev_version: "0.94.0",
}),
);
});
it("lists the retained export files with their sizes", () => {
share.review = {
preparation_id: "preparation-1",
canvas_id: "canvas-1",
workspace_id: "workspace-1",
release_id: "release-1",
metadata: { package_id: "canvas-one", version: "1.0.0" },
sha256: "digest",
files: [{ path: "assets/logo.svg", bytes: 12 }],
bundle_bytes: 20,
source_bytes: 18,
expires_at: "2026-09-11T12:00:00Z",
bundle_download: "",
source_download: "",
};
share.download.mockReset().mockResolvedValue(undefined);
render(<CanvasShareDialog canvas={canvas} open onOpenChange={vi.fn()} />);
expect(screen.getByText("assets/logo.svg")).toBeTruthy();
expect(screen.getByText("canvases:downloadSize:12")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "canvases:downloadBundle" }));
fireEvent.click(screen.getByRole("button", { name: "canvases:downloadSource" }));
expect(share.download).toHaveBeenNthCalledWith(1, "bundle");
expect(share.download).toHaveBeenNthCalledWith(2, "source");
});
});
@@ -0,0 +1,348 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@kandev/ui/drawer";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { Textarea } from "@kandev/ui/textarea";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { useCanvasShare } from "@/hooks/domains/canvas/use-canvas-share";
import type { DistributionMetadata } from "@/lib/api/domains/canvas-distribution-api";
import type { Canvas } from "@/lib/api/domains/canvas-api";
import { formatNumber } from "@/lib/i18n/formats";
import { CanvasShareHelp } from "./canvas-share-help";
type ShareMetadata = DistributionMetadata & { source_mode: "static" | "project" };
// eslint-disable-next-line complexity -- Seeding each editable distribution field keeps the form independent from API shape changes.
function seedShareMetadata(canvas: Canvas | null): ShareMetadata {
const release = canvas?.active_release;
const sourceMode = release?.source_mode === "project" ? "project" : "static";
return {
package_id: release?.package_id ?? "",
version: release?.version ?? "",
display_name: release?.display_name ?? canvas?.title ?? "",
description: release?.description ?? "",
author: release?.author ?? "",
license: release?.license ?? "",
source_mode: sourceMode,
min_kandev_version: release?.min_kandev_version ?? "",
repo_url: release?.repo_url ?? "",
};
}
// eslint-disable-next-line max-lines-per-function -- The responsive share dialog owns one cohesive metadata and review flow.
export function CanvasShareDialog({
canvas,
open,
onOpenChange,
}: {
canvas: Canvas | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const { t } = useTranslation();
const { isMobile } = useResponsiveBreakpoint();
const share = useCanvasShare(canvas);
const { reset, cancel, invalidate } = share;
const [metadata, setMetadata] = useState<ShareMetadata>(() => seedShareMetadata(canvas));
useEffect(() => {
if (open) {
setMetadata(seedShareMetadata(canvas));
} else {
reset();
}
}, [canvas?.active_release_id, canvas?.id, open, reset]);
const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen) void cancel();
onOpenChange(nextOpen);
};
const close = () => handleOpenChange(false);
const updateMetadata = <K extends keyof ShareMetadata>(key: K, value: ShareMetadata[K]) => {
invalidate();
setMetadata((current) => ({ ...current, [key]: value }));
};
const prepare = () =>
void share.prepare({
...metadata,
package_id: metadata.package_id?.trim(),
version: metadata.version?.trim(),
display_name: metadata.display_name?.trim(),
description: metadata.description?.trim(),
author: metadata.author?.trim(),
license: metadata.license?.trim(),
min_kandev_version: metadata.min_kandev_version?.trim(),
repo_url: metadata.repo_url?.trim() || undefined,
});
const body = (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto overscroll-contain px-4 py-4">
{!canvas?.active_release_id || canvas.active_release_status !== "valid" ? (
<p className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
{t("canvases:shareNoRelease")}
</p>
) : (
<>
<p className="text-sm text-muted-foreground">
{t("canvases:prepareDownloadsDescription")}
</p>
<ShareMetadataForm metadata={metadata} onChange={updateMetadata} />
{!share.review && (
<Button
className="min-h-11 cursor-pointer md:min-h-7 [@media(pointer:coarse)]:min-h-11"
disabled={share.loading}
onClick={prepare}
>
{share.loading ? t("canvases:sharing") : t("canvases:prepareDownloads")}
</Button>
)}
{Boolean(share.error) && (
<p role="alert" className="text-sm text-destructive">
{t("canvases:shareFailed")}
</p>
)}
{share.review && (
<ExportReview
review={share.review}
loading={share.loading}
onDownload={share.download}
/>
)}
<CanvasShareHelp review={share.review} />
</>
)}
</div>
);
const footer = (
<div className="flex shrink-0 flex-col-reverse gap-2 border-t px-4 py-3 md:flex-row md:justify-end">
<Button
variant="outline"
className="min-h-11 cursor-pointer md:min-h-7 [@media(pointer:coarse)]:min-h-11"
onClick={close}
>
{t("common:cancel")}
</Button>
</div>
);
if (isMobile) {
return (
<Drawer open={open} onOpenChange={handleOpenChange}>
<DrawerContent className="flex h-[100dvh] max-h-[100dvh] flex-col overflow-hidden">
<DrawerHeader className="shrink-0 px-4 py-3 text-left">
<DrawerTitle>{t("canvases:shareCanvas")}</DrawerTitle>
<DrawerDescription>{t("canvases:shareCanvasDescription")}</DrawerDescription>
</DrawerHeader>
{body}
<DrawerFooter className="shrink-0 p-0">{footer}</DrawerFooter>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl">
<DialogHeader className="shrink-0 px-4 pb-1 pt-3 text-left">
<DialogTitle>{t("canvases:shareCanvas")}</DialogTitle>
<DialogDescription>{t("canvases:shareCanvasDescription")}</DialogDescription>
</DialogHeader>
{body}
<DialogFooter className="p-0">{footer}</DialogFooter>
</DialogContent>
</Dialog>
);
}
function ExportReview({
review,
loading,
onDownload,
}: {
review: NonNullable<ReturnType<typeof useCanvasShare>["review"]>;
loading: boolean;
onDownload: (kind: "bundle" | "source") => Promise<void>;
}) {
const { t } = useTranslation();
return (
<section
className="space-y-3 rounded-lg border border-border/70 p-4"
data-testid="canvas-export-review"
>
<div>
<h3 className="font-medium">{t("canvases:downloadsReady")}</h3>
<p className="text-xs text-muted-foreground">
{review.metadata.display_name ?? review.canvas_id} · v{review.metadata.version ?? ""}
</p>
</div>
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-sm">
<dt className="text-muted-foreground">{t("canvases:packageId")}</dt>
<dd className="break-all font-mono">{review.metadata.package_id ?? ""}</dd>
<dt className="text-muted-foreground">{t("canvases:packageVersion")}</dt>
<dd>{review.metadata.version ?? ""}</dd>
<dt className="text-muted-foreground">{t("canvases:fileInventory")}</dt>
<dd>
<span>{t("canvases:fileCount", { count: review.files.length })}</span>
<ul
aria-label={t("canvases:fileInventory")}
className="mt-1 max-h-36 space-y-1 overflow-y-auto rounded-md bg-muted/50 p-2 text-xs"
data-testid="canvas-export-file-inventory"
>
{review.files.map((file) => (
<li key={`${file.path}:${file.bytes}`} className="flex justify-between gap-3">
<span className="min-w-0 break-all">{file.path}</span>
<span className="shrink-0 text-muted-foreground">
{t("canvases:downloadSize", { size: formatNumber(file.bytes) })}
</span>
</li>
))}
</ul>
</dd>
<dt className="text-muted-foreground">{t("canvases:bundleSize")}</dt>
<dd>{t("canvases:downloadSize", { size: formatNumber(review.bundle_bytes) })}</dd>
<dt className="text-muted-foreground">{t("canvases:sourceSize")}</dt>
<dd>{t("canvases:downloadSize", { size: formatNumber(review.source_bytes) })}</dd>
</dl>
<div className="flex flex-col gap-2 sm:flex-row">
<Button
className="min-h-11 flex-1 cursor-pointer md:min-h-7 [@media(pointer:coarse)]:min-h-11"
disabled={loading}
onClick={() => void onDownload("bundle")}
>
{t("canvases:downloadBundle")}
</Button>
<Button
variant="outline"
className="min-h-11 flex-1 cursor-pointer md:min-h-7 [@media(pointer:coarse)]:min-h-11"
disabled={loading}
onClick={() => void onDownload("source")}
>
{t("canvases:downloadSource")}
</Button>
</div>
<p className="text-xs text-muted-foreground">{t("canvases:privateContentReminder")}</p>
</section>
);
}
// eslint-disable-next-line max-lines-per-function -- The metadata fields stay together so every edit shares the same invalidation path.
function ShareMetadataForm({
metadata,
onChange,
}: {
metadata: ShareMetadata;
onChange: <K extends keyof ShareMetadata>(key: K, value: ShareMetadata[K]) => void;
}) {
const { t } = useTranslation();
return (
<section className="space-y-3 rounded-lg border border-border/70 p-4">
<div>
<h3 className="font-medium">{t("canvases:distributionMetadata")}</h3>
<p className="text-xs text-muted-foreground">{t("canvases:distributionMetadataHelp")}</p>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="canvas-share-package-id">{t("canvases:packageId")}</Label>
<Input
id="canvas-share-package-id"
value={metadata.package_id ?? ""}
onChange={(event) => onChange("package_id", event.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-version">{t("canvases:packageVersion")}</Label>
<Input
id="canvas-share-version"
value={metadata.version ?? ""}
onChange={(event) => onChange("version", event.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-display-name">{t("canvases:displayName")}</Label>
<Input
id="canvas-share-display-name"
value={metadata.display_name ?? ""}
onChange={(event) => onChange("display_name", event.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-author">{t("canvases:author")}</Label>
<Input
id="canvas-share-author"
value={metadata.author ?? ""}
onChange={(event) => onChange("author", event.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-license">{t("canvases:license")}</Label>
<Input
id="canvas-share-license"
value={metadata.license ?? ""}
onChange={(event) => onChange("license", event.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-min-version">{t("canvases:minKandevVersion")}</Label>
<Input
id="canvas-share-min-version"
value={metadata.min_kandev_version ?? ""}
onChange={(event) => onChange("min_kandev_version", event.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-source-mode">{t("canvases:sourceMode")}</Label>
<Select
value={metadata.source_mode}
onValueChange={(value) =>
onChange("source_mode", value as ShareMetadata["source_mode"])
}
>
<SelectTrigger id="canvas-share-source-mode">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="static">{t("canvases:sourceModeStatic")}</SelectItem>
<SelectItem value="project">{t("canvases:sourceModeProject")}</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-repo-url">{t("canvases:repositoryUrl")}</Label>
<Input
id="canvas-share-repo-url"
value={metadata.repo_url ?? ""}
onChange={(event) => onChange("repo_url", event.target.value)}
inputMode="url"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="canvas-share-description">{t("canvases:description")}</Label>
<Textarea
id="canvas-share-description"
value={metadata.description ?? ""}
onChange={(event) => onChange("description", event.target.value)}
rows={3}
/>
</div>
</section>
);
}
@@ -0,0 +1,23 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
import { CanvasShareHelp } from "./canvas-share-help";
afterEach(() => cleanup());
describe("CanvasShareHelp", () => {
it("shows a copyable canvas registry example", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
render(<CanvasShareHelp review={null} />);
expect(screen.getByText(/kind: canvas/)).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "canvases:copyRegistryExample" }));
expect(writeText).toHaveBeenCalledWith(expect.stringContaining("previews:"));
await waitFor(() =>
expect(screen.getByRole("button", { name: "canvases:registryExampleCopied" })).toBeTruthy(),
);
});
});
@@ -0,0 +1,69 @@
"use client";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui/button";
import type { ExportReview } from "@/lib/api/domains/canvas-distribution-api";
// i18n-exempt: registry discriminator in the copyable example, not user-facing prose.
const REGISTRY_CANVAS_KIND = "canvas";
export function CanvasShareHelp({ review }: { review: ExportReview | null }) {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const example = useMemo(
() =>
[
`- id: ${review?.metadata.package_id ?? t("canvases:examplePackageId")}`,
` repo: ${t("canvases:exampleRepository")}`,
` kind: ${REGISTRY_CANVAS_KIND}`,
` previews:`,
` - url: ${t("canvases:examplePreviewUrl")}`,
` alt: ${t("canvases:examplePreviewAlt")}`,
].join("\n"),
[review?.metadata.package_id, t],
);
const copy = async () => {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(example);
} else {
const textarea = document.createElement("textarea");
textarea.value = example;
textarea.setAttribute("readonly", "true");
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
textarea.remove();
}
setCopied(true);
};
return (
<details className="rounded-lg border border-border/70 p-4">
<summary className="cursor-pointer font-medium">{t("canvases:howToShare")}</summary>
<div className="mt-3 space-y-3 text-sm text-muted-foreground">
<p>{t("canvases:shareStepDownload")}</p>
<p>{t("canvases:shareStepRepository")}</p>
<p>{t("canvases:shareStepRelease")}</p>
<p>{t("canvases:shareStepSend")}</p>
<div className="space-y-2">
<p>{t("canvases:registryExample")}</p>
<pre className="overflow-x-auto rounded-md bg-muted p-3 text-xs text-foreground">
{example}
</pre>
<Button
type="button"
variant="outline"
className="min-h-11 cursor-pointer"
onClick={() => void copy()}
>
{copied ? t("canvases:registryExampleCopied") : t("canvases:copyRegistryExample")}
</Button>
</div>
</div>
</details>
);
}
@@ -0,0 +1,91 @@
import { cleanup, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { InstallReview } from "@/lib/api/domains/canvas-distribution-api";
const review: InstallReview = {
preparation_id: "preparation-1",
workspace_id: "workspace-b",
metadata: {
package_id: "canvas-one",
version: "1.0.0",
display_name: "Canvas One",
description: "A shared canvas",
author: "Author One",
license: "Apache-2.0",
source_mode: "project",
min_kandev_version: "0.94.0",
repo_url: "https://example.test/canvas-one",
},
sha256: "package-digest",
archive_sha256: "archive-digest",
permissions: { reads: [], writes: [], events: [], external_origins: [], shared_state: false },
origin_kind: "url",
expires_at: "2026-09-11T12:00:00Z",
};
const install = {
review,
result: null,
loading: false,
error: null,
prepareUrl: vi.fn(),
prepareCatalog: vi.fn(),
prepareUpload: vi.fn(),
confirm: vi.fn(),
cancel: vi.fn(),
reset: vi.fn(),
invalidate: vi.fn(),
};
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
useResponsiveBreakpoint: () => ({ isMobile: false }),
}));
vi.mock("@/hooks/domains/canvas/use-canvas-install", () => ({
useCanvasInstall: () => install,
}));
vi.mock("./marketplace-preview-gallery", () => ({ MarketplacePreviewGallery: () => null }));
vi.mock("@kandev/ui/dialog", () => ({
Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
open ? <>{children}</> : null,
DialogContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
DialogDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
DialogFooter: ({ children }: { children?: ReactNode }) => <footer>{children}</footer>,
DialogHeader: ({ children }: { children?: ReactNode }) => <header>{children}</header>,
DialogTitle: ({ children }: { children?: ReactNode }) => <h2>{children}</h2>,
}));
vi.mock("@kandev/ui/drawer", () => ({
Drawer: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
open ? <>{children}</> : null,
DrawerContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
DrawerDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
DrawerFooter: ({ children }: { children?: ReactNode }) => <footer>{children}</footer>,
DrawerHeader: ({ children }: { children?: ReactNode }) => <header>{children}</header>,
DrawerTitle: ({ children }: { children?: ReactNode }) => <h2>{children}</h2>,
}));
import { CanvasInstallDialog } from "./canvas-install-dialog";
afterEach(() => cleanup());
describe("CanvasInstallDialog", () => {
it("shows inspected metadata, destination, and empty permission groups", () => {
render(
<CanvasInstallDialog
open
onOpenChange={vi.fn()}
workspaceId="workspace-b"
workspaceName="Workspace B"
entry={null}
/>,
);
expect(screen.getByText("A shared canvas")).toBeTruthy();
expect(screen.getByText("Author One")).toBeTruthy();
expect(screen.getByText("Apache-2.0")).toBeTruthy();
expect(screen.getByText("0.94.0")).toBeTruthy();
expect(screen.getByText(/Workspace B \(workspace-b\)/)).toBeTruthy();
expect(screen.getAllByText("plugins:none")).toHaveLength(5);
});
});
@@ -0,0 +1,342 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@kandev/ui/drawer";
import { Input } from "@kandev/ui/input";
import { settingsActionClassName } from "@/components/settings/settings-control";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { useCanvasInstall } from "@/hooks/domains/canvas/use-canvas-install";
import { canvasHref } from "@/lib/api/domains/canvas-api";
import type { MarketplaceEntry } from "@/lib/types/plugins";
import { MarketplacePreviewGallery } from "./marketplace-preview-gallery";
type InstallMode = "upload" | "url";
// i18n-exempt: package extension filter, not user-facing copy.
const CANVAS_BUNDLE_ACCEPT = ".tar.gz,.tgz";
// eslint-disable-next-line max-lines-per-function, complexity -- One responsive review flow owns its preparation and confirmation states.
export function CanvasInstallDialog({
open,
onOpenChange,
workspaceId,
workspaceName,
entry,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
workspaceId: string;
workspaceName?: string;
entry: MarketplaceEntry | null;
}) {
const { t } = useTranslation();
const { isMobile } = useResponsiveBreakpoint();
const [mode, setMode] = useState<InstallMode>(entry ? "url" : "upload");
const [file, setFile] = useState<File | null>(null);
const [url, setUrl] = useState("");
const install = useCanvasInstall(workspaceId);
useEffect(() => {
if (!open) {
install.reset();
return;
}
install.invalidate();
setMode(entry ? "url" : "upload");
setFile(null);
setUrl("");
install.reset();
}, [entry?.id, entry?.version, open, install.invalidate, install.reset]);
useEffect(() => {
if (open) install.invalidate();
}, [open, workspaceId, install.invalidate]);
const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen) void install.cancel();
onOpenChange(nextOpen);
};
const close = () => handleOpenChange(false);
const updateMode = (nextMode: InstallMode) => {
install.invalidate();
setMode(nextMode);
};
const updateFile = (nextFile: File | null) => {
install.invalidate();
setFile(nextFile);
};
const updateUrl = (nextUrl: string) => {
install.invalidate();
setUrl(nextUrl);
};
const inspect = async () => {
if (entry) {
await install.prepareCatalog({
source_id: entry.source_id,
package_id: entry.id,
expected_version: entry.version,
expected_sha256: entry.package_sha256,
repository_url: entry.repo_url,
});
return;
}
if (mode === "upload" && file) {
await install.prepareUpload(file);
return;
}
if (mode === "url" && url.trim()) await install.prepareUrl(url.trim());
};
const body = (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto overscroll-contain px-4 py-4">
{entry ? (
<div className="space-y-3 rounded-lg border border-border/70 p-3">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<p className="truncate font-medium">{entry.name}</p>
<p className="text-xs text-muted-foreground">
{entry.id} · v{entry.version}
</p>
</div>
<span className="text-xs text-muted-foreground">{entry.source_name}</span>
</div>
<MarketplacePreviewGallery previews={entry.previews} />
<p className="text-xs text-muted-foreground">{t("plugins:previewInstallIndependent")}</p>
</div>
) : (
<div className="space-y-3">
<div className="flex gap-2">
<Button
type="button"
variant={mode === "upload" ? "secondary" : "outline"}
className={settingsActionClassName("flex-1 cursor-pointer")}
onClick={() => updateMode("upload")}
>
{t("plugins:uploadBundle")}
</Button>
<Button
type="button"
variant={mode === "url" ? "secondary" : "outline"}
className={settingsActionClassName("flex-1 cursor-pointer")}
onClick={() => updateMode("url")}
>
{t("plugins:directLink")}
</Button>
</div>
{mode === "upload" ? (
<label className="block space-y-2 text-sm font-medium" htmlFor="canvas-install-file">
{t("plugins:chooseBundle")}
<Input
id="canvas-install-file"
type="file"
accept={CANVAS_BUNDLE_ACCEPT}
onChange={(event) => updateFile(event.target.files?.[0] ?? null)}
className="cursor-pointer"
/>
</label>
) : (
<label className="block space-y-2 text-sm font-medium" htmlFor="canvas-install-url">
{t("plugins:directLink")}
<Input
id="canvas-install-url"
value={url}
onChange={(event) => updateUrl(event.target.value)}
placeholder={t("plugins:bundleUrlPlaceholder")}
inputMode="url"
/>
</label>
)}
</div>
)}
{Boolean(install.error) && (
<p role="alert" className="text-sm text-destructive">
{t("plugins:installFailed")}
</p>
)}
{install.loading && !install.review && (
<p role="status" className="text-sm text-muted-foreground">
{t("plugins:inspectingBundle")}
</p>
)}
{install.review && !install.result && (
<InstallReviewCard review={install.review} workspaceName={workspaceName} />
)}
{install.result && (
<div
className="space-y-3 rounded-lg border border-emerald-500/40 bg-emerald-500/10 p-4"
role="status"
>
<p className="font-medium">{t("plugins:installedCanvas")}</p>
<a
className="text-sm underline"
href={canvasHref(install.result.canvas.id)}
onClick={() => onOpenChange(false)}
>
{t("plugins:openCanvas")}
</a>
</div>
)}
</div>
);
const footer = (
<div className="flex shrink-0 flex-col-reverse gap-2 border-t px-4 py-3 md:flex-row md:justify-end">
<Button
type="button"
variant="outline"
className={settingsActionClassName("cursor-pointer")}
onClick={close}
>
{t("common:cancel")}
</Button>
{!install.result &&
(install.review ? (
<Button
type="button"
className={settingsActionClassName("cursor-pointer")}
disabled={install.loading}
onClick={() => void install.confirm()}
>
{install.loading ? t("plugins:installingCanvas") : t("plugins:confirmInstall")}
</Button>
) : (
<Button
type="button"
className={settingsActionClassName("cursor-pointer")}
disabled={install.loading || (!entry && (mode === "upload" ? !file : !url.trim()))}
onClick={() => void inspect()}
>
{install.loading ? t("plugins:inspectingBundle") : t("plugins:reviewBundle")}
</Button>
))}
</div>
);
if (isMobile) {
return (
<Drawer open={open} onOpenChange={handleOpenChange}>
<DrawerContent className="flex h-[100dvh] max-h-[100dvh] flex-col overflow-hidden">
<DrawerHeader className="shrink-0 px-4 py-3 text-left">
<DrawerTitle>{t("plugins:installCanvasTitle")}</DrawerTitle>
<DrawerDescription>{t("plugins:installCanvasDescription")}</DrawerDescription>
</DrawerHeader>
{body}
<DrawerFooter className="shrink-0 p-0">{footer}</DrawerFooter>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl">
<DialogHeader className="shrink-0 px-4 pb-1 pt-3 text-left">
<DialogTitle>{t("plugins:installCanvasTitle")}</DialogTitle>
<DialogDescription>{t("plugins:installCanvasDescription")}</DialogDescription>
</DialogHeader>
{body}
<DialogFooter className="p-0">{footer}</DialogFooter>
</DialogContent>
</Dialog>
);
}
function InstallReviewCard({
review,
workspaceName,
}: {
review: NonNullable<ReturnType<typeof useCanvasInstall>["review"]>;
workspaceName?: string;
}) {
const { t } = useTranslation();
const metadata = review.metadata;
const groups = [
[t("canvases:permissionReads"), review.permissions.reads ?? []],
[t("canvases:permissionWrites"), review.permissions.writes ?? []],
[t("canvases:permissionEvents"), review.permissions.events ?? []],
[t("canvases:permissionExternalOrigins"), review.permissions.external_origins ?? []],
] as const;
return (
<section
className="space-y-3 rounded-lg border border-border/70 p-4"
data-testid="canvas-install-review"
>
<div>
<p className="font-medium">{t("plugins:packageVerified")}</p>
<p className="text-sm text-muted-foreground">
{metadata.display_name} · v{metadata.version}
</p>
</div>
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">
<dt className="text-muted-foreground">{t("plugins:packageId")}</dt>
<dd className="break-all font-mono">{metadata.package_id}</dd>
<dt className="text-muted-foreground">{t("plugins:packageDigest")}</dt>
<dd className="break-all font-mono">{review.sha256}</dd>
{review.archive_sha256 && (
<>
<dt className="text-muted-foreground">{t("plugins:archiveDigest")}</dt>
<dd className="break-all font-mono">{review.archive_sha256}</dd>
</>
)}
<dt className="text-muted-foreground">{t("plugins:source")}</dt>
<dd>{review.origin_kind}</dd>
<dt className="text-muted-foreground">{t("plugins:destination")}</dt>
<dd>
{workspaceName ?? t("plugins:workspace")} ({review.workspace_id})
</dd>
<dt className="text-muted-foreground">{t("canvases:description")}</dt>
<dd>{metadata.description}</dd>
<dt className="text-muted-foreground">{t("canvases:author")}</dt>
<dd>{metadata.author}</dd>
<dt className="text-muted-foreground">{t("canvases:license")}</dt>
<dd>{metadata.license}</dd>
<dt className="text-muted-foreground">{t("canvases:sourceMode")}</dt>
<dd>{metadata.source_mode}</dd>
<dt className="text-muted-foreground">{t("canvases:minKandevVersion")}</dt>
<dd>{metadata.min_kandev_version}</dd>
{metadata.repo_url && (
<>
<dt className="text-muted-foreground">{t("canvases:repositoryUrl")}</dt>
<dd className="break-all">{metadata.repo_url}</dd>
</>
)}
</dl>
<div className="space-y-2">
<h4 className="text-sm font-medium">{t("plugins:packagePermissions")}</h4>
<div className="grid gap-2 sm:grid-cols-2">
{groups.map(([label, values]) => (
<div key={label} className="text-xs">
<p className="text-muted-foreground">{label}</p>
<p>{values.length ? values.join(", ") : t("plugins:none")}</p>
</div>
))}
</div>
<div className="text-xs">
<p className="text-muted-foreground">{t("canvases:sharedState")}</p>
<p>{review.permissions.shared_state ? t("canvases:yes") : t("plugins:none")}</p>
</div>
</div>
</section>
);
}
@@ -0,0 +1,56 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import type { MarketplaceEntry } from "@/lib/types/plugins";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("./marketplace-preview-gallery", () => ({
MarketplacePreviewGallery: () => <div data-testid="preview-gallery" />,
}));
vi.mock("./plugin-repo-link", () => ({
PluginRepoLink: () => <a href="https://example.test/repo">plugins:repo</a>,
}));
import { CanvasMarketplaceDetail } from "./canvas-marketplace-detail";
afterEach(() => cleanup());
const entry: MarketplaceEntry = {
id: "canvas-one",
kind: "canvas",
name: "Canvas One",
description: "A reviewed canvas",
author: "author",
categories: ["planning"],
icon_url: "",
repo_url: "https://example.test/repo",
version: "1.0.0",
min_kandev_version: "0.94.0",
license: "MIT",
package_url: "https://example.test/canvas.tar.gz",
package_sha256: "digest",
previews: [{ url: "https://example.test/cover.png", alt: "Cover" }],
permissions: {
reads: ["tasks"],
writes: [],
events: ["task.updated"],
shared_state: true,
external_origins: [],
},
stars: 2,
updated_at: "2026-09-11T00:00:00Z",
install_state: "available",
source_id: "official",
source_name: "Official",
};
describe("CanvasMarketplaceDetail", () => {
it("shows the shared gallery, permission groups, and review action", () => {
render(<CanvasMarketplaceDetail entry={entry} onBack={vi.fn()} onInstall={vi.fn()} />);
expect(screen.getByTestId("preview-gallery")).toBeTruthy();
expect(screen.getByText("A reviewed canvas")).toBeTruthy();
expect(screen.getByText("tasks")).toBeTruthy();
expect(screen.getByText("task.updated")).toBeTruthy();
expect(screen.getByRole("button", { name: "plugins:reviewAndInstall" })).toBeTruthy();
});
});
@@ -0,0 +1,79 @@
"use client";
import { IconArrowLeft } from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { useTranslation } from "react-i18next";
import type { MarketplaceEntry } from "@/lib/types/plugins";
import { MarketplacePreviewGallery } from "./marketplace-preview-gallery";
import { PluginRepoLink } from "./plugin-repo-link";
export function CanvasMarketplaceDetail({
entry,
onBack,
onInstall,
}: {
entry: MarketplaceEntry;
onBack: () => void;
onInstall: () => void;
}) {
const { t } = useTranslation();
const permissions = entry.permissions;
const groups = [
[t("canvases:permissionReads"), permissions?.reads ?? []],
[t("canvases:permissionWrites"), permissions?.writes ?? []],
[t("canvases:permissionEvents"), permissions?.events ?? []],
[t("canvases:permissionExternalOrigins"), permissions?.external_origins ?? []],
] as const;
return (
<div className="space-y-5" data-testid={`canvas-marketplace-detail-${entry.id}`}>
<Button variant="ghost" className="cursor-pointer" onClick={onBack}>
<IconArrowLeft className="mr-2 h-4 w-4" />
{t("plugins:backToCanvases")}
</Button>
<div className="grid gap-6 lg:grid-cols-[minmax(0,1.2fr)_minmax(18rem,1fr)]">
<MarketplacePreviewGallery previews={entry.previews} />
<div className="space-y-4">
<div>
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-xl font-semibold">{entry.name}</h2>
<Badge variant="secondary">v{entry.version}</Badge>
</div>
<p className="mt-1 text-sm text-muted-foreground">
{t("plugins:byAuthor", { author: entry.author })}
</p>
</div>
<p className="text-sm leading-6 text-muted-foreground">{entry.description}</p>
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-sm">
<dt className="text-muted-foreground">{t("plugins:license")}</dt>
<dd>{entry.license || t("plugins:notSet")}</dd>
<dt className="text-muted-foreground">{t("plugins:requiresVersion")}</dt>
<dd>{entry.min_kandev_version || t("plugins:notSet")}</dd>
</dl>
<PluginRepoLink url={entry.repo_url} className="inline-flex" />
<Button
className="w-full cursor-pointer"
onClick={onInstall}
disabled={entry.install_state === "installed"}
>
{entry.install_state === "installed"
? t("plugins:installed")
: t("plugins:reviewAndInstall")}
</Button>
</div>
</div>
<section className="space-y-3 rounded-xl border border-border/70 p-4">
<h3 className="font-medium">{t("plugins:permissions")}</h3>
<div className="grid gap-3 sm:grid-cols-2">
{groups.map(([label, values]) => (
<div key={label} className="space-y-1">
<p className="text-xs font-medium text-muted-foreground">{label}</p>
<p className="text-sm">{values.length ? values.join(", ") : t("plugins:none")}</p>
</div>
))}
</div>
{permissions?.shared_state && <p className="text-sm">{t("canvases:sharedState")}</p>}
</section>
</div>
);
}
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { resolveCanvasMarketplaceWorkspaceId } from "./canvas-marketplace";
describe("resolveCanvasMarketplaceWorkspaceId", () => {
const firstWorkspace = "workspace-a";
const secondWorkspace = "workspace-b";
it("preserves an explicit valid destination when the active workspace differs", () => {
expect(
resolveCanvasMarketplaceWorkspaceId(secondWorkspace, firstWorkspace, [
{ id: firstWorkspace },
{ id: secondWorkspace },
]),
).toBe(secondWorkspace);
});
it("uses the active workspace when the current destination is unavailable", () => {
expect(
resolveCanvasMarketplaceWorkspaceId("workspace-missing", secondWorkspace, [
{ id: firstWorkspace },
{ id: secondWorkspace },
]),
).toBe(secondWorkspace);
});
});
@@ -0,0 +1,342 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { IconLayoutGrid, IconRefresh } from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { useAppStore } from "@/components/state-provider";
import { settingsActionClassName } from "@/components/settings/settings-control";
import { useIsAdmin } from "@/hooks/domains/auth/use-is-admin";
import { useMarketplace } from "@/hooks/domains/plugins/use-marketplace";
import type { CatalogQuery } from "@/lib/api/domains/marketplace-api";
import type { MarketplaceCatalog, MarketplaceEntry } from "@/lib/types/plugins";
import { MarketplaceSourcesDialog } from "./marketplace-sources-dialog";
import { CanvasInstallDialog } from "./canvas-install-dialog";
import { CanvasMarketplaceDetail } from "./canvas-marketplace-detail";
const ALL_CATEGORIES = "__all__";
const CANVAS_ACTION_CLASS = settingsActionClassName("cursor-pointer");
export function resolveCanvasMarketplaceWorkspaceId(
currentWorkspaceId: string,
activeWorkspaceId: string | null | undefined,
workspaces: ReadonlyArray<{ id: string }>,
): string {
if (workspaces.some((workspace) => workspace.id === currentWorkspaceId)) {
return currentWorkspaceId;
}
if (activeWorkspaceId && workspaces.some((workspace) => workspace.id === activeWorkspaceId)) {
return activeWorkspaceId;
}
return workspaces[0]?.id ?? "";
}
// eslint-disable-next-line max-lines-per-function, complexity -- One marketplace surface owns filtering, detail, and install transitions.
export function CanvasMarketplace() {
const { t } = useTranslation();
const workspaces = useAppStore((state) => state.workspaces.items);
const activeWorkspaceId = useAppStore((state) => state.workspaces.activeId);
const canManageSources = useIsAdmin();
const [workspaceId, setWorkspaceId] = useState(activeWorkspaceId ?? workspaces[0]?.id ?? "");
const [text, setText] = useState("");
const [category, setCategory] = useState(ALL_CATEGORIES);
const [sort, setSort] = useState<CatalogQuery["sort"]>("stars");
const [selected, setSelected] = useState<MarketplaceEntry | null>(null);
const [installEntry, setInstallEntry] = useState<MarketplaceEntry | null>(null);
const [installOpen, setInstallOpen] = useState(false);
const [sourcesOpen, setSourcesOpen] = useState(false);
useEffect(() => {
const nextWorkspaceId = resolveCanvasMarketplaceWorkspaceId(
workspaceId,
activeWorkspaceId,
workspaces,
);
if (nextWorkspaceId !== workspaceId) {
setWorkspaceId(nextWorkspaceId);
}
}, [activeWorkspaceId, workspaceId, workspaces]);
const { catalog, loading, error, reload } = useMarketplace({
q: text.trim() || undefined,
sort,
kind: "canvas",
});
const entries = useMemo(() => {
const candidates =
catalog.canvases ?? catalog.plugins.filter((entry) => entry.kind === "canvas");
return category === ALL_CATEGORIES
? candidates
: candidates.filter((entry) => entry.categories.includes(category));
}, [catalog.canvases, catalog.plugins, category]);
const categories = useMemo(() => {
const values = new Set<string>();
for (const entry of catalog.canvases ??
catalog.plugins.filter((item) => item.kind === "canvas")) {
entry.categories.forEach((value) => values.add(value));
}
return Array.from(values).sort();
}, [catalog.canvases, catalog.plugins]);
if (selected) {
return (
<div className="space-y-4">
<CanvasMarketplaceDetail
entry={selected}
onBack={() => setSelected(null)}
onInstall={() => {
setInstallEntry(selected);
setInstallOpen(true);
}}
/>
{workspaceId && (
<CanvasInstallDialog
open={installOpen}
onOpenChange={(open) => {
setInstallOpen(open);
if (!open) setInstallEntry(null);
}}
workspaceId={workspaceId}
workspaceName={workspaces.find((workspace) => workspace.id === workspaceId)?.name}
entry={installEntry}
/>
)}
</div>
);
}
return (
<div className="space-y-4" data-testid="canvas-marketplace">
<div className="flex flex-col gap-3 rounded-xl border border-border/70 bg-card p-4">
<div
className="flex flex-col gap-2 md:flex-row md:items-center"
data-testid="canvas-marketplace-toolbar"
>
<div className="min-w-0 flex-1">
<h2 className="text-lg font-semibold">{t("plugins:tabCanvases")}</h2>
<p className="text-sm text-muted-foreground">
{t("plugins:canvasMarketplaceDescription")}
</p>
</div>
<Button
variant="outline"
className={CANVAS_ACTION_CLASS}
onClick={() => void reload()}
disabled={loading}
>
<IconRefresh className="mr-1.5 h-4 w-4" />
{t("plugins:refresh")}
</Button>
{canManageSources && (
<Button
variant="outline"
className={CANVAS_ACTION_CLASS}
onClick={() => setSourcesOpen(true)}
>
{t("plugins:sources")}
</Button>
)}
<Button
className={CANVAS_ACTION_CLASS}
onClick={() => {
setInstallEntry(null);
setInstallOpen(true);
}}
>
{t("plugins:installCanvas")}
</Button>
</div>
<div className="grid gap-2 md:grid-cols-[minmax(0,1fr)_minmax(12rem,auto)_minmax(10rem,auto)]">
<Input
value={text}
onChange={(event) => setText(event.target.value)}
placeholder={t("plugins:searchCanvases")}
data-testid="canvas-marketplace-search"
/>
<Select value={workspaceId || undefined} onValueChange={setWorkspaceId}>
<SelectTrigger data-testid="canvas-marketplace-workspace">
<SelectValue placeholder={t("plugins:selectWorkspace")} />
</SelectTrigger>
<SelectContent>
{workspaces.map((workspace) => (
<SelectItem key={workspace.id} value={workspace.id}>
{workspace.name}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="flex gap-2">
<Select value={category} onValueChange={setCategory}>
<SelectTrigger className="min-w-0 flex-1" data-testid="canvas-marketplace-category">
<SelectValue placeholder={t("plugins:category")} />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL_CATEGORIES}>{t("plugins:allCategories")}</SelectItem>
{categories.map((value) => (
<SelectItem key={value} value={value}>
{value}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={sort} onValueChange={(value) => setSort(value as CatalogQuery["sort"])}>
<SelectTrigger className="min-w-0 flex-1" data-testid="canvas-marketplace-sort">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="stars">{t("plugins:sortMostStars")}</SelectItem>
<SelectItem value="recent">{t("plugins:sortRecentlyUpdated")}</SelectItem>
<SelectItem value="name">{t("plugins:sortName")}</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<CanvasSourceHealth catalog={catalog} />
{error && (
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
{error}
</div>
)}
{loading && entries.length === 0 && (
<p
className="rounded-lg border border-dashed p-6 text-sm text-muted-foreground"
role="status"
>
{t("plugins:loadingCanvasesMarketplace")}
</p>
)}
{!loading && entries.length === 0 && (
<div className="rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground">
{text.trim() || category !== ALL_CATEGORIES
? t("plugins:noCanvasesMatchSearch")
: t("plugins:noCanvasesAvailable")}
</div>
)}
{entries.length > 0 && (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
{t("plugins:canvasesAvailable", { count: entries.length })}
</p>
<div className="grid gap-3 md:grid-cols-2">
{entries.map((entry) => (
<CanvasMarketplaceCard
key={`${entry.source_id}:${entry.id}`}
entry={entry}
onOpen={() => setSelected(entry)}
onInstall={() => {
setInstallEntry(entry);
setInstallOpen(true);
}}
/>
))}
</div>
</div>
)}
{canManageSources && (
<MarketplaceSourcesDialog
open={sourcesOpen}
sources={catalog.sources}
onOpenChange={setSourcesOpen}
onChanged={() => void reload()}
/>
)}
{workspaceId && (
<CanvasInstallDialog
open={installOpen}
onOpenChange={(open) => {
setInstallOpen(open);
if (!open) setInstallEntry(null);
}}
workspaceId={workspaceId}
workspaceName={workspaces.find((workspace) => workspace.id === workspaceId)?.name}
entry={installEntry}
/>
)}
</div>
);
}
function CanvasMarketplaceCard({
entry,
onOpen,
onInstall,
}: {
entry: MarketplaceEntry;
onOpen: () => void;
onInstall: () => void;
}) {
const { t } = useTranslation();
const cover = entry.previews?.[0];
const [imageFailed, setImageFailed] = useState(false);
return (
<article
className="overflow-hidden rounded-xl border border-border/70 bg-card"
data-testid={`canvas-marketplace-entry-${entry.id}`}
>
<button type="button" className="block w-full cursor-pointer text-left" onClick={onOpen}>
<div className="flex aspect-[16/8] items-center justify-center bg-muted/40">
{cover && !imageFailed ? (
<img
src={cover.url}
alt={cover.alt}
className="h-full w-full object-cover"
onError={() => setImageFailed(true)}
/>
) : (
<IconLayoutGrid className="h-10 w-10 text-muted-foreground" aria-hidden="true" />
)}
</div>
<div className="space-y-2 p-4">
<div className="flex flex-wrap items-center gap-2">
<h3 className="min-w-0 flex-1 truncate font-medium">{entry.name}</h3>
<Badge variant="secondary">v{entry.version}</Badge>
</div>
<p className="line-clamp-2 text-sm text-muted-foreground">{entry.description}</p>
<p className="text-xs text-muted-foreground">
{t("plugins:byAuthor", { author: entry.author })}
</p>
</div>
</button>
<div className="flex items-center justify-between gap-2 border-t px-4 py-3">
<span className="text-xs text-muted-foreground">{entry.source_name}</span>
<Button
className={CANVAS_ACTION_CLASS}
variant="outline"
onClick={onInstall}
disabled={entry.install_state === "installed"}
>
{entry.install_state === "installed"
? t("plugins:installed")
: t("plugins:installCanvas")}
</Button>
</div>
</article>
);
}
function CanvasSourceHealth({ catalog }: { catalog: MarketplaceCatalog }) {
const { t } = useTranslation();
const degraded = catalog.sources.filter((source) => source.enabled && source.healthy === false);
if (degraded.length === 0) return null;
return (
<div
className="space-y-1 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-400"
data-testid="canvas-marketplace-degraded-sources"
>
{degraded.map((source) => (
<p key={source.id}>
{t("plugins:canvasSourceUnreachable", {
name: source.name,
detail: source.error ? `: ${source.error}` : "",
})}
</p>
))}
</div>
);
}
@@ -9,6 +9,7 @@ import { formatNumber } from "@/lib/i18n/formats";
import type { MarketplaceEntry } from "@/lib/types/plugins";
import { SETTINGS_TYPOGRAPHY } from "@/components/settings/settings-typography";
import { PluginRepoLink } from "./plugin-repo-link";
import { MarketplacePreviewGallery } from "./marketplace-preview-gallery";
// Id of the built-in official source (marketplace.officialSourceID). Entries
// from any other source get a source badge; the official one does not.
@@ -61,6 +62,8 @@ export function MarketplaceEntryRow({
/>
</div>
{entry.previews?.length ? <MarketplacePreviewGallery previews={entry.previews} /> : null}
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
<span className="inline-flex items-center gap-1">
<IconStar className="h-3.5 w-3.5" />
@@ -0,0 +1,45 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => {
if (key === "plugins:previewPosition") return `${values?.current}/${values?.total}`;
return key;
},
}),
}));
import { MarketplacePreviewGallery } from "./marketplace-preview-gallery";
afterEach(() => cleanup());
describe("MarketplacePreviewGallery", () => {
it("keeps ordered previews navigable and exposes the selected alt text", () => {
render(
<MarketplacePreviewGallery
previews={[
{ url: "https://cdn.test/one.png", alt: "First screen" },
{ url: "https://cdn.test/two.png", alt: "Second screen" },
]}
/>,
);
expect(screen.getByAltText("First screen")).toBeTruthy();
expect(screen.getByText("1/2")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "plugins:nextPreview" }));
expect(screen.getByAltText("Second screen")).toBeTruthy();
expect(screen.getByText("2/2")).toBeTruthy();
});
it("shows a retry state when the cover image fails", () => {
render(
<MarketplacePreviewGallery
previews={[{ url: "https://cdn.test/bad.png", alt: "Preview" }]}
/>,
);
fireEvent.error(screen.getByAltText("Preview"));
expect(screen.getByText("plugins:previewImageFailed")).toBeTruthy();
expect(screen.getByRole("button", { name: "plugins:retry" })).toBeTruthy();
});
});
@@ -0,0 +1,116 @@
"use client";
import { useState } from "react";
import { IconChevronLeft, IconChevronRight, IconMaximize, IconPhoto } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@kandev/ui/dialog";
import { useTranslation } from "react-i18next";
import type { MarketplacePreview } from "@/lib/types/plugins";
// eslint-disable-next-line max-lines-per-function -- The gallery keeps image, navigation, and enlargement state together.
export function MarketplacePreviewGallery({ previews }: { previews?: MarketplacePreview[] }) {
const { t } = useTranslation();
const [index, setIndex] = useState(0);
const [failed, setFailed] = useState<Record<number, boolean>>({});
const [expanded, setExpanded] = useState(false);
if (!previews?.length) return null;
const selected = previews[Math.min(index, previews.length - 1)];
const hasMany = previews.length > 1;
const move = (delta: number) =>
setIndex((value) => (value + delta + previews.length) % previews.length);
return (
<div className="space-y-2" aria-label={t("plugins:previewImages")}>
<div className="relative overflow-hidden rounded-lg border border-border/70 bg-muted/30 aspect-video">
{failed[index] ? (
<div className="flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-xs text-muted-foreground">
<IconPhoto className="h-6 w-6" />
<span>{t("plugins:previewImageFailed")}</span>
<Button
variant="ghost"
size="sm"
className="cursor-pointer"
onClick={() => setFailed((value) => ({ ...value, [index]: false }))}
>
{t("plugins:retry")}
</Button>
</div>
) : (
<img
src={selected.url}
alt={selected.alt}
className="h-full w-full object-cover"
loading="lazy"
referrerPolicy="no-referrer"
onError={() => setFailed((value) => ({ ...value, [index]: true }))}
/>
)}
<Button
variant="secondary"
size="icon"
className="absolute bottom-2 right-2 cursor-pointer"
aria-label={t("plugins:enlargePreview")}
onClick={() => setExpanded(true)}
>
<IconMaximize className="h-4 w-4" />
</Button>
</div>
{hasMany && (
<div className="flex items-center justify-between gap-2">
<Button
variant="ghost"
size="icon"
className="cursor-pointer"
aria-label={t("plugins:previousPreview")}
onClick={() => move(-1)}
>
<IconChevronLeft className="h-4 w-4" />
</Button>
<span className="text-xs text-muted-foreground" aria-live="polite">
{t("plugins:previewPosition", { current: index + 1, total: previews.length })}
</span>
<Button
variant="ghost"
size="icon"
className="cursor-pointer"
aria-label={t("plugins:nextPreview")}
onClick={() => move(1)}
>
<IconChevronRight className="h-4 w-4" />
</Button>
</div>
)}
{hasMany && (
<div className="flex gap-2 overflow-x-auto pb-1">
{previews.map((preview, previewIndex) => (
<button
key={`${preview.url}-${previewIndex}`}
type="button"
className={`h-12 w-16 shrink-0 overflow-hidden rounded border cursor-pointer ${previewIndex === index ? "border-primary ring-1 ring-primary" : "border-border/70"}`}
aria-label={t("plugins:selectPreview", { position: previewIndex + 1 })}
onClick={() => setIndex(previewIndex)}
>
<img
src={preview.url}
alt=""
className="h-full w-full object-cover"
loading="lazy"
referrerPolicy="no-referrer"
/>
</button>
))}
</div>
)}
<Dialog open={expanded} onOpenChange={setExpanded}>
<DialogContent className="max-w-5xl">
<DialogTitle>{t("plugins:previewImages")}</DialogTitle>
<img
src={selected.url}
alt={selected.alt}
className="max-h-[75vh] w-full object-contain"
referrerPolicy="no-referrer"
/>
</DialogContent>
</Dialog>
</div>
);
}
@@ -10,11 +10,13 @@ import { SettingsPageTemplate } from "@/components/settings/settings-page-templa
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { useAutoUpdateSettings } from "@/hooks/domains/plugins/use-auto-update-settings";
import { useIsAdmin } from "@/hooks/domains/auth/use-is-admin";
import { useFeature } from "@/hooks/domains/features/use-feature";
import { usePlugins } from "@/hooks/domains/plugins/use-plugins";
import { usePluginSetupStatus } from "@/hooks/domains/plugins/use-plugin-setup-status";
import { usePluginUpdates } from "@/hooks/domains/plugins/use-plugin-updates";
import { InstallPluginDialog } from "./install-plugin-dialog";
import { MarketplaceBrowser } from "./marketplace-browser";
import { CanvasMarketplace } from "./canvas-marketplace";
import { PluginRow, type PluginRowUpdateState } from "./plugin-row";
import { PluginUpdateStatus } from "./plugin-update-status";
import { usePluginActions } from "./use-plugin-actions";
@@ -29,6 +31,7 @@ import { settingsActionClassName } from "@/components/settings/settings-control"
export function PluginsSettings() {
const { t } = useTranslation();
const canManage = useIsAdmin();
const canvasesEnabled = useFeature("canvases");
const { isFinePointer } = useResponsiveBreakpoint();
const list = usePlugins();
const actions = usePluginActions();
@@ -69,6 +72,15 @@ export function PluginsSettings() {
<TabsTrigger value="browse" data-testid="plugins-tab-browse" className="cursor-pointer">
{t("plugins:tabBrowse")}
</TabsTrigger>
{canvasesEnabled && (
<TabsTrigger
value="canvases"
data-testid="plugins-tab-canvases"
className="cursor-pointer"
>
{t("plugins:tabCanvases")}
</TabsTrigger>
)}
</TabsList>
<TabsContent value="installed" className="space-y-6">
@@ -86,6 +98,12 @@ export function PluginsSettings() {
<TabsContent value="browse">
<MarketplaceBrowser onInstallUrl={handleMarketplaceInstall} canManage={canManage} />
</TabsContent>
{canvasesEnabled && (
<TabsContent value="canvases">
<CanvasMarketplace />
</TabsContent>
)}
</Tabs>
{canManage && (
@@ -8,6 +8,7 @@ import {
IconKey,
IconRefresh,
IconRestore,
IconShare3,
IconTrash,
} from "@tabler/icons-react";
import {
@@ -38,6 +39,7 @@ import { useCanvasLifecycleRevision } from "@/lib/canvas-lifecycle";
import { CanvasTaskCreateLauncher } from "@/components/canvas/canvas-task-create-launcher";
import { SettingsErrorText, SettingsPageHeader } from "./settings-typography";
import { CanvasReleaseDialog } from "./canvas-lifecycle-dialogs";
import { CanvasShareDialog } from "./canvas-share-dialog";
import { controlSizingClassName } from "@kandev/ui/control-sizing";
const canvasActionClassName = controlSizingClassName("standard", "cursor-pointer");
@@ -53,6 +55,7 @@ function canvasStatusLabel(status: string, t: (key: string) => string): string {
return labels[status] ?? status;
}
// eslint-disable-next-line max-lines-per-function -- Workspace canvas actions share one lifecycle refresh and state owner.
function useWorkspaceCanvasState(workspaceId: string) {
const { t } = useTranslation();
const router = useRouter();
@@ -60,6 +63,7 @@ function useWorkspaceCanvasState(workspaceId: string) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [releaseCanvas, setReleaseCanvas] = useState<Canvas | null>(null);
const [shareCanvas, setShareCanvas] = useState<Canvas | null>(null);
const [removeTarget, setRemoveTarget] = useState<Canvas | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const requestRef = useRef(0);
@@ -144,6 +148,7 @@ function useWorkspaceCanvasState(workspaceId: string) {
loading,
error,
releaseCanvas,
shareCanvas,
removeTarget,
busyId,
active: canvases.filter((canvas) => canvas.status !== "archived"),
@@ -154,10 +159,12 @@ function useWorkspaceCanvasState(workspaceId: string) {
remove,
setCanvases,
setReleaseCanvas,
setShareCanvas,
setRemoveTarget,
};
}
// eslint-disable-next-line max-lines-per-function -- The page composes lifecycle dialogs with the active and archived lists.
export function WorkspaceCanvasesPage({ workspaceId }: { workspaceId: string }) {
const { t } = useTranslation();
const workspaceName = useAppStore(
@@ -168,6 +175,7 @@ export function WorkspaceCanvasesPage({ workspaceId }: { workspaceId: string })
loading,
error,
releaseCanvas,
shareCanvas,
removeTarget,
busyId,
active,
@@ -178,6 +186,7 @@ export function WorkspaceCanvasesPage({ workspaceId }: { workspaceId: string })
remove,
setCanvases,
setReleaseCanvas,
setShareCanvas,
setRemoveTarget,
} = useWorkspaceCanvasState(workspaceId);
@@ -217,6 +226,7 @@ export function WorkspaceCanvasesPage({ workspaceId }: { workspaceId: string })
busyId={busyId}
onEdit={edit}
onReleases={setReleaseCanvas}
onShare={setShareCanvas}
onArchive={(canvas) => void changeStatus(canvas, "archive")}
onRestore={(canvas) => void changeStatus(canvas, "restore")}
onRemove={setRemoveTarget}
@@ -229,6 +239,7 @@ export function WorkspaceCanvasesPage({ workspaceId }: { workspaceId: string })
busyId={busyId}
onEdit={edit}
onReleases={setReleaseCanvas}
onShare={setShareCanvas}
onArchive={(canvas) => void changeStatus(canvas, "archive")}
onRestore={(canvas) => void changeStatus(canvas, "restore")}
onRemove={setRemoveTarget}
@@ -250,6 +261,13 @@ export function WorkspaceCanvasesPage({ workspaceId }: { workspaceId: string })
onOpenChange={(open) => !open && setRemoveTarget(null)}
onConfirm={remove}
/>
<CanvasShareDialog
canvas={shareCanvas}
open={shareCanvas !== null}
onOpenChange={(open) => {
if (!open) setShareCanvas(null);
}}
/>
</div>
);
}
@@ -260,6 +278,7 @@ function CanvasGroup({
busyId,
onEdit,
onReleases,
onShare,
onArchive,
onRestore,
onRemove,
@@ -269,6 +288,7 @@ function CanvasGroup({
busyId: string | null;
onEdit: (canvas: Canvas) => void;
onReleases: (canvas: Canvas) => void;
onShare: (canvas: Canvas) => void;
onArchive: (canvas: Canvas) => void;
onRestore: (canvas: Canvas) => void;
onRemove: (canvas: Canvas) => void;
@@ -284,6 +304,7 @@ function CanvasGroup({
busyId={busyId}
onEdit={onEdit}
onReleases={onReleases}
onShare={onShare}
onArchive={onArchive}
onRestore={onRestore}
onRemove={onRemove}
@@ -340,6 +361,7 @@ function CanvasRow({
busyId,
onEdit,
onReleases,
onShare,
onArchive,
onRestore,
onRemove,
@@ -348,6 +370,7 @@ function CanvasRow({
busyId: string | null;
onEdit: (canvas: Canvas) => void;
onReleases: (canvas: Canvas) => void;
onShare: (canvas: Canvas) => void;
onArchive: (canvas: Canvas) => void;
onRestore: (canvas: Canvas) => void;
onRemove: (canvas: Canvas) => void;
@@ -387,6 +410,14 @@ function CanvasRow({
<IconKey className="mr-1.5 h-3.5 w-3.5" />
{t("canvases:permissionsAndReleases")}
</Button>
<Button
variant="outline"
className={canvasActionClassName}
onClick={() => onShare(canvas)}
>
<IconShare3 className="mr-1.5 h-3.5 w-3.5" />
{t("canvases:shareCanvas")}
</Button>
<CanvasStatusAction
canvas={canvas}
busy={busyId === canvas.id}
@@ -207,6 +207,12 @@ function canvasManifest(canvas: CanvasRecord, options?: CanvasSourceOptions): st
'display_name: "E2E Plugin Canvas"',
'description: "Canvas fixture for Playwright acceptance coverage."',
'author: "Kandev E2E"',
'min_kandev_version: "0.94.0"',
"distribution:",
" schema_version: 1",
' kind: "canvas"',
' license: "MIT"',
' source_mode: "static"',
"ui:",
" web_apps:",
" - key: main",
@@ -0,0 +1,166 @@
import { expect, test } from "../../fixtures/test-base";
import { waitForFiniteAnimations } from "../../helpers/animations";
import { expectControlHeight } from "../../helpers/control-sizing";
import { enableCanvasFeature } from "./canvas-fixture";
const CANVAS_ENTRY = {
id: "canvas-release-board",
kind: "canvas",
name: "Release board",
description: "A portable release board for workspace planning.",
author: "Kandev E2E",
categories: ["planning"],
icon_url: "",
repo_url: "https://github.com/example/release-board",
version: "1.2.0",
min_kandev_version: "0.94.0",
license: "MIT",
package_url: "https://downloads.example.test/canvas-release-board-1.2.0.tar.gz",
package_sha256: "a".repeat(64),
previews: [
{
url: "https://images.example.test/release-board-cover.png",
alt: "Release board with grouped milestones",
},
{
url: "https://images.example.test/release-board-detail.png",
alt: "Release board milestone details",
},
],
permissions: {
reads: ["tasks"],
writes: [],
events: ["task.updated"],
shared_state: false,
external_origins: [],
},
stars: 12,
updated_at: "2026-09-01T00:00:00.000Z",
install_state: "available",
source_id: "official",
source_name: "Kandev Official",
};
function canvasCatalog() {
return {
plugins: [],
canvases: [CANVAS_ENTRY],
sources: [
{
id: "official",
name: "Kandev Official",
url: "https://registry.example.test/index.json",
enabled: true,
builtin: true,
healthy: true,
},
],
};
}
async function mockCanvasCatalog(page: import("@playwright/test").Page) {
await page.route("https://images.example.test/**", async (route) => {
await route.fulfill({
status: 200,
contentType: "image/png",
body: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
"base64",
),
});
});
await page.route("**/api/plugins/marketplace*", async (route) => {
if (route.request().method() !== "GET") {
await route.fallback();
return;
}
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(canvasCatalog()),
});
});
}
test.describe("Canvas marketplace", () => {
test("browses a registry canvas, opens details, and keeps manual install available", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
test.setTimeout(90_000);
const releaseFeature = await enableCanvasFeature(backend, apiClient, seedData.workspaceId);
try {
await mockCanvasCatalog(testPage);
await testPage.goto("/settings/plugins");
await testPage.getByTestId("plugins-tab-canvases").click();
const card = testPage.getByTestId(`canvas-marketplace-entry-${CANVAS_ENTRY.id}`);
await expect(card).toBeVisible();
await expect(card.locator(`img[alt="${CANVAS_ENTRY.previews[0].alt}"]`)).toBeVisible();
await expect(testPage.getByTestId("canvas-marketplace-search")).toBeVisible();
const marketplace = testPage.getByTestId("canvas-marketplace");
const toolbar = marketplace.getByTestId("canvas-marketplace-toolbar");
await expectControlHeight(toolbar.getByRole("button", { name: "Refresh", exact: true }), 28);
await expectControlHeight(toolbar.getByRole("button", { name: "Sources", exact: true }), 28);
await expectControlHeight(
toolbar.getByRole("button", { name: "Install canvas", exact: true }),
28,
);
await expectControlHeight(marketplace.getByTestId("canvas-marketplace-search"), 28);
await expectControlHeight(marketplace.getByTestId("canvas-marketplace-workspace"), 28);
await expectControlHeight(marketplace.getByTestId("canvas-marketplace-category"), 28);
await expectControlHeight(marketplace.getByTestId("canvas-marketplace-sort"), 28);
await card.getByRole("button").first().click();
const detail = testPage.getByTestId(`canvas-marketplace-detail-${CANVAS_ENTRY.id}`);
await expect(detail).toBeVisible();
await expect(detail.getByLabel("Preview images")).toBeVisible();
await expect(detail.getByText("tasks")).toBeVisible();
await detail.getByRole("button", { name: "Review and install", exact: true }).click();
const installDialog = testPage.getByRole("dialog").last();
await expect(installDialog).toBeVisible();
await expect(installDialog.getByText("Release board")).toBeVisible();
await expect(
installDialog.getByText("Preview images are registry metadata.", { exact: false }),
).toBeVisible();
await expect(installDialog.getByText("Preview images")).toBeVisible();
await installDialog.getByRole("button", { name: "Cancel", exact: true }).click();
await detail.getByRole("button", { name: "Back to canvases", exact: true }).click();
await testPage
.getByTestId("canvas-marketplace")
.getByRole("button", { name: "Install canvas", exact: true })
.first()
.click();
const manualDialog = testPage.getByRole("dialog").last();
await expect(
manualDialog.getByRole("button", { name: "Upload bundle", exact: true }),
).toBeVisible();
await waitForFiniteAnimations(manualDialog);
await expectControlHeight(
manualDialog.getByRole("button", { name: "Upload bundle", exact: true }),
28,
);
await expectControlHeight(
manualDialog.getByRole("button", { name: "Direct link", exact: true }),
28,
);
await expectControlHeight(
manualDialog.getByRole("button", { name: "Cancel", exact: true }),
28,
);
await manualDialog.getByRole("button", { name: "Direct link", exact: true }).click();
const directLink = manualDialog.getByLabel("Direct link", { exact: true });
await expect(directLink).toBeVisible();
await expectControlHeight(directLink, 28);
await expect(manualDialog.getByText("Screenshot", { exact: false })).toHaveCount(0);
} finally {
await releaseFeature();
}
});
});
@@ -0,0 +1,71 @@
import { expect, test } from "../../fixtures/test-base";
import {
approvePendingCanvas,
canvasHref,
enableCanvasFeature,
removeCanvas,
promoteCanvas,
seedTaskCanvas,
} from "./canvas-fixture";
test.describe("Canvas sharing", () => {
test("prepares bundle and source downloads from the active release", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
test.setTimeout(180_000);
const releaseFeature = await enableCanvasFeature(backend, apiClient, seedData.workspaceId);
let canvasId: string | undefined;
try {
const seeded = await seedTaskCanvas(testPage, apiClient, seedData);
canvasId = seeded.canvas.id;
const approved = seeded.canvas.pending_release
? await approvePendingCanvas(apiClient, seeded.canvas)
: seeded.canvas;
await testPage.goto(canvasHref(approved.id));
await expect(testPage.getByTestId("canvas-host-route")).toBeVisible({ timeout: 30_000 });
await testPage.getByRole("button", { name: "Share canvas", exact: true }).click();
const taskDialog = testPage.getByRole("dialog").last();
await expect(taskDialog).toBeVisible();
await taskDialog.getByRole("button", { name: "Prepare downloads", exact: true }).click();
await expect(taskDialog.getByTestId("canvas-export-review")).toBeVisible({
timeout: 30_000,
});
await taskDialog.getByRole("button", { name: "Cancel", exact: true }).click();
const active = await promoteCanvas(apiClient, approved);
await testPage.goto(canvasHref(active.id));
await expect(testPage.getByTestId("canvas-host-route")).toBeVisible({ timeout: 30_000 });
await expect(
testPage.getByRole("button", { name: "Share canvas", exact: true }),
).toBeVisible();
await testPage.getByRole("button", { name: "Share canvas", exact: true }).click();
const dialog = testPage.getByRole("dialog").last();
await expect(dialog).toBeVisible();
await expect(
dialog.getByText("Kandev creates bounded archives", { exact: false }),
).toBeVisible();
await dialog.getByRole("button", { name: "Prepare downloads", exact: true }).click();
const review = dialog.getByTestId("canvas-export-review");
await expect(review).toBeVisible({ timeout: 30_000 });
await expect(
review.getByRole("button", { name: "Download bundle", exact: true }),
).toBeVisible();
await expect(
review.getByRole("button", { name: "Download source", exact: true }),
).toBeVisible();
await expect(
dialog.getByText("Check the archive for private content", { exact: false }),
).toBeVisible();
} finally {
if (canvasId) await removeCanvas(apiClient, canvasId);
await releaseFeature();
}
});
});
@@ -0,0 +1,120 @@
import { expect, test } from "../../fixtures/test-base";
import { expectTouchControl } from "../../helpers/control-sizing";
import { enableCanvasFeature } from "./canvas-fixture";
const CANVAS_ENTRY = {
id: "canvas-mobile-board",
kind: "canvas",
name: "Mobile board",
description: "A portable board with a focused phone detail view.",
author: "Kandev E2E",
categories: ["planning"],
icon_url: "",
repo_url: "https://github.com/example/mobile-board",
version: "1.0.0",
min_kandev_version: "0.94.0",
license: "MIT",
package_url: "https://downloads.example.test/canvas-mobile-board-1.0.0.tar.gz",
package_sha256: "b".repeat(64),
previews: [
{
url: "https://images.example.test/mobile-board.png",
alt: "Mobile board with a compact task list",
},
],
permissions: { reads: ["tasks"], writes: [], events: [], shared_state: false },
stars: 4,
updated_at: "2026-09-01T00:00:00.000Z",
install_state: "available",
source_id: "official",
source_name: "Kandev Official",
};
async function mockCanvasCatalog(page: import("@playwright/test").Page) {
await page.route("https://images.example.test/**", async (route) => {
await route.fulfill({
status: 200,
contentType: "image/png",
body: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
"base64",
),
});
});
await page.route("**/api/plugins/marketplace*", async (route) => {
if (route.request().method() !== "GET") {
await route.fallback();
return;
}
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
plugins: [],
canvases: [CANVAS_ENTRY],
sources: [
{
id: "official",
name: "Kandev Official",
url: "https://registry.example.test/index.json",
enabled: true,
builtin: true,
healthy: true,
},
],
}),
});
});
}
test.describe("Canvas marketplace on mobile", () => {
test("uses one-column cards, focused details, and reachable install controls", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
test.setTimeout(90_000);
const releaseFeature = await enableCanvasFeature(backend, apiClient, seedData.workspaceId);
try {
await mockCanvasCatalog(testPage);
await testPage.goto("/settings/plugins");
await testPage.getByTestId("plugins-tab-canvases").tap();
const marketplace = testPage.getByTestId("canvas-marketplace");
const toolbar = marketplace.getByTestId("canvas-marketplace-toolbar");
await expectTouchControl(toolbar.getByRole("button", { name: "Refresh", exact: true }));
await expectTouchControl(toolbar.getByRole("button", { name: "Sources", exact: true }));
await expectTouchControl(
toolbar.getByRole("button", { name: "Install canvas", exact: true }),
);
await expectTouchControl(marketplace.getByTestId("canvas-marketplace-search"));
await expectTouchControl(marketplace.getByTestId("canvas-marketplace-workspace"));
await expectTouchControl(marketplace.getByTestId("canvas-marketplace-category"));
await expectTouchControl(marketplace.getByTestId("canvas-marketplace-sort"));
const card = testPage.getByTestId(`canvas-marketplace-entry-${CANVAS_ENTRY.id}`);
await expect(card).toBeVisible();
expect((await card.boundingBox())?.width).toBeGreaterThan(280);
await card.getByRole("button").first().tap();
const detail = testPage.getByTestId(`canvas-marketplace-detail-${CANVAS_ENTRY.id}`);
await expect(detail).toBeVisible();
const install = detail.getByRole("button", { name: "Review and install", exact: true });
await expect(install).toBeVisible();
expect((await install.boundingBox())?.height).toBeGreaterThanOrEqual(44);
expect(
await testPage.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),
).toBe(true);
await install.tap();
const dialog = testPage.getByRole("dialog").last();
await expect(dialog.getByText("Preview images")).toBeVisible();
expect(
(await dialog.getByRole("button", { name: "Cancel", exact: true }).boundingBox())?.height,
).toBeGreaterThanOrEqual(44);
} finally {
await releaseFeature();
}
});
});
@@ -0,0 +1,60 @@
import { expect, test } from "../../fixtures/test-base";
import { expectTouchControl } from "../../helpers/control-sizing";
import {
approvePendingCanvas,
canvasHref,
enableCanvasFeature,
removeCanvas,
promoteCanvas,
seedTaskCanvas,
} from "./canvas-fixture";
test.describe("Canvas sharing on mobile", () => {
test("keeps sharing actions in a focused drawer with touch-sized downloads", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
test.setTimeout(180_000);
const releaseFeature = await enableCanvasFeature(backend, apiClient, seedData.workspaceId);
let canvasId: string | undefined;
try {
const seeded = await seedTaskCanvas(testPage, apiClient, seedData, true);
canvasId = seeded.canvas.id;
const approved = seeded.canvas.pending_release
? await approvePendingCanvas(apiClient, seeded.canvas)
: seeded.canvas;
const active = await promoteCanvas(apiClient, approved);
await testPage.goto(canvasHref(active.id));
await expect(testPage.getByTestId("canvas-host-route")).toBeVisible({ timeout: 30_000 });
await testPage.getByTestId("canvas-mobile-actions").tap();
const actions = testPage.getByTestId("canvas-mobile-actions-sheet");
await expect(actions).toBeVisible();
await actions.getByRole("button", { name: "Share canvas", exact: true }).tap();
const drawer = testPage.getByRole("dialog").last();
await expect(drawer).toBeVisible();
await expectTouchControl(drawer.getByLabel("Package ID", { exact: true }));
await expectTouchControl(drawer.getByRole("combobox", { name: "Source mode" }));
const prepare = drawer.getByRole("button", { name: "Prepare downloads", exact: true });
await expect(prepare).toBeVisible();
expect((await prepare.boundingBox())?.height).toBeGreaterThanOrEqual(44);
await prepare.tap();
const review = drawer.getByTestId("canvas-export-review");
await expect(review).toBeVisible({ timeout: 30_000 });
expect(
(await review.getByRole("button", { name: "Download source", exact: true }).boundingBox())
?.height,
).toBeGreaterThanOrEqual(44);
expect(
await testPage.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),
).toBe(true);
} finally {
if (canvasId) await removeCanvas(apiClient, canvasId);
await releaseFeature();
}
});
});
@@ -0,0 +1,127 @@
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const prepareCanvasInstall = vi.fn();
const confirmCanvasInstall = vi.fn();
const cancelCanvasInstall = vi.fn();
const uploadCanvasInstall = vi.fn();
const WORKSPACE_ID = "workspace-1";
const FIRST_URL = "https://example.test/one.tar.gz";
vi.mock("@/lib/api/domains/canvas-distribution-api", () => ({
prepareCanvasInstall: (...args: unknown[]) => prepareCanvasInstall(...args),
confirmCanvasInstall: (...args: unknown[]) => confirmCanvasInstall(...args),
cancelCanvasInstall: (...args: unknown[]) => cancelCanvasInstall(...args),
uploadCanvasInstall: (...args: unknown[]) => uploadCanvasInstall(...args),
}));
import { useCanvasInstall } from "./use-canvas-install";
afterEach(() => cleanup());
function review(id: string) {
return {
preparation_id: id,
workspace_id: WORKSPACE_ID,
metadata: {
package_id: "canvas-one",
version: "1.0.0",
display_name: "Canvas One",
description: "",
author: "author",
license: "MIT",
source_mode: "static" as const,
min_kandev_version: "0.1.0",
},
sha256: `package-${id}`,
archive_sha256: `archive-${id}`,
permissions: {},
origin_kind: "url" as const,
expires_at: "2026-09-11T12:00:00Z",
};
}
beforeEach(() => {
prepareCanvasInstall.mockReset();
confirmCanvasInstall.mockReset();
cancelCanvasInstall.mockReset().mockResolvedValue(undefined);
uploadCanvasInstall.mockReset();
});
describe("useCanvasInstall", () => {
it("does not let an older inspection overwrite a newer one", async () => {
let resolveFirst: (value: ReturnType<typeof review>) => void = () => undefined;
const first = new Promise<ReturnType<typeof review>>((resolve) => {
resolveFirst = resolve;
});
prepareCanvasInstall.mockReturnValueOnce(first).mockResolvedValueOnce(review("second"));
const { result } = renderHook(() => useCanvasInstall(WORKSPACE_ID));
let firstRequest: Promise<unknown> | undefined;
await act(async () => {
firstRequest = result.current.prepareUrl(FIRST_URL);
});
await act(async () => {
await result.current.prepareUrl("https://example.test/two.tar.gz");
});
expect(result.current.review?.preparation_id).toBe("second");
resolveFirst(review("first"));
await act(async () => {
await firstRequest;
});
expect(result.current.review?.preparation_id).toBe("second");
});
it("confirms the archive digest shown by the review", async () => {
prepareCanvasInstall.mockResolvedValueOnce(review("one"));
confirmCanvasInstall.mockResolvedValueOnce({ canvas: { id: "canvas-1" }, receipt: {} });
const { result } = renderHook(() => useCanvasInstall(WORKSPACE_ID));
await act(async () => {
await result.current.prepareUrl(FIRST_URL);
});
await act(async () => {
await result.current.confirm();
});
expect(confirmCanvasInstall).toHaveBeenCalledWith("one", "archive-one");
await waitFor(() => expect(result.current.result?.canvas.id).toBe("canvas-1"));
});
it("invalidates a staged review and cancels its server preparation", async () => {
prepareCanvasInstall.mockResolvedValueOnce(review("one"));
const { result } = renderHook(() => useCanvasInstall(WORKSPACE_ID));
await act(async () => {
await result.current.prepareUrl(FIRST_URL);
});
act(() => result.current.invalidate());
expect(result.current.review).toBeNull();
expect(result.current.loading).toBe(false);
expect(cancelCanvasInstall).toHaveBeenCalledWith("one");
});
it("does not restore an inspection that finishes after source editing", async () => {
let resolveInspection: (value: ReturnType<typeof review>) => void = () => undefined;
const inspection = new Promise<ReturnType<typeof review>>((resolve) => {
resolveInspection = resolve;
});
prepareCanvasInstall.mockReturnValueOnce(inspection);
const { result } = renderHook(() => useCanvasInstall("workspace-1"));
let request: Promise<unknown> | undefined;
await act(async () => {
request = result.current.prepareUrl("https://example.test/one.tar.gz");
});
act(() => result.current.invalidate());
resolveInspection(review("one"));
await act(async () => {
await request;
});
expect(result.current.review).toBeNull();
expect(result.current.loading).toBe(false);
});
});
@@ -0,0 +1,142 @@
import { useCallback, useRef, useState } from "react";
import {
cancelCanvasInstall,
confirmCanvasInstall,
prepareCanvasInstall,
type InstallRequest,
type InstallResult,
type InstallReview,
uploadCanvasInstall,
} from "@/lib/api/domains/canvas-distribution-api";
// eslint-disable-next-line max-lines-per-function -- Preparation, invalidation, and confirmation share one generation guard.
export function useCanvasInstall(workspaceId: string) {
const [review, setReview] = useState<InstallReview | null>(null);
const [result, setResult] = useState<InstallResult | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<unknown>(null);
const generation = useRef(0);
const reviewRef = useRef<InstallReview | null>(null);
const updateReview = useCallback((next: InstallReview | null) => {
reviewRef.current = next;
setReview(next);
}, []);
const begin = useCallback(
async (operation: () => Promise<InstallReview>) => {
const current = ++generation.current;
setLoading(true);
setError(null);
updateReview(null);
setResult(null);
try {
const next = await operation();
if (generation.current === current) updateReview(next);
return next;
} catch (reason) {
if (generation.current === current) {
updateReview(null);
setError(reason);
}
throw reason;
} finally {
if (generation.current === current) setLoading(false);
}
},
[updateReview],
);
const prepareUrl = useCallback(
(bundleUrl: string) =>
begin(() =>
prepareCanvasInstall({
workspace_id: workspaceId,
origin_kind: "url",
bundle_url: bundleUrl,
}),
),
[begin, workspaceId],
);
const prepareCatalog = useCallback(
(request: Omit<InstallRequest, "workspace_id" | "bundle_url" | "origin_kind">) =>
begin(() =>
prepareCanvasInstall({ ...request, workspace_id: workspaceId, origin_kind: "registry" }),
),
[begin, workspaceId],
);
const prepareUpload = useCallback(
(file: File) =>
begin(() => uploadCanvasInstall(file, { workspace_id: workspaceId, origin_kind: "upload" })),
[begin, workspaceId],
);
const confirm = useCallback(async () => {
if (!review) return null;
const current = generation.current;
setLoading(true);
setError(null);
try {
const next = await confirmCanvasInstall(
review.preparation_id,
review.archive_sha256 ?? review.sha256,
);
if (generation.current === current) setResult(next);
return next;
} catch (reason) {
if (generation.current === current) setError(reason);
throw reason;
} finally {
if (generation.current === current) setLoading(false);
}
}, [review]);
const cancel = useCallback(async () => {
generation.current += 1;
const currentReview = reviewRef.current;
if (currentReview) {
await cancelCanvasInstall(currentReview.preparation_id).catch(() => undefined);
}
updateReview(null);
setResult(null);
setError(null);
setLoading(false);
}, [updateReview]);
const invalidate = useCallback(() => {
generation.current += 1;
const currentReview = reviewRef.current;
reviewRef.current = null;
setReview(null);
setResult(null);
setError(null);
setLoading(false);
if (currentReview) {
void cancelCanvasInstall(currentReview.preparation_id).catch(() => undefined);
}
}, []);
const reset = useCallback(() => {
generation.current += 1;
updateReview(null);
setResult(null);
setError(null);
setLoading(false);
}, [updateReview]);
return {
review,
result,
loading,
error,
prepareUrl,
prepareCatalog,
prepareUpload,
confirm,
cancel,
reset,
invalidate,
};
}
@@ -0,0 +1,119 @@
import { act, cleanup, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const prepareCanvasExport = vi.fn();
const downloadCanvasExport = vi.fn();
const cancelCanvasExport = vi.fn();
const triggerBlobDownload = vi.fn();
vi.mock("@/lib/api/domains/canvas-distribution-api", () => ({
prepareCanvasExport: (...args: unknown[]) => prepareCanvasExport(...args),
downloadCanvasExport: (...args: unknown[]) => downloadCanvasExport(...args),
cancelCanvasExport: (...args: unknown[]) => cancelCanvasExport(...args),
}));
vi.mock("@/lib/utils/file-download", () => ({
triggerBlobDownload: (...args: unknown[]) => triggerBlobDownload(...args),
}));
import type { Canvas } from "@/lib/api/domains/canvas-api";
import { useCanvasShare } from "./use-canvas-share";
afterEach(() => cleanup());
const canvas: Canvas = {
id: "canvas-1",
plugin_instance_id: "instance-1",
plugin_id: "canvas-1",
workspace_id: "workspace-1",
scope_kind: "workspace",
title: "Canvas",
status: "active",
active_release_id: "release-1",
active_release_status: "valid",
};
const review = {
preparation_id: "prep-1",
canvas_id: "canvas-1",
workspace_id: "workspace-1",
release_id: "release-1",
metadata: { package_id: "canvas-1", version: "1.0.0", display_name: "Canvas" },
sha256: "digest",
files: [{ path: "manifest.yaml", bytes: 10 }],
bundle_bytes: 100,
source_bytes: 200,
expires_at: "2026-09-11T12:00:00Z",
bundle_download: "bundle",
source_download: "source",
};
beforeEach(() => {
prepareCanvasExport.mockReset().mockResolvedValue(review);
downloadCanvasExport.mockReset().mockResolvedValue(new Blob(["data"]));
cancelCanvasExport.mockReset().mockResolvedValue(undefined);
triggerBlobDownload.mockReset();
});
describe("useCanvasShare", () => {
it("prepares from the active release and downloads both archive kinds", async () => {
const { result } = renderHook(() => useCanvasShare(canvas));
await act(async () => {
await result.current.prepare();
});
expect(prepareCanvasExport).toHaveBeenCalledWith("canvas-1", {
workspace_id: "workspace-1",
expected_release_id: "release-1",
metadata: undefined,
});
await act(async () => {
await result.current.download("bundle");
await result.current.download("source");
});
expect(downloadCanvasExport).toHaveBeenNthCalledWith(1, "prep-1", "bundle");
expect(downloadCanvasExport).toHaveBeenNthCalledWith(2, "prep-1", "source");
expect(triggerBlobDownload.mock.calls[0]?.[1]).toBe("canvas-1-1.0.0.tar.gz");
expect(triggerBlobDownload.mock.calls[1]?.[1]).toBe("canvas-1-1.0.0.zip");
});
it("does not let a stale download update state after the review is reset", async () => {
let resolveDownload: (value: Blob) => void = () => undefined;
downloadCanvasExport.mockReturnValueOnce(
new Promise<Blob>((resolve) => {
resolveDownload = resolve;
}),
);
const { result } = renderHook(() => useCanvasShare(canvas));
await act(async () => {
await result.current.prepare();
});
let download: Promise<void> | undefined;
await act(async () => {
download = result.current.download("bundle");
});
await act(async () => {
result.current.reset();
resolveDownload(new Blob(["stale"]));
await download;
});
expect(triggerBlobDownload).not.toHaveBeenCalled();
expect(result.current.review).toBeNull();
expect(result.current.loading).toBe(false);
});
it("invalidates a staged export and cancels its server preparation", async () => {
const { result } = renderHook(() => useCanvasShare(canvas));
await act(async () => {
await result.current.prepare({ license: "MIT" });
});
act(() => result.current.invalidate());
expect(result.current.review).toBeNull();
expect(result.current.loading).toBe(false);
expect(cancelCanvasExport).toHaveBeenCalledWith("prep-1");
});
});
@@ -0,0 +1,108 @@
import { useCallback, useRef, useState } from "react";
import {
cancelCanvasExport,
downloadCanvasExport,
prepareCanvasExport,
type DistributionMetadata,
type ExportReview,
} from "@/lib/api/domains/canvas-distribution-api";
import type { Canvas } from "@/lib/api/domains/canvas-api";
import { triggerBlobDownload } from "@/lib/utils/file-download";
export function useCanvasShare(canvas: Canvas | null) {
const [review, setReview] = useState<ExportReview | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<unknown>(null);
const generation = useRef(0);
const reviewRef = useRef<ExportReview | null>(null);
const updateReview = useCallback((next: ExportReview | null) => {
reviewRef.current = next;
setReview(next);
}, []);
const prepare = useCallback(
async (metadata?: DistributionMetadata) => {
if (!canvas?.active_release_id) return null;
const current = ++generation.current;
setLoading(true);
setError(null);
updateReview(null);
try {
const next = await prepareCanvasExport(canvas.id, {
workspace_id: canvas.workspace_id,
expected_release_id: canvas.active_release_id,
metadata,
});
if (generation.current === current) updateReview(next);
return next;
} catch (reason) {
if (generation.current === current) {
updateReview(null);
setError(reason);
}
throw reason;
} finally {
if (generation.current === current) setLoading(false);
}
},
[canvas, updateReview],
);
const download = useCallback(
async (kind: "bundle" | "source") => {
if (!review) return;
const current = ++generation.current;
setLoading(true);
setError(null);
try {
const blob = await downloadCanvasExport(review.preparation_id, kind);
const packageId = review.metadata.package_id ?? review.canvas_id;
const version = review.metadata.version ?? "release";
if (generation.current === current) {
triggerBlobDownload(
blob,
`${packageId}-${version}.${kind === "bundle" ? "tar.gz" : "zip"}`,
);
}
} catch (reason) {
if (generation.current === current) setError(reason);
throw reason;
} finally {
if (generation.current === current) setLoading(false);
}
},
[review],
);
const cancel = useCallback(async () => {
generation.current += 1;
const currentReview = reviewRef.current;
if (currentReview) {
await cancelCanvasExport(currentReview.preparation_id).catch(() => undefined);
}
updateReview(null);
setError(null);
}, [updateReview]);
const invalidate = useCallback(() => {
generation.current += 1;
const currentReview = reviewRef.current;
reviewRef.current = null;
setReview(null);
setError(null);
setLoading(false);
if (currentReview) {
void cancelCanvasExport(currentReview.preparation_id).catch(() => undefined);
}
}, []);
const reset = useCallback(() => {
generation.current += 1;
updateReview(null);
setError(null);
setLoading(false);
}, [updateReview]);
return { review, loading, error, prepare, download, cancel, reset, invalidate };
}
@@ -25,12 +25,12 @@ export function useMarketplace(query: CatalogQuery) {
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const { q, category, sort } = query;
const { q, category, sort, kind } = query;
useEffect(() => {
let cancelled = false;
setLoading(true);
getMarketplaceCatalog({ q, category, sort })
getMarketplaceCatalog({ q, category, sort, ...(kind ? { kind } : {}) })
.then((result) => {
if (cancelled) return;
setCatalog(result);
@@ -46,7 +46,7 @@ export function useMarketplace(query: CatalogQuery) {
return () => {
cancelled = true;
};
}, [q, category, sort, reloadKey]);
}, [q, category, sort, kind, reloadKey]);
const softReload = useCallback(() => setReloadKey((key) => key + 1), []);
+3 -1
View File
@@ -137,7 +137,9 @@ export async function fetchBlob(pathOrUrl: string, options?: ApiRequestOptions):
// interim-settings interlock token on mutating requests.
function buildRequestHeaders(options?: ApiRequestOptions): Headers {
const headers = requestHeaders(options?.init?.headers);
headers.set("Content-Type", "application/json");
const body = options?.init?.body;
const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
if (!isFormData) headers.set("Content-Type", "application/json");
if (isMutation(options?.init?.method)) {
const token = readInterimSettingsInterlockToken();
if (token) headers.set(interimSettingsInterlockHeader, token);
+9
View File
@@ -6,6 +6,15 @@ export type CanvasReleaseStatus = "valid" | "pending_permission" | "invalid" | "
export type CanvasRelease = {
id: string;
package_id?: string;
version?: string;
display_name?: string;
description?: string;
author?: string;
license?: string;
source_mode?: "static" | "project" | string;
min_kandev_version?: string;
repo_url?: string;
package_digest?: string;
validation_status: CanvasReleaseStatus | string;
validation_error?: string;
@@ -0,0 +1,77 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://api.test" }),
}));
import {
cancelCanvasInstall,
prepareCanvasInstall,
uploadCanvasInstall,
} from "./canvas-distribution-api";
type FetchInput = Parameters<typeof fetch>[0];
type FetchInit = Parameters<typeof fetch>[1];
const fetchSpy = vi.fn<(...args: [FetchInput, FetchInit?]) => Promise<Response>>();
beforeEach(() => {
fetchSpy.mockReset();
vi.stubGlobal("fetch", fetchSpy);
});
afterEach(() => vi.unstubAllGlobals());
function jsonResponse(body: unknown) {
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
describe("canvas distribution API", () => {
it("posts a catalog install request with provenance and archive digest", async () => {
fetchSpy.mockResolvedValueOnce(jsonResponse({ preparation_id: "p1" }));
await prepareCanvasInstall({
workspace_id: "workspace-1",
origin_kind: "registry",
source_id: "official",
package_id: "canvas-one",
expected_version: "1.0.0",
expected_sha256: "abc",
});
const [url, init] = fetchSpy.mock.calls.at(-1) ?? [];
expect(String(url)).toBe("http://api.test/api/v1/canvases/install-preparations");
expect(init?.method).toBe("POST");
expect(JSON.parse(String(init?.body))).toMatchObject({
workspace_id: "workspace-1",
origin_kind: "registry",
expected_sha256: "abc",
});
});
it("uploads the bundle as multipart without a JSON content type", async () => {
fetchSpy.mockResolvedValueOnce(jsonResponse({ preparation_id: "p1" }));
const file = new File(["bundle"], "canvas.tar.gz", { type: "application/gzip" });
await uploadCanvasInstall(file, { workspace_id: "workspace-1", origin_kind: "upload" });
const [, init] = fetchSpy.mock.calls.at(-1) ?? [];
expect(init?.method).toBe("POST");
expect(init?.body).toBeInstanceOf(FormData);
expect((init?.body as FormData).get("package")).toBe(file);
expect(new Headers(init?.headers).get("Content-Type")).toBeNull();
});
it("cancels an install preparation by id", async () => {
fetchSpy.mockResolvedValueOnce(jsonResponse({}));
await cancelCanvasInstall("prep/one");
const [url, init] = fetchSpy.mock.calls.at(-1) ?? [];
expect(String(url)).toBe("http://api.test/api/v1/canvases/install-preparations/prep%2Fone");
expect(init?.method).toBe("DELETE");
});
});
@@ -0,0 +1,169 @@
import { fetchBlob, fetchJson, type ApiRequestOptions } from "../client";
import type { Canvas, CanvasPermissionReview } from "./canvas-api";
export type DistributionMetadata = {
package_id?: string;
version?: string;
display_name?: string;
description?: string;
author?: string;
license?: string;
source_mode?: "static" | "project";
min_kandev_version?: string;
repo_url?: string;
};
export type DistributionFile = { path: string; bytes: number };
export type ExportReview = {
preparation_id: string;
canvas_id: string;
workspace_id: string;
release_id: string;
metadata: DistributionMetadata;
sha256: string;
files: DistributionFile[];
bundle_bytes: number;
source_bytes: number;
expires_at: string;
bundle_download: string;
source_download: string;
};
export type InstallReview = {
preparation_id: string;
workspace_id: string;
metadata: Required<
Pick<
DistributionMetadata,
| "package_id"
| "version"
| "display_name"
| "description"
| "author"
| "license"
| "source_mode"
| "min_kandev_version"
>
> & { repo_url?: string };
sha256: string;
archive_sha256?: string;
permissions: CanvasPermissionReview;
origin_kind: "upload" | "url" | "registry";
source_id?: string;
repository_url?: string;
expires_at: string;
};
export type InstallRequest = {
workspace_id: string;
origin_kind?: "upload" | "url" | "registry";
source_id?: string;
repository_url?: string;
package_id?: string;
expected_version?: string;
expected_sha256?: string;
bundle_url?: string;
};
export type InstallResult = { canvas: Canvas; receipt: Record<string, unknown> };
const EXPORTS = "/api/v1/canvases";
const INSTALLS = "/api/v1/canvases/install-preparations";
export function prepareCanvasExport(
canvasId: string,
request: { workspace_id: string; expected_release_id: string; metadata?: DistributionMetadata },
options?: ApiRequestOptions,
): Promise<ExportReview> {
return fetchJson<ExportReview>(`${EXPORTS}/${encodeURIComponent(canvasId)}/exports`, {
...options,
init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify(request) },
});
}
export function getCanvasExport(
preparationId: string,
options?: ApiRequestOptions,
): Promise<ExportReview> {
return fetchJson<ExportReview>(
`${EXPORTS}/exports/${encodeURIComponent(preparationId)}`,
options,
);
}
export function downloadCanvasExport(
preparationId: string,
kind: "bundle" | "source",
options?: ApiRequestOptions,
): Promise<Blob> {
return fetchBlob(`${EXPORTS}/exports/${encodeURIComponent(preparationId)}/${kind}`, options);
}
export function cancelCanvasExport(
preparationId: string,
options?: ApiRequestOptions,
): Promise<void> {
return fetchJson<void>(`${EXPORTS}/exports/${encodeURIComponent(preparationId)}`, {
...options,
init: { ...(options?.init ?? {}), method: "DELETE" },
});
}
export function prepareCanvasInstall(
request: InstallRequest,
options?: ApiRequestOptions,
): Promise<InstallReview> {
return fetchJson<InstallReview>(INSTALLS, {
...options,
init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify(request) },
});
}
export function uploadCanvasInstall(
file: File,
fields: Omit<InstallRequest, "bundle_url">,
options?: ApiRequestOptions,
): Promise<InstallReview> {
const body = new FormData();
body.set("package", file);
Object.entries(fields).forEach(([key, value]) => {
if (value) body.set(key, value);
});
return fetchJson<InstallReview>(INSTALLS, {
...options,
init: { ...(options?.init ?? {}), method: "POST", body },
});
}
export function getCanvasInstall(
preparationId: string,
options?: ApiRequestOptions,
): Promise<InstallReview> {
return fetchJson<InstallReview>(`${INSTALLS}/${encodeURIComponent(preparationId)}`, options);
}
export function confirmCanvasInstall(
preparationId: string,
expectedDigest: string,
options?: ApiRequestOptions,
): Promise<InstallResult> {
return fetchJson<InstallResult>(`${INSTALLS}/${encodeURIComponent(preparationId)}/confirm`, {
...options,
init: {
...(options?.init ?? {}),
method: "POST",
body: JSON.stringify({ approved: true, expected_digest: expectedDigest }),
},
});
}
export function cancelCanvasInstall(
preparationId: string,
options?: ApiRequestOptions,
): Promise<void> {
return fetchJson<void>(`${INSTALLS}/${encodeURIComponent(preparationId)}`, {
...options,
init: { ...(options?.init ?? {}), method: "DELETE" },
});
}
@@ -79,6 +79,22 @@ describe("getMarketplaceCatalog", () => {
expect(String(url)).toBe("http://api.test/api/plugins/marketplace");
expect(result).toEqual({ plugins: [], sources: [] });
});
it("encodes the catalog kind and preserves canvas entries", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse({
plugins: [],
canvases: [entry({ id: "canvas-one", kind: "canvas" })],
sources: [],
}),
);
const result = await getMarketplaceCatalog({ kind: "canvas" });
const [url] = fetchSpy.mock.calls.at(-1) ?? [];
expect(String(url)).toBe("http://api.test/api/plugins/marketplace?kind=canvas");
expect(result.canvases?.[0].id).toBe("canvas-one");
});
});
describe("marketplace sources", () => {
+7 -1
View File
@@ -8,6 +8,7 @@ export type CatalogQuery = {
q?: string;
category?: string;
sort?: "stars" | "name" | "recent";
kind?: "plugin" | "canvas";
};
function toQueryString(query?: CatalogQuery): string {
@@ -16,6 +17,7 @@ function toQueryString(query?: CatalogQuery): string {
if (query.q) params.set("q", query.q);
if (query.category) params.set("category", query.category);
if (query.sort) params.set("sort", query.sort);
if (query.kind) params.set("kind", query.kind);
const s = params.toString();
return s ? `?${s}` : "";
}
@@ -32,7 +34,11 @@ export async function getMarketplaceCatalog(
...options,
cache: "no-store",
});
return { plugins: res.plugins ?? [], sources: res.sources ?? [] };
return {
plugins: res.plugins ?? [],
...(res.canvases ? { canvases: res.canvases } : {}),
sources: res.sources ?? [],
};
}
// listMarketplaceSources returns every configured source, built-in first
+18
View File
@@ -134,6 +134,19 @@ export interface PluginSettings {
*/
export type MarketplaceInstallState = "available" | "installed" | "update_available";
export interface MarketplacePreview {
url: string;
alt: string;
}
export interface MarketplacePermissions {
reads?: string[];
writes?: string[];
events?: string[];
shared_state?: boolean;
external_origins?: string[];
}
/**
* One plugin in the marketplace catalog: the published index entry annotated
* with the source it came from and its install state. Mirrors
@@ -141,6 +154,7 @@ export type MarketplaceInstallState = "available" | "installed" | "update_availa
*/
export interface MarketplaceEntry {
id: string;
kind?: "plugin" | "canvas";
name: string;
description: string;
author: string;
@@ -150,8 +164,11 @@ export interface MarketplaceEntry {
repo_url: string;
version: string;
min_kandev_version: string;
license?: string;
package_url: string;
package_sha256: string;
previews?: MarketplacePreview[];
permissions?: MarketplacePermissions;
/** Null when the registry couldn't read the repo's star count. */
stars: number | null;
updated_at: string;
@@ -182,6 +199,7 @@ export interface MarketplaceSource {
/** The merged, deduped catalog across all enabled sources. */
export interface MarketplaceCatalog {
plugins: MarketplaceEntry[];
canvases?: MarketplaceEntry[];
sources: MarketplaceSource[];
}
+44 -1
View File
@@ -104,5 +104,48 @@
"sourceActorSystem": "Kandev",
"sourceActorUnknown": "Unknown author",
"archivedCanvasActionHelp": "This canvas is archived. Restore it from workspace settings before changing it.",
"disabledCanvasActionHelp": "This canvas is disabled. Enable it before changing it."
"disabledCanvasActionHelp": "This canvas is disabled. Enable it before changing it.",
"shareCanvas": "Share canvas",
"shareCanvasDescription": "Prepare a verified bundle or source archive for review and sharing.",
"prepareDownloads": "Prepare downloads",
"prepareDownloadsDescription": "Kandev creates bounded archives from the selected active release. No screenshots are included in sharing.",
"downloadsReady": "Downloads are ready",
"packageId": "Package ID",
"packageVersion": "Package version",
"distributionMetadata": "Distribution metadata",
"distributionMetadataHelp": "Review and complete the package identity before downloads are prepared.",
"displayName": "Display name",
"description": "Description",
"author": "Author",
"license": "License",
"sourceMode": "Source mode",
"sourceModeStatic": "Static application",
"sourceModeProject": "Project source",
"minKandevVersion": "Minimum Kandev version",
"repositoryUrl": "Repository URL",
"fileInventory": "File inventory",
"fileCount_one": "{{count}} file",
"fileCount_other": "{{count}} files",
"bundleSize": "Bundle size",
"sourceSize": "Source size",
"downloadSize": "{{size}} bytes",
"downloadBundle": "Download bundle",
"downloadSource": "Download source",
"privateContentReminder": "Check the archive for private content before you share it.",
"howToShare": "How to share",
"shareStepDownload": "Download the bundle for installation or the source archive for review.",
"shareStepRepository": "Publish the source in a repository when you are ready to maintain it.",
"shareStepRelease": "Create a reviewed release and record its package digest.",
"shareStepSend": "Send the package or a reviewed registry entry to the intended recipients.",
"sharing": "Preparing downloads…",
"shareFailed": "The canvas downloads could not be prepared.",
"shareNoRelease": "This canvas has no valid active release to share.",
"registryExample": "Optional registry entry example",
"copyRegistryExample": "Copy registry example",
"registryExampleCopied": "Registry example copied",
"examplePackageId": "my-canvas",
"exampleRepository": "your-org/my-canvas",
"examplePreviewUrl": "https://cdn.example.com/my-canvas-cover.webp",
"examplePreviewAlt": "Canvas overview",
"yes": "Yes"
}
+49 -1
View File
@@ -132,5 +132,53 @@
"uploadFile": "Upload file",
"utilityAgentsUnavailable": "Utility agents unavailable",
"viewRaw": "View raw",
"yes": "yes"
"yes": "yes",
"tabCanvases": "Canvases",
"canvasMarketplaceDescription": "Browse reviewed canvas packages and inspect permissions before installation.",
"searchCanvases": "Search canvases…",
"selectWorkspace": "Select workspace",
"canvasesAvailable_one": "{{count}} canvas available",
"canvasesAvailable_other": "{{count}} canvases available",
"noCanvasesAvailable": "No canvases are available yet.",
"noCanvasesMatchSearch": "No canvases match your search.",
"loadingCanvasesMarketplace": "Loading canvases marketplace…",
"canvasSourceUnreachable": "{{name}} is unreachable{{detail}}; its canvases are hidden.",
"installCanvas": "Install canvas",
"backToCanvases": "Back to canvases",
"previewImages": "Preview images",
"previewImageFailed": "This preview could not be loaded.",
"retry": "Try again",
"enlargePreview": "Enlarge preview",
"previousPreview": "Previous preview",
"nextPreview": "Next preview",
"previewPosition": "Preview {{current}} of {{total}}",
"selectPreview": "Select preview {{position}}",
"license": "License",
"requiresVersion": "Requires Kandev",
"reviewAndInstall": "Review and install",
"permissions": "Permissions",
"none": "None",
"installCanvasTitle": "Install canvas",
"installCanvasDescription": "Review the package identity and permissions before it is installed in this workspace.",
"uploadBundle": "Upload bundle",
"directLink": "Direct link",
"chooseBundle": "Choose a canvas bundle",
"bundleUrlPlaceholder": "https://example.com/canvas.tar.gz",
"reviewBundle": "Review bundle",
"inspectingBundle": "Inspecting bundle…",
"packageVerified": "Package verified",
"packagePermissions": "Package permissions",
"packageId": "Package ID",
"packageDigest": "Package digest",
"archiveDigest": "Archive digest",
"source": "Source",
"destination": "Destination",
"previewInstallIndependent": "Preview images are registry metadata. They are not part of the package or its permissions.",
"confirmInstall": "Confirm installation",
"installingCanvas": "Installing canvas…",
"installedCanvas": "Canvas installed",
"openCanvas": "Open canvas",
"installFailed": "The canvas could not be installed. Review the package and try again.",
"sourceUnavailable": "The selected marketplace source is unavailable.",
"workspace": "Workspace"
}
+44 -1
View File
@@ -104,5 +104,48 @@
"sourceActorSystem": "Ķàńďēv",
"sourceActorUnknown": "Ũńķńōŵń àũţĥōŕ",
"archivedCanvasActionHelp": "Ţĥĩś ćàńvàś ĩś àŕćĥĩvēď. Ŕēśţōŕē ĩţ ƒŕōḿ ŵōŕķśƥàćē śēţţĩńĝś ƀēƒōŕē ćĥàńĝĩńĝ ĩţ.",
"disabledCanvasActionHelp": "Ţĥĩś ćàńvàś ĩś ďĩśàƀĺēď. Ēńàƀĺē ĩţ ƀēƒōŕē ćĥàńĝĩńĝ ĩţ."
"disabledCanvasActionHelp": "Ţĥĩś ćàńvàś ĩś ďĩśàƀĺēď. Ēńàƀĺē ĩţ ƀēƒōŕē ćĥàńĝĩńĝ ĩţ.",
"shareCanvas": "Śĥàŕē ćàńvàś",
"shareCanvasDescription": "Ƥŕēƥàŕē à vēŕĩƒĩēď ƀũńďĺē ōŕ śōũŕćē àŕćĥĩvē ƒōŕ ŕēvĩēŵ àńď śĥàŕĩńĝ.",
"prepareDownloads": "Ƥŕēƥàŕē ďōŵńĺōàďś",
"prepareDownloadsDescription": "Ķàńďēv ćŕēàţēś ƀōũńďēď àŕćĥĩvēś ƒŕōḿ ţĥē śēĺēćţēď àćţĩvē ŕēĺēàśē. Ńō śćŕēēńśĥōţś àŕē ĩńćĺũďēď ĩń śĥàŕĩńĝ.",
"downloadsReady": "Ďōŵńĺōàďś àŕē ŕēàďŷ",
"packageId": "Ƥàćķàĝē ĨĎ",
"packageVersion": "Ƥàćķàĝē vēŕśĩōń",
"distributionMetadata": "Ďĩśţŕĩƀũţĩōń ḿēţàďàţà",
"distributionMetadataHelp": "Ŕēvĩēŵ àńď ćōḿƥĺēţē ţĥē ƥàćķàĝē ĩďēńţĩţŷ ƀēƒōŕē ďōŵńĺōàďś àŕē ƥŕēƥàŕēď.",
"displayName": "Ďĩśƥĺàŷ ńàḿē",
"description": "Ďēśćŕĩƥţĩōń",
"author": "Àũţĥōŕ",
"license": "Ĺĩćēńśē",
"sourceMode": "Śōũŕćē ḿōďē",
"sourceModeStatic": "Śţàţĩć àƥƥĺĩćàţĩōń",
"sourceModeProject": "Ƥŕōĵēćţ śōũŕćē",
"minKandevVersion": "Ḿĩńĩḿũḿ Ķàńďēv vēŕśĩōń",
"repositoryUrl": "Ŕēƥōśĩţōŕŷ ŨŔĹ",
"fileInventory": "Ƒĩĺē ĩńvēńţōŕŷ",
"fileCount_one": "{{count}} ƒĩĺē",
"fileCount_other": "{{count}} ƒĩĺēś",
"bundleSize": "Ɓũńďĺē śĩźē",
"sourceSize": "Śōũŕćē śĩźē",
"downloadSize": "{{size}} ƀŷţēś",
"downloadBundle": "Ďōŵńĺōàď ƀũńďĺē",
"downloadSource": "Ďōŵńĺōàď śōũŕćē",
"privateContentReminder": "Ćĥēćķ ţĥē àŕćĥĩvē ƒōŕ ƥŕĩvàţē ćōńţēńţ ƀēƒōŕē ŷōũ śĥàŕē ĩţ.",
"howToShare": "Ĥōŵ ţō śĥàŕē",
"shareStepDownload": "Ďōŵńĺōàď ţĥē ƀũńďĺē ƒōŕ ĩńśţàĺĺàţĩōń ōŕ ţĥē śōũŕćē àŕćĥĩvē ƒōŕ ŕēvĩēŵ.",
"shareStepRepository": "Ƥũƀĺĩśĥ ţĥē śōũŕćē ĩń à ŕēƥōśĩţōŕŷ ŵĥēń ŷōũ àŕē ŕēàďŷ ţō ḿàĩńţàĩń ĩţ.",
"shareStepRelease": "Ćŕēàţē à ŕēvĩēŵēď ŕēĺēàśē àńď ŕēćōŕď ĩţś ƥàćķàĝē ďĩĝēśţ.",
"shareStepSend": "Śēńď ţĥē ƥàćķàĝē ōŕ à ŕēvĩēŵēď ŕēĝĩśţŕŷ ēńţŕŷ ţō ţĥē ĩńţēńďēď ŕēćĩƥĩēńţś.",
"sharing": "Ƥŕēƥàŕĩńĝ ďōŵńĺōàďś…",
"shareFailed": "Ţĥē ćàńvàś ďōŵńĺōàďś ćōũĺď ńōţ ƀē ƥŕēƥàŕēď.",
"shareNoRelease": "Ţĥĩś ćàńvàś ĥàś ńō vàĺĩď àćţĩvē ŕēĺēàśē ţō śĥàŕē.",
"registryExample": "Ōƥţĩōńàĺ ŕēĝĩśţŕŷ ēńţŕŷ ēxàḿƥĺē",
"copyRegistryExample": "Ćōƥŷ ŕēĝĩśţŕŷ ēxàḿƥĺē",
"registryExampleCopied": "Ŕēĝĩśţŕŷ ēxàḿƥĺē ćōƥĩēď",
"examplePackageId": "ḿŷ-ćàńvàś",
"exampleRepository": "ŷōũŕ-ōŕĝ/ḿŷ-ćàńvàś",
"examplePreviewUrl": "ĥţţƥś://ćďń.ēxàḿƥĺē.ćōḿ/ḿŷ-ćàńvàś-ćōvēŕ.ŵēƀƥ",
"examplePreviewAlt": "Ćàńvàś ōvēŕvĩēŵ",
"yes": "Ŷēś"
}
+49 -1
View File
@@ -132,5 +132,53 @@
"uploadFile": "Ũƥĺōàď ƒĩĺē",
"utilityAgentsUnavailable": "Ũţĩĺĩţŷ àĝēńţś ũńàvàĩĺàƀĺē",
"viewRaw": "Vĩēŵ ŕàŵ",
"yes": "ŷēś"
"yes": "ŷēś",
"tabCanvases": "Ćàńvàśēś",
"canvasMarketplaceDescription": "Ɓŕōŵśē ŕēvĩēŵēď ćàńvàś ƥàćķàĝēś àńď ĩńśƥēćţ ƥēŕḿĩśśĩōńś ƀēƒōŕē ĩńśţàĺĺàţĩōń.",
"searchCanvases": "Śēàŕćĥ ćàńvàśēś…",
"selectWorkspace": "Śēĺēćţ ŵōŕķśƥàćē",
"canvasesAvailable_one": "{{count}} ćàńvàś àvàĩĺàƀĺē",
"canvasesAvailable_other": "{{count}} ćàńvàśēś àvàĩĺàƀĺē",
"noCanvasesAvailable": "Ńō ćàńvàśēś àŕē àvàĩĺàƀĺē ŷēţ.",
"noCanvasesMatchSearch": "Ńō ćàńvàśēś ḿàţćĥ ŷōũŕ śēàŕćĥ.",
"loadingCanvasesMarketplace": "Ĺōàďĩńĝ ćàńvàśēś ḿàŕķēţƥĺàćē…",
"canvasSourceUnreachable": "{{name}} ĩś ũńŕēàćĥàƀĺē{{detail}}; ĩţś ćàńvàśēś àŕē ĥĩďďēń.",
"installCanvas": "Ĩńśţàĺĺ ćàńvàś",
"backToCanvases": "Ɓàćķ ţō ćàńvàśēś",
"previewImages": "Ƥŕēvĩēŵ ĩḿàĝēś",
"previewImageFailed": "Ţĥĩś ƥŕēvĩēŵ ćōũĺď ńōţ ƀē ĺōàďēď.",
"retry": "Ţŕŷ àĝàĩń",
"enlargePreview": "Ēńĺàŕĝē ƥŕēvĩēŵ",
"previousPreview": "Ƥŕēvĩōũś ƥŕēvĩēŵ",
"nextPreview": "Ńēxţ ƥŕēvĩēŵ",
"previewPosition": "Ƥŕēvĩēŵ {{current}} ōƒ {{total}}",
"selectPreview": "Śēĺēćţ ƥŕēvĩēŵ {{position}}",
"license": "Ĺĩćēńśē",
"requiresVersion": "Ŕēqũĩŕēś Ķàńďēv",
"reviewAndInstall": "Ŕēvĩēŵ àńď ĩńśţàĺĺ",
"permissions": "Ƥēŕḿĩśśĩōńś",
"none": "Ńōńē",
"installCanvasTitle": "Ĩńśţàĺĺ ćàńvàś",
"installCanvasDescription": "Ŕēvĩēŵ ţĥē ƥàćķàĝē ĩďēńţĩţŷ àńď ƥēŕḿĩśśĩōńś ƀēƒōŕē ĩţ ĩś ĩńśţàĺĺēď ĩń ţĥĩś ŵōŕķśƥàćē.",
"uploadBundle": "Ũƥĺōàď ƀũńďĺē",
"directLink": "Ďĩŕēćţ ĺĩńķ",
"chooseBundle": "Ćĥōōśē à ćàńvàś ƀũńďĺē",
"bundleUrlPlaceholder": "ĥţţƥś://ēxàḿƥĺē.ćōḿ/ćàńvàś.ţàŕ.ĝź",
"reviewBundle": "Ŕēvĩēŵ ƀũńďĺē",
"inspectingBundle": "Ĩńśƥēćţĩńĝ ƀũńďĺē…",
"packageVerified": "Ƥàćķàĝē vēŕĩƒĩēď",
"packagePermissions": "Ƥàćķàĝē ƥēŕḿĩśśĩōńś",
"packageId": "Ƥàćķàĝē ĨĎ",
"packageDigest": "Ƥàćķàĝē ďĩĝēśţ",
"archiveDigest": "Àŕćĥĩvē ďĩĝēśţ",
"source": "Śōũŕćē",
"destination": "Ďēśţĩńàţĩōń",
"previewInstallIndependent": "Ƥŕēvĩēŵ ĩḿàĝēś àŕē ŕēĝĩśţŕŷ ḿēţàďàţà. Ţĥēŷ àŕē ńōţ ƥàŕţ ōƒ ţĥē ƥàćķàĝē ōŕ ĩţś ƥēŕḿĩśśĩōńś.",
"confirmInstall": "Ćōńƒĩŕḿ ĩńśţàĺĺàţĩōń",
"installingCanvas": "Ĩńśţàĺĺĩńĝ ćàńvàś…",
"installedCanvas": "Ćàńvàś ĩńśţàĺĺēď",
"openCanvas": "Ōƥēń ćàńvàś",
"installFailed": "Ţĥē ćàńvàś ćōũĺď ńōţ ƀē ĩńśţàĺĺēď. Ŕēvĩēŵ ţĥē ƥàćķàĝē àńď ţŕŷ àĝàĩń.",
"sourceUnavailable": "Ţĥē śēĺēćţēď ḿàŕķēţƥĺàćē śōũŕćē ĩś ũńàvàĩĺàƀĺē.",
"workspace": "Ŵōŕķśƥàćē"
}
+44 -1
View File
@@ -104,5 +104,48 @@
"sourceActorSystem": "Kandev",
"sourceActorUnknown": "Autor desconhecido",
"archivedCanvasActionHelp": "Este canvas está arquivado. Restaura-o nas definições da área de trabalho antes de o alterar.",
"disabledCanvasActionHelp": "Este canvas está desativado. Ativa-o antes de o alterar."
"disabledCanvasActionHelp": "Este canvas está desativado. Ativa-o antes de o alterar.",
"shareCanvas": "Partilhar canvas",
"shareCanvasDescription": "Prepare um pacote ou arquivo de origem verificado para revisão e partilha.",
"prepareDownloads": "Preparar transferências",
"prepareDownloadsDescription": "O Kandev cria arquivos limitados a partir da versão ativa selecionada. A partilha não inclui imagens de pré-visualização.",
"downloadsReady": "Transferências prontas",
"packageId": "ID do pacote",
"packageVersion": "Versão do pacote",
"distributionMetadata": "Metadados de distribuição",
"distributionMetadataHelp": "Reveja e complete a identidade do pacote antes de preparar as transferências.",
"displayName": "Nome de apresentação",
"description": "Descrição",
"author": "Autor",
"license": "Licença",
"sourceMode": "Modo de origem",
"sourceModeStatic": "Aplicação estática",
"sourceModeProject": "Código-fonte do projeto",
"minKandevVersion": "Versão mínima do Kandev",
"repositoryUrl": "URL do repositório",
"fileInventory": "Inventário de ficheiros",
"fileCount_one": "{{count}} ficheiro",
"fileCount_other": "{{count}} ficheiros",
"bundleSize": "Tamanho do pacote",
"sourceSize": "Tamanho da origem",
"downloadSize": "{{size}} octetos",
"downloadBundle": "Transferir pacote",
"downloadSource": "Transferir origem",
"privateContentReminder": "Verifique se o arquivo contém conteúdo privado antes de o partilhar.",
"howToShare": "Como partilhar",
"shareStepDownload": "Transfira o pacote para instalação ou o arquivo de origem para revisão.",
"shareStepRepository": "Publique a origem num repositório quando estiver pronto para a manter.",
"shareStepRelease": "Crie uma versão revista e registe o digest do pacote.",
"shareStepSend": "Envie o pacote ou uma entrada de registry revista aos destinatários pretendidos.",
"sharing": "A preparar transferências…",
"shareFailed": "Não foi possível preparar as transferências do canvas.",
"shareNoRelease": "Este canvas não tem uma versão ativa válida para partilhar.",
"registryExample": "Exemplo opcional de entrada do registry",
"copyRegistryExample": "Copiar exemplo do registry",
"registryExampleCopied": "Exemplo do registry copiado",
"examplePackageId": "o-meu-canvas",
"exampleRepository": "a-sua-org/o-meu-canvas",
"examplePreviewUrl": "https://cdn.exemplo.pt/o-meu-canvas-capa.webp",
"examplePreviewAlt": "Visão geral do canvas",
"yes": "Sim"
}
+49 -1
View File
@@ -132,5 +132,53 @@
"utilityAgentsUnavailable": "Agentes utilitários indisponíveis",
"viewRaw": "Ver o original",
"yes": "sim",
"pluginDialog": "Janela do plugin"
"pluginDialog": "Janela do plugin",
"tabCanvases": "Canvas",
"canvasMarketplaceDescription": "Explore pacotes de canvas revistos e analise as permissões antes da instalação.",
"searchCanvases": "Pesquisar canvas…",
"selectWorkspace": "Selecionar workspace",
"canvasesAvailable_one": "{{count}} canvas disponível",
"canvasesAvailable_other": "{{count}} canvas disponíveis",
"noCanvasesAvailable": "Ainda não existem canvas disponíveis.",
"noCanvasesMatchSearch": "Nenhum canvas corresponde à pesquisa.",
"loadingCanvasesMarketplace": "A carregar o marketplace de canvas…",
"canvasSourceUnreachable": "Não é possível aceder a {{name}}{{detail}}; os seus canvas estão ocultos.",
"installCanvas": "Instalar canvas",
"backToCanvases": "Voltar aos canvas",
"previewImages": "Imagens de pré-visualização",
"previewImageFailed": "Não foi possível carregar esta pré-visualização.",
"retry": "Tentar novamente",
"enlargePreview": "Ampliar pré-visualização",
"previousPreview": "Pré-visualização anterior",
"nextPreview": "Próxima pré-visualização",
"previewPosition": "Pré-visualização {{current}} de {{total}}",
"selectPreview": "Selecionar pré-visualização {{position}}",
"license": "Licença",
"requiresVersion": "Requer Kandev",
"reviewAndInstall": "Rever e instalar",
"permissions": "Permissões",
"none": "Nenhuma",
"installCanvasTitle": "Instalar canvas",
"installCanvasDescription": "Reveja a identidade e as permissões do pacote antes de o instalar neste workspace.",
"uploadBundle": "Carregar pacote",
"directLink": "Ligação direta",
"chooseBundle": "Escolher um pacote de canvas",
"bundleUrlPlaceholder": "https://exemplo.pt/canvas.tar.gz",
"reviewBundle": "Rever pacote",
"inspectingBundle": "A analisar o pacote…",
"packageVerified": "Pacote verificado",
"packagePermissions": "Permissões do pacote",
"packageId": "ID do pacote",
"packageDigest": "Digest do pacote",
"archiveDigest": "Digest do arquivo",
"source": "Origem",
"destination": "Destino",
"previewInstallIndependent": "As imagens de pré-visualização são metadados do registry. Não fazem parte do pacote nem das suas permissões.",
"confirmInstall": "Confirmar instalação",
"installingCanvas": "A instalar o canvas…",
"installedCanvas": "Canvas instalado",
"openCanvas": "Abrir canvas",
"installFailed": "Não foi possível instalar o canvas. Reveja o pacote e tente novamente.",
"sourceUnavailable": "A origem de marketplace selecionada não está disponível.",
"workspace": "Área de trabalho"
}
+44 -1
View File
@@ -104,5 +104,48 @@
"sourceActorSystem": "Kandev",
"sourceActorUnknown": "未知作者",
"archivedCanvasActionHelp": "此画布已归档。请先在工作区设置中恢复它,然后再进行更改。",
"disabledCanvasActionHelp": "此画布已禁用。请先启用它,然后再进行更改。"
"disabledCanvasActionHelp": "此画布已禁用。请先启用它,然后再进行更改。",
"shareCanvas": "分享画布",
"shareCanvasDescription": "准备经过验证的包或源代码归档,以便审核和分享。",
"prepareDownloads": "准备下载",
"prepareDownloadsDescription": "Kandev 从选定的活动版本创建有大小限制的归档。分享时不包含预览图片。",
"downloadsReady": "下载已准备好",
"packageId": "包 ID",
"packageVersion": "包版本",
"distributionMetadata": "分发元数据",
"distributionMetadataHelp": "准备下载前,请检查并补充包身份信息。",
"displayName": "显示名称",
"description": "描述",
"author": "作者",
"license": "许可证",
"sourceMode": "源模式",
"sourceModeStatic": "静态应用",
"sourceModeProject": "项目源代码",
"minKandevVersion": "最低 Kandev 版本",
"repositoryUrl": "代码仓库 URL",
"fileInventory": "文件清单",
"fileCount_one": "{{count}} 个文件",
"fileCount_other": "{{count}} 个文件",
"bundleSize": "包大小",
"sourceSize": "源代码大小",
"downloadSize": "{{size}} 字节",
"downloadBundle": "下载包",
"downloadSource": "下载源代码",
"privateContentReminder": "分享前请检查归档中是否包含私人内容。",
"howToShare": "如何分享",
"shareStepDownload": "下载用于安装的包,或下载用于审核的源代码归档。",
"shareStepRepository": "准备维护源代码时,将其发布到代码仓库。",
"shareStepRelease": "创建经过审核的版本并记录其包摘要。",
"shareStepSend": "将包或经过审核的 registry 条目发送给指定接收者。",
"sharing": "正在准备下载…",
"shareFailed": "无法准备画布下载。",
"shareNoRelease": "此画布没有可分享的有效活动版本。",
"registryExample": "可选的 registry 条目示例",
"copyRegistryExample": "复制 registry 示例",
"registryExampleCopied": "已复制 registry 示例",
"examplePackageId": "我的画布",
"exampleRepository": "你的组织/我的画布",
"examplePreviewUrl": "https://cdn.example.cn/my-canvas-cover.webp",
"examplePreviewAlt": "画布概览",
"yes": "是"
}
+49 -1
View File
@@ -132,5 +132,53 @@
"utilityAgentsUnavailable": "辅助智能体不可用",
"viewRaw": "查看原始内容",
"yes": "是",
"pluginDialog": "插件对话框"
"pluginDialog": "插件对话框",
"tabCanvases": "画布",
"canvasMarketplaceDescription": "浏览经过审核的画布包,并在安装前查看权限。",
"searchCanvases": "搜索画布…",
"selectWorkspace": "选择工作区",
"canvasesAvailable_one": "有 {{count}} 个画布",
"canvasesAvailable_other": "有 {{count}} 个画布",
"noCanvasesAvailable": "暂时没有可用的画布。",
"noCanvasesMatchSearch": "没有画布符合搜索条件。",
"loadingCanvasesMarketplace": "正在加载画布市场…",
"canvasSourceUnreachable": "无法访问 {{name}}{{detail}};其画布已隐藏。",
"installCanvas": "安装画布",
"backToCanvases": "返回画布",
"previewImages": "预览图片",
"previewImageFailed": "无法加载此预览。",
"retry": "重试",
"enlargePreview": "放大预览",
"previousPreview": "上一个预览",
"nextPreview": "下一个预览",
"previewPosition": "第 {{current}} 个预览,共 {{total}} 个",
"selectPreview": "选择第 {{position}} 个预览",
"license": "许可证",
"requiresVersion": "需要 Kandev",
"reviewAndInstall": "查看并安装",
"permissions": "权限",
"none": "无",
"installCanvasTitle": "安装画布",
"installCanvasDescription": "安装到此工作区前,请查看包的身份和权限。",
"uploadBundle": "上传包",
"directLink": "直接链接",
"chooseBundle": "选择画布包",
"bundleUrlPlaceholder": "https://example.cn/canvas.tar.gz",
"reviewBundle": "查看包",
"inspectingBundle": "正在检查包…",
"packageVerified": "包已验证",
"packagePermissions": "包权限",
"packageId": "包 ID",
"packageDigest": "包摘要",
"archiveDigest": "归档摘要",
"source": "来源",
"destination": "目标位置",
"previewInstallIndependent": "预览图片是 registry 元数据,不属于包或其权限。",
"confirmInstall": "确认安装",
"installingCanvas": "正在安装画布…",
"installedCanvas": "画布已安装",
"openCanvas": "打开画布",
"installFailed": "无法安装画布。请查看包后重试。",
"sourceUnavailable": "所选市场来源不可用。",
"workspace": "工作区"
}
+44 -1
View File
@@ -104,5 +104,48 @@
"sourceActorSystem": "Kandev",
"sourceActorUnknown": "未知作者",
"archivedCanvasActionHelp": "此畫布已歸檔。請先在工作區設定中恢復它,然後再進行更改。",
"disabledCanvasActionHelp": "此畫布已停用。請先啟用它,然後再進行更改。"
"disabledCanvasActionHelp": "此畫布已停用。請先啟用它,然後再進行更改。",
"shareCanvas": "分享畫布",
"shareCanvasDescription": "準備經過驗證的包或原始碼歸檔,以便審核和分享。",
"prepareDownloads": "準備下載",
"prepareDownloadsDescription": "Kandev 從選定的活動版本建立有大小限制的歸檔。分享時不包含預覽圖片。",
"downloadsReady": "下載已準備好",
"packageId": "包 ID",
"packageVersion": "包版本",
"distributionMetadata": "分發元數據",
"distributionMetadataHelp": "準備下載前,請檢查並補充包身份資訊。",
"displayName": "顯示名稱",
"description": "描述",
"author": "作者",
"license": "許可證",
"sourceMode": "源模式",
"sourceModeStatic": "靜態應用",
"sourceModeProject": "項目原始碼",
"minKandevVersion": "最低 Kandev 版本",
"repositoryUrl": "程式碼儲存庫 URL",
"fileInventory": "檔案清單",
"fileCount_one": "{{count}} 個檔案",
"fileCount_other": "{{count}} 個檔案",
"bundleSize": "包大小",
"sourceSize": "原始碼大小",
"downloadSize": "{{size}} 字節",
"downloadBundle": "下載包",
"downloadSource": "下載原始碼",
"privateContentReminder": "分享前請檢查歸檔中是否包含私人內容。",
"howToShare": "如何分享",
"shareStepDownload": "下載用於安裝的包,或下載用於審核的原始碼歸檔。",
"shareStepRepository": "準備維護原始碼時,將其發佈到程式碼儲存庫。",
"shareStepRelease": "建立經過審核的版本並記錄其包摘要。",
"shareStepSend": "將包或經過審核的 registry 條目傳送給指定接收者。",
"sharing": "正在準備下載…",
"shareFailed": "無法準備畫布下載。",
"shareNoRelease": "此畫布沒有可分享的有效活動版本。",
"registryExample": "可選的 registry 條目示例",
"copyRegistryExample": "複製 registry 示例",
"registryExampleCopied": "已複製 registry 示例",
"examplePackageId": "我的畫布",
"exampleRepository": "你的組織/我的畫布",
"examplePreviewUrl": "https://cdn.example.cn/my-canvas-cover.webp",
"examplePreviewAlt": "畫布概覽",
"yes": "是"
}
+49 -1
View File
@@ -132,5 +132,53 @@
"utilityAgentsUnavailable": "輔助代理程式不可用",
"viewRaw": "查看原始內容",
"yes": "是",
"pluginDialog": "外掛程式對話框"
"pluginDialog": "外掛程式對話框",
"tabCanvases": "畫布",
"canvasMarketplaceDescription": "瀏覽經過審核的畫布包,並在安裝前查看權限。",
"searchCanvases": "搜尋畫布…",
"selectWorkspace": "選擇工作區",
"canvasesAvailable_one": "有 {{count}} 個畫布",
"canvasesAvailable_other": "有 {{count}} 個畫布",
"noCanvasesAvailable": "暫時沒有可用的畫布。",
"noCanvasesMatchSearch": "沒有畫布符合搜尋條件。",
"loadingCanvasesMarketplace": "正在載入畫布市場…",
"canvasSourceUnreachable": "無法存取 {{name}}{{detail}};其畫布已隱藏。",
"installCanvas": "安裝畫布",
"backToCanvases": "返回畫布",
"previewImages": "預覽圖片",
"previewImageFailed": "無法載入此預覽。",
"retry": "重試",
"enlargePreview": "放大預覽",
"previousPreview": "上一個預覽",
"nextPreview": "下一個預覽",
"previewPosition": "第 {{current}} 個預覽,共 {{total}} 個",
"selectPreview": "選擇第 {{position}} 個預覽",
"license": "許可證",
"requiresVersion": "需要 Kandev",
"reviewAndInstall": "查看並安裝",
"permissions": "權限",
"none": "無",
"installCanvasTitle": "安裝畫布",
"installCanvasDescription": "安裝到此工作區前,請查看包的身份和權限。",
"uploadBundle": "上傳包",
"directLink": "直接連結",
"chooseBundle": "選擇畫布包",
"bundleUrlPlaceholder": "https://example.cn/canvas.tar.gz",
"reviewBundle": "查看包",
"inspectingBundle": "正在檢查包…",
"packageVerified": "包已驗證",
"packagePermissions": "包權限",
"packageId": "包 ID",
"packageDigest": "包摘要",
"archiveDigest": "歸檔摘要",
"source": "來源",
"destination": "目標位置",
"previewInstallIndependent": "預覽圖片是 registry 元數據,不屬於包或其權限。",
"confirmInstall": "確認安裝",
"installingCanvas": "正在安裝畫布…",
"installedCanvas": "畫布已安裝",
"openCanvas": "開啟畫布",
"installFailed": "無法安裝畫布。請查看包後重試。",
"sourceUnavailable": "所選市場來源不可用。",
"workspace": "工作區"
}
+44 -1
View File
@@ -104,5 +104,48 @@
"sourceActorSystem": "Kandev",
"sourceActorUnknown": "未知作者",
"archivedCanvasActionHelp": "此畫布已歸檔。請先在工作區設定中恢復它,然後再進行更改。",
"disabledCanvasActionHelp": "此畫布已停用。請先啟用它,然後再進行更改。"
"disabledCanvasActionHelp": "此畫布已停用。請先啟用它,然後再進行更改。",
"shareCanvas": "分享畫布",
"shareCanvasDescription": "準備經過驗證的包或原始碼歸檔,以便稽核和分享。",
"prepareDownloads": "準備下載",
"prepareDownloadsDescription": "Kandev 從選定的活動版本建立有大小限制的歸檔。分享時不包含預覽圖片。",
"downloadsReady": "下載已準備好",
"packageId": "包 ID",
"packageVersion": "包版本",
"distributionMetadata": "分發後設資料",
"distributionMetadataHelp": "準備下載前,請檢查並補充包身分資訊。",
"displayName": "顯示名稱",
"description": "描述",
"author": "作者",
"license": "許可證",
"sourceMode": "源模式",
"sourceModeStatic": "靜態應用",
"sourceModeProject": "專案原始碼",
"minKandevVersion": "最低 Kandev 版本",
"repositoryUrl": "程式碼儲存庫 URL",
"fileInventory": "檔案清單",
"fileCount_one": "{{count}} 個檔案",
"fileCount_other": "{{count}} 個檔案",
"bundleSize": "包大小",
"sourceSize": "原始碼大小",
"downloadSize": "{{size}} 位元組",
"downloadBundle": "下載包",
"downloadSource": "下載原始碼",
"privateContentReminder": "分享前請檢查歸檔中是否包含私人內容。",
"howToShare": "如何分享",
"shareStepDownload": "下載用於安裝的包,或下載用於稽核的原始碼歸檔。",
"shareStepRepository": "準備維護原始碼時,將其釋出到程式碼儲存庫。",
"shareStepRelease": "建立經過稽核的版本並記錄其包摘要。",
"shareStepSend": "將包或經過稽核的 registry 條目傳送給指定接收者。",
"sharing": "正在準備下載…",
"shareFailed": "無法準備畫布下載。",
"shareNoRelease": "此畫布沒有可分享的有效活動版本。",
"registryExample": "可選的 registry 條目示例",
"copyRegistryExample": "複製 registry 示例",
"registryExampleCopied": "已複製 registry 示例",
"examplePackageId": "我的畫布",
"exampleRepository": "你的組織/我的畫布",
"examplePreviewUrl": "https://cdn.example.cn/my-canvas-cover.webp",
"examplePreviewAlt": "畫布概覽",
"yes": "是"
}
+49 -1
View File
@@ -132,5 +132,53 @@
"utilityAgentsUnavailable": "輔助代理程式不可用",
"viewRaw": "檢視原始內容",
"yes": "是",
"pluginDialog": "外掛對話方塊"
"pluginDialog": "外掛對話方塊",
"tabCanvases": "畫布",
"canvasMarketplaceDescription": "瀏覽經過稽核的畫布包,並在安裝前檢視權限。",
"searchCanvases": "搜尋畫布…",
"selectWorkspace": "選擇工作區",
"canvasesAvailable_one": "有 {{count}} 個畫布",
"canvasesAvailable_other": "有 {{count}} 個畫布",
"noCanvasesAvailable": "暫時沒有可用的畫布。",
"noCanvasesMatchSearch": "沒有畫布符合搜尋條件。",
"loadingCanvasesMarketplace": "正在載入畫布市場…",
"canvasSourceUnreachable": "無法存取 {{name}}{{detail}};其畫布已隱藏。",
"installCanvas": "安裝畫布",
"backToCanvases": "返回畫布",
"previewImages": "預覽圖片",
"previewImageFailed": "無法載入此預覽。",
"retry": "重試",
"enlargePreview": "放大預覽",
"previousPreview": "上一個預覽",
"nextPreview": "下一個預覽",
"previewPosition": "第 {{current}} 個預覽,共 {{total}} 個",
"selectPreview": "選擇第 {{position}} 個預覽",
"license": "許可證",
"requiresVersion": "需要 Kandev",
"reviewAndInstall": "檢視並安裝",
"permissions": "權限",
"none": "無",
"installCanvasTitle": "安裝畫布",
"installCanvasDescription": "安裝到此工作區前,請檢視包的身分和權限。",
"uploadBundle": "上傳包",
"directLink": "直接連結",
"chooseBundle": "選擇畫布包",
"bundleUrlPlaceholder": "https://example.cn/canvas.tar.gz",
"reviewBundle": "檢視包",
"inspectingBundle": "正在檢查包…",
"packageVerified": "包已驗證",
"packagePermissions": "包權限",
"packageId": "包 ID",
"packageDigest": "包摘要",
"archiveDigest": "歸檔摘要",
"source": "來源",
"destination": "目標位置",
"previewInstallIndependent": "預覽圖片是 registry 後設資料,不屬於包或其權限。",
"confirmInstall": "確認安裝",
"installingCanvas": "正在安裝畫布…",
"installedCanvas": "畫布已安裝",
"openCanvas": "開啟畫布",
"installFailed": "無法安裝畫布。請檢視包後重試。",
"sourceUnavailable": "所選市場來源不可用。",
"workspace": "工作區"
}
@@ -0,0 +1,30 @@
---
created: 2026-09-14
status: done
requirements:
- REQ-PLUGINS-MARKETPLACE-002
system_design:
- ../../specs/plugins/system-design/marketplace.md
legacy_specs: []
---
# Implementation plan: Plugin marketplace previews
Extend the existing native-plugin marketplace with optional registry-owned
preview galleries while preserving legacy entries and the current installation
path. The canvas marketplace plan consumes the same registry and gallery
primitives, but the plugin requirement remains owned by this package.
## Scope
- Ordered optional preview metadata for official and custom plugin listings.
- Cover and details gallery behavior with keyboard, touch, and image failures.
- Existing no-preview rows and native install actions.
- Plugin marketplace, manifest, authoring, and registry README guidance.
## Work orders
- [ ] [Task 01: Extend plugin marketplace previews](task-01-plugin-previews.md)
Dependencies: 01. The single work order keeps the plugin requirement and its
system design in one lookup scope for documentation validation.
@@ -0,0 +1,115 @@
---
id: "01-plugin-previews"
title: "Extend plugin marketplace previews"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-PLUGINS-MARKETPLACE-002
acceptance_criteria:
- AC-PLUGINS-MARKETPLACE-002.1
- AC-PLUGINS-MARKETPLACE-002.2
- AC-PLUGINS-MARKETPLACE-002.3
- AC-PLUGINS-MARKETPLACE-002.4
system_design:
- ../../specs/plugins/system-design/marketplace.md
---
# Task 01: Extend plugin marketplace previews
## Summary
Complete the optional native-plugin preview extension that shares the registry
metadata and gallery primitives used by canvas entries. Keep preview metadata
outside plugin packages and preserve the existing native installation path.
## In scope
- Ordered optional `previews: [{url, alt}]` fields for official and custom
plugin registry entries and generated catalog records.
- First-image cover presentation, details gallery, keyboard and touch controls,
image-position descriptions, one-image mode, and contained image failures.
- Existing plugin rows and install actions when a listing has no previews.
- Registry-owned preview metadata, so URLs, descriptions, and order can change
without releasing a plugin version.
- Shared gallery tests and native-plugin marketplace regression coverage.
- Public plugin marketplace and manifest guidance, the linked authoring guide,
and plugin registry README examples.
## Out of scope
Canvas package validation, canvas installation review, screenshot requirements
for bundle creation, native plugin package changes, and a new installation path.
## Acceptance
- Official and custom plugin entries accept an ordered HTTPS preview list while
existing entries without previews remain valid.
- Listings with previews show the first image as the cover and expose the full
gallery; listings without previews keep their current row and install action.
- Gallery navigation works with keyboard and touch, retains installation when an
image fails, and never executes package code in the preview.
- Preview metadata remains registry-owned and can change independently of plugin
package releases.
## Verification
```bash
rtk bash -lc 'KANDEV_CANVAS_PACKAGE_INSPECTOR=apps/backend/bin/canvas-package node --test plugin-registry/build-index.test.mjs'
(cd apps/web && rtk pnpm exec vitest run components/settings/plugins/marketplace-preview-gallery.test.tsx components/settings/plugins/plugin-row.test.tsx)
(cd apps/web && rtk pnpm e2e:run --project chromium tests/plugins/plugins.spec.ts -- --retries=0)
(cd apps/web && rtk pnpm e2e:run --project mobile-chrome tests/plugins/mobile-plugin-settings-row.spec.ts -- --retries=0)
rtk proxy node --test scripts/validate-public-docs.test.mjs
rtk git diff --check -- docs/public/plugins-marketplace.md docs/public/plugins-manifest.md docs/public/plugins-authoring.md plugin-registry/README.md
```
Use local fixtures and the built inspector. Do not publish a registry entry or
execute a plugin while testing preview details.
## Files likely touched
- `plugin-registry/schema.json`, `build-index.mjs`, and `build-index.test.mjs`
- `apps/web/components/settings/plugins/marketplace-preview-gallery.tsx`
- Existing plugin row/details components and their focused tests
- `apps/web/components/settings/plugins/plugins-settings.tsx`
- `apps/web/lib/api/domains/marketplace-api.ts` and marketplace hooks/tests
- `apps/web/src/locales/{en,pt-pt,zh-cn,zh-hk,zh-tw,pseudo}/`
- `docs/public/plugins-marketplace.md`
- `docs/public/plugins-manifest.md`
- `docs/public/plugins-authoring.md`
- `plugin-registry/README.md`
## Dependencies
The canvas marketplace plan provides the shared registry and gallery primitives;
the plugin contract remains independently traceable to the plugin design.
## Risks
Do not make previews part of a plugin manifest or release archive. Remote image
failures must not block native installation, and the details surface must never
load a runtime URL or execute package code.
## Parallelism
`sequential`
## Inputs
- Plugin marketplace requirements and the registry preview system design.
- Existing `buildEntry`, `build-index.test.mjs`, plugin rows, and native install
dialog.
- Shared marketplace gallery behavior and the plugin documentation validation
guide.
## Results
Implemented optional ordered plugin previews in registry and catalog records,
shared gallery details with keyboard and touch controls, image-failure fallback,
and unchanged native installation for entries without previews. Updated the
plugin marketplace, manifest, authoring, and registry README guidance.
Verification: the existing plugin marketplace regression passed 16 tests; the
registry build-index suite and shared gallery coverage passed with the canvas
marketplace validation; public documentation validation and diff checks passed.
+446
View File
@@ -0,0 +1,446 @@
---
created: 2026-09-10
status: done
requirements:
- REQ-CANVASES-MARKETPLACE-001
- REQ-CANVASES-MARKETPLACE-002
- REQ-CANVASES-MARKETPLACE-003
- REQ-CANVASES-MARKETPLACE-004
- REQ-CANVASES-MARKETPLACE-005
- REQ-CANVASES-MARKETPLACE-006
system_design:
- ../../specs/canvases/system-design/marketplace-sharing.md
legacy_specs: []
---
# Implementation plan: Canvas marketplace
## Overview
Add canvas distribution to the existing Plugins marketplace. Authors download
an installable bundle and source project, then follow manual repository and
registry instructions. Recipients inspect screenshots and permissions before
installing an independent workspace canvas.
The [requirements](../../specs/canvases/requirements/marketplace-sharing.md) and
[design](../../specs/canvases/system-design/marketplace-sharing.md) are the
authoritative pair. The selected owner is Canvases because it owns reusable
canvas identity, source lineage, workspace instances, and discovery.
Implementation is complete across the seven sequential work orders: portable
package contract, export preparation, reviewed installation, registry
enrichment, marketplace UI, sharing UI, and public instructions. The optional
native-plugin preview extension is tracked in the companion plugin plan. No native
implementation subagents were authorized by this plan. Each work order's
Results section records its implementation and validation evidence.
## Scope
### In scope
- One existing marketplace with a dedicated Canvases tab in Plugins settings.
- `.tar.gz` upload, direct HTTPS bundle link, and catalog installation.
- Required registry cover URL and up to seven additional previews for canvases.
- Registry cover and preview URLs for canvas entries.
- Screenshot-free bundle creation, source downloads, and upload/link installs.
- Package metadata, source mode, license, compatibility, and permission review.
- Download bundle and source ZIP from the same prepared release snapshot.
- Manual repository/release/sharing instructions and PR-based registry listing.
- Independent workspace copies, durable provenance, retry-safe confirmation.
- Static runtime isolation, workspace authorization, quotas, and disabled paths.
- Desktop and phone UI, localization, targeted E2E, author/public documentation.
### Out of scope
- Repository-URL installation, cloning, builds during install, or new hosting.
- Automated code-host publishing, repository creation, or registry PR submission.
- Canvas updates/replacement, state export, credentials, or public live instances.
- Screenshot capture, ratings, payments, telemetry, and a standalone website.
- Runtime toggle promotion, new flags, or native binary canvas execution.
## Baseline and companion plans
The `plugin-backed-canvases` package is marked done. The UX follow-up records
Tasks 01-06 complete and Task 07's external ACP evaluation outstanding.
This plan extends their source-retention and discovery boundaries; it does not
reopen their completed work or change their historical verification results.
Implementation must preserve the one-core-read authoring contract. The external
ACP evaluation is not an additional delivery gate for this feature.
## Technical approach
### Portable package boundary
Extend `internal/plugins/manifest` with optional typed distribution metadata.
Extend `internal/plugins/webapp` with strict distribution validation, checksum
coverage, source-only file retention, and safe
export writers. `Runtime.Serve` denies `distribution/` files. The native
`pkgtar` installer stays unchanged. Add `cmd/canvas-package` for offline
inspection through the production validator; the registry builder uses this
command instead of implementing a second parser.
No-build source remains the current application files. Build-based source is
retained under `distribution/source/` in the same immutable release. Extend
authoring collection and Quick Chat materialization to preserve that subtree.
### Export and installation boundary
Add a small canvas distribution service with expiring, bounded, user-bound
preparations. Export reads the immutable active artifact and derives both
downloads without touching the executor or changing the active release.
Installation stages one inspected package and approves those exact bytes.
Add `InstallPrepared` through the canvas/instance transaction boundary and one
`canvas_install_receipts` table. The receipt preserves provenance and prevents
duplicate confirmation after timeout/restart. Reuse artifact cleanup,
workspace admission, grants, and lifecycle invalidations. Native plugin
registry records and its auto-update poller do not contain canvas instances.
New browser routes live beside `backendapp/canvas_routes.go` in focused files.
Authorize human workspace access at service boundaries; server-side URL fetch
uses bounded, public-destination-only transport. Tests inject a local transport.
### Registry and catalog boundary
Add optional `kind: canvas` to the existing pointer schema. The builder fetches
the exact versioned bundle, inspects it, and requires its archive digest.
Preview URLs come from the registry and pass unchanged into the generated index.
Use the proposed [registry schema](registry-entry.schema.json) for canvas entries;
there is no image extraction, mirroring, or Pages media staging. Use additive catalog
fields and kind filtering. Instance annotations are workspace-authorized and
must not enter the shared source cache. Old native entries keep their behavior.
### UI boundary
`PluginsSettings` adds Canvases alongside Installed and Browse. Add domain hooks
and a typed canvas-distribution API client; reuse existing gallery/dialog,
permission summary, upload, and settings primitives where they fit. Details
and review derive from one shared model across viewports. Share is host-owned,
available from the task/workspace canvas and workspace rows. All copy uses the
five real locales and generated Traditional Chinese/pseudo catalogs.
## ASCII UI preview
All views below are proposed. Structure, action order, permissions before
confirmation, explicit image controls, and separate phone composition are
requirements. Names, image proportions, and spacing are illustrative.
### UI-01: Canvas catalog
Entry: Settings > Plugins > Canvases, or Browse shared canvases from a workspace.
Maps to AC-CANVASES-MARKETPLACE-004.1, 005.2, 005.4, 006.1, and 006.2.
```text
Desktop
+-------------------------------------------------------------------+
| Plugins |
| Installed | Browse | CANVASES |
| Workspace [Project A v] Search [____________] Sort [Recent v] |
| [Install canvas] |
| +----------------------+ +----------------------+ |
| | [cover screenshot] | | [cover screenshot] | |
| | Sprint board 1.0.0 | | Release viewer | |
| | by example-author | | by contributor | |
| | Description... | | Description... | |
| | [View details] | | 2 copies [Open v] | |
| +----------------------+ +----------------------+ |
+-------------------------------------------------------------------+
Phone
+------------------------------+
| Plugins |
| Installed | Browse | Canvases |
| Workspace [Project A v] |
| Search [_____________] |
| Sort [Recent v] |
| [Install canvas] |
| +--------------------------+ |
| | [cover screenshot] | |
| | Sprint board / author | |
| | Description... | |
| | [View details] | |
| +--------------------------+ |
+------------------------------+
```
Cards open details by pointer, keyboard, or tap. One page scroll owns the list.
Empty: explain no matching canvases, retain search and Install canvas. Failed
source: inline source warning plus Retry; healthy results remain visible.
Loading: skeleton covers with a status announcement. Gate-off: no Canvases tab.
### UI-02: Canvas details and install review
Use "Preview images" as the gallery label for canvas details.
Entry: catalog card or inspected upload/link. Maps to
AC-CANVASES-MARKETPLACE-002.3, 004.2-004.6, 005.3, and 006.1-006.3.
```text
Desktop details
+-------------------------------------------------------------------+
| [Back to canvases] Sprint board 1.0.0 [Close] |
| +--------------------------------+ by example-author |
| | | Description |
| | [selected image] | License: MIT [Repository] |
| | | Requires Kandev ... |
| +--------------------------------+ |
| [Previous] 1 / 3 [Next] [thumb 1] [thumb 2] [thumb 3] |
| Permissions |
| Read: tasks, workflows Write: none |
| Events: none State: none Network: none |
| Workspace [Project A v] [Review & install] |
+-------------------------------------------------------------------+
Phone details / final review
+------------------------------+
| [Back] Sprint board | fixed
| 1.0.0 / by example-author |
| [selected image] |
| [Previous] 1 / 3 [Next] |
| Description, license, repo | one scrolling body
| Permissions |
| Read: tasks, workflows |
| Write: none |
| Events / State / Network |
| Workspace [Project A v] |
| Package verified / version |
|------------------------------|
| [Install in Project A] | fixed, safe-area footer
+------------------------------+
Upload/direct-link entry (shared order)
+-------------------------------------+
| Install canvas |
| Upload bundle | Direct link |
| [Choose .tar.gz file] |
| Workspace [Project A v] |
| [Cancel] [Review bundle] |
+-------------------------------------+
```
The desktop review uses the same detail surface with authoritative inspected
metadata. Catalog Review & install stages bytes first; the final Install action
explicitly approves the displayed permissions. No runtime iframe appears here.
Phone inputs use a focused full-height form. No two-column detail remains
mounted on phones. Upload/link reviews omit the gallery; registry reviews label
images as listing previews, separate from verified permissions. Image enlargement replaces the gallery region with Back to
details; it does not nest another dialog. One image hides previous/next.
States: inspecting shows progress; failed inspection retains input; expired or
changed review offers Review again; incompatible package disables confirmation
with the required version; failed image shows a placeholder and Retry; success
shows Installed in Project A and Open canvas. Add another copy always starts a
new review; retrying a successful request returns its original copy.
### UI-03: Share canvas
Entry: host Share action or workspace canvas row. Maps to
AC-CANVASES-MARKETPLACE-001.2-001.3, 002.1, 003.1-003.2, 003.4, and 006.1-006.3.
Screenshots are supplied later in the registry entry, never in this form.
```text
Desktop
+-------------------------------------------------------------------+
| Share canvas [Close] |
| Active release: 1.0.0 |
| Package ID [sprint-board] Version [1.0.0] |
| Name [Sprint board] Author [________] License [________] |
| Description [____________________________________________] |
| Source: [Static application v] |
| [How to share] [Prepare downloads] |
|-------------------------------------------------------------------|
| Ready: review included files [Expand] |
| Check exported files for private content. |
| Bundle: ... MiB Source: ... MiB |
| [Download bundle] [Download source] |
+-------------------------------------------------------------------+
Phone
+------------------------------+
| [Back] Share canvas | fixed
| Active release: 1.0.0 |
| Package ID [___________] |
| Version [____] |
| Name / author / license | one scrolling body
| Description [__________] |
| Source [Static v] |
| [How to share] |
| Ready: included files, sizes |
| Check for private content. |
| [Download bundle] |
| [Download source] |
|------------------------------|
| [Prepare downloads] | fixed until ready
+------------------------------+
```
Download controls appear only for the current prepared snapshot. After ready,
the footer can show Close while both downloads stay reachable in the body;
neither download dismisses the form. Form edits invalidate prepared output.
Missing source shows Edit and republish guidance. New active release requires
preparation again. Closing discards temporary share inputs, not canvas data.
### UI-04: Sharing instructions
Entry: How to share in UI-03. Maps to AC-CANVASES-MARKETPLACE-003.3-003.4 and 006.1.
```text
Desktop information dialog Phone inset bottom drawer
+--------------------------------+ +------------------------------+
| How to share [X] | | How to share [X] |
| 1. Download source + bundle | | Download source + bundle |
| 2. Create a repository | | Create/upload repository |
| 3. Upload source | | Publish bundle; copy link |
| 4. Publish bundle; copy link | | Send link or file |
| 5. Send the link or file | | Add to registry (optional) |
| Optional: list in Kandev | | [Copy registry example] |
| [Copy registry example] | | [Done] |
| [Done]| +------------------------------+
+--------------------------------+
```
Keep instruction steps in a bounded scroll body; fixed title/dismiss and bottom
safe-area padding. Closing returns focus to How to share and preserves UI-03.
The copy action copies text only. No remote creation action is offered.
Registry instructions include the required canvas screenshot URLs and alt text,
cover ordering, and the same fields for custom marketplace registries.
## Tests
All test files/methods below are proposed unless explicitly named as existing.
Work-order frontmatter lists each full AC identity, including those abbreviated
in this table. Use nearby `@covers` annotations when method names are insufficient.
| AC suffixes under AC-CANVASES-MARKETPLACE | Planned evidence |
| --- | --- |
| 001.1, 001.2, 001.4 | `webapp/distribution_test.go`: `TestDistributionPackageRoundTrip`, `TestDistributionSourceModes`, `TestDistributionRejectsNonCanvas`; `backendapp/canvas_distribution_source_test.go`: `TestCanvasProjectSourceSurvivesEditAndExecutorCleanup` |
| 001.3, 003.1, 003.2, 003.4 | `canvas/distribution_export_test.go`: `TestCanvasExportSnapshot`, `TestCanvasExportExclusions`, `TestCanvasExportStaleRelease`, `TestCanvasExportNoLifecycleMutation` |
| 002.1, 002.2, 002.4 | `plugin-registry/canvas-index.test.mjs`: registry URL/list shape and cover order; export/install tests prove screenshots are not required |
| 002.3, 004.2 | `canvas-marketplace-detail.test.tsx`: gallery ordering, one-image mode, broken image, permission groups; `backendapp/canvas_distribution_routes_test.go`: `TestCanvasInstallReviewUsesPackagePermissions` |
| 004.1, 004.3, 004.4 | `canvas/distribution_install_test.go`: `TestCanvasInstallSources`, `TestCanvasInstallDigestReview`, `TestCanvasInstallAtomicFailure`, `TestCanvasInstallRestart` |
| 004.5, 004.6 | `canvas/distribution_install_test.go`: `TestCanvasInstallConcurrentRetry`, `TestCanvasInstallIndependentCopy`; `backendapp/canvas_distribution_routes_test.go`: `TestCanvasDistributionWorkspaceAuthorization` |
| 005.1, 005.3 | `plugin-registry/canvas-index.test.mjs`: exact release asset, actual manifest, required registry URLs, source, ID/version, checksum, image metadata independent of package, invalid PR rejection |
| 005.2, 005.4 | `marketplace/canvas_catalog_test.go`: `TestCanvasCatalogWorkspaceProjection`, `TestCanvasCatalogDegradedSource`, `TestCanvasCatalogLegacyEntries`; existing marketplace client/hook tests |
| 003.3 | `canvas-share-help.test.tsx`: complete manual instructions and exact registry example; public-doc validators |
| 006.1, 006.2, 006.3 | Desktop/phone E2E below; API/hook stale-response tests; i18n checks and pseudo-locale rendered pass |
| 006.4 | `backendapp/canvas_distribution_routes_test.go`: `TestCanvasDistributionFeatureOff`; frontend tab/hook tests; existing native plugin tests; `TestDistributionLegacyLocalPackage` |
Additional package tests cover encoded source-subtree access, archive traversal,
links, expansion bombs, duplicate normalized paths, binary contributions
disguised by category, and current file budgets. Registry tests cover URL schemes,
credentials/fragments, list bounds, alt text, and custom-source equivalence.
Receipt tests cover lost response, restart, concurrent confirm, quota races,
workspace deletion, fresh schema, replay, and gated PostgreSQL behavior.
## E2E tests
Use the existing `e2e/tests/canvas/canvas-fixture.ts` pattern with disposable
workspaces, a known mock-agent canvas, and a locally served catalog/package.
Enable the existing feature explicitly and restore it in cleanup. The new
tests must fail, rather than skip, if their required fixture is unavailable.
| File and project | UI flows and AC mapping |
| --- | --- |
| `tests/canvas/canvas-marketplace.spec.ts`, chromium | UI-01/UI-02: search, three images, permission review, upload and link, registry install, reload/Open, additional copy, expired review, bad digest, source outage; 002.3, 004.1-004.6, 005.2-005.4 |
| `tests/canvas/mobile-canvas-marketplace.spec.ts`, mobile-chrome | UI-01/UI-02 by tap: browse, gallery controls, workspace selection, upload/link/catalog review, install/Open, one-column layout, viewport containment and focus; 006.1-006.2 plus same install/gallery criteria |
| `tests/canvas/canvas-sharing.spec.ts`, chromium | UI-03/UI-04: no screenshot input, metadata, prepare, both downloads, help with registry URLs, import screenshot-free bundle and open resulting canvas; 001.1-001.3, 002.1, 003.1-003.4 |
| `tests/canvas/mobile-canvas-sharing.spec.ts`, mobile-chrome | UI-03/UI-04: screenshot-free preparation, both downloads, help drawer/back, input retention, pseudo-locale, actual touch targets, keyboard/safe-area containment; 006.1-006.3 plus sharing criteria |
Use real backend inspection/confirmation and local fixture HTTP; do not intercept
the install response into a fake success. Preview details must not issue a
runtime URL request. Capture downloads and inspect archive contents. Use causal
HTTP/WS waits, no arbitrary sleeps, and no display server or real provider account.
## Work orders
- [ ] [Task 01: Define portable canvas packages](task-01-portable-packages.md)
- [ ] [Task 02: Prepare canvas exports](task-02-export-preparation.md)
- [ ] [Task 03: Install reviewed canvas bundles](task-03-reviewed-installation.md)
- [ ] [Task 04: Publish canvas catalog entries](task-04-registry-catalog.md)
- [ ] [Task 05: Build canvas marketplace browsing](task-05-marketplace-ui.md)
- [ ] [Task 06: Add canvas sharing controls](task-06-sharing-ui.md)
- [ ] [Task 07: Document canvas distribution](task-07-distribution-docs.md)
Dependencies: 01 -> 02 -> 03 -> 04 -> 05 -> 06 -> 07. This deliberately uses
sequential delivery because schema, shared UI/API models, and fixtures overlap.
The optional native-plugin preview extension is delivered by the companion
[plugin marketplace previews plan](../canvas-marketplace-plugin/plan.md).
## Verification commands
Run each work order's exact block from the repository root. Work orders use
isolated subshells for working directories. Install workspace dependencies once
before the first pnpm command: `(cd apps && rtk pnpm install --frozen-lockfile)`.
No product commands below have been run during this design turn.
The work orders own Go/package tests, registry Node tests, focused Vitest,
typecheck, affected-file lint, i18n, and managed desktop/phone E2E commands.
Managed E2E builds fresh production artifacts. No all-worker overrides or
overlapping full suites are allowed. Persistence work includes SQL guard and
store-conformance checks; PostgreSQL needs `KANDEV_TEST_POSTGRES_DSN`.
Design-package checks:
```bash
rtk proxy python3 scripts/lint-spec-files.test.py
rtk proxy python3 scripts/lint-spec-files.py --all
rtk git diff --check -- docs/specs docs/plans/canvas-marketplace
rtk git status --short -- docs/specs docs/plans/canvas-marketplace
```
## Verification results
Initial design validation on 2026-09-10 (before the registry-image revision):
- `python3 scripts/lint-spec-files.test.py`: passed, 36 tests.
- `python3 scripts/lint-spec-files.py --all`: passed.
- Requirement/work-order/link audit: six requirements, 26 acceptance criteria,
seven work orders, and ten new documents checked. Every criterion has a work
order; all relative document links and system-design paths resolve.
- `git diff --check -- docs/specs docs/plans/canvas-marketplace`: passed.
- New-document whitespace audit: passed, including untracked work orders.
- `git status --short -- docs/specs docs/plans/canvas-marketplace`: inspected;
the package and index/cross-reference edits are present and uncommitted.
Registry-image revision validation on 2026-09-10:
- Specification linter tests: passed, 36 tests; full specification lint passed.
- Traceability/link audit: seven requirements, 30 criteria, seven work orders;
all criteria assigned and document/design links resolved.
- Proposed JSON Schema parses and contains the preview definition and
conditional canvas requirement. Full JSON Schema engine validation was not
run in this environment; implementation owns semantic schema test cases.
- Tracked diff and new-document whitespace checks passed.
The revision adds the Plugins-owned preview requirement and the proposed schema
artifact; it does not change the production registry schema yet.
Implementation checks were not run; all seven work orders remain pending.
Record actual command results here and in each task during delivery.
## Risks
- The current source allowlist excludes TS/TSX and YAML; widening must be
limited to an inert subtree that runtime URLs cannot serve.
- Registry image URLs can change or fail independently of package releases;
gallery failure must not block valid installation or imply package corruption.
- Registry metadata currently uses a shallow parser and nullable hash. Canvas
entries need production inspection without breaking native plugin entries.
- Receipt insertion, grants, count admission, and artifact references must be
atomic across retries and supported database dialects.
- Host URL fetch must not gain private-network access through DNS or redirects.
- Shared catalog caching must never retain a user's workspace instance annotations.
- Old clients must fail safely on static canvas bundles; set a real minimum
compatible release before shipping the format.
- Private data embedded in exported files cannot be reliably removed
automatically. Show the exact inventory and author review reminder.
- Official registry discovery remains GitHub-only. Other hosts can share public
direct bundle links or files; the helper must explain that distinction.
## Design handoff
The next phase is explicit implementation of these work orders with TDD.
This package does not authorize commits, pushes, registry submissions, or
external publishing. Public docs are updated with implementation, not presented
as shipped behavior during this planning turn.
@@ -0,0 +1,116 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/kdlbs/kandev/blob/main/plugin-registry/schema.json",
"title": "Kandev marketplace registry",
"description": "Proposed registry schema for plugin and canvas repositories. Preview image URLs belong to registry entries; release metadata remains package-owned.",
"type": "object",
"additionalProperties": false,
"required": [
"plugins"
],
"properties": {
"plugins": {
"type": "array",
"description": "The curated list of plugin repositories, one entry per plugin.",
"items": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"repo"
],
"properties": {
"id": {
"type": "string",
"description": "Stable plugin identifier. MUST equal the plugin manifest `id` of the repo's latest release. Unique across the file.",
"pattern": "^[a-z0-9][a-z0-9-]*$"
},
"repo": {
"type": "string",
"description": "GitHub repository in owner/name form; the release source for this plugin.",
"pattern": "^[^/]+/[^/]+$"
},
"featured": {
"type": "boolean",
"description": "When true, a maintainer has pinned this entry above star order in the catalog.",
"default": false
},
"categories": {
"type": "array",
"description": "Curation-only category tags used for filtering in the catalog.",
"items": {
"type": "string"
}
},
"kind": {
"type": "string",
"enum": [
"plugin",
"canvas"
],
"default": "plugin",
"description": "Omitted kind means plugin for backward compatibility; canvas kind must match the validated package."
},
"previews": {
"type": "array",
"maxItems": 8,
"items": {
"$ref": "#/$defs/preview"
},
"description": "Ordered preview images. First image is the cover. Optional for plugins; required for canvas registry listings."
}
},
"allOf": [
{
"if": {
"required": [
"kind"
],
"properties": {
"kind": {
"const": "canvas"
}
}
},
"then": {
"required": [
"previews"
],
"properties": {
"previews": {
"minItems": 1
}
}
}
}
]
}
}
},
"$defs": {
"preview": {
"type": "object",
"additionalProperties": false,
"required": [
"url",
"alt"
],
"properties": {
"url": {
"type": "string",
"format": "uri",
"pattern": "^https://",
"maxLength": 2048,
"description": "Direct HTTPS image URL. Credentials and fragments are rejected by registry validation."
},
"alt": {
"type": "string",
"minLength": 1,
"maxLength": 300,
"pattern": "\\S",
"description": "Description of the preview image for accessibility."
}
}
}
}
}
@@ -0,0 +1,118 @@
---
id: "01-portable-packages"
title: "Define portable canvas packages"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-CANVASES-MARKETPLACE-001
- REQ-CANVASES-MARKETPLACE-002
- REQ-CANVASES-MARKETPLACE-006
acceptance_criteria:
- AC-CANVASES-MARKETPLACE-001.1
- AC-CANVASES-MARKETPLACE-001.2
- AC-CANVASES-MARKETPLACE-001.3
- AC-CANVASES-MARKETPLACE-001.4
- AC-CANVASES-MARKETPLACE-002.1
- AC-CANVASES-MARKETPLACE-006.4
system_design:
- ../../specs/canvases/system-design/marketplace-sharing.md
---
# Task 01: Define portable canvas packages
## Summary
Define the canvas distribution profile in the existing plugin manifest and
static validator. Preserve editable source with immutable releases and expose
a reusable offline inspector for registry validation.
## In scope
- Typed distribution metadata, source modes, checksum validation, compatibility,
exactly one canvas app, and rejection of other plugin contributions.
- Screenshot-free bundle/source validation; registry previews are not manifest fields.
- Source-only project subtree, bounded authoring transfer, immutable retention,
Quick Chat materialization, and runtime denial of distribution paths.
- Deterministic bundle/source archive writers and production offline inspector.
- Minimal embedded authoring reference changes needed to keep source modes valid;
Task 07 owns the full sharing instructions.
## Out of scope
HTTP downloads, registry fetching, canvas installation, UI, and native installer changes.
## Acceptance
- Distribution round-trip fixtures retain matching static/project source and
application assets while malformed, incomplete, disguised native, and oversized
bundles fail. No screenshot or preview URL is required.
- Runtime requests cannot read the inert source subtree through plain,
encoded, or normalized aliases; editing retains original build inputs after
the author executor is unavailable.
- The offline inspector and host use the same validator and a shared descriptor
fixture. Native managed-plugin installation tests remain unchanged and pass.
## Verification
Run from repository root. Start with focused RED cases, then run these blocks
after implementation. The new test files/methods are named in the plan.
```bash
(cd apps/backend && rtk go test -race ./internal/plugins/manifest ./internal/plugins/webapp ./internal/plugins/pkgtar ./cmd/canvas-package -count=1)
(cd apps/backend && rtk go test -race ./internal/backendapp -run 'TestCanvas.*(Source|Scaffold|Edit)' -count=1)
(cd apps/backend && rtk go test -race ./internal/agentctl/server/api -run Canvas -count=1)
(cd apps/backend && rtk go test ./internal/mcp/canvasskill -count=1)
rtk git diff --check
```
## Files likely touched
Existing:
- `apps/backend/internal/plugins/manifest/manifest.go`, `validate.go`
- `apps/backend/internal/plugins/webapp/package.go`, `runtime.go`
- `apps/backend/internal/backendapp/canvas_authoring.go`, `canvas_routes.go`
- `apps/backend/internal/agentctl/server/api/workspace_canvas_source.go`
- `apps/backend/internal/mcp/canvasskill/files/references/manifest.md`
New:
- `apps/backend/internal/plugins/manifest/distribution.go`
- `apps/backend/internal/plugins/webapp/distribution.go`, `distribution_test.go`
- `apps/backend/internal/backendapp/canvas_distribution_source_test.go`
- `apps/backend/cmd/canvas-package/main.go`, `main_test.go`
- Adjacent focused archive-writer tests and shared static/project fixture files.
## Dependencies
None. Follow the existing plugin-backed canvas runtime contract.
## Risks
A file-extension exception must not broaden runtime serving. Preserve the
current package byte/file budgets, source transfer fencing, and authoring core
inventory. Build-source declarations cannot prove that arbitrary builds succeed;
fixtures must prove both supported source modes and their documented commands.
## Parallelism
`sequential`
## Inputs
- Design: Package profile, Source retention, Validation.
- Existing `webapp/package_test.go`, `runtime_test.go`, authoring/edit tests.
- `apps/backend/AGENTS.md` and both scoped agentctl AGENTS files before changes.
- Existing canvas authoring guide and one-core-read inventory contract.
## Results
Implemented the typed canvas distribution profile, strict manifest/package and
source validation, checksum coverage, deterministic bundle/source archives,
runtime source isolation, bounded source retention, and the offline inspector.
The authoring reference and fixture preserve static/project source behavior.
Verification: the package/manifest/webapp/pkgtar/inspector race suite passed 210
tests, the agentctl canvas-source race suite passed 6 tests, the backend canvas
source/scaffold/edit race suite passed 7 tests, the authoring skill suite passed
7 tests, and the relevant backend suite passed 1,587 tests across 8 packages.
@@ -0,0 +1,103 @@
---
id: "02-export-preparation"
title: "Prepare canvas exports"
status: done
wave: 2
depends_on:
- "01-portable-packages"
plan: "plan.md"
requirements:
- REQ-CANVASES-MARKETPLACE-001
- REQ-CANVASES-MARKETPLACE-003
- REQ-CANVASES-MARKETPLACE-006
acceptance_criteria:
- AC-CANVASES-MARKETPLACE-001.2
- AC-CANVASES-MARKETPLACE-001.3
- AC-CANVASES-MARKETPLACE-003.1
- AC-CANVASES-MARKETPLACE-003.2
- AC-CANVASES-MARKETPLACE-003.4
- AC-CANVASES-MARKETPLACE-006.4
system_design:
- ../../specs/canvases/system-design/marketplace-sharing.md
---
# Task 02: Prepare canvas exports
## Summary
Prepare both downloadable formats from one active immutable release. Introduce
the bounded temporary preparation store that the install review will also use.
## In scope
- User/workspace-bound preparations, 15-minute expiry, admission accounting,
request leases, cancel, startup cleanup, and safe failure cleanup.
- Export preparation with metadata, inventory and size preview. No screenshot input.
- Authenticated bundle/source downloads with safe headers.
- Reauthorization and active-release checks before prepare/download.
- Stable error codes, content-free diagnostics, and no executor dependence.
## Out of scope
Permanent share-profile settings, external publication, installation mutations,
frontend forms, and changes to canvas runtime state.
## Acceptance
- Export preparation and both downloads refer to the same validated snapshot;
form/release changes invalidate it and unauthorized requests disclose nothing.
- Source/state exclusion, screenshot-free preparation, expiry, cancellation, interrupted
streaming, quotas, and restart cleanup leave the active release unchanged.
- Preparation routes are absent when canvases are disabled; download access
requires current human workspace authority even if an ID is known.
## Verification
```bash
(cd apps/backend && rtk go test -race ./internal/canvas -run 'TestCanvasExport|TestCanvasPreparation' -count=1)
(cd apps/backend && rtk go test -race ./internal/backendapp -run 'TestCanvasExport|TestCanvasPreparation|TestCanvasDistributionFeatureOff' -count=1)
rtk git diff --check
```
## Files likely touched
New:
- `apps/backend/internal/canvas/distribution.go`, `distribution_preparation.go`
- `apps/backend/internal/canvas/distribution_export.go`, `distribution_export_test.go`
- `apps/backend/internal/canvas/distribution_preparation_test.go`
- `apps/backend/internal/backendapp/canvas_distribution_routes.go`, `canvas_distribution_routes_test.go`
Existing integration points:
- `apps/backend/internal/backendapp/canvas_routes.go` and service composition
- `apps/backend/internal/plugins/webapp/package.go` artifact read interface
## Dependencies
Task 01's validated package and archive writers.
## Risks
Do not mistake opaque IDs for authorization. Cleanup must not race a live
download or delete a shared immutable artifact. Bound compressed outputs and
multipart input before memory allocation. Avoid collecting task workspace files.
## Parallelism
`sequential`
## Inputs
- Design: Validation and bounded preparation, Export preparation, HTTP contracts.
- `canvasEditService.loadEditableCanvas` for immutable artifact authorization.
- Existing canvas route/feature-off tests and safe attachment response patterns.
## Results
Implemented user-bound, expiring export preparations with quota and cleanup
handling, immutable active-release snapshots, metadata/inventory review, and
authenticated bundle/source downloads. The export path is screenshot-free and
does not depend on the executor.
Verification: the canvas export/preparation race tests passed 3 tests, the
desktop sharing E2E passed, and the mobile sharing E2E passed. The full relevant
backend suite and SQL guard also passed.
@@ -0,0 +1,121 @@
---
id: "03-reviewed-installation"
title: "Install reviewed canvas bundles"
status: done
wave: 3
depends_on:
- "02-export-preparation"
plan: "plan.md"
requirements:
- REQ-CANVASES-MARKETPLACE-001
- REQ-CANVASES-MARKETPLACE-004
- REQ-CANVASES-MARKETPLACE-006
acceptance_criteria:
- AC-CANVASES-MARKETPLACE-001.1
- AC-CANVASES-MARKETPLACE-001.4
- AC-CANVASES-MARKETPLACE-004.1
- AC-CANVASES-MARKETPLACE-004.2
- AC-CANVASES-MARKETPLACE-004.3
- AC-CANVASES-MARKETPLACE-004.4
- AC-CANVASES-MARKETPLACE-004.5
- AC-CANVASES-MARKETPLACE-004.6
- AC-CANVASES-MARKETPLACE-006.4
system_design:
- ../../specs/canvases/system-design/marketplace-sharing.md
---
# Task 03: Install reviewed canvas bundles
## Summary
Install an inspected static canvas as an independent workspace instance after
explicit permission approval. Preserve reviewed bytes and retry identity across
the database transaction.
## In scope
- Upload and direct-link preparation, authoritative package/permission review without required images,
expected digest, bounded HTTPS fetch, redirect/DNS destination validation.
- Catalog-reference resolver interface; Task 04 wires actual catalog entries.
- `InstallPrepared`, workspace admission, atomic instance/release/grant creation,
receipt/provenance persistence, and existing lifecycle invalidation.
- Idempotent retry, concurrent confirmation, restart replay, deletion handling,
safe artifact compensation, and native-install authority isolation.
- Additive receipt schema, migration/replay fixtures, persistence descriptor
updates where the existing canvas store's conformance contract requires them.
## Out of scope
Repository cloning, provider credentials, replacing/updating existing canvases,
frontend review controls, and native plugin auto-update changes.
## Acceptance
- Upload/link installs execute only inspected bytes after current workspace
authorization and full permission approval, with no instance before confirm.
- Concurrent or retried confirmation creates one instance; a new review creates
an independent copy. Receipt, provenance, grants, and release survive restart.
- Invalid URL/digest/package, revoked workspace, quota/DB failure, and disabled
routes leave existing data unchanged; supported schema replay checks pass.
## Verification
```bash
(cd apps/backend && rtk go test -race ./internal/canvas ./internal/plugins/instances -count=1)
(cd apps/backend && rtk go test -race ./internal/backendapp -run 'TestCanvasInstall|TestCanvasDistribution' -count=1)
(cd apps/backend && rtk go run ./cmd/sqlguard ./internal)
(cd apps/backend && rtk go test -race ./internal/persistence/storeconformance -count=1)
rtk git diff --check
```
Run the same targeted canvas/instance tests with `KANDEV_TEST_POSTGRES_DSN`
set when the test database is available. Record skipped PostgreSQL evidence
explicitly; do not report SQLite replay as cross-dialect evidence.
## Files likely touched
- `apps/backend/internal/canvas/distribution_install.go`, `distribution_install_test.go` (new)
- `apps/backend/internal/canvas/distribution_download.go`, `distribution_download_test.go` (new)
- `apps/backend/internal/canvas/repository.go`, `service.go`, `types.go`
- `apps/backend/internal/plugins/instances/store.go` and focused transaction tests
- `apps/backend/internal/backendapp/canvas_distribution_routes.go`, route tests
- Existing canvas schema registration, storage cleanup, and conformance fixtures
## Dependencies
Tasks 01-02. Use a narrow catalog resolver interface with fixture data until Task 04.
## Risks
A sequence of independently committed create/publish/approve calls is not atomic.
Use the existing store transaction boundary and receipt uniqueness. PostgreSQL
locking must cover admission and concurrent retries. DNS checks must bind to the
actual connection destination, not only an earlier lookup.
## Parallelism
`sequential`
## Inputs
- Design: Install preparation, Commit and persistence, Authorization.
- Existing `canvas.PublishPackage`, `instances.Store` transaction/cleanup tests.
- `canvasHTTPHandler.authorizeWorkspace`, authentication scoping guidance.
- Existing native-plugin install tests as a compatibility boundary.
## Results
Implemented upload, direct HTTPS link, and catalog-reference preparation;
server-side digest/package/permission review; bounded public-destination
fetching; atomic workspace install integration; provenance and receipt
persistence; and retry-safe confirmation.
Verification: the canvas installation/export race selection passed 3 tests, the
full relevant backend suite passed 1,587 tests across 8 packages, and SQL guard
passed. Existing native plugin installation paths remained covered by the
16-test plugin E2E regression.
Review remediation: production confirmation now uses the canvas service's
single transaction for instance, release, grants, and receipt ownership. It
also reauthorizes retry paths, fails closed on receipt-store errors, and
compensates a newly-created artifact when the transaction cannot commit.

Some files were not shown because too many files have changed in this diff Show More