fix(security): enforce credential and filesystem trust boundaries (#861)

Bind provider credentials to canonical or explicitly configured HTTPS origins and preserve that policy across remote consumers. Reject cross-site credentialed reads, linked fallback directories, and discovered-agent writes outside the source; audit staged content before rooted atomic publication.

Add boundary regressions, private Git update coverage, stable cross-platform fixtures, and aligned documentation. Verified the integrated main baseline with all executed CI checks passing.
This commit is contained in:
Willie
2026-11-11 23:17:54 +08:00
committed by GitHub
parent 3872cb5525
commit c040917bc7
95 changed files with 1824 additions and 500 deletions
@@ -0,0 +1,85 @@
# Security Boundaries
## Scope
Defensive regression verification for credential origin authorization, repository `.agents/skills` fallback discovery, and discovered-agent destination writes. Tests use dummy tokens, local HTTP test servers, and temporary filesystem/Git fixtures; do not supply real credentials or probe external hosts. This runbook does not install remote resources.
## Environment
Run each step inside the isolated Linux devcontainer with the checkout at `/workspace`, Go dependencies already cached, and Git available. Use the repository's mdproof runner for this file only; do not run on the host. `GOPROXY=off GOSUMDB=off` prevents dependency downloads. Every step is independent. These commands are verification instructions, not a record of an executed result.
## Steps
### 1. Credential authorization and browser remote-read origins
Provider-looking names and nondefault ports must not receive provider tokens. Explicit configured Gitea/CNB hosts and the generic HTTPS fallback remain supported, including grouped skill updates and tracked agent updates. GitHub clients must not forward authorization across origins, and cross-site browser searches and previews must be rejected before fetching.
```bash
set -eu
cd /workspace
export GOPROXY=off GOSUMDB=off
unset GITHUB_TOKEN GH_TOKEN GITLAB_TOKEN BITBUCKET_TOKEN BITBUCKET_USERNAME AZURE_DEVOPS_TOKEN GITEA_TOKEN CNB_TOKEN SKILLSHARE_GIT_TOKEN
go test -count=1 -v ./internal/install -run '^(TestProviderCredentialsRejectUntrustedOrigins|TestForgeRequestsScopeProviderCredentials|TestForgeFallbackPreservesCredentialOrigin)$'
go test -count=1 -v ./internal/github -run '^(TestNewRequestScopesGitHubCredentials|TestClientDoesNotForwardCredentialsAcrossOrigins)$'
go test -count=1 -v ./internal/search -run '^(TestFetchPreviewDoesNotAuthorizeProviderLookalikes|TestBuildHubRequest_GitHubHeaders)$'
go test -count=1 -v ./internal/server -run '^(TestCrossSitePreviewIsRefused|TestCrossSiteHubSearchIsRefused)$'
go test -count=1 -v ./internal/install ./cmd/skillshare -run '^(TestUpdateSkillsFromRepo_ConfiguredHosts|TestBatchUpdateTrackedAgents_ConfiguredHosts)$'
```
**Expected**
- exit_code: 0
- --- PASS: TestProviderCredentialsRejectUntrustedOrigins
- --- PASS: TestForgeRequestsScopeProviderCredentials
- --- PASS: TestForgeFallbackPreservesCredentialOrigin
- --- PASS: TestNewRequestScopesGitHubCredentials
- --- PASS: TestClientDoesNotForwardCredentialsAcrossOrigins
- --- PASS: TestFetchPreviewDoesNotAuthorizeProviderLookalikes
- --- PASS: TestBuildHubRequest_GitHubHeaders
- --- PASS: TestCrossSitePreviewIsRefused
- --- PASS: TestCrossSiteHubSearchIsRefused
- --- PASS: TestUpdateSkillsFromRepo_ConfiguredHosts
- --- PASS: TestBatchUpdateTrackedAgents_ConfiguredHosts
### 2. Real-directory fallback discovery
Linked `.agents` or `skills` components must not expose aliases of excluded skills, even when source links are followed. Real fallback directories beneath an intentionally followed repository root must still work.
```bash
set -eu
cd /workspace
export GOPROXY=off GOSUMDB=off
go test -count=1 -v ./internal/sourcewalk -run '^TestAgentsSkillsDirRequiresRealDirectories$'
go test -count=1 -v ./internal/skillserve -run '^(TestBuild_RefusesAgentsFallbackAliasesOfExcludedSkills|TestBuild_ServesRealAgentsFallbackThroughFollowedRepoRoot)$'
```
**Expected**
- exit_code: 0
- --- PASS: TestAgentsSkillsDirRequiresRealDirectories
- --- PASS: TestBuild_RefusesAgentsFallbackAliasesOfExcludedSkills
- --- PASS: TestBuild_ServesRealAgentsFallbackThroughFollowedRepoRoot
### 3. Rooted agent publication and audit preservation
Fresh, forced, and update writes must refuse intermediate and final destination links, including dangling links. An audit block must preserve installed contents. Normal installs, updates, metadata, dry runs, and supported followed roots must continue working.
```bash
set -eu
cd /workspace
export GOPROXY=off GOSUMDB=off
go test -count=1 -v ./internal/install -run '^(TestInstallAgentFromDiscovery_TrackedDestinationEscape|TestDiscoveredAgent_RefusesDestinationLinks|TestDiscoveredAgent_BlockedAuditPreservesInstalledContent|TestDiscoveredAgent_InstallUpdateMetadataAndDryRun|TestDiscoveredAgent_FollowPolicyAndLinkedSourceRoot)$'
```
**Expected**
- exit_code: 0
- --- PASS: TestInstallAgentFromDiscovery_TrackedDestinationEscape
- --- PASS: TestDiscoveredAgent_RefusesDestinationLinks
- --- PASS: TestDiscoveredAgent_BlockedAuditPreservesInstalledContent
- --- PASS: TestDiscoveredAgent_InstallUpdateMetadataAndDryRun
- --- PASS: TestDiscoveredAgent_FollowPolicyAndLinkedSourceRoot
## Pass Criteria
Every named test runs and passes; skipped or missing tests are not evidence. The fixtures verify that untrusted origins receive no provider authorization, linked fallback components are not discovered, destination links cannot redirect writes, and blocked agent audits preserve previous bytes. Tests own and clean their temporary fixtures. Windows junction and native file-link behavior additionally requires the existing Windows link runbooks on Windows; Linux results do not establish Windows verification.
+19 -17
View File
@@ -50,7 +50,7 @@ type checkOptions struct {
json bool
diff bool // --diff: show each skill's changes since install
parseOpts install.ParseOptions // how --diff parses recorded sources
parseOpts install.ParseOptions // source parsing and remote credential authorization
}
// collectCheckItems reads metadata and partitions items for parallel checking.
@@ -58,12 +58,13 @@ type checkOptions struct {
// without a remote are already resolved (no network needed).
// projectRoot is the base of relative local sources; "" in global mode.
// follow resolves linked skill directories before they are hashed.
func collectCheckItems(sourceDir, projectRoot string, repos []string, skills []string, follow *sourcewalk.Follow) ([]check.RepoCheckInput, *check.Resolution) {
func collectCheckItems(sourceDir, projectRoot string, repos []string, skills []string, follow *sourcewalk.Follow, parseOpts install.ParseOptions) ([]check.RepoCheckInput, *check.Resolution) {
var repoInputs []check.RepoCheckInput
for _, repo := range repos {
repoInputs = append(repoInputs, check.RepoCheckInput{
Name: repo,
RepoPath: filepath.Join(sourceDir, repo),
Name: repo,
RepoPath: filepath.Join(sourceDir, repo),
ParseOptions: parseOpts,
})
}
@@ -80,10 +81,11 @@ func collectCheckItems(sourceDir, projectRoot string, repos []string, skills []s
// resolveCheckSkills asks the remotes of a planned skill check in parallel,
// reporting the skill count of each finished remote to progressBar (may be nil).
func resolveCheckSkills(plan *check.Resolution, progressBar *ui.ProgressBar) []checkSkillResult {
func resolveCheckSkills(plan *check.Resolution, progressBar *ui.ProgressBar, parseOpts install.ParseOptions) []checkSkillResult {
// Without a context the check runs to completion, so the error is always nil.
resolved, _ := plan.Run(context.Background(), check.Options{
Parallel: true,
ParseOptions: parseOpts,
Parallel: true,
OnRemoteDone: func(skills int) {
if progressBar != nil {
progressBar.Add(skills)
@@ -208,7 +210,7 @@ func cmdCheck(args []string) error {
logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, err)
return err
}
cmdErr := renderAgentCheck(projectCfg.EffectiveAgentsSource(cwd), opts.groups, opts.json)
cmdErr := renderAgentCheck(projectCfg.EffectiveAgentsSource(cwd), opts.groups, opts.json, parseOptsFromProjectConfig(projectCfg))
logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, cmdErr)
return cmdErr
}
@@ -225,14 +227,14 @@ func cmdCheck(args []string) error {
// Agent-only check: scan agents source directory and skip repo checks.
if kind == kindAgents {
agentsDir := cfg.EffectiveAgentsSource()
cmdErr := renderAgentCheck(agentsDir, opts.groups, opts.json)
cmdErr := renderAgentCheck(agentsDir, opts.groups, opts.json, parseOptsFromConfig(cfg))
logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, cmdErr)
return cmdErr
}
// No names and no groups → check all (existing behavior)
if len(opts.names) == 0 && len(opts.groups) == 0 {
cmdErr := runCheck(cfg.EffectiveSkillsSource(), "", opts.json, targetNamesFromConfig(cfg.Targets), cfg.SkillsWalk())
cmdErr := runCheck(cfg.EffectiveSkillsSource(), "", opts.json, targetNamesFromConfig(cfg.Targets), cfg.SkillsWalk(), parseOptsFromConfig(cfg))
logCheckOp(cfgPath, 0, 0, 0, 0, scope, start, cmdErr)
return cmdErr
}
@@ -259,7 +261,7 @@ func logCheckOp(cfgPath string, repos, skills, updatesAvailable, errors int, sco
oplog.WriteWithLimit(cfgPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
}
func runCheck(sourceDir, projectRoot string, jsonOutput bool, extraTargetNames []string, walk sourcewalk.Options) error {
func runCheck(sourceDir, projectRoot string, jsonOutput bool, extraTargetNames []string, walk sourcewalk.Options, parseOpts install.ParseOptions) error {
start := time.Now()
var scanSpinner *ui.Spinner
@@ -299,7 +301,7 @@ func runCheck(sourceDir, projectRoot string, jsonOutput bool, extraTargetNames [
}
// Collect & group
repoInputs, plan := collectCheckItems(sourceDir, projectRoot, repos, skills, walk.Follow)
repoInputs, plan := collectCheckItems(sourceDir, projectRoot, repos, skills, walk.Follow, parseOpts)
if scanSpinner != nil {
scanSpinner.Stop()
@@ -321,7 +323,7 @@ func runCheck(sourceDir, projectRoot string, jsonOutput bool, extraTargetNames [
}
repoOutputs := check.ParallelCheckRepos(repoInputs, repoOnDone)
skillResults := resolveCheckSkills(plan, progressBar)
skillResults := resolveCheckSkills(plan, progressBar, parseOpts)
if progressBar != nil {
progressBar.Stop()
@@ -616,7 +618,7 @@ func runCheckFiltered(sourceDir, projectRoot string, opts *checkOptions, walks .
}
}
repoInputs, plan := collectCheckItems(sourceDir, projectRoot, repoNames, skillNames, follow)
repoInputs, plan := collectCheckItems(sourceDir, projectRoot, repoNames, skillNames, follow, opts.parseOpts)
total := len(repoInputs) + plan.RemoteSkills()
isSingle := len(targets) == 1
@@ -639,7 +641,7 @@ func runCheckFiltered(sourceDir, projectRoot string, opts *checkOptions, walks .
}
repoOutputs := check.ParallelCheckRepos(repoInputs, repoOnDone)
skillResults := resolveCheckSkills(plan, progressBar)
skillResults := resolveCheckSkills(plan, progressBar, opts.parseOpts)
if progressBar != nil {
progressBar.Stop()
@@ -780,7 +782,7 @@ func formatSourceShort(source string) string {
// renderAgentCheck runs CheckAgents and displays results (text or JSON).
// If groups is non-empty, only agents in those group subdirectories are shown.
func renderAgentCheck(agentsDir string, groups []string, jsonMode bool) error {
func renderAgentCheck(agentsDir string, groups []string, jsonMode bool, parseOpts install.ParseOptions) error {
agentResults := check.CheckAgents(agentsDir)
if len(groups) > 0 {
@@ -804,10 +806,10 @@ func renderAgentCheck(agentsDir string, groups []string, jsonMode bool) error {
}
if len(tracked) > 0 {
if jsonMode {
check.EnrichAgentResultsWithRemote(tracked, nil)
check.EnrichAgentResultsWithRemote(tracked, nil, parseOpts)
} else {
sp := ui.StartSpinner(fmt.Sprintf("Checking %s...", plural(len(tracked), "tracked agent")))
check.EnrichAgentResultsWithRemote(tracked, nil)
check.EnrichAgentResultsWithRemote(tracked, nil, parseOpts)
sp.Stop()
}
for i, idx := range trackedIndices {
+1 -1
View File
@@ -30,7 +30,7 @@ func cmdCheckProject(root string, opts *checkOptions) error {
// No names and no groups → check all (existing behavior)
if len(opts.names) == 0 && len(opts.groups) == 0 {
return runCheck(sourcePath, root, opts.json, extraNames, projectSkillsWalk(root, projectCfg))
return runCheck(sourcePath, root, opts.json, extraNames, projectSkillsWalk(root, projectCfg), parseOptsFromProjectConfig(projectCfg))
}
// Filtered check
+9 -9
View File
@@ -310,7 +310,7 @@ func handleExistingInit(opts *initOptions) (bool, error) {
}
}
}
setupGitRemote(gitRoot, opts.remoteURL, opts.dryRun, opts.noGit)
setupGitRemote(gitRoot, opts.remoteURL, opts.dryRun, opts.noGit, parseOptsFromConfig(cfg))
if opts.dryRun {
fmt.Println()
ui.DryRun()
@@ -622,7 +622,7 @@ func commitSourceFiles(sourcePath, skills string) error {
return nil
}
func setupGitRemote(sourcePath, remoteURL string, dryRun, noGit bool) bool {
func setupGitRemote(sourcePath, remoteURL string, dryRun, noGit bool, parseOpts install.ParseOptions) bool {
// Check if git is initialized
gitDir := filepath.Join(sourcePath, ".git")
if _, err := os.Stat(gitDir); os.IsNotExist(err) {
@@ -660,10 +660,10 @@ func setupGitRemote(sourcePath, remoteURL string, dryRun, noGit bool) bool {
ui.Row(ui.MarkNone, "Remote", "would add origin → "+remoteURL, gitRowWidth)
return false
}
return addRemote(sourcePath, remoteURL)
return addRemote(sourcePath, remoteURL, parseOpts)
}
func addRemote(sourcePath, remoteURL string) bool {
func addRemote(sourcePath, remoteURL string, parseOpts install.ParseOptions) bool {
// SetOrAddRemote validates the URL (rejecting flag-smuggling values that
// begin with "-") and passes "--" before positional args. setupGitRemote
// has already confirmed origin is absent, so this takes the add path.
@@ -675,7 +675,7 @@ func addRemote(sourcePath, remoteURL string) bool {
ui.Row(ui.MarkOK, "Remote", "origin → "+remoteURL, gitRowWidth)
// Try to fetch and auto-pull if remote has existing skills
hadSkills := tryPullAfterRemoteSetup(sourcePath, remoteURL)
hadSkills := tryPullAfterRemoteSetup(sourcePath, remoteURL, parseOpts)
if !hadSkills {
ui.Next("skillshare push", "share your skills")
}
@@ -683,7 +683,7 @@ func addRemote(sourcePath, remoteURL string) bool {
}
// remoteFetchEnv returns env vars for non-interactive remote checks.
func remoteFetchEnv(remoteURL string) []string {
func remoteFetchEnv(remoteURL string, parseOpts install.ParseOptions) []string {
env := gitenv.Environ()
env = append(env,
"GIT_TERMINAL_PROMPT=0",
@@ -695,7 +695,7 @@ func remoteFetchEnv(remoteURL string) []string {
if v, ok := os.LookupEnv("GIT_SSH_COMMAND"); !ok || strings.TrimSpace(v) == "" {
env = append(env, "GIT_SSH_COMMAND=ssh -o BatchMode=yes -o ConnectTimeout=8")
}
if authEnv := install.AuthEnvForURL(remoteURL); len(authEnv) > 0 {
if authEnv := install.AuthEnvForURL(remoteURL, parseOpts); len(authEnv) > 0 {
env = append(env, authEnv...)
}
return env
@@ -703,7 +703,7 @@ func remoteFetchEnv(remoteURL string) []string {
// tryPullAfterRemoteSetup attempts to fetch from remote and pull if it has content.
// Returns true if remote had content (pulled or warned), false if remote is empty/unreachable.
func tryPullAfterRemoteSetup(sourcePath, remoteURL string) bool {
func tryPullAfterRemoteSetup(sourcePath, remoteURL string, parseOpts install.ParseOptions) bool {
spinner := ui.StartSpinner("Checking remote for existing skills...")
// Try to fetch (inject HTTPS token auth when available)
@@ -711,7 +711,7 @@ func tryPullAfterRemoteSetup(sourcePath, remoteURL string) bool {
defer cancel()
fetchCmd := gitenv.CommandContext(fetchCtx, "fetch", "origin")
fetchCmd.Dir = sourcePath
fetchCmd.Env = remoteFetchEnv(remoteURL)
fetchCmd.Env = remoteFetchEnv(remoteURL, parseOpts)
if output, err := fetchCmd.CombinedOutput(); err != nil {
spinner.Stop()
if errors.Is(fetchCtx.Err(), context.DeadlineExceeded) {
+1 -1
View File
@@ -160,7 +160,7 @@ func applyRemote(p *initPlan, res *initResult, hadRepo bool) {
res.warnings = append(res.warnings, fmt.Sprintf("%s already had a git repo, so the remote's skills were not pulled. Run: skillshare pull", utils.FoldHomePath(res.gitRoot)))
return
}
if err := pullRemote(res.gitRoot, p.remoteURL); err != nil {
if err := pullRemote(res.gitRoot, p.remoteURL, parseOptsFromConfig(res.cfg)); err != nil {
res.pullErr = err
return
}
+5 -3
View File
@@ -9,8 +9,10 @@ import (
"strings"
"time"
"skillshare/internal/config"
gitops "skillshare/internal/git"
"skillshare/internal/gitenv"
"skillshare/internal/install"
ssync "skillshare/internal/sync"
)
@@ -53,7 +55,7 @@ func inspectRemote(url string) *remoteRepo {
defer cancel()
repo := filepath.Join(tmp, "repo")
cmd := gitenv.CommandContext(ctx, "clone", "--depth", "1", "--quiet", "--", url, repo)
cmd.Env = remoteFetchEnv(url)
cmd.Env = remoteFetchEnv(url, parseOptsFromConfig(&config.Config{}))
if out, err := cmd.CombinedOutput(); err != nil {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
r.reason = "timed out"
@@ -105,12 +107,12 @@ func remoteFailureReason(out string) string {
// pullRemote fetches origin and moves the repo at gitRoot onto the remote's
// default branch. The caller must make sure gitRoot holds no work of its own.
func pullRemote(gitRoot, url string) error {
func pullRemote(gitRoot, url string, parseOpts install.ParseOptions) error {
ctx, cancel := context.WithTimeout(context.Background(), remoteFetchTimeout*4)
defer cancel()
fetch := gitenv.CommandContext(ctx, "fetch", "origin")
fetch.Dir = gitRoot
fetch.Env = remoteFetchEnv(url)
fetch.Env = remoteFetchEnv(url, parseOpts)
if out, err := fetch.CombinedOutput(); err != nil {
return fmt.Errorf("fetch failed: %s", remoteFailureReason(string(out)))
}
+4 -2
View File
@@ -6,6 +6,8 @@ import (
"path/filepath"
"strings"
"testing"
"skillshare/internal/install"
)
func envValue(env []string, key string) (string, bool) {
@@ -79,7 +81,7 @@ func TestCommitSourceFiles_NoChangesReturnsNil(t *testing.T) {
func TestRemoteFetchEnv_DisablesInteractivePrompts(t *testing.T) {
t.Setenv("GIT_SSH_COMMAND", "")
env := remoteFetchEnv("https://github.com/org/repo.git")
env := remoteFetchEnv("https://github.com/org/repo.git", install.ParseOptions{})
if v, ok := envValue(env, "GIT_TERMINAL_PROMPT"); !ok || v != "0" {
t.Fatalf("expected GIT_TERMINAL_PROMPT=0, got %q (present=%v)", v, ok)
@@ -102,7 +104,7 @@ func TestRemoteFetchEnv_RespectsExistingSSHCommand(t *testing.T) {
custom := "ssh -i /tmp/custom-key"
t.Setenv("GIT_SSH_COMMAND", custom)
env := remoteFetchEnv("https://github.com/org/repo.git")
env := remoteFetchEnv("https://github.com/org/repo.git", install.ParseOptions{})
if v, ok := envValue(env, "GIT_SSH_COMMAND"); !ok || v != custom {
t.Fatalf("expected existing GIT_SSH_COMMAND to be preserved, got %q (present=%v)", v, ok)
}
+5 -4
View File
@@ -9,6 +9,7 @@ import (
"skillshare/internal/config"
gitops "skillshare/internal/git"
"skillshare/internal/gitenv"
"skillshare/internal/install"
"skillshare/internal/oplog"
"skillshare/internal/ui"
)
@@ -91,7 +92,7 @@ func pullFromRemote(cfg *config.Config, dryRun, force bool) error {
return nil
}
info, remoteEmpty, err := integrateRemote(source, force, cfg.GitRoot == "root", spinner)
info, remoteEmpty, err := integrateRemote(source, force, cfg.GitRoot == "root", spinner, parseOptsFromConfig(cfg))
if err != nil {
return err
}
@@ -114,10 +115,10 @@ func pullFromRemote(cfg *config.Config, dryRun, force bool) error {
// keepConfig (root scope) keeps this machine's config.yaml on later pulls even
// when the remote tracks one, and warns so the user can untrack it with push.
// FirstPull refuses that case instead (ErrRemoteTracksConfig).
func integrateRemote(source string, force, keepConfig bool, spinner *ui.Spinner) (info *gitops.UpdateInfo, remoteEmpty bool, err error) {
func integrateRemote(source string, force, keepConfig bool, spinner *ui.Spinner, opts install.ParseOptions) (info *gitops.UpdateInfo, remoteEmpty bool, err error) {
if !gitops.HasUpstream(source) {
spinner.Update("Fetching from remote...")
info, err = gitops.FirstPull(source, force)
info, err = gitops.FirstPull(source, force, opts)
if errors.Is(err, gitops.ErrNoRemoteBranches) {
return nil, true, nil
} else if errors.Is(err, gitops.ErrRemoteTracksConfig) {
@@ -157,7 +158,7 @@ func integrateRemote(source string, force, keepConfig bool, spinner *ui.Spinner)
}
spinner.Update("Running git pull...")
if info, err = gitops.PullWithEnv(source, gitops.AuthEnvForRepo(source)); err != nil {
if info, err = gitops.PullWithEnv(source, gitops.AuthEnvForRepo(source, opts)); err != nil {
spinner.Fail("git pull failed")
fmt.Println(err.Error())
hintGitRemoteError(err.Error())
+6 -6
View File
@@ -190,10 +190,10 @@ func hintGitRemoteError(output string) {
}
// gitPush pushes to remote, auto-setting upstream on first push.
func gitPush(sourcePath string, spinner *ui.Spinner) error {
func gitPush(sourcePath string, spinner *ui.Spinner, opts install.ParseOptions) error {
spinner.Update("Pushing to remote...")
authEnv := gitops.AuthEnvForRepo(sourcePath)
authEnv := gitops.AuthEnvForRepo(sourcePath, opts)
cmd := gitenv.Command(gitops.PushArgs(sourcePath, authEnv)...)
cmd.Dir = sourcePath
cmd.Env = append(cmd.Env, "LC_ALL=C")
@@ -251,7 +251,7 @@ func cmdPush(args []string) (err error) {
return err
}
if cfg.GitRoot == "root" {
if err := gitops.CheckUnpushedConfigHistory(source); err != nil {
if err := gitops.CheckUnpushedConfigHistory(source, parseOptsFromConfig(cfg)); err != nil {
spinner.Fail("Cannot safely push config.yaml history")
return err
}
@@ -318,7 +318,7 @@ func cmdPush(args []string) (err error) {
if opts.pull {
pullStart := time.Now()
spinner = ui.StartSpinner("Pulling from remote...")
info, _, err := integrateRemote(source, false, cfg.GitRoot == "root", spinner)
info, _, err := integrateRemote(source, false, cfg.GitRoot == "root", spinner, parseOptsFromConfig(cfg))
if err != nil {
if hasChanges {
ui.Note("Your changes are committed locally; resolve, then run: skillshare push --pull")
@@ -351,12 +351,12 @@ func cmdPush(args []string) (err error) {
}
if cfg.GitRoot == "root" {
if err := gitops.CheckUnpushedConfigHistory(source); err != nil {
if err := gitops.CheckUnpushedConfigHistory(source, parseOptsFromConfig(cfg)); err != nil {
return err
}
}
spinner = ui.StartSpinner("Pushing to remote...")
if err := gitPush(source, spinner); err != nil {
if err := gitPush(source, spinner, parseOptsFromConfig(cfg)); err != nil {
return err
}
+40 -11
View File
@@ -111,20 +111,49 @@ func cmdSearch(args []string) error {
limit = 0
}
var parseOpts install.ParseOptions
if indexURL != "" {
parseOpts, err = searchParseOptions(mode, cwd)
if err != nil {
return err
}
}
// JSON mode: silent search, output JSON
if jsonOutput {
return searchJSON(query, limit, indexURL)
return searchJSON(query, limit, indexURL, parseOpts)
}
// Interactive mode
return searchInteractive(query, limit, listOnly, indexURL, mode, cwd)
return searchInteractive(query, limit, listOnly, indexURL, mode, cwd, parseOpts)
}
func searchJSON(query string, limit int, indexURL string) error {
func searchParseOptions(mode runMode, cwd string) (install.ParseOptions, error) {
if mode == modeProject {
if _, err := os.Stat(config.ProjectConfigPath(cwd)); os.IsNotExist(err) {
return parseOptsFromProjectConfig(&config.ProjectConfig{}), nil
}
cfg, err := config.LoadProject(cwd)
if err != nil {
return install.ParseOptions{}, err
}
return parseOptsFromProjectConfig(cfg), nil
}
if _, err := os.Stat(config.ConfigPath()); os.IsNotExist(err) {
return parseOptsFromConfig(&config.Config{}), nil
}
cfg, err := config.Load()
if err != nil {
return install.ParseOptions{}, err
}
return parseOptsFromConfig(cfg), nil
}
func searchJSON(query string, limit int, indexURL string, opts install.ParseOptions) error {
var results []search.SearchResult
var err error
if indexURL != "" {
results, err = search.SearchFromIndexURL(query, limit, indexURL)
results, err = search.SearchFromIndexURL(query, limit, indexURL, opts)
} else {
results, err = search.Search(query, limit)
}
@@ -143,7 +172,7 @@ func searchJSON(query string, limit int, indexURL string) error {
return nil
}
func searchInteractive(query string, limit int, listOnly bool, indexURL string, mode runMode, cwd string) error {
func searchInteractive(query string, limit int, listOnly bool, indexURL string, mode runMode, cwd string, opts install.ParseOptions) error {
// No query provided: prompt for one
isHub := indexURL != ""
if query == "" {
@@ -156,14 +185,14 @@ func searchInteractive(query string, limit int, listOnly bool, indexURL string,
// List-only mode: single search and exit
if listOnly {
_, err := doSearch(query, limit, true, indexURL, mode, cwd)
_, err := doSearch(query, limit, true, indexURL, mode, cwd, opts)
return err
}
// Interactive loop mode
currentQuery := query
for {
searchAgain, err := doSearch(currentQuery, limit, false, indexURL, mode, cwd)
searchAgain, err := doSearch(currentQuery, limit, false, indexURL, mode, cwd, opts)
if err != nil {
return err
}
@@ -188,7 +217,7 @@ func searchInteractive(query string, limit int, listOnly bool, indexURL string,
}
// doSearch performs a search and returns (searchAgain, error)
func doSearch(query string, limit int, listOnly bool, indexURL string, mode runMode, cwd string) (bool, error) {
func doSearch(query string, limit int, listOnly bool, indexURL string, mode runMode, cwd string, opts install.ParseOptions) (bool, error) {
where := "GitHub"
if indexURL != "" {
where = "the index"
@@ -202,7 +231,7 @@ func doSearch(query string, limit int, listOnly bool, indexURL string, mode runM
var results []search.SearchResult
var err error
if indexURL != "" {
results, err = search.SearchFromIndexURL(query, limit, indexURL)
results, err = search.SearchFromIndexURL(query, limit, indexURL, opts)
} else {
results, err = search.Search(query, limit)
}
@@ -403,7 +432,7 @@ func installFromSearchResultProject(result search.SearchResult, cwd string) (err
// Install
spinner := ui.StartSpinner(fmt.Sprintf("Installing %s...", result.Source))
opts := install.InstallOptions{}
opts := install.InstallOptions{ParseOptions: parseOptsFromProjectConfig(runtime.config)}
if result.Skill != "" {
opts.Skills = []string{result.Skill}
}
@@ -478,7 +507,7 @@ func installFromSearchResult(result search.SearchResult, cfg *config.Config) (er
// Install
spinner := ui.StartSpinner(fmt.Sprintf("Installing %s...", result.Source))
opts := install.InstallOptions{}
opts := install.InstallOptions{ParseOptions: parseOptsFromConfig(cfg)}
if result.Skill != "" {
opts.Skills = []string{result.Skill}
}
+21 -21
View File
@@ -246,13 +246,13 @@ type sourceGroup struct {
// repoSourceForGroupedClone converts a subdir source into a repo-root source.
// This keeps provider-specific details (GitLab/Bitbucket/Azure/GitHub) by
// parsing CloneURL directly, then ensures Subdir is cleared for whole-repo clone.
func repoSourceForGroupedClone(src *install.Source) install.Source {
func repoSourceForGroupedClone(src *install.Source, opts install.ParseOptions) install.Source {
repoSource := *src
repoSource.Subdir = ""
repoSource.Raw = repoSource.CloneURL
// Re-parse CloneURL to get a canonical root-level name/type.
if root, err := install.ParseSource(repoSource.CloneURL); err == nil {
if root, err := install.ParseSourceWithOptions(repoSource.CloneURL, opts); err == nil {
repoSource.Type = root.Type
repoSource.Raw = root.Raw
repoSource.Name = root.Name
@@ -266,12 +266,12 @@ func repoSourceForGroupedClone(src *install.Source) install.Source {
// Web URLs whose ref may contain "/" are settled with resolveRef first.
// Results that cannot be grouped (parse failure, local path, non-subdir singles)
// are returned in the singles slice to be installed individually.
func groupByRepo(selected []search.SearchResult, resolveRef func(*install.Source) error) (groups []sourceGroup, singles []search.SearchResult) {
func groupByRepo(selected []search.SearchResult, opts install.ParseOptions, resolveRef func(*install.Source) error) (groups []sourceGroup, singles []search.SearchResult) {
buckets := make(map[string]*sourceGroup) // keyed by CloneURL and ref
var order []string // preserve insertion order
for _, sr := range selected {
src, err := install.ParseSource(sr.Source)
src, err := install.ParseSourceWithOptions(sr.Source, opts)
if err == nil && src.HasAmbiguousWebRef() {
err = resolveRef(src)
}
@@ -313,8 +313,8 @@ func groupByRepo(selected []search.SearchResult, resolveRef func(*install.Source
// matchDiscoveredSkill finds a SkillInfo in the discovery result that matches
// the given search result's expected subdir path.
func matchDiscoveredSkill(discovery *install.DiscoveryResult, sr search.SearchResult) (install.SkillInfo, bool) {
src, err := install.ParseSource(sr.Source)
func matchDiscoveredSkill(discovery *install.DiscoveryResult, sr search.SearchResult, opts install.ParseOptions) (install.SkillInfo, bool) {
src, err := install.ParseSourceWithOptions(sr.Source, opts)
if err != nil {
return install.SkillInfo{}, false
}
@@ -355,7 +355,7 @@ func collectSearchInstallGlobal(result search.SearchResult, cfg *config.Config,
return r
}
opts := install.InstallOptions{OnProgress: onProgress}
opts := install.InstallOptions{OnProgress: onProgress, ParseOptions: parseOptsFromConfig(cfg)}
if result.Skill != "" {
opts.Skills = []string{result.Skill}
}
@@ -408,7 +408,7 @@ func collectSearchInstallProject(result search.SearchResult, cwd string, onProgr
return r
}
opts := install.InstallOptions{OnProgress: onProgress}
opts := install.InstallOptions{OnProgress: onProgress, ParseOptions: parseOptsFromProjectConfig(runtime.config)}
if result.Skill != "" {
opts.Skills = []string{result.Skill}
}
@@ -450,7 +450,7 @@ func batchInstallFromSearchWithProgress(selected []search.SearchResult, mode run
resultMap := make(map[string]searchInstallResult, len(selected))
// Resolve source directory for the current mode.
sourceDir, err := resolveBatchSourceDir(mode, cfg, cwd)
sourceDir, parseOpts, err := resolveBatchSource(mode, cfg, cwd)
if err != nil {
progress.stop()
return err
@@ -468,12 +468,12 @@ func batchInstallFromSearchWithProgress(selected []search.SearchResult, mode run
// Group by repo: skills sharing the same CloneURL are cloned once.
var refs install.RemoteRefs
groups, singles := groupByRepo(selected, refs.Resolve)
groups, singles := groupByRepo(selected, parseOpts, refs.Resolve)
// Phase 1: grouped install — clone each repo once, install multiple skills.
for _, group := range groups {
// Build a whole-repo source (no Subdir) for cloning.
repoSource := repoSourceForGroupedClone(group.source)
repoSource := repoSourceForGroupedClone(group.source, parseOpts)
// Use the first skill's name for clone progress display.
cloneLabel := group.results[0].Name
@@ -507,7 +507,7 @@ func batchInstallFromSearchWithProgress(selected []search.SearchResult, mode run
for _, sr := range group.results {
progress.updateStatus(sr.Name, "installing...")
r := installFromDiscoveryResult(discovery, sr, sourceDir)
r := installFromDiscoveryResult(discovery, sr, sourceDir, parseOpts)
if r.status == "failed" && r.detail == "skill not found in repo" {
// Can't match in whole-repo discovery — fall back to per-skill install.
fallback = append(fallback, sr)
@@ -574,24 +574,24 @@ func batchInstallFromSearchWithProgress(selected []search.SearchResult, mode run
return nil
}
// resolveBatchSourceDir returns the skill source directory for the given mode.
// resolveBatchSource returns the skill source directory and host policy for the mode.
// For project mode, it requires an initialized project config.
func resolveBatchSourceDir(mode runMode, cfg *config.Config, cwd string) (string, error) {
func resolveBatchSource(mode runMode, cfg *config.Config, cwd string) (string, install.ParseOptions, error) {
if mode == modeProject {
if err := ensureProjectConfig(cwd); err != nil {
return "", fmt.Errorf("project config: %w", err)
return "", install.ParseOptions{}, fmt.Errorf("project config: %w", err)
}
runtime, err := loadProjectRuntime(cwd)
if err != nil {
return "", fmt.Errorf("load config: %w", err)
return "", install.ParseOptions{}, fmt.Errorf("load config: %w", err)
}
return runtime.sourcePath, nil
return runtime.sourcePath, parseOptsFromProjectConfig(runtime.config), nil
}
return cfg.EffectiveSkillsSource(), nil
return cfg.EffectiveSkillsSource(), parseOptsFromConfig(cfg), nil
}
// installFromDiscoveryResult installs a single skill from a pre-cloned discovery result.
func installFromDiscoveryResult(discovery *install.DiscoveryResult, sr search.SearchResult, sourceDir string) searchInstallResult {
func installFromDiscoveryResult(discovery *install.DiscoveryResult, sr search.SearchResult, sourceDir string, opts install.ParseOptions) searchInstallResult {
r := searchInstallResult{
name: sr.Name,
source: sr.Source,
@@ -606,14 +606,14 @@ func installFromDiscoveryResult(discovery *install.DiscoveryResult, sr search.Se
return r
}
skill, found := matchDiscoveredSkill(discovery, sr)
skill, found := matchDiscoveredSkill(discovery, sr, opts)
if !found {
r.status = "failed"
r.detail = "skill not found in repo"
return r
}
installResult, err := install.InstallFromDiscovery(discovery, skill, destPath, install.InstallOptions{})
installResult, err := install.InstallFromDiscovery(discovery, skill, destPath, install.InstallOptions{ParseOptions: opts})
if err != nil {
r.status = "failed"
r.detail = err.Error()
+53 -2
View File
@@ -2,12 +2,15 @@ package main
import (
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"skillshare/internal/install"
"skillshare/internal/search"
"skillshare/internal/testutil"
)
func TestClassifyFailureDetail(t *testing.T) {
@@ -145,7 +148,7 @@ func TestRepoSourceForGroupedClone(t *testing.T) {
t.Fatalf("test input must include subdir, got empty for %q", tt.input)
}
repo := repoSourceForGroupedClone(src)
repo := repoSourceForGroupedClone(src, install.ParseOptions{})
if repo.Subdir != "" {
t.Errorf("repo.Subdir = %q, want empty", repo.Subdir)
@@ -199,7 +202,7 @@ func TestGroupByRepo_PinnedWebURLs(t *testing.T) {
{Name: "h", Source: "github.com/org/skills/skills/h"},
}
groups, singles := groupByRepo(selected, resolve)
groups, singles := groupByRepo(selected, install.ParseOptions{}, resolve)
var got []string
for _, g := range groups {
@@ -221,3 +224,51 @@ func TestGroupByRepo_PinnedWebURLs(t *testing.T) {
t.Errorf("singles = %v, want %v", single, want)
}
}
func TestGroupByRepo_ConfiguredHosts(t *testing.T) {
base := t.TempDir()
repo := testutil.SetupBareRemoteRepo(t, base)
const skillA = "---\nname: a\ndescription: First skill\n---\n# First skill\n"
const skillB = "---\nname: b\ndescription: Second skill\n---\n# Second skill\n"
testutil.SeedRemoteBranch(t, base, repo, "main", map[string]string{
"skills/a/SKILL.md": skillA,
"skills/b/SKILL.md": skillB,
})
for _, tt := range []struct {
host, username, tokenVar string
opts install.ParseOptions
}{
{"cnb.corp.example", "cnb", "CNB_TOKEN", install.ParseOptions{CNBHosts: []string{"cnb.corp.example"}}},
{"forge.corp.example", "x-access-token", "GITEA_TOKEN", install.ParseOptions{GiteaHosts: []string{"forge.corp.example"}}},
} {
t.Run(tt.host, func(t *testing.T) {
t.Setenv(tt.tokenVar, "grouped-search-token")
testutil.ServePrivateGit(t, repo, tt.username, "grouped-search-token")
selected := []search.SearchResult{
{Name: "a", Source: "https://" + tt.host + "/org/repo/skills/a"},
{Name: "b", Source: "https://" + tt.host + "/org/repo/skills/b"},
}
groups, singles := groupByRepo(selected, tt.opts, func(*install.Source) error { return nil })
if len(groups) != 1 || len(singles) != 0 {
t.Fatalf("groups = %d, singles = %d; want one shared clone", len(groups), len(singles))
}
root := repoSourceForGroupedClone(groups[0].source, tt.opts)
discovery, err := install.DiscoverFromGitWithProgress(&root, nil)
if err != nil {
t.Fatal(err)
}
defer install.CleanupDiscovery(discovery)
dest := t.TempDir()
for _, result := range selected {
got := installFromDiscoveryResult(discovery, result, dest, tt.opts)
if got.status != "installed" {
t.Fatalf("grouped install %s: %+v", result.Name, got)
}
body, err := os.ReadFile(filepath.Join(dest, result.Name, "SKILL.md"))
if err != nil || !strings.Contains(string(body), "name: "+result.Name) {
t.Fatalf("installed %s content = %q, error = %v", result.Name, body, err)
}
}
})
}
}
+3 -2
View File
@@ -168,6 +168,7 @@ func batchUpdateAgents(agentsDir string, agents []check.AgentCheckResult, opts *
uc := &updateContext{
sourcePath: agentsDir,
projectRoot: projectRoot,
parseOpts: parseOpts,
opts: &updateOptions{
force: opts.force,
skipAudit: opts.skipAudit,
@@ -751,12 +752,12 @@ func runAgentUpdates(scope agentUpdateScope, results []check.AgentCheckResult, o
}
if opts.jsonOutput {
check.EnrichAgentResultsWithRemote(tracked, nil)
check.EnrichAgentResultsWithRemote(tracked, nil, scope.parseOpts)
} else {
// Stopped after the check, not per remote: agents with nothing to
// ask a remote about never call back.
sp := ui.StartSpinner("Checking " + plural(len(tracked), "agent") + " for updates...")
check.EnrichAgentResultsWithRemote(tracked, nil)
check.EnrichAgentResultsWithRemote(tracked, nil, scope.parseOpts)
sp.Stop()
}
mergeTrackedAgentResults(results, tracked)
+1
View File
@@ -32,6 +32,7 @@ func (uc *updateContext) isProject() bool {
func (uc *updateContext) makeInstallOpts() install.InstallOptions {
opts := install.InstallOptions{
ParseOptions: uc.parseOpts,
Force: true,
AuditOverride: uc.opts.force,
Reinstall: uc.opts.force,
+9 -8
View File
@@ -43,14 +43,15 @@ func runTrackedRepoUpdate(uc *updateContext, repoPath string, onProgress func(st
}
opts := update.TrackedRepoOptions{
SourceDir: uc.sourcePath,
Force: uc.opts.force,
DryRun: uc.opts.dryRun,
SkipAudit: uc.opts.skipAudit,
Threshold: uc.opts.threshold,
ProjectRoot: uc.projectRoot,
Follow: uc.follow,
OnProgress: onProgress,
ParseOptions: uc.parseOpts,
SourceDir: uc.sourcePath,
Force: uc.opts.force,
DryRun: uc.opts.dryRun,
SkipAudit: uc.opts.skipAudit,
Threshold: uc.opts.threshold,
ProjectRoot: uc.projectRoot,
Follow: uc.follow,
OnProgress: onProgress,
}
declined := false
if ui.IsTTY() {
+52
View File
@@ -7,9 +7,61 @@ import (
"testing"
"skillshare/internal/audit"
"skillshare/internal/check"
"skillshare/internal/install"
"skillshare/internal/testutil"
)
func TestBatchUpdateTrackedAgents_ConfiguredHosts(t *testing.T) {
for _, tt := range []struct {
host, username, tokenVar string
opts install.ParseOptions
}{
{"cnb.corp.example", "cnb", "CNB_TOKEN", install.ParseOptions{CNBHosts: []string{"cnb.corp.example"}}},
{"gitea.corp.example", "x-access-token", "GITEA_TOKEN", install.ParseOptions{GiteaHosts: []string{"gitea.corp.example"}}},
} {
t.Run(tt.host, func(t *testing.T) {
base := t.TempDir()
remote := testutil.SetupBareRemoteRepo(t, base)
testutil.SeedRemoteBranch(t, base, remote, "main", map[string]string{"reviewer.md": "# Original agent\n"})
root := filepath.Join(base, "agents")
checkout := filepath.Join(root, "_repo")
// The private transport replaces global Git config; keep checkout
// line endings stable when it disables the Windows autocrlf default.
testutil.RunGit(t, "", "clone", "--config", "core.autocrlf=false", remote, checkout)
before := testutil.RunGit(t, checkout, "rev-parse", "HEAD")
const updated = "# Updated reviewer\nReview changes carefully.\n"
seed := filepath.Join(base, "seed-main")
if err := os.WriteFile(filepath.Join(seed, "reviewer.md"), []byte(updated), 0o644); err != nil {
t.Fatal(err)
}
testutil.RunGit(t, seed, "add", ".")
testutil.RunGit(t, seed, "commit", "-m", "update reviewer")
testutil.RunGit(t, seed, "push", "origin", "HEAD:main")
t.Setenv(tt.tokenVar, "tracked-agent-update-token")
testutil.ServePrivateGit(t, remote, tt.username, "tracked-agent-update-token")
cloneURL := "https://" + tt.host + "/org/repo.git"
testutil.RunGit(t, checkout, "remote", "set-url", "origin", cloneURL)
store := install.NewMetadataStore()
store.Set("_repo", &install.MetadataEntry{Source: cloneURL, Kind: "agent", Tracked: true, Branch: "main"})
if err := store.Save(root); err != nil {
t.Fatal(err)
}
agents := []check.AgentCheckResult{{Name: "_repo/reviewer.md", RepoPath: checkout, RepoURL: cloneURL}}
items, count, failed := batchUpdateAgents(root, agents, &updateAgentArgs{}, "", false, tt.opts)
if count != 1 || failed != 0 {
t.Fatalf("tracked agent update: updated=%d, failed=%d, items=%+v", count, failed, items)
}
if body, err := os.ReadFile(filepath.Join(checkout, "reviewer.md")); err != nil || string(body) != updated {
t.Fatalf("updated agent content = %q, error = %v", body, err)
}
if after := testutil.RunGit(t, checkout, "rev-parse", "HEAD"); after == before {
t.Fatal("tracked checkout did not advance to the updated revision")
}
})
}
}
func TestIsSecurityError(t *testing.T) {
tests := []struct {
err error
+2 -2
View File
@@ -142,7 +142,7 @@ func checkOneAgent(store *install.MetadataStore, sourcePath, relPath string) Age
// EnrichAgentResultsWithRemote checks agents that have RepoURL + Version
// against the remote head of the branch they were installed from.
// Each remote branch is probed once; every agent is compared with its own version.
func EnrichAgentResultsWithRemote(results []AgentCheckResult, onDone func()) {
func EnrichAgentResultsWithRemote(results []AgentCheckResult, onDone func(), parseOpts install.ParseOptions) {
groups := make(map[remoteKey][]int)
var refs []remoteKey
for i, r := range results {
@@ -162,7 +162,7 @@ func EnrichAgentResultsWithRemote(results []AgentCheckResult, onDone func()) {
inputs := make([]URLCheckInput, len(refs))
for i, ref := range refs {
inputs[i] = URLCheckInput{RepoURL: ref.url, Branch: ref.branch}
inputs[i] = URLCheckInput{RepoURL: ref.url, Branch: ref.branch, ParseOptions: parseOpts}
}
outputs := ParallelCheckURLs(inputs, onDone)
+3 -3
View File
@@ -18,7 +18,7 @@ func TestEnrichAgentResultsWithRemote_Failure(t *testing.T) {
{Name: "current", RepoURL: missingRepo, Version: "abc", Status: "up_to_date"},
{Name: "edited", RepoURL: missingRepo, Version: "abc", Status: "drifted"},
}
EnrichAgentResultsWithRemote(results, nil)
EnrichAgentResultsWithRemote(results, nil, install.ParseOptions{})
for _, r := range results {
if r.Status != "error" || r.Message == "" {
t.Errorf("remote failure must be reported: %+v", r)
@@ -195,7 +195,7 @@ func TestEnrichAgentResultsWithRemote_ComparesEachAgentAtItsBranch(t *testing.T)
{Name: "stale", RepoURL: repo, Version: oldMain, Status: "up_to_date"},
{Name: "on-dev", RepoURL: repo, Branch: "dev", Version: dev, Status: "up_to_date"},
}
EnrichAgentResultsWithRemote(results, nil)
EnrichAgentResultsWithRemote(results, nil, install.ParseOptions{})
want := map[string]string{"current": "up_to_date", "stale": "update_available", "on-dev": "up_to_date"}
for _, r := range results {
@@ -258,7 +258,7 @@ func TestCheckAgents_TrackedRepoComparedAtItsBranch(t *testing.T) {
git(agentsDir, "clone", "-q", "-b", "dev", origin, "_repo")
results := CheckAgents(agentsDir)
EnrichAgentResultsWithRemote(results, nil)
EnrichAgentResultsWithRemote(results, nil, install.ParseOptions{})
if len(results) != 1 || results[0].Status != "up_to_date" || results[0].Branch != "dev" {
t.Fatalf("expected the tracked agent up to date on dev, got %+v", results)
}
+9 -6
View File
@@ -4,14 +4,16 @@ import (
"sync"
"skillshare/internal/git"
"skillshare/internal/install"
)
const maxWorkers = 8
// RepoCheckInput describes a tracked repo to check.
type RepoCheckInput struct {
Name string
RepoPath string
Name string
RepoPath string
ParseOptions install.ParseOptions
}
// RepoCheckOutput holds the result of checking a single repo.
@@ -25,8 +27,9 @@ type RepoCheckOutput struct {
// URLCheckInput describes a remote URL to probe.
type URLCheckInput struct {
RepoURL string
Branch string
RepoURL string
Branch string
ParseOptions install.ParseOptions
}
// URLCheckOutput holds the result of probing a remote URL.
@@ -85,7 +88,7 @@ func checkOneRepo(r RepoCheckInput) RepoCheckOutput {
return out
}
behind, err := git.GetBehindCountWithAuth(r.RepoPath)
behind, err := git.GetBehindCountWithAuth(r.RepoPath, r.ParseOptions)
if err != nil {
out.Status = "error"
out.Message = err.Error()
@@ -120,7 +123,7 @@ func ParallelCheckURLs(urls []URLCheckInput, onDone func()) []URLCheckOutput {
defer wg.Done()
defer func() { <-sem }()
hash, err := GitRemote{}.Hash(input.RepoURL, input.Branch)
hash, err := (GitRemote{ParseOptions: input.ParseOptions}).Hash(input.RepoURL, input.Branch)
outputs[idx] = URLCheckOutput{
RepoURL: input.RepoURL,
RemoteHash: hash,
+13 -10
View File
@@ -42,21 +42,24 @@ type Remote interface {
}
// GitRemote is the Remote backed by git, with token auth for private repos.
type GitRemote struct{}
func (GitRemote) Hash(repoURL, branch string) (string, error) {
if branch != "" {
return git.GetRemoteRefHashWithAuth(repoURL, branch)
}
return git.GetRemoteHeadHashWithAuth(repoURL)
type GitRemote struct {
ParseOptions install.ParseOptions
}
func (GitRemote) TreeHashes(repoURL, branch string) map[string]string {
return FetchRemoteTreeHashesForRef(repoURL, branch)
func (r GitRemote) Hash(repoURL, branch string) (string, error) {
if branch != "" {
return git.GetRemoteRefHashWithAuth(repoURL, branch, r.ParseOptions)
}
return git.GetRemoteHeadHashWithAuth(repoURL, r.ParseOptions)
}
func (r GitRemote) TreeHashes(repoURL, branch string) map[string]string {
return FetchRemoteTreeHashesForRef(repoURL, branch, r.ParseOptions)
}
// Options configures Resolution.Run.
type Options struct {
ParseOptions install.ParseOptions
// Remote is the source of remote hashes; nil means GitRemote.
Remote Remote
// Parallel checks up to maxWorkers remotes at once instead of one by one.
@@ -126,7 +129,7 @@ func (r *Resolution) RemoteSkills() int {
func (r *Resolution) Run(ctx context.Context, opts Options) ([]SkillResult, error) {
remote := opts.Remote
if remote == nil {
remote = GitRemote{}
remote = GitRemote{ParseOptions: opts.ParseOptions}
}
resolved := make([][]SkillResult, len(r.groups))
+4 -4
View File
@@ -15,13 +15,13 @@ import (
//
// Returns nil on any error (unsupported git version, network failure, etc.)
// so callers can fall back to commit-level comparison.
func FetchRemoteTreeHashes(repoURL string) map[string]string {
return FetchRemoteTreeHashesForRef(repoURL, "")
func FetchRemoteTreeHashes(repoURL string, opts install.ParseOptions) map[string]string {
return FetchRemoteTreeHashesForRef(repoURL, "", opts)
}
// FetchRemoteTreeHashesForRef is FetchRemoteTreeHashes for a specific branch.
// An empty ref means the remote HEAD.
func FetchRemoteTreeHashesForRef(repoURL, ref string) map[string]string {
func FetchRemoteTreeHashesForRef(repoURL, ref string, opts install.ParseOptions) map[string]string {
if ref == "" {
ref = "HEAD"
}
@@ -44,7 +44,7 @@ func FetchRemoteTreeHashesForRef(repoURL, ref string) map[string]string {
fetchCmd := gitenv.Command(fetchArgs...)
fetchCmd.Dir = tmpDir
// Inject auth env for private repos
if extraEnv := install.AuthEnvForURL(repoURL); len(extraEnv) > 0 {
if extraEnv := install.AuthEnvForURL(repoURL, opts); len(extraEnv) > 0 {
fetchCmd.Env = append(fetchCmd.Env, extraEnv...)
}
if out, err := fetchCmd.CombinedOutput(); err != nil {
+9 -7
View File
@@ -5,6 +5,8 @@ import (
"os/exec"
"path/filepath"
"testing"
"skillshare/internal/install"
)
func TestParseLsTreeOutput(t *testing.T) {
@@ -50,7 +52,7 @@ func TestFetchRemoteTreeHashes_Valid(t *testing.T) {
// Set up a bare remote repo with a subdir
remote := setupBareRepoWithSubdir(t, "skills/my-skill", "SKILL.md", "# Test Skill")
result := FetchRemoteTreeHashes("file://" + remote)
result := FetchRemoteTreeHashes("file://"+remote, install.ParseOptions{})
if result == nil {
t.Fatal("expected non-nil result")
}
@@ -70,7 +72,7 @@ func TestFetchRemoteTreeHashes_Valid(t *testing.T) {
}
func TestFetchRemoteTreeHashes_InvalidURL(t *testing.T) {
result := FetchRemoteTreeHashes("file:///nonexistent/repo")
result := FetchRemoteTreeHashes("file:///nonexistent/repo", install.ParseOptions{})
if result != nil {
t.Errorf("expected nil for invalid URL, got %v", result)
}
@@ -79,7 +81,7 @@ func TestFetchRemoteTreeHashes_InvalidURL(t *testing.T) {
func TestFetchRemoteTreeHashes_SubdirNotFound(t *testing.T) {
remote := setupBareRepoWithSubdir(t, "skills/exists", "SKILL.md", "# Exists")
result := FetchRemoteTreeHashes("file://" + remote)
result := FetchRemoteTreeHashes("file://"+remote, install.ParseOptions{})
if result == nil {
t.Fatal("expected non-nil result")
}
@@ -107,7 +109,7 @@ func TestFetchRemoteTreeHashes_StableAfterUnrelatedChange(t *testing.T) {
gitRun(t, work, "commit", "-m", "add stable skill")
gitRun(t, work, "push", "origin", "HEAD")
hash1 := FetchRemoteTreeHashes("file://" + bare)
hash1 := FetchRemoteTreeHashes("file://"+bare, install.ParseOptions{})
if hash1 == nil {
t.Fatal("expected non-nil result for first fetch")
}
@@ -119,7 +121,7 @@ func TestFetchRemoteTreeHashes_StableAfterUnrelatedChange(t *testing.T) {
gitRun(t, work, "commit", "-m", "unrelated change")
gitRun(t, work, "push", "origin", "HEAD")
hash2 := FetchRemoteTreeHashes("file://" + bare)
hash2 := FetchRemoteTreeHashes("file://"+bare, install.ParseOptions{})
if hash2 == nil {
t.Fatal("expected non-nil result for second fetch")
}
@@ -155,7 +157,7 @@ func TestFetchRemoteTreeHashes_SymlinkBlanksContainingDirs(t *testing.T) {
gitRun(t, work, "commit", "-m", "add skills")
gitRun(t, work, "push", "origin", "HEAD")
result := FetchRemoteTreeHashes("file://" + bare)
result := FetchRemoteTreeHashes("file://"+bare, install.ParseOptions{})
if result == nil {
t.Fatal("expected non-nil result")
}
@@ -230,7 +232,7 @@ func TestFetchRemoteTreeHashes_IgnoresCallerGitDir(t *testing.T) {
}
t.Setenv("GIT_DIR", filepath.Join(host, ".git"))
FetchRemoteTreeHashes("file://" + remote)
FetchRemoteTreeHashes("file://"+remote, install.ParseOptions{})
out, _ := exec.Command("git", "config", "--file", filepath.Join(host, ".git", "config"), "core.bare").Output()
if string(out) != "false\n" {
+16 -16
View File
@@ -230,8 +230,8 @@ func scanGitProgress(data []byte, atEOF bool) (advance int, token []byte, err er
}
// PullWithAuth runs git pull with token auth env inferred from origin remote.
func PullWithAuth(repoPath string) (*UpdateInfo, error) {
return PullWithEnv(repoPath, AuthEnvForRepo(repoPath))
func PullWithAuth(repoPath string, opts install.ParseOptions) (*UpdateInfo, error) {
return PullWithEnv(repoPath, AuthEnvForRepo(repoPath, opts))
}
// PullWithProgress runs git pull and optionally streams progress lines to
@@ -559,8 +559,8 @@ func Commit(dir, msg string) error {
// PushRemoteWithAuth pushes to the default remote with token auth env inferred
// from origin remote.
func PushRemoteWithAuth(dir string) error {
return PushRemoteWithEnv(dir, AuthEnvForRepo(dir))
func PushRemoteWithAuth(dir string, opts install.ParseOptions) error {
return PushRemoteWithEnv(dir, AuthEnvForRepo(dir, opts))
}
// PushRemoteWithEnv pushes to the default remote with additional environment
@@ -685,8 +685,8 @@ var ErrRemoteTracksConfig = errors.New("remote tracks config.yaml")
// branch. Local content is kept by merging the remote history (it may be
// unrelated); with force, or with nothing local, the branch is reset to the
// remote instead. Returns ErrNoRemoteBranches while origin is still empty.
func FirstPull(dir string, force bool) (*UpdateInfo, error) {
authEnv := AuthEnvForRepo(dir)
func FirstPull(dir string, force bool, opts install.ParseOptions) (*UpdateInfo, error) {
authEnv := AuthEnvForRepo(dir, opts)
fetch := gitenv.Command("fetch", "origin")
fetch.Dir = dir
fetch.Env = append(append(fetch.Env, "LC_ALL=C"), authEnv...)
@@ -864,8 +864,8 @@ func GetBehindCount(repoPath string) (int, error) {
// GetBehindCountWithAuth fetches from origin and returns how many commits local
// is behind, injecting HTTPS token auth based on origin remote when available.
func GetBehindCountWithAuth(repoPath string) (int, error) {
return GetBehindCountWithEnv(repoPath, AuthEnvForRepo(repoPath))
func GetBehindCountWithAuth(repoPath string, opts install.ParseOptions) (int, error) {
return GetBehindCountWithEnv(repoPath, AuthEnvForRepo(repoPath, opts))
}
// GetBehindCountWithEnv is like GetBehindCount but with additional env vars.
@@ -894,8 +894,8 @@ func GetRemoteHeadHash(repoURL string) (string, error) {
// GetRemoteHeadHashWithAuth returns remote HEAD hash with HTTPS token auth
// injection when token env vars are available.
func GetRemoteHeadHashWithAuth(repoURL string) (string, error) {
return GetRemoteHeadHashWithEnv(repoURL, install.AuthEnvForURL(repoURL))
func GetRemoteHeadHashWithAuth(repoURL string, opts install.ParseOptions) (string, error) {
return GetRemoteHeadHashWithEnv(repoURL, install.AuthEnvForURL(repoURL, opts))
}
// remoteHashTimeout bounds lightweight remote probes used by check/status flows.
@@ -918,8 +918,8 @@ func GetRemoteRefHash(repoURL, branch string) (string, error) {
}
// GetRemoteRefHashWithAuth returns the remote ref hash with HTTPS token auth.
func GetRemoteRefHashWithAuth(repoURL, branch string) (string, error) {
return GetRemoteRefHashWithEnv(repoURL, branch, install.AuthEnvForURL(repoURL))
func GetRemoteRefHashWithAuth(repoURL, branch string, opts install.ParseOptions) (string, error) {
return GetRemoteRefHashWithEnv(repoURL, branch, install.AuthEnvForURL(repoURL, opts))
}
// GetRemoteRefHashWithEnv returns the hash of a specific ref (branch, tag, or
@@ -1011,8 +1011,8 @@ func abbrevHash(hash string) string {
}
// ForcePullWithAuth runs force-pull flow with token auth env inferred from origin remote.
func ForcePullWithAuth(repoPath string) (*UpdateInfo, error) {
return ForcePullWithEnv(repoPath, AuthEnvForRepo(repoPath))
func ForcePullWithAuth(repoPath string, opts install.ParseOptions) (*UpdateInfo, error) {
return ForcePullWithEnv(repoPath, AuthEnvForRepo(repoPath, opts))
}
// ForcePullWithProgress runs fetch+hard-reset and optionally streams fetch
@@ -1073,9 +1073,9 @@ func ForcePullWithEnv(repoPath string, extraEnv []string) (*UpdateInfo, error) {
}
// AuthEnvForRepo returns HTTPS token auth env vars for the repo's origin remote.
func AuthEnvForRepo(repoPath string) []string {
func AuthEnvForRepo(repoPath string, opts install.ParseOptions) []string {
url, _ := GetRemoteURL(repoPath)
return install.AuthEnvForURL(url)
return install.AuthEnvForURL(url, opts)
}
// GetRemoteURL returns the fetch URL for the "origin" remote.
+44 -13
View File
@@ -66,7 +66,7 @@ func TestPushRemoteWithEnv_TokenNotInError(t *testing.T) {
t.Setenv("PATH", fakeBin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("GITHUB_TOKEN", token)
extraEnv := install.AuthEnvForURL("https://github.com/org/repo.git")
extraEnv := install.AuthEnvForURL("https://github.com/org/repo.git", install.ParseOptions{})
err := PushRemoteWithEnv(t.TempDir(), extraEnv)
if err == nil {
@@ -105,7 +105,7 @@ func TestPushRemoteWithEnv_PreservesStdoutDiagnostics(t *testing.T) {
t.Setenv("PATH", fakeBin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("GITHUB_TOKEN", token)
extraEnv := install.AuthEnvForURL("https://github.com/org/repo.git")
extraEnv := install.AuthEnvForURL("https://github.com/org/repo.git", install.ParseOptions{})
err := PushRemoteWithEnv(t.TempDir(), extraEnv)
if err == nil {
@@ -273,7 +273,7 @@ func TestAuthEnvForRepo_UsesGitHubToken(t *testing.T) {
addRemote(t, repo, "https://github.com/org/private-repo.git")
t.Setenv("GITHUB_TOKEN", "ghp_test_token_123")
env := AuthEnvForRepo(repo)
env := AuthEnvForRepo(repo, install.ParseOptions{})
for _, want := range []string{
"GIT_CONFIG_KEY_0=credential.https://github.com.helper",
"SKILLSHARE_GIT_AUTH_USERNAME=x-access-token",
@@ -290,7 +290,7 @@ func TestAuthEnvForRepo_UsesGitLabToken(t *testing.T) {
addRemote(t, repo, "https://gitlab.com/group/private-repo.git")
t.Setenv("GITLAB_TOKEN", "glpat_test_token_123")
env := AuthEnvForRepo(repo)
env := AuthEnvForRepo(repo, install.ParseOptions{})
for _, want := range []string{
"GIT_CONFIG_KEY_0=credential.https://gitlab.com.helper",
"SKILLSHARE_GIT_AUTH_USERNAME=oauth2",
@@ -308,7 +308,7 @@ func TestAuthEnvForRepo_NoTokenReturnsNil(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
env := AuthEnvForRepo(repo)
env := AuthEnvForRepo(repo, install.ParseOptions{})
if env != nil {
t.Fatalf("expected nil auth env without tokens, got: %v", env)
}
@@ -320,7 +320,7 @@ func TestAuthEnvForRepo_SSHRemote_ReturnsNil(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "ghp_test_token_123")
t.Setenv("SKILLSHARE_GIT_TOKEN", "generic-token")
env := AuthEnvForRepo(repo)
env := AuthEnvForRepo(repo, install.ParseOptions{})
if env != nil {
t.Fatalf("expected nil auth env for SSH remote, got: %v", env)
}
@@ -985,7 +985,7 @@ func TestFirstPull_MergesUnrelatedRemoteHistory(t *testing.T) {
}
runGit(t, repo, "remote", "add", "origin", remote)
if _, err := FirstPull(repo, false); err != nil {
if _, err := FirstPull(repo, false, install.ParseOptions{}); err != nil {
t.Fatalf("FirstPull() error: %v", err)
}
_, statErr := os.Stat(filepath.Join(repo, "remote-skill", "SKILL.md"))
@@ -999,7 +999,7 @@ func TestFirstPull_KeepsFilesOnlyLocalCommits(t *testing.T) {
repo := initTestRepo(t) // commits README.md at the root, no directories
runGit(t, repo, "remote", "add", "origin", remote)
if _, err := FirstPull(repo, false); err != nil {
if _, err := FirstPull(repo, false, install.ParseOptions{}); err != nil {
t.Fatalf("FirstPull() error: %v", err)
}
if _, err := os.Stat(filepath.Join(repo, "README.md")); err != nil {
@@ -1026,7 +1026,7 @@ func TestFirstPull_RootScopeScaffoldMergesAndStaysClean(t *testing.T) {
}
runGit(t, repo, "remote", "add", "origin", remote)
if _, err := FirstPull(repo, false); err != nil {
if _, err := FirstPull(repo, false, install.ParseOptions{}); err != nil {
t.Fatalf("FirstPull() error: %v", err)
}
if dirty, err := IsDirty(repo); err != nil || dirty {
@@ -1057,7 +1057,7 @@ func TestFirstPull_RootScopeRemoteTracksConfig_Refused(t *testing.T) {
runGit(t, repo, "remote", "add", "origin", remote)
// Merge path (force=false) must refuse
_, err := FirstPull(repo, false)
_, err := FirstPull(repo, false, install.ParseOptions{})
if !errors.Is(err, ErrRemoteTracksConfig) {
t.Fatalf("FirstPull(force=false) err = %v, want ErrRemoteTracksConfig", err)
}
@@ -1070,7 +1070,7 @@ func TestFirstPull_RootScopeRemoteTracksConfig_Refused(t *testing.T) {
}
// Reset path (force=true) must also refuse
_, err = FirstPull(repo, true)
_, err = FirstPull(repo, true, install.ParseOptions{})
if !errors.Is(err, ErrRemoteTracksConfig) {
t.Fatalf("FirstPull(force=true) err = %v, want ErrRemoteTracksConfig", err)
}
@@ -1095,7 +1095,7 @@ func TestFirstPull_NonRootScopeRemoteTracksConfig_Allowed(t *testing.T) {
runGit(t, repo, "config", "user.name", "test")
runGit(t, repo, "remote", "add", "origin", remote)
if _, err := FirstPull(repo, false); err != nil {
if _, err := FirstPull(repo, false, install.ParseOptions{}); err != nil {
t.Fatalf("FirstPull() error: %v", err)
}
}
@@ -1106,7 +1106,7 @@ func TestFirstPull_EmptyRemoteReportsNoBranches(t *testing.T) {
repo := initTestRepo(t)
runGit(t, repo, "remote", "add", "origin", remote)
if _, err := FirstPull(repo, false); !errors.Is(err, ErrNoRemoteBranches) {
if _, err := FirstPull(repo, false, install.ParseOptions{}); !errors.Is(err, ErrNoRemoteBranches) {
t.Fatalf("FirstPull() error = %v, want ErrNoRemoteBranches", err)
}
}
@@ -1128,3 +1128,34 @@ func TestGetCurrentFullHash_IgnoresCallerGitDir(t *testing.T) {
t.Errorf("GetCurrentFullHash() = %s, want %s from the repo, not GIT_DIR", got, want)
}
}
func TestAuthEnvForRepo_ConfiguredProviderOrigins(t *testing.T) {
for _, provider := range []struct {
name string
token string
opts install.ParseOptions
}{
{"gitea", "GITEA_TOKEN", install.ParseOptions{GiteaHosts: []string{"forge.example"}}},
{"cnb", "CNB_TOKEN", install.ParseOptions{CNBHosts: []string{"forge.example"}}},
} {
t.Run(provider.name, func(t *testing.T) {
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
t.Setenv(provider.token, "private-provider-token")
for _, host := range []string{"forge.example", "forge.example.attacker.test"} {
repo := initTestRepo(t)
addRemote(t, repo, "https://"+host+"/org/repo.git")
env := AuthEnvForRepo(repo, provider.opts)
if host == "forge.example" {
if !slices.Contains(env, "SKILLSHARE_GIT_AUTH_PASSWORD=private-provider-token") {
t.Fatalf("configured provider origin missing credentials: %v", env)
}
} else if env != nil {
t.Fatalf("lookalike origin received credentials: %v", env)
}
if env := AuthEnvForRepo(repo, install.ParseOptions{}); env != nil {
t.Fatalf("unconfigured provider origin received credentials: %v", env)
}
}
})
}
}
+2 -2
View File
@@ -49,8 +49,8 @@ func (e *PullConflictError) Error() string {
}
// PullWithResolution retries a pull with the user's reviewed choices, preserving both histories.
func PullWithResolution(repoPath string, resolution *PullResolution) (*UpdateInfo, error) {
return pullWithResolution(repoPath, AuthEnvForRepo(repoPath), nil, resolution)
func PullWithResolution(repoPath string, resolution *PullResolution, opts install.ParseOptions) (*UpdateInfo, error) {
return pullWithResolution(repoPath, AuthEnvForRepo(repoPath, opts), nil, resolution)
}
func conflictVersion(dir, path string, stage int) ConflictVersion {
+5 -4
View File
@@ -12,6 +12,7 @@ import (
"strings"
"skillshare/internal/gitenv"
"skillshare/internal/install"
)
// WriteScopeGitignore ensures a .gitignore at dir. If none exists it writes a
@@ -243,7 +244,7 @@ func (e *UnpushedConfigHistoryError) Error() string {
// `push --pull` can integrate first. Deletions alone are safe; combined merge
// diffs check new resolutions without treating config inherited from upstream
// as a new local change. The check never changes the index, worktree, or refs.
func CheckUnpushedConfigHistory(dir string) error {
func CheckUnpushedConfigHistory(dir string, opts install.ParseOptions) error {
head := gitenv.Command("rev-parse", "--verify", "--quiet", "HEAD")
head.Dir = dir
if err := head.Run(); err != nil {
@@ -258,7 +259,7 @@ func CheckUnpushedConfigHistory(dir string) error {
args := []string{"--no-replace-objects", "log", "--format=%x00%h", "--full-history", "--root",
"-c", "--diff-filter=AMT", "--no-renames", "--no-show-signature", "--raw"}
cmd := gitenv.Command()
live, rejected, ok := liveRemoteCommits(dir, remote, branch)
live, rejected, ok := liveRemoteCommits(dir, remote, branch, opts)
if rejected {
return nil
}
@@ -313,7 +314,7 @@ func CheckUnpushedConfigHistory(dir string) error {
// remote-tracking refs can be stale after the remote was rewritten to drop a
// leaked config.yaml, so they are only the fallback (ok=false) when the remote
// cannot be reached, in which case the push itself fails too.
func liveRemoteCommits(dir, remote, branch string) (objects []string, rejected, ok bool) {
func liveRemoteCommits(dir, remote, branch string, opts install.ParseOptions) (objects []string, rejected, ok bool) {
getURLs := gitenv.Command("remote", "get-url", "--push", "--all", remote)
getURLs.Dir = dir
out, err := getURLs.Output()
@@ -326,7 +327,7 @@ func liveRemoteCommits(dir, remote, branch string) (objects []string, rejected,
for _, url := range strings.Split(strings.TrimSpace(string(out)), "\n") {
lsRemote := gitenv.Command("ls-remote", "--symref", url)
lsRemote.Dir = dir
lsRemote.Env = append(lsRemote.Env, AuthEnvForRepo(dir)...)
lsRemote.Env = append(lsRemote.Env, install.AuthEnvForURL(url, opts)...)
refs, err := lsRemote.Output()
if err != nil {
return nil, false, false
+13 -11
View File
@@ -7,6 +7,8 @@ import (
"path/filepath"
"strings"
"testing"
"skillshare/internal/install"
)
func TestCheckUnpushedConfigHistory(t *testing.T) {
@@ -56,7 +58,7 @@ func TestCheckUnpushedConfigHistory(t *testing.T) {
gitExec(t, dir, "add", "--", tc.path)
gitExec(t, dir, "commit", "-m", "modify config")
}
err := CheckUnpushedConfigHistory(dir)
err := CheckUnpushedConfigHistory(dir, install.ParseOptions{})
var historyErr *UnpushedConfigHistoryError
if errors.As(err, &historyErr) != tc.wantUnsafe {
t.Fatalf("CheckUnpushedConfigHistory() = %v; wantUnsafe=%t", err, tc.wantUnsafe)
@@ -74,7 +76,7 @@ func TestCheckUnpushedConfigHistory(t *testing.T) {
func TestCheckUnpushedConfigHistory_FirstPush(t *testing.T) {
dir := t.TempDir()
gitExec(t, dir, "init")
if err := CheckUnpushedConfigHistory(dir); err != nil {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); err != nil {
t.Fatalf("unborn branch: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("local\n"), 0o644); err != nil {
@@ -83,7 +85,7 @@ func TestCheckUnpushedConfigHistory_FirstPush(t *testing.T) {
gitExec(t, dir, "add", "config.yaml")
gitExec(t, dir, "commit", "-m", "initial config")
var historyErr *UnpushedConfigHistoryError
if err := CheckUnpushedConfigHistory(dir); !errors.As(err, &historyErr) || historyErr.HasUpstream || len(historyErr.Commits) != 1 {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); !errors.As(err, &historyErr) || historyErr.HasUpstream || len(historyErr.Commits) != 1 {
t.Fatalf("first push = %v; want initial commit refused without upstream", err)
}
}
@@ -101,7 +103,7 @@ func TestCheckUnpushedConfigHistory_Renames(t *testing.T) {
gitExec(t, dir, "mv", "config.yaml", "note.yaml")
gitExec(t, dir, "commit", "-m", "rename away from config")
var historyErr *UnpushedConfigHistoryError
if err := CheckUnpushedConfigHistory(dir); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
t.Fatalf("renames = %v; want only rename into config refused", err)
}
}
@@ -120,7 +122,7 @@ func TestCheckUnpushedConfigHistory_MergeAddsConfig(t *testing.T) {
gitExec(t, dir, "add", "config.yaml")
gitExec(t, dir, "commit", "-m", "merge with config")
var historyErr *UnpushedConfigHistoryError
if err := CheckUnpushedConfigHistory(dir); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
t.Fatalf("merge = %v; want config introduced by merge refused", err)
}
}
@@ -139,7 +141,7 @@ func TestCheckUnpushedConfigHistory_NoUpstreamIgnoresPublishedConfig(t *testing.
gitExec(t, dir, "push", "origin", "main")
gitExec(t, dir, "rm", "--cached", "config.yaml")
gitExec(t, dir, "commit", "-m", "Keep config.yaml out of version control")
if err := CheckUnpushedConfigHistory(dir); err != nil {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); err != nil {
t.Fatalf("published config with only a local deletion = %v; want allowed", err)
}
}
@@ -162,7 +164,7 @@ func TestCheckUnpushedConfigHistory_StaleRemoteRefAfterRewrite(t *testing.T) {
gitExec(t, dir, "commit", "--allow-empty", "-m", "later work")
var historyErr *UnpushedConfigHistoryError
if err := CheckUnpushedConfigHistory(dir); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
t.Fatalf("stale remote-tracking ref = %v; want the leaked commit refused", err)
}
}
@@ -186,7 +188,7 @@ func TestCheckUnpushedConfigHistory_ChecksEveryPushURL(t *testing.T) {
gitExec(t, dir, "remote", "set-url", "--add", "--push", "origin", mirror)
var historyErr *UnpushedConfigHistoryError
if err := CheckUnpushedConfigHistory(dir); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
t.Fatalf("push URL without the commit = %v; want the leaked commit refused", err)
}
}
@@ -208,7 +210,7 @@ func TestCheckUnpushedConfigHistory_IgnoresReplaceRefs(t *testing.T) {
gitExec(t, dir, "replace", "main", "clean")
var historyErr *UnpushedConfigHistoryError
if err := CheckUnpushedConfigHistory(dir); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
t.Fatalf("replaced commit = %v; want the original leaked commit refused", err)
}
}
@@ -235,7 +237,7 @@ func TestCheckUnpushedConfigHistory_BehindRemoteAllowsPublishedConfig(t *testing
// The remote tip is unknown here, so the push is rejected as non-fast-forward
// and `push --pull` must be allowed to pull first.
if err := CheckUnpushedConfigHistory(dir); err != nil {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); err != nil {
t.Fatalf("behind remote with published config = %v; want allowed", err)
}
}
@@ -259,7 +261,7 @@ func TestCheckUnpushedConfigHistory_GoneUpstreamChecksOrigin(t *testing.T) {
gitExec(t, dir, "update-ref", "-d", "refs/remotes/fork/main")
var historyErr *UnpushedConfigHistoryError
if err := CheckUnpushedConfigHistory(dir); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
if err := CheckUnpushedConfigHistory(dir, install.ParseOptions{}); !errors.As(err, &historyErr) || len(historyErr.Commits) != 1 {
t.Fatalf("gone upstream = %v; want the commit refused because origin lacks it", err)
}
}
+23 -6
View File
@@ -26,13 +26,25 @@ func (e *RateLimitError) Error() string {
return msg
}
// NewClient creates an HTTP client for GitHub/GHE APIs.
// NewClient keeps provider authorization on the initial forge API or hub origin.
func NewClient() *http.Client {
return &http.Client{Timeout: 15 * time.Second}
return &http.Client{
Timeout: 15 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("stopped after 10 redirects")
}
if req.URL.Scheme != via[0].URL.Scheme || !strings.EqualFold(req.URL.Host, via[0].URL.Host) {
req.Header.Del("Authorization")
req.Header.Del("PRIVATE-TOKEN")
}
return nil
},
}
}
// NewRequest creates a GET request with default GitHub headers and optional
// token auth (GITHUB_TOKEN / GH_TOKEN / gh auth token).
// NewRequest creates a GET request with default GitHub headers. GitHub
// credentials are attached only to its public API and raw-content HTTPS origins.
func NewRequest(url string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
@@ -41,8 +53,13 @@ func NewRequest(url string) (*http.Request, error) {
req.Header.Set("Accept", "application/vnd.github.v3+json")
if token := GetToken(); token != "" {
req.Header.Set("Authorization", "token "+token)
if req.URL.Scheme == "https" && (req.URL.Port() == "" || req.URL.Port() == "443") {
switch strings.ToLower(req.URL.Hostname()) {
case "api.github.com", "raw.githubusercontent.com":
if token := GetToken(); token != "" {
req.Header.Set("Authorization", "token "+token)
}
}
}
return req, nil
+87
View File
@@ -0,0 +1,87 @@
package github
import (
"io"
"net/http"
"strings"
"testing"
)
func TestNewRequestScopesGitHubCredentials(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "audit-dummy-token")
for _, tt := range []struct {
url string
want string
}{
{"https://api.github.com/repos/o/r", "token audit-dummy-token"},
{"https://raw.githubusercontent.com/o/r/main/SKILL.md", "token audit-dummy-token"},
{"https://github.attacker.invalid/api/v3/repos/o/r", ""},
{"https://api.github.com.attacker.invalid/repos/o/r", ""},
{"https://api.github.com:8443/repos/o/r", ""},
{"http://api.github.com/repos/o/r", ""},
} {
t.Run(tt.url, func(t *testing.T) {
req, err := NewRequest(tt.url)
if err != nil {
t.Fatal(err)
}
if got := req.Header.Get("Authorization"); got != tt.want {
t.Fatalf("Authorization = %q, want %q", got, tt.want)
}
})
}
}
type credentialRedirectTransport func(*http.Request) (*http.Response, error)
func (f credentialRedirectTransport) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r)
}
func TestClientDoesNotForwardCredentialsAcrossOrigins(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "audit-dummy-token")
for _, tt := range []struct {
redirect string
want string
}{
{"https://api.github.com/finish", "token audit-dummy-token"},
{"https://sub.api.github.com/finish", ""},
{"https://api.github.com:8443/finish", ""},
{"http://api.github.com/finish", ""},
{"https://unrelated.invalid/finish", ""},
} {
t.Run(tt.redirect, func(t *testing.T) {
finalAuth := "not reached"
finalPrivate := "not reached"
client := NewClient()
client.Transport = credentialRedirectTransport(func(r *http.Request) (*http.Response, error) {
header := make(http.Header)
status := http.StatusOK
if r.URL.Path == "/start" {
header.Set("Location", tt.redirect)
status = http.StatusFound
} else {
finalAuth = r.Header.Get("Authorization")
finalPrivate = r.Header.Get("PRIVATE-TOKEN")
}
return &http.Response{StatusCode: status, Header: header, Body: io.NopCloser(strings.NewReader("fixture")), Request: r}, nil
})
req, err := NewRequest("https://api.github.com/start")
if err != nil {
t.Fatal(err)
}
req.Header.Set("PRIVATE-TOKEN", "audit-dummy-token")
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if finalAuth != tt.want {
t.Fatalf("redirect Authorization = %q, want %q", finalAuth, tt.want)
}
if want := strings.TrimPrefix(tt.want, "token "); finalPrivate != want {
t.Fatalf("redirect PRIVATE-TOKEN = %q, want %q", finalPrivate, want)
}
})
}
}
+43 -10
View File
@@ -73,10 +73,9 @@ func detectPlatform(cloneURL string) Platform {
return PlatformUnknown
}
// resolveToken looks up a token from environment variables based on the
// detected platform. Platform-specific vars take priority over the generic
// SKILLSHARE_GIT_TOKEN. Returns empty strings if no token is available or
// the URL is not HTTPS.
// resolveToken looks up HTTPS credentials. Provider tokens require a trusted
// host; platform-name heuristics are only for parsing, never authorization.
// SKILLSHARE_GIT_TOKEN remains an explicit fallback for any HTTPS source.
func resolveToken(cloneURL string) (token, username string) {
return resolveTokenWithOptions(cloneURL, nil, nil)
}
@@ -86,7 +85,7 @@ func resolveTokenWithOptions(cloneURL string, cnbHosts, giteaHosts []string) (to
return "", ""
}
platform := detectPlatformWithOptions(cloneURL, cnbHosts, giteaHosts)
platform := credentialPlatform(cloneURL, cnbHosts, giteaHosts)
switch platform {
case PlatformGitHub:
if t := os.Getenv("GITHUB_TOKEN"); t != "" {
@@ -126,7 +125,7 @@ func resolveTokenWithOptions(cloneURL string, cnbHosts, giteaHosts []string) (to
if u := urlUsername(cloneURL); u != "" {
return t, u
}
switch platform {
switch detectPlatformWithOptions(cloneURL, cnbHosts, giteaHosts) {
case PlatformGitLab:
return t, "oauth2"
case PlatformBitbucket:
@@ -138,6 +137,40 @@ func resolveTokenWithOptions(cloneURL string, cnbHosts, giteaHosts []string) (to
return "", ""
}
// credentialPlatform binds provider credentials to their public HTTPS origin,
// or an explicitly configured CNB/Gitea host, not a provider-looking name.
func credentialPlatform(rawURL string, cnbHosts, giteaHosts []string) Platform {
u, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || !strings.EqualFold(u.Scheme, "https") || (u.Port() != "" && u.Port() != "443") {
return PlatformUnknown
}
host := strings.ToLower(u.Hostname())
switch host {
case "github.com", "api.github.com", "raw.githubusercontent.com":
return PlatformGitHub
case "gitlab.com":
return PlatformGitLab
case "bitbucket.org":
return PlatformBitbucket
case "dev.azure.com":
return PlatformAzureDevOps
case "cnb.cool":
return PlatformCNB
case "gitea.com":
return PlatformGitea
}
if strings.HasSuffix(host, ".visualstudio.com") {
return PlatformAzureDevOps
}
if hostMatchesAny(host, cnbHosts) {
return PlatformCNB
}
if hostMatchesAny(host, giteaHosts) {
return PlatformGitea
}
return PlatformUnknown
}
// authEnv returns environment variables that give git the token through a
// credential helper set via GIT_CONFIG_COUNT/KEY/VALUE (Git 2.31+). The token
// itself travels only in SKILLSHARE_GIT_AUTH_PASSWORD, never in config or argv.
@@ -187,14 +220,14 @@ const (
// AuthEnvForURL returns git auth injection env for HTTPS clone/pull URLs.
// Returns nil when no token is available or URL is not HTTPS.
func AuthEnvForURL(cloneURL string) []string {
return authEnv(cloneURL)
func AuthEnvForURL(cloneURL string, opts ParseOptions) []string {
return authEnvWithOptions(cloneURL, opts.CNBHosts, opts.GiteaHosts)
}
// ResolveTokenForURL returns token credentials resolved from env vars for the
// provided HTTPS URL. Returns empty strings when no token is available.
func ResolveTokenForURL(cloneURL string) (token, username string) {
return resolveToken(cloneURL)
func ResolveTokenForURL(cloneURL string, opts ParseOptions) (token, username string) {
return resolveTokenWithOptions(cloneURL, opts.CNBHosts, opts.GiteaHosts)
}
// DetectPlatformForURL identifies the git hosting platform for a URL.
+29 -1
View File
@@ -196,7 +196,7 @@ func TestResolveToken(t *testing.T) {
},
{
name: "gitea token",
url: "https://gitea.example.com/org/repo.git",
url: "https://gitea.com/org/repo.git",
envVars: map[string]string{"GITEA_TOKEN": "gitea_pat"},
wantTok: "gitea_pat",
wantUser: "x-access-token",
@@ -557,3 +557,31 @@ func TestSanitizeTokens(t *testing.T) {
})
}
}
func TestProviderCredentialsRejectUntrustedOrigins(t *testing.T) {
tests := []struct {
url, variable string
}{
{"https://github.attacker.invalid/o/r.git", "GITHUB_TOKEN"},
{"https://github.attacker.invalid/o/r.git", "GH_TOKEN"},
{"https://gitlab.attacker.invalid/o/r.git", "GITLAB_TOKEN"},
{"https://bitbucket.attacker.invalid/o/r.git", "BITBUCKET_TOKEN"},
{"https://cnb.cool.attacker.invalid/o/r.git", "CNB_TOKEN"},
{"https://gitea.attacker.invalid/o/r.git", "GITEA_TOKEN"},
{"https://github.com:8443/o/r.git", "GITHUB_TOKEN"},
{"https://github.company.invalid/o/r.git", "GITHUB_TOKEN"},
{"https://gitlab.company.invalid/o/r.git", "GITLAB_TOKEN"},
}
for _, tt := range tests {
t.Run(tt.variable+"/"+tt.url, func(t *testing.T) {
resetAuthTestEnv(t)
t.Setenv(tt.variable, "audit-dummy-provider-token")
if token, _ := resolveToken(tt.url); token != "" {
t.Fatal("provider credential selected for an untrusted origin")
}
if got := authEnv(tt.url); got != nil {
t.Fatal("Git credential helper exposes a provider credential to an untrusted origin")
}
})
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ func UpdateSkillsFromRepo(repoURL, branch string, skillTargets map[string]string
return nil, fmt.Errorf("repoURL is required")
}
source, err := ParseSource(repoURL)
source, err := ParseSourceWithOptions(repoURL, opts.ParseOptions)
if err != nil {
return nil, fmt.Errorf("failed to parse repo URL %q: %w", repoURL, err)
}
+49
View File
@@ -12,6 +12,55 @@ import (
"skillshare/internal/testutil"
)
func TestUpdateSkillsFromRepo_ConfiguredHosts(t *testing.T) {
for _, tt := range []struct {
host, username, tokenVar string
opts ParseOptions
}{
{"cnb.corp.example", "cnb", "CNB_TOKEN", ParseOptions{CNBHosts: []string{"cnb.corp.example"}}},
{"gitea.corp.example", "x-access-token", "GITEA_TOKEN", ParseOptions{GiteaHosts: []string{"gitea.corp.example"}}},
} {
t.Run(tt.host, func(t *testing.T) {
base := t.TempDir()
repo := testutil.SetupBareRemoteRepo(t, base)
files := map[string]string{
"skills/a/SKILL.md": "---\nname: a\n---\n# Updated first skill\n",
"skills/b/SKILL.md": "---\nname: b\n---\n# Updated second skill\n",
}
testutil.SeedRemoteBranch(t, base, repo, "main", files)
t.Setenv(tt.tokenVar, "grouped-update-token")
testutil.ServePrivateGit(t, repo, tt.username, "grouped-update-token")
root := t.TempDir()
targets := make(map[string]string)
for _, name := range []string{"a", "b"} {
dest := filepath.Join(root, name)
if err := os.MkdirAll(dest, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dest, "SKILL.md"), []byte("# Old skill\n"), 0o644); err != nil {
t.Fatal(err)
}
targets["skills/"+name] = dest
}
result, err := UpdateSkillsFromRepo("https://"+tt.host+"/org/repo.git", "main", targets, InstallOptions{
ParseOptions: tt.opts, SourceDir: root, Update: true, Force: true,
})
if err != nil {
t.Fatal(err)
}
if len(result.Errors) != 0 {
t.Fatalf("grouped update failed: %v", result.Errors)
}
for subdir, dest := range targets {
body, err := os.ReadFile(filepath.Join(dest, "SKILL.md"))
if err != nil || string(body) != files[subdir+"/SKILL.md"] {
t.Fatalf("updated %s content = %q, error = %v", subdir, body, err)
}
}
})
}
}
func TestIsSkillCurrentAtRepoState_RootSkillCommitMatch(t *testing.T) {
repo := initTestRepo(t)
if err := os.WriteFile(filepath.Join(repo, "SKILL.md"), []byte("# Root"), 0644); err != nil {
+2 -2
View File
@@ -70,7 +70,7 @@ func TestShallowCloneToTemp(t *testing.T) {
gitAdd(t, src, ".")
gitCommit(t, src, "init")
dir, err := ShallowCloneToTemp(src, "")
dir, err := ShallowCloneToTemp(src, "", ParseOptions{})
if err != nil {
t.Fatalf("ShallowCloneToTemp: %v", err)
}
@@ -82,7 +82,7 @@ func TestShallowCloneToTemp(t *testing.T) {
}
func TestShallowCloneToTemp_BadURL(t *testing.T) {
dir, err := ShallowCloneToTemp(t.TempDir()+"/does-not-exist", "")
dir, err := ShallowCloneToTemp(t.TempDir()+"/does-not-exist", "", ParseOptions{})
if err == nil {
t.Fatalf("expected error cloning nonexistent repo, got dir %q", dir)
}
+2 -2
View File
@@ -26,7 +26,7 @@ type GitUpdateCandidate struct {
// StageGitUpdate clones the current branch and preserves the pull's local Git
// configuration. discard omits local edits for the update command's force mode.
func StageGitUpdate(repoPath string, discard bool) (_ *GitUpdateCandidate, err error) {
func StageGitUpdate(repoPath string, discard bool, opts ParseOptions) (_ *GitUpdateCandidate, err error) {
repoPath, err = filepath.Abs(repoPath)
if err != nil {
return nil, err
@@ -48,7 +48,7 @@ func StageGitUpdate(repoPath string, discard bool) (_ *GitUpdateCandidate, err e
}
// Partial clones lack intermediate blobs; git >= 2.45.1 refuses to
// lazy-fetch them through a local upload-pack unless re-enabled.
env := append(AuthEnvForURL(getRemoteURL(repoPath)), "GIT_NO_LAZY_FETCH=0")
env := append(AuthEnvForURL(getRemoteURL(repoPath), opts), "GIT_NO_LAZY_FETCH=0")
c := &GitUpdateCandidate{Path: filepath.Join(temp, filepath.Base(repoPath)), BeforeHash: before, repoPath: repoPath, tempDir: temp, discard: discard, state: state, env: env}
defer func() {
if err != nil {
+4 -4
View File
@@ -43,7 +43,7 @@ func testGitUpdateCandidatePreservesLocalChanges(t *testing.T, autocrlf, worktre
t.Fatal(err)
}
before := testutil.RunGit(t, repo, "status", "--porcelain")
candidate, err := StageGitUpdate(repo, false)
candidate, err := StageGitUpdate(repo, false, ParseOptions{})
if err != nil {
t.Fatal(err)
}
@@ -60,7 +60,7 @@ func testGitUpdateCandidatePreservesLocalChanges(t *testing.T, autocrlf, worktre
}
// Use a fast-forward candidate; git itself refuses divergent merges with
// staged local changes, just as it did before staging was introduced.
if err := gitPull(candidate.Path, nil); err != nil {
if err := gitPull(candidate.Path, nil, nil); err != nil {
t.Fatal(err)
}
revision, err := getGitFullHash(candidate.Path)
@@ -145,12 +145,12 @@ func TestGitUpdateCandidateFailedPublicationPreservesCheckout(t *testing.T) {
if err != nil {
t.Fatal(err)
}
candidate, err := StageGitUpdate(repo, force)
candidate, err := StageGitUpdate(repo, force, ParseOptions{})
if err != nil {
t.Fatal(err)
}
defer candidate.Close()
if err := gitPull(candidate.Path, nil); err != nil {
if err := gitPull(candidate.Path, nil, nil); err != nil {
t.Fatal(err)
}
revision := testutil.RunGit(t, candidate.Path, "rev-parse", "HEAD")
+51 -48
View File
@@ -11,6 +11,8 @@ import (
"path/filepath"
"strings"
"time"
ghclient "skillshare/internal/github"
)
type giteaContentItem struct {
@@ -67,8 +69,9 @@ func downloadGiteaDir(owner, repo, path, destDir string, source *Source, onProgr
onProgress("Downloading via Gitea API...")
}
client := &http.Client{Timeout: 30 * time.Second}
if err := giteaDownloadDirRecursive(client, apiBase, owner, repo, strings.Trim(path, "/"), destDir, onProgress); err != nil {
client := ghclient.NewClient()
client.Timeout = 30 * time.Second
if err := giteaDownloadDirRecursive(client, source.GiteaHosts, apiBase, owner, repo, strings.Trim(path, "/"), destDir, onProgress); err != nil {
return "", err
}
@@ -81,21 +84,14 @@ func downloadGiteaDir(owner, repo, path, destDir string, source *Source, onProgr
// giteaAPIBase returns the base API URL for a Gitea instance.
func giteaAPIBase(source *Source) string {
host := strings.ToLower(extractHost(source.CloneURL))
scheme := "https"
// For standard gitea.com, use api.gitea.com convention
// For self-hosted, use https://{host}/api/v1
if host == "gitea.com" {
return "https://gitea.com/api/v1"
}
return fmt.Sprintf("%s://%s/api/v1", scheme, host)
return forgeAPIOrigin(source) + "/api/v1"
}
// giteaDownloadDirRecursive recursively downloads a directory via the Gitea Contents API.
func giteaDownloadDirRecursive(client *http.Client, apiBase, owner, repo, path, destDir string, onProgress ProgressCallback) error {
func giteaDownloadDirRecursive(client *http.Client, hosts []string, apiBase, owner, repo, path, destDir string, onProgress ProgressCallback) error {
contentsURL := buildGiteaContentsURL(apiBase, owner, repo, path)
req, err := giteaNewRequest(contentsURL)
req, err := giteaNewRequest(contentsURL, hosts)
if err != nil {
return err
}
@@ -137,7 +133,7 @@ func giteaDownloadDirRecursive(client *http.Client, apiBase, owner, repo, path,
if onProgress != nil {
onProgress(fmt.Sprintf("Downloading %s", item.Path))
}
return giteaDownloadFile(client, apiBase, item.DownloadURL, target)
return giteaDownloadFile(client, hosts, apiBase, item.DownloadURL, target)
}
// Directory listing response: [{type, name, path, download_url, ...}]
@@ -157,7 +153,7 @@ func giteaDownloadDirRecursive(client *http.Client, apiBase, owner, repo, path,
if err := os.MkdirAll(childDir, 0755); err != nil {
return err
}
if err := giteaDownloadDirRecursive(client, apiBase, owner, repo, item.Path, childDir, onProgress); err != nil {
if err := giteaDownloadDirRecursive(client, hosts, apiBase, owner, repo, item.Path, childDir, onProgress); err != nil {
return err
}
case "file":
@@ -165,7 +161,7 @@ func giteaDownloadDirRecursive(client *http.Client, apiBase, owner, repo, path,
if onProgress != nil {
onProgress(fmt.Sprintf("Downloading %s", item.Path))
}
if err := giteaDownloadFile(client, apiBase, item.DownloadURL, target); err != nil {
if err := giteaDownloadFile(client, hosts, apiBase, item.DownloadURL, target); err != nil {
return err
}
}
@@ -179,11 +175,11 @@ func giteaDownloadDirRecursive(client *http.Client, apiBase, owner, repo, path,
// giteaDownloadFile downloads a single file from a URL the server named.
// The request carries the token, so a URL on another origin is refused; the
// caller then falls back to a git clone, which only talks to the source host.
func giteaDownloadFile(client *http.Client, apiBase, fileURL, destPath string) error {
func giteaDownloadFile(client *http.Client, hosts []string, apiBase, fileURL, destPath string) error {
if !sameOrigin(apiBase, fileURL) {
return fmt.Errorf("download URL %q is not on the API host", fileURL)
}
req, err := giteaNewRequest(fileURL)
req, err := giteaNewRequest(fileURL, hosts)
if err != nil {
return err
}
@@ -203,7 +199,7 @@ func giteaDownloadFile(client *http.Client, apiBase, fileURL, destPath string) e
// giteaNewRequest creates a GET request with Gitea API headers and optional
// token authentication (GITEA_TOKEN or platform-resolved token).
func giteaNewRequest(reqURL string) (*http.Request, error) {
func giteaNewRequest(reqURL string, hosts []string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return nil, err
@@ -211,11 +207,7 @@ func giteaNewRequest(reqURL string) (*http.Request, error) {
req.Header.Set("Accept", "application/json")
// Try GITEA_TOKEN first, then SKILLSHARE_GIT_TOKEN
token := os.Getenv("GITEA_TOKEN")
if token == "" {
token = os.Getenv("SKILLSHARE_GIT_TOKEN")
}
token, _ := resolveTokenWithOptions(reqURL, nil, hosts)
if token != "" {
req.Header.Set("Authorization", "token "+token)
}
@@ -228,12 +220,16 @@ func giteaFetchLatestCommitHash(apiBase, owner, repo string, source *Source) (st
commitsURL := fmt.Sprintf("%s/repos/%s/%s/commits?per_page=1",
strings.TrimRight(apiBase, "/"), url.PathEscape(owner), url.PathEscape(repo))
req, err := giteaNewRequest(commitsURL)
var hosts []string
if source != nil {
hosts = source.GiteaHosts
}
req, err := giteaNewRequest(commitsURL, hosts)
if err != nil {
return "", err
}
client := &http.Client{Timeout: 15 * time.Second}
client := ghclient.NewClient()
resp, err := client.Do(req)
if err != nil {
return "", err
@@ -249,7 +245,7 @@ func giteaFetchLatestCommitHash(apiBase, owner, repo string, source *Source) (st
// Fallback: use git ls-remote
if source != nil && source.CloneURL != "" {
return getRemoteHeadCommit(source.CloneURL)
return getRemoteHeadCommit(source.CloneURL, source.authEnv())
}
return "", fmt.Errorf("failed to fetch latest commit hash")
@@ -311,15 +307,16 @@ func downloadCNBDir(repo, path, destDir string, source *Source, onProgress Progr
if repo == "" {
return "", fmt.Errorf("cnb download requires repo")
}
apiBase := cnbAPIBase(source)
apiBase := forgeAPIOrigin(source)
if err := os.MkdirAll(destDir, 0755); err != nil {
return "", err
}
if onProgress != nil {
onProgress("Downloading via CNB API...")
}
client := &http.Client{Timeout: 30 * time.Second}
if err := cnbDownloadDirRecursive(client, apiBase, repo, strings.Trim(path, "/"), destDir, onProgress); err != nil {
client := ghclient.NewClient()
client.Timeout = 30 * time.Second
if err := cnbDownloadDirRecursive(client, source.CNBHosts, apiBase, repo, strings.Trim(path, "/"), destDir, onProgress); err != nil {
return "", err
}
commitHash, err := cnbFetchLatestCommitHash(apiBase, repo, source)
@@ -329,14 +326,19 @@ func downloadCNBDir(repo, path, destDir string, source *Source, onProgress Progr
return shortCommitHash(commitHash), nil
}
func cnbAPIBase(source *Source) string {
host := strings.ToLower(extractHost(source.CloneURL))
return fmt.Sprintf("https://%s", host)
func forgeAPIOrigin(source *Source) string {
u, err := url.Parse(source.CloneURL)
if err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" {
// An API fallback must not upgrade an untrusted scheme or erase a
// nondefault port before the credential authorization check.
return u.Scheme + "://" + u.Host
}
return "https://" + strings.ToLower(extractHost(source.CloneURL))
}
func cnbDownloadDirRecursive(client *http.Client, apiBase, repo, path, destDir string, onProgress ProgressCallback) error {
func cnbDownloadDirRecursive(client *http.Client, hosts []string, apiBase, repo, path, destDir string, onProgress ProgressCallback) error {
contentsURL := buildCNBContentsURL(apiBase, repo, path)
req, err := cnbNewRequest(contentsURL)
req, err := cnbNewRequest(contentsURL, hosts)
if err != nil {
return err
}
@@ -352,10 +354,10 @@ func cnbDownloadDirRecursive(client *http.Client, apiBase, repo, path, destDir s
if err := json.NewDecoder(resp.Body).Decode(&item); err != nil {
return fmt.Errorf("failed to parse CNB contents response: %w", err)
}
return cnbWriteContentItem(client, apiBase, repo, item, destDir, onProgress)
return cnbWriteContentItem(client, hosts, apiBase, repo, item, destDir, onProgress)
}
func cnbWriteContentItem(client *http.Client, apiBase, repo string, item cnbContentItem, destDir string, onProgress ProgressCallback) error {
func cnbWriteContentItem(client *http.Client, hosts []string, apiBase, repo string, item cnbContentItem, destDir string, onProgress ProgressCallback) error {
switch item.Type {
case "tree":
entries := item.Entries
@@ -370,14 +372,14 @@ func cnbWriteContentItem(client *http.Client, apiBase, repo string, item cnbCont
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
if err := cnbDownloadDirRecursive(client, apiBase, repo, entry.Path, target, onProgress); err != nil {
if err := cnbDownloadDirRecursive(client, hosts, apiBase, repo, entry.Path, target, onProgress); err != nil {
return err
}
case "blob":
if onProgress != nil {
onProgress(fmt.Sprintf("Downloading %s", entry.Path))
}
if err := cnbDownloadFile(client, apiBase, repo, entry.Path, target); err != nil {
if err := cnbDownloadFile(client, hosts, apiBase, repo, entry.Path, target); err != nil {
return err
}
case "empty":
@@ -406,8 +408,8 @@ func cnbWriteContentItem(client *http.Client, apiBase, repo string, item cnbCont
return fmt.Errorf("unsupported CNB content type %q", item.Type)
}
func cnbDownloadFile(client *http.Client, apiBase, repo, filePath, destPath string) error {
req, err := cnbNewRequest(buildCNBContentsURL(apiBase, repo, filePath))
func cnbDownloadFile(client *http.Client, hosts []string, apiBase, repo, filePath, destPath string) error {
req, err := cnbNewRequest(buildCNBContentsURL(apiBase, repo, filePath), hosts)
if err != nil {
return err
}
@@ -441,16 +443,13 @@ func cnbWriteBlob(item cnbContentItem, destPath string) error {
return writeDownloadedFile(destPath, bytes.NewReader(data))
}
func cnbNewRequest(reqURL string) (*http.Request, error) {
func cnbNewRequest(reqURL string, hosts []string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.cnb.api+json")
token := os.Getenv("CNB_TOKEN")
if token == "" {
token = os.Getenv("SKILLSHARE_GIT_TOKEN")
}
token, _ := resolveTokenWithOptions(reqURL, hosts, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
@@ -459,11 +458,15 @@ func cnbNewRequest(reqURL string) (*http.Request, error) {
func cnbFetchLatestCommitHash(apiBase, repo string, source *Source) (string, error) {
commitsURL := fmt.Sprintf("%s/%s/-/git/commits?page=1&page_size=1", strings.TrimRight(apiBase, "/"), escapeRepoPath(repo))
req, err := cnbNewRequest(commitsURL)
var hosts []string
if source != nil {
hosts = source.CNBHosts
}
req, err := cnbNewRequest(commitsURL, hosts)
if err != nil {
return "", err
}
client := &http.Client{Timeout: 15 * time.Second}
client := ghclient.NewClient()
resp, err := client.Do(req)
if err == nil {
defer resp.Body.Close()
@@ -475,7 +478,7 @@ func cnbFetchLatestCommitHash(apiBase, repo string, source *Source) (string, err
}
}
if source != nil && source.CloneURL != "" {
return getRemoteHeadCommit(source.CloneURL)
return getRemoteHeadCommit(source.CloneURL, source.authEnv())
}
return "", fmt.Errorf("failed to fetch latest commit hash")
}
+62 -4
View File
@@ -28,7 +28,7 @@ func TestGiteaDownloadDir_WritesNestedFiles(t *testing.T) {
defer srv.Close()
dest := t.TempDir()
if err := giteaDownloadDirRecursive(srv.Client(), srv.URL+"/api/v1", "o", "r", "skills", dest, nil); err != nil {
if err := giteaDownloadDirRecursive(srv.Client(), nil, srv.URL+"/api/v1", "o", "r", "skills", dest, nil); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(filepath.Join(dest, "ref", "a.md"))
@@ -49,7 +49,7 @@ func TestGiteaDownloadDir_RefusesDownloadURLOnAnotherHost(t *testing.T) {
}))
defer srv.Close()
err := giteaDownloadDirRecursive(srv.Client(), srv.URL+"/api/v1", "o", "r", "", t.TempDir(), nil)
err := giteaDownloadDirRecursive(srv.Client(), nil, srv.URL+"/api/v1", "o", "r", "", t.TempDir(), nil)
if err == nil || !strings.Contains(err.Error(), "not on the API host") {
t.Fatalf("err = %v", err)
}
@@ -64,7 +64,7 @@ func TestGiteaDownloadDir_RefusesTraversalName(t *testing.T) {
}))
defer srv.Close()
if err := giteaDownloadDirRecursive(srv.Client(), srv.URL, "o", "r", "", t.TempDir(), nil); err == nil {
if err := giteaDownloadDirRecursive(srv.Client(), nil, srv.URL, "o", "r", "", t.TempDir(), nil); err == nil {
t.Fatal("expected an error for a \"..\" name")
}
}
@@ -84,7 +84,7 @@ func TestCNBDownloadDir_WritesBlobFromTree(t *testing.T) {
defer srv.Close()
dest := t.TempDir()
if err := cnbDownloadDirRecursive(srv.Client(), srv.URL, "org/repo", "skills", dest, nil); err != nil {
if err := cnbDownloadDirRecursive(srv.Client(), nil, srv.URL, "org/repo", "skills", dest, nil); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(filepath.Join(dest, "SKILL.md"))
@@ -92,3 +92,61 @@ func TestCNBDownloadDir_WritesBlobFromTree(t *testing.T) {
t.Fatalf("file = %q, %v", got, err)
}
}
func TestForgeRequestsScopeProviderCredentials(t *testing.T) {
tests := []struct {
name, url, variable, want string
hosts []string
request func(string, []string) (*http.Request, error)
}{
{"Gitea public", "https://gitea.com/api/v1/repos/o/r", "GITEA_TOKEN", "token audit-dummy", nil, giteaNewRequest},
{"Gitea lookalike", "https://gitea.attacker.invalid/api/v1/repos/o/r", "GITEA_TOKEN", "", nil, giteaNewRequest},
{"Gitea explicit", "https://forge.company.invalid/api/v1/repos/o/r", "GITEA_TOKEN", "token audit-dummy", []string{"forge.company.invalid"}, giteaNewRequest},
{"Gitea plaintext", "http://forge.company.invalid/api/v1/repos/o/r", "GITEA_TOKEN", "", []string{"forge.company.invalid"}, giteaNewRequest},
{"CNB public", "https://cnb.cool/o/r/-/git/contents", "CNB_TOKEN", "Bearer audit-dummy", nil, cnbNewRequest},
{"CNB lookalike", "https://cnb.cool.attacker.invalid/o/r/-/git/contents", "CNB_TOKEN", "", nil, cnbNewRequest},
{"CNB explicit", "https://forge.company.invalid/o/r/-/git/contents", "CNB_TOKEN", "Bearer audit-dummy", []string{"forge.company.invalid"}, cnbNewRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resetAuthTestEnv(t)
t.Setenv(tt.variable, "audit-dummy")
req, err := tt.request(tt.url, tt.hosts)
if err != nil {
t.Fatal(err)
}
if got := req.Header.Get("Authorization"); got != tt.want {
t.Fatalf("Authorization = %q, want %q", got, tt.want)
}
})
}
}
func TestForgeFallbackPreservesCredentialOrigin(t *testing.T) {
for _, sourceURL := range []string{
"http://forge.company.invalid/o/r.git",
"https://forge.company.invalid:8443/o/r.git",
} {
t.Run(sourceURL, func(t *testing.T) {
resetAuthTestEnv(t)
t.Setenv("GITEA_TOKEN", "audit-dummy")
t.Setenv("CNB_TOKEN", "audit-dummy")
source := &Source{CloneURL: sourceURL}
for _, constructor := range []struct {
base string
request func(string, []string) (*http.Request, error)
}{
{giteaAPIBase(source), giteaNewRequest},
{forgeAPIOrigin(source), cnbNewRequest},
} {
req, err := constructor.request(constructor.base, []string{"forge.company.invalid"})
if err != nil {
t.Fatal(err)
}
if got := req.Header.Get("Authorization"); got != "" {
t.Fatalf("fallback changed credential origin: %s received authorization", req.URL)
}
}
})
}
}
+3 -3
View File
@@ -230,18 +230,18 @@ func fetchLatestCommitHash(owner, repo, apiBase string, source *Source) (string,
// Fallback for edge cases (e.g. GHE API path differences): use git ls-remote.
if source != nil && source.CloneURL != "" {
return getRemoteHeadCommit(source.CloneURL)
return getRemoteHeadCommit(source.CloneURL, source.authEnv())
}
return "", fmt.Errorf("failed to fetch latest commit hash")
}
func getRemoteHeadCommit(cloneURL string) (string, error) {
func getRemoteHeadCommit(cloneURL string, extraEnv []string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), gitCommandTimeout)
defer cancel()
cmd := gitCommand(ctx, "ls-remote", cloneURL, "HEAD")
cmd.Env = append(cmd.Env, authEnv(cloneURL)...)
cmd.Env = append(cmd.Env, extraEnv...)
out, err := cmd.Output()
if err != nil {
return "", err
+3
View File
@@ -33,6 +33,9 @@ type InstallOptions struct {
Branch string // Git branch to clone from (empty = remote default)
SourceDir string // Skills root dir for centralized metadata (set by caller)
Lock *Lock // Pinned commits for InstallFromConfig (project mode); nil = follow the branch
ParseOptions ParseOptions // Explicit credential host policy for existing checkouts
// AuditOverride lets an install proceed despite audit findings at/above the
// block threshold. Deliberately separate from Force, which only means
// "overwrite what is already there" and is set unconditionally by update and
+281
View File
@@ -0,0 +1,281 @@
package install
import (
"errors"
"os"
"os/exec"
"path/filepath"
"testing"
"skillshare/internal/audit"
"skillshare/internal/sourcefs"
"skillshare/internal/sourcewalk"
)
func agentDiscoveryFixture(t *testing.T, content string) (*DiscoveryResult, AgentInfo) {
t.Helper()
repo := t.TempDir()
agent := AgentInfo{Name: "reviewer", Path: "agents/team/reviewer.md", FileName: "reviewer.md"}
path := filepath.Join(repo, filepath.FromSlash(agent.Path))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
return &DiscoveryResult{
RepoPath: repo,
Source: &Source{Type: SourceTypeLocalPath, Raw: repo, Path: repo},
}, agent
}
func TestInstallAgentFromDiscovery_TrackedDestinationEscape(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
repo := initTestRepo(t)
outside := t.TempDir()
if err := os.Symlink(outside, filepath.Join(repo, "escape")); err != nil {
t.Fatal(err)
}
agentPath := "agents/_trap/escape/CLAUDE.md"
path := filepath.Join(repo, filepath.FromSlash(agentPath))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("# Benign agent\nReview changes carefully.\n"), 0o644); err != nil {
t.Fatal(err)
}
gitAdd(t, repo, ".")
gitCommit(t, repo, "add agent and destination link")
source, err := ParseSource(fileURL(repo))
if err != nil {
t.Fatal(err)
}
root := filepath.Join(t.TempDir(), "agents-source")
if _, err := InstallTrackedRepo(source, root, InstallOptions{
Name: "trap", Kind: "agent", Track: true, SourceDir: root,
}); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "_trap", "escape")
if info, err := os.Lstat(link); err != nil || info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("tracked fixture did not plant destination link: %v, %v", info, err)
}
discovery, err := DiscoverFromGit(source)
if err != nil {
t.Fatal(err)
}
defer CleanupDiscovery(discovery)
var target *AgentInfo
for i := range discovery.Agents {
if discovery.Agents[i].Path == agentPath {
target = &discovery.Agents[i]
break
}
}
if target == nil {
t.Fatalf("fixture agent not discovered: %+v", discovery.Agents)
}
_, err = InstallAgentFromDiscovery(discovery, *target, root, InstallOptions{Kind: "agent", SourceDir: root})
if !errors.Is(err, sourcefs.ErrLink) {
t.Fatalf("expected destination link refusal, got %v", err)
}
if _, err := os.Lstat(filepath.Join(outside, "CLAUDE.md")); !os.IsNotExist(err) {
t.Fatalf("agent escaped the destination root: %v", err)
}
}
func TestDiscoveredAgent_RefusesDestinationLinks(t *testing.T) {
for _, operation := range []string{"install", "force", "update"} {
for _, component := range []string{"intermediate", "final", "dangling final"} {
t.Run(operation+"/"+component, func(t *testing.T) {
discovery, agent := agentDiscoveryFixture(t, "# Reviewer\nReview changes carefully.\n")
root, outside := t.TempDir(), t.TempDir()
external := filepath.Join(outside, "reviewer.md")
if component != "dangling final" {
if err := os.WriteFile(external, []byte("external original"), 0o644); err != nil {
t.Fatal(err)
}
}
link := filepath.Join(root, "team")
target := outside
if component != "intermediate" {
if err := os.MkdirAll(link, 0o755); err != nil {
t.Fatal(err)
}
link = filepath.Join(link, agent.FileName)
target = external
}
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
opts := InstallOptions{Kind: "agent", SourceDir: root, Force: operation == "force"}
var err error
if operation == "update" {
_, err = UpdateAgentFromDiscovery(discovery, agent, root, opts)
} else {
_, err = InstallAgentFromDiscovery(discovery, agent, root, opts)
}
if !errors.Is(err, sourcefs.ErrLink) {
t.Fatalf("expected destination link refusal, got %v", err)
}
if component == "dangling final" {
if _, err := os.Lstat(external); !os.IsNotExist(err) {
t.Fatalf("external file created: %v", err)
}
} else if data, err := os.ReadFile(external); err != nil || string(data) != "external original" {
t.Fatalf("external file changed: %q, %v", data, err)
}
if info, err := os.Lstat(link); err != nil || info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("destination link replaced: %v, %v", info, err)
}
if entries, err := os.ReadDir(outside); err != nil || len(entries) > 1 {
t.Fatalf("external directory changed: %v, %v", entries, err)
}
})
}
}
}
func TestDiscoveredAgent_BlockedAuditPreservesInstalledContent(t *testing.T) {
for _, update := range []bool{false, true} {
name := "force install"
if update {
name = "update"
}
t.Run(name, func(t *testing.T) {
discovery, agent := agentDiscoveryFixture(t, "# Reviewer\nReview changes carefully.\n")
root := t.TempDir()
opts := InstallOptions{SourceDir: root, AuditThreshold: audit.SeverityHigh}
if _, err := InstallAgentFromDiscovery(discovery, agent, root, opts); err != nil {
t.Fatal(err)
}
dest := filepath.Join(root, "team", agent.FileName)
before, err := os.ReadFile(filepath.Join(root, MetadataFileName))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(resolveDiscoveredAgentSourcePath(discovery, agent), []byte("# Reviewer\nsudo apt-get install -y jq\n"), 0o644); err != nil {
t.Fatal(err)
}
opts.Force = true
if update {
_, err = UpdateAgentFromDiscovery(discovery, agent, root, opts)
} else {
_, err = InstallAgentFromDiscovery(discovery, agent, root, opts)
}
if !errors.Is(err, audit.ErrBlocked) {
t.Fatalf("expected audit rejection, got %v", err)
}
if data, err := os.ReadFile(dest); err != nil || string(data) != "# Reviewer\nReview changes carefully.\n" {
t.Fatalf("installed agent changed on audit block: %q, %v", data, err)
}
if data, err := os.ReadFile(filepath.Join(root, MetadataFileName)); err != nil || string(data) != string(before) {
t.Fatalf("metadata changed on audit block: %q, %v", data, err)
}
})
}
}
func TestDiscoveredAgent_InstallUpdateMetadataAndDryRun(t *testing.T) {
discovery, agent := agentDiscoveryFixture(t, "# Reviewer\nReview changes carefully.\n")
root := filepath.Join(t.TempDir(), "agents")
destDir := filepath.Join(root, "group", "nested")
// Legacy callers omit SourceDir; Into belongs to the source root, while
// the discovered agent's own nested path must remain part of its key.
opts := InstallOptions{Into: "group/nested"}
result, err := InstallAgentFromDiscovery(discovery, agent, destDir, InstallOptions{Into: opts.Into, DryRun: true})
if err != nil || result.Action != "would install" {
t.Fatalf("dry run install: %+v, %v", result, err)
}
if _, err := os.Stat(root); !os.IsNotExist(err) {
t.Fatalf("dry run created source directory: %v", err)
}
result, err = InstallAgentFromDiscovery(discovery, agent, destDir, opts)
if err != nil || result.Action != "installed" || result.AuditSkipped || result.AuditThreshold == "" || len(result.Warnings) != 0 {
t.Fatalf("install: %+v, %v", result, err)
}
dest := filepath.Join(destDir, "team", agent.FileName)
if result.SkillPath != dest {
t.Fatalf("destination = %q, want %q", result.SkillPath, dest)
}
key := "group/nested/team/reviewer"
store, err := LoadMetadata(root)
if err != nil || store.Get(key) == nil || store.Get(key).EffectiveKind() != "agent" {
t.Fatalf("agent metadata missing at %q: %+v, %v", key, store, err)
}
if err := os.WriteFile(resolveDiscoveredAgentSourcePath(discovery, agent), []byte("# Updated reviewer\n"), 0o644); err != nil {
t.Fatal(err)
}
result, err = InstallAgentFromDiscovery(discovery, agent, destDir, opts)
if err != nil || result.Action != "skipped" {
t.Fatalf("existing install must skip: %+v, %v", result, err)
}
result, err = UpdateAgentFromDiscovery(discovery, agent, destDir, InstallOptions{Into: opts.Into, DryRun: true})
if err != nil || result.Action != "would reinstall from source" {
t.Fatalf("dry run update: %+v, %v", result, err)
}
if data, err := os.ReadFile(dest); err != nil || string(data) != "# Reviewer\nReview changes carefully.\n" {
t.Fatalf("skip/dry run changed installed agent: %q, %v", data, err)
}
result, err = UpdateAgentFromDiscovery(discovery, agent, destDir, opts)
if err != nil || result.Action != "updated" || len(result.Warnings) != 0 {
t.Fatalf("update: %+v, %v", result, err)
}
if data, err := os.ReadFile(dest); err != nil || string(data) != "# Updated reviewer\n" {
t.Fatalf("updated content: %q, %v", data, err)
}
opts.Force, opts.SkipAudit = true, true
result, err = InstallAgentFromDiscovery(discovery, agent, destDir, opts)
if err != nil || result.Action != "installed" || !result.AuditSkipped {
t.Fatalf("forced install with skipped audit: %+v, %v", result, err)
}
store, err = LoadMetadata(root)
hash, hashErr := computeSingleFileHash(dest)
if err != nil || hashErr != nil || store.Get(key) == nil || store.Get(key).FileHashes[agent.FileName] != hash {
t.Fatalf("updated metadata not rooted at %q: %+v, %v, %v", key, store, err, hashErr)
}
}
func TestDiscoveredAgent_FollowPolicyAndLinkedSourceRoot(t *testing.T) {
for _, linkedRoot := range []bool{false, true} {
name := "followed first-level link"
if linkedRoot {
name = "linked source root"
}
t.Run(name, func(t *testing.T) {
discovery, agent := agentDiscoveryFixture(t, "# Reviewer\n")
root, external := t.TempDir(), t.TempDir()
opts := InstallOptions{SourceDir: root}
if linkedRoot {
root = filepath.Join(root, "agents")
if err := os.Symlink(external, root); err != nil {
t.Fatal(err)
}
opts.SourceDir = root
} else {
if err := os.Symlink(external, filepath.Join(root, "team")); err != nil {
t.Fatal(err)
}
opts.SourceFollow = sourcewalk.NewFollow(root, nil)
}
if _, err := InstallAgentFromDiscovery(discovery, agent, root, opts); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(resolveDiscoveredAgentSourcePath(discovery, agent), []byte("# Updated reviewer\n"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := UpdateAgentFromDiscovery(discovery, agent, root, opts); err != nil {
t.Fatal(err)
}
dest := filepath.Join(external, agent.FileName)
if linkedRoot {
dest = filepath.Join(external, "team", agent.FileName)
}
if data, err := os.ReadFile(dest); err != nil || string(data) != "# Updated reviewer\n" {
t.Fatalf("supported link target not updated: %q, %v", data, err)
}
})
}
}
+64 -71
View File
@@ -7,6 +7,7 @@ import (
"path/filepath"
"strings"
"skillshare/internal/sourcefs"
"skillshare/internal/sourcewalk"
"skillshare/internal/utils"
)
@@ -181,7 +182,7 @@ func writeDiscoveredAgentMetadata(discovery *DiscoveryResult, agent AgentInfo, d
return WriteMetaToStore(sourceDir, destFile, meta)
}
func installAgentFromDiscoveryInternal(discovery *DiscoveryResult, agent AgentInfo, destFile string, opts InstallOptions, writeMeta bool) (*InstallResult, error) {
func installAgentFromDiscoveryInternal(discovery *DiscoveryResult, agent AgentInfo, destFile string, opts InstallOptions, update bool) (*InstallResult, error) {
result := &InstallResult{
SkillName: agent.Name,
Source: buildDiscoverySkillSource(discovery.Source, agent.Path),
@@ -190,17 +191,32 @@ func installAgentFromDiscoveryInternal(discovery *DiscoveryResult, agent AgentIn
if opts.DryRun {
result.Action = "would install"
if update {
result.Action = "would reinstall from source"
}
return result, nil
}
if err := os.MkdirAll(filepath.Dir(destFile), 0755); err != nil {
return nil, fmt.Errorf("failed to create agents directory: %w", err)
src, err := sourcefs.Create(opts.SourceDir, opts.SourceFollow)
if err != nil {
return nil, fmt.Errorf("failed to open agents directory: %w", err)
}
if _, err := os.Stat(destFile); err == nil && !opts.Force {
result.Action = "skipped"
result.Warnings = append(result.Warnings, "agent already exists (use --force to overwrite)")
return result, nil
defer src.Close()
rel, err := src.Rel(destFile)
if err != nil {
return nil, err
}
if err := src.CheckNoLink(rel); err != nil {
return nil, fmt.Errorf("unsafe agent destination: %w", err)
}
if _, err := src.Lstat(rel); err == nil {
if !update && !opts.Force {
result.Action = "skipped"
result.Warnings = append(result.Warnings, "agent already exists (use --force to overwrite)")
return result, nil
}
} else if !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to check agent destination: %w", err)
}
data, err := os.ReadFile(resolveDiscoveredAgentSourcePath(discovery, agent))
@@ -208,21 +224,45 @@ func installAgentFromDiscoveryInternal(discovery *DiscoveryResult, agent AgentIn
return nil, fmt.Errorf("failed to read agent %s: %w", agent.FileName, err)
}
if err := os.WriteFile(destFile, data, 0644); err != nil {
return nil, fmt.Errorf("failed to write agent %s: %w", agent.FileName, err)
// Audit an isolated file before publishing, including forced installs.
// A rejected audit can only clean up this temporary tree, never the
// existing agent or a file reached through a destination link.
tempDir, err := os.MkdirTemp("", "skillshare-agent-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp directory: %w", err)
}
if err := auditInstalledAgent(destFile, result, opts); err != nil {
defer os.RemoveAll(tempDir)
stage, err := sourcefs.Open(tempDir)
if err != nil {
return nil, fmt.Errorf("failed to open staged agent directory: %w", err)
}
defer stage.Close()
tempName := filepath.Base(destFile)
if err := stage.WriteFile(tempName, data, 0o644); err != nil {
return nil, fmt.Errorf("failed to stage agent %s: %w", agent.FileName, err)
}
auditOpts := opts
auditOpts.AuditAcceptRoot, auditOpts.AuditAcceptPath = opts.auditAcceptTarget(destFile)
auditOpts.SourceDir = tempDir
auditOpts.SourceFollow = nil
if err := auditInstalledAgent(filepath.Join(tempDir, tempName), result, auditOpts); err != nil {
return nil, err
}
if writeMeta {
if err := writeDiscoveredAgentMetadata(discovery, agent, destFile, opts.SourceDir); err != nil {
result.Warnings = append(result.Warnings, fmt.Sprintf("failed to write metadata: %v", err))
}
if err := src.MkdirAll(filepath.Dir(rel), 0o755); err != nil {
return nil, fmt.Errorf("failed to create agents directory: %w", err)
}
if err := src.WriteFileAtomic(rel, data, 0o644); err != nil {
return nil, fmt.Errorf("failed to write agent %s: %w", agent.FileName, err)
}
if err := writeDiscoveredAgentMetadata(discovery, agent, destFile, opts.SourceDir); err != nil {
result.Warnings = append(result.Warnings, fmt.Sprintf("failed to write metadata: %v", err))
}
result.Action = "installed"
if update {
result.Action = "updated"
}
return result, nil
}
@@ -243,6 +283,7 @@ func skillsRootFor(destPath string, opts InstallOptions) string {
}
func installImpl(source *Source, destPath string, opts InstallOptions) (*InstallResult, error) {
opts.ParseOptions.CNBHosts, opts.ParseOptions.GiteaHosts = source.CNBHosts, source.GiteaHosts
opts.SourceDir = skillsRootFor(destPath, opts)
result := &InstallResult{
@@ -726,65 +767,17 @@ func checkSkillFile(skillPath string, result *InstallResult) {
// InstallAgentFromDiscovery installs a single agent (.md file) from a discovery result.
// Unlike skill install (directory copy), agent install copies a single file.
func InstallAgentFromDiscovery(discovery *DiscoveryResult, agent AgentInfo, destDir string, opts InstallOptions) (*InstallResult, error) {
// Derive the source root from destDir + Into, not the agent's nested
// relative path, so callers without SourceDir retain stable metadata keys.
opts.SourceDir = skillsRootFor(filepath.Join(destDir, filepath.Base(agent.Path)), opts)
destFile := filepath.Join(destDir, filepath.FromSlash(installAgentRelativePath(agent)))
return installAgentFromDiscoveryInternal(discovery, agent, destFile, opts, true)
return installAgentFromDiscoveryInternal(discovery, agent, destFile, opts, false)
}
func UpdateAgentFromDiscovery(discovery *DiscoveryResult, agent AgentInfo, destDir string, opts InstallOptions) (*InstallResult, error) {
relPath := installAgentRelativePath(agent)
destFile := filepath.Join(destDir, filepath.FromSlash(relPath))
result := &InstallResult{
SkillName: agent.Name,
Source: buildDiscoverySkillSource(discovery.Source, agent.Path),
SkillPath: destFile,
}
if opts.DryRun {
result.Action = "would reinstall from source"
return result, nil
}
tempDir, err := os.MkdirTemp("", "skillshare-agent-update-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp directory: %w", err)
}
defer os.RemoveAll(tempDir)
tempFile := filepath.Join(tempDir, filepath.FromSlash(relPath))
innerOpts := opts
innerOpts.DryRun = false
innerOpts.Update = false
innerOpts.SourceDir = tempDir
innerOpts.AuditAcceptRoot = opts.SourceDir
innerOpts.AuditAcceptPath = destFile
innerResult, err := installAgentFromDiscoveryInternal(discovery, agent, tempFile, innerOpts, false)
if err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(destFile), 0755); err != nil {
return nil, fmt.Errorf("failed to create agents directory: %w", err)
}
// os.Rename is atomic on POSIX and overwrites the destination. If it
// fails (e.g. cross-device EXDEV on exotic setups), fall back to copy.
if err := os.Rename(tempFile, destFile); err != nil {
data, readErr := os.ReadFile(tempFile)
if readErr != nil {
return nil, fmt.Errorf("failed to read staged agent: %w", readErr)
}
if writeErr := os.WriteFile(destFile, data, 0644); writeErr != nil {
return nil, fmt.Errorf("failed to move updated agent: %w", writeErr)
}
}
if err := writeDiscoveredAgentMetadata(discovery, agent, destFile, opts.SourceDir); err != nil {
innerResult.Warnings = append(innerResult.Warnings, fmt.Sprintf("failed to write metadata: %v", err))
}
innerResult.SkillPath = destFile
innerResult.Action = "updated"
return innerResult, nil
opts.SourceDir = skillsRootFor(filepath.Join(destDir, filepath.Base(agent.Path)), opts)
destFile := filepath.Join(destDir, filepath.FromSlash(installAgentRelativePath(agent)))
return installAgentFromDiscoveryInternal(discovery, agent, destFile, opts, true)
}
// computeSingleFileHash computes the sha256 hash for a single file.
+1
View File
@@ -168,6 +168,7 @@ func InstallFromConfig(ctx InstallContext, opts InstallOptions) (ConfigInstallRe
CNBHosts: ctx.CNBHosts(),
GiteaHosts: ctx.GiteaHosts(),
}
opts.ParseOptions = parseOpts
// ── Classify skills: tracked / plain (groupable vs singles) ──
var tracked []SkillEntryDTO
+7 -10
View File
@@ -453,38 +453,35 @@ func cloneFallbackSourcesForNestedGitLabURL(source *Source) []Source {
// shallow (depth 1) clone, injecting auth env for the URL. The caller owns the
// returned directory and must remove it. branch may be empty to use the remote
// default. On error the temp directory is removed and an empty path returned.
func ShallowCloneToTemp(cloneURL, branch string) (string, error) {
func ShallowCloneToTemp(cloneURL, branch string, opts ParseOptions) (string, error) {
dir, err := os.MkdirTemp("", "skillshare-clone-*")
if err != nil {
return "", err
}
if err := cloneRepo(cloneURL, dir, branch, true, nil); err != nil {
if err := cloneRepoWithEnv(cloneURL, dir, branch, true, AuthEnvForURL(cloneURL, opts), nil); err != nil {
cleanupTempRepo(dir)
return "", err
}
return dir, nil
}
// gitPull performs a git pull (quiet mode).
// If the remote uses HTTPS and a token is available, it injects
// authentication via GIT_CONFIG env vars (same mechanism as cloneRepo).
func gitPull(repoPath string, onProgress ProgressCallback) error {
remoteURL := getRemoteURL(repoPath)
// gitPull performs a quiet pull with the operation's resolved credentials.
func gitPull(repoPath string, extraEnv []string, onProgress ProgressCallback) error {
args := []string{"pull", "--quiet"}
if onProgress != nil {
args = []string{"pull", "--progress"}
}
return runGitCommandWithProgress(args, repoPath, authEnv(remoteURL), onProgress)
return runGitCommandWithProgress(args, repoPath, extraEnv, onProgress)
}
// gitForcePull moves the checkout to its upstream branch, discarding local
// edits. It fetches first, so a failed fetch leaves the edits in place.
func gitForcePull(repoPath string, onProgress ProgressCallback) error {
func gitForcePull(repoPath string, extraEnv []string, onProgress ProgressCallback) error {
args := []string{"fetch", "--quiet"}
if onProgress != nil {
args = []string{"fetch", "--progress"}
}
if err := runGitCommandWithProgress(args, repoPath, authEnv(getRemoteURL(repoPath)), onProgress); err != nil {
if err := runGitCommandWithProgress(args, repoPath, extraEnv, onProgress); err != nil {
return err
}
return runGitCommandEnv([]string{"reset", "--hard", "--quiet", "@{u}"}, repoPath, nil)
+3 -2
View File
@@ -83,6 +83,7 @@ func installTrackedRepoImpl(source *Source, sourceDir string, opts InstallOption
if err := resolveWebRef(source); err != nil {
return nil, err
}
opts.ParseOptions.CNBHosts, opts.ParseOptions.GiteaHosts = source.CNBHosts, source.GiteaHosts
// Determine repo name: opts.Name (--name or the name recorded in config) >
// TrackName (owner-repo, so two repos both called "skills" don't collide) >
@@ -302,12 +303,12 @@ func updateTrackedRepo(repoPath string, result *TrackedRepoResult, opts InstallO
return nil, err
}
candidate, err := StageGitUpdate(repoPath, false)
candidate, err := StageGitUpdate(repoPath, false, opts.ParseOptions)
if err != nil {
return nil, fmt.Errorf("failed to stage update: %w", err)
}
defer candidate.Close()
if err := gitPull(candidate.Path, opts.OnProgress); err != nil {
if err := gitPull(candidate.Path, AuthEnvForURL(getRemoteURL(repoPath), opts.ParseOptions), opts.OnProgress); err != nil {
return nil, fmt.Errorf("failed to update: %w", err)
}
+1 -1
View File
@@ -61,7 +61,7 @@ func handleUpdate(source *Source, destPath string, result *InstallResult, opts I
if _, followed := opts.SourceFollow.Resolve(destPath); opts.Reinstall && !followed {
pull = gitForcePull
}
if err := pull(destPath, opts.OnProgress); err != nil {
if err := pull(destPath, source.authEnv(), opts.OnProgress); err != nil {
return nil, fmt.Errorf("failed to update: %w", err)
}
+1 -1
View File
@@ -168,7 +168,7 @@ func relockGitRepo(repoPath, sha string, opts InstallOptions) error {
if err != nil || before == "" {
return fmt.Errorf("cannot read the current commit of %s", repoPath)
}
if err := resetTrackedToCommit(repoPath, sha, AuthEnvForURL(getRemoteURL(repoPath))); err != nil {
if err := resetTrackedToCommit(repoPath, sha, AuthEnvForURL(getRemoteURL(repoPath), opts.ParseOptions)); err != nil {
return err
}
if opts.SkipAudit {
+2 -13
View File
@@ -23,20 +23,9 @@ func TestSourceType_String(t *testing.T) {
}
}
func TestAuthEnvForURL_NoToken(t *testing.T) {
// With no environment tokens set, AuthEnvForURL should return empty
t.Setenv("GITHUB_TOKEN", "")
t.Setenv("GH_TOKEN", "")
t.Setenv("GITLAB_TOKEN", "")
env := AuthEnvForURL("https://github.com/user/repo.git")
// Should not panic; may return empty or contain config entries
_ = env
}
func TestResolveTokenForURL_NoToken(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "")
t.Setenv("GH_TOKEN", "")
token, username := ResolveTokenForURL("https://github.com/user/repo.git")
resetAuthTestEnv(t)
token, username := ResolveTokenForURL("https://github.com/user/repo.git", ParseOptions{})
if token != "" {
t.Errorf("expected empty token, got %q", token)
}
+39 -4
View File
@@ -1,10 +1,14 @@
package search
import (
"net/http"
"os"
"os/exec"
"path/filepath"
"testing"
"skillshare/internal/install"
"skillshare/internal/testutil"
)
const sampleHubIndex = `{"schemaVersion":1,"skills":[{"name":"alpha","description":"A skill","source":"o/r"}]}`
@@ -49,7 +53,7 @@ func runGitT(t *testing.T, dir string, args ...string) {
func TestReadIndexFromGitClone_DefaultFile(t *testing.T) {
repo := initGitRepoWithFile(t, defaultHubIndexFile, sampleHubIndex)
doc, err := readIndexFromGitClone(repo, defaultHubIndexFile)
doc, err := readIndexFromGitClone(repo, defaultHubIndexFile, install.ParseOptions{})
if err != nil {
t.Fatalf("readIndexFromGitClone: %v", err)
}
@@ -61,7 +65,7 @@ func TestReadIndexFromGitClone_DefaultFile(t *testing.T) {
func TestReadIndexFromGitClone_CustomSubdir(t *testing.T) {
repo := initGitRepoWithFile(t, "hubs/team.json", sampleHubIndex)
doc, err := readIndexFromGitClone(repo, "hubs/team.json")
doc, err := readIndexFromGitClone(repo, "hubs/team.json", install.ParseOptions{})
if err != nil {
t.Fatalf("readIndexFromGitClone: %v", err)
}
@@ -73,7 +77,7 @@ func TestReadIndexFromGitClone_CustomSubdir(t *testing.T) {
func TestReadIndexFromGitClone_MissingFile(t *testing.T) {
repo := initGitRepoWithFile(t, defaultHubIndexFile, sampleHubIndex)
if _, err := readIndexFromGitClone(repo, "nope.json"); err == nil {
if _, err := readIndexFromGitClone(repo, "nope.json", install.ParseOptions{}); err == nil {
t.Fatal("expected error for missing index file")
}
}
@@ -82,8 +86,39 @@ func TestReadIndexFromGitClone_PathTraversalRejected(t *testing.T) {
repo := initGitRepoWithFile(t, defaultHubIndexFile, sampleHubIndex)
for _, rel := range []string{"../escape.json", "../../etc/passwd", "/etc/passwd"} {
if _, err := readIndexFromGitClone(repo, rel); err == nil {
if _, err := readIndexFromGitClone(repo, rel, install.ParseOptions{}); err == nil {
t.Errorf("expected error for traversal path %q", rel)
}
}
}
func TestFetchPreview_ConfiguredCloneAuthorization(t *testing.T) {
repo := initGitRepoWithFile(t, "skills/foo/SKILL.md", sampleSkillMD)
for _, tt := range []struct {
name, host, username, tokenVar string
opts install.ParseOptions
}{
{"cnb", "cnb.corp.example", "cnb", "CNB_TOKEN", install.ParseOptions{CNBHosts: []string{"cnb.corp.example"}}},
{"gitea", "forge.corp.example", "x-access-token", "GITEA_TOKEN", install.ParseOptions{GiteaHosts: []string{"forge.corp.example"}}},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv(tt.tokenVar, "private-repo-token")
testutil.ServePrivateGit(t, repo, tt.username, "private-repo-token")
source := "https://" + tt.host + "/org/repo.git/skills/foo"
preview, err := FetchPreview(http.DefaultClient, source, "", tt.opts)
if err != nil {
t.Fatal(err)
}
if preview.Content != sampleSkillMD {
t.Fatal("authenticated clone did not return the private skill")
}
if _, err := FetchPreview(http.DefaultClient, source, "", install.ParseOptions{}); err == nil {
t.Fatal("unconfigured host unexpectedly accessed the private skill")
}
lookalike := "https://" + tt.name + ".attacker.invalid/org/repo.git/skills/foo"
if _, err := FetchPreview(http.DefaultClient, lookalike, "", tt.opts); err == nil {
t.Fatal("lookalike host unexpectedly accessed the private skill")
}
})
}
}
+16 -16
View File
@@ -9,8 +9,8 @@ import (
"path/filepath"
"sort"
"strings"
"time"
ghclient "skillshare/internal/github"
"skillshare/internal/install"
)
@@ -42,9 +42,9 @@ type hubSourceContext struct {
// SearchFromIndexURL searches skills from a private index.json URL or local path.
// A limit of 0 means no limit (return all results).
func SearchFromIndexURL(query string, limit int, indexURL string) ([]SearchResult, error) {
func SearchFromIndexURL(query string, limit int, indexURL string, opts install.ParseOptions) ([]SearchResult, error) {
hubCtx := hubSourceContextFromURL(indexURL)
doc, err := loadIndex(indexURL)
doc, err := loadIndex(indexURL, opts)
if err != nil {
return nil, err
}
@@ -231,7 +231,7 @@ func invalidHubJSONError(source string, err error) error {
return fmt.Errorf("hub index at %s is not valid JSON — expected a skillshare-hub.json file (the URL may return an HTML page instead of raw JSON): %w", source, err)
}
func loadIndex(indexURL string) (*indexDocument, error) {
func loadIndex(indexURL string, opts install.ParseOptions) (*indexDocument, error) {
s := strings.TrimSpace(indexURL)
if s == "" {
return nil, fmt.Errorf("hub URL is required")
@@ -241,12 +241,12 @@ func loadIndex(indexURL string) (*indexDocument, error) {
// shallowly and read the index file from it. Auth is handled by the user's
// SSH agent/keys, which works for private and enterprise (GHE) hosts.
if install.IsSSHURL(s) {
return loadIndexViaSSH(s)
return loadIndexViaSSH(s, opts)
}
if strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") {
client := &http.Client{Timeout: 15 * time.Second}
req, err := buildHubRequest(s)
client := ghclient.NewClient()
req, err := buildHubRequest(s, opts)
if err != nil {
return nil, err
}
@@ -281,8 +281,8 @@ func loadIndex(indexURL string) (*indexDocument, error) {
// reading the index file. The index path within the repo is taken from the
// //path suffix (e.g. git@host:org/repo.git//hubs/team.json); when absent it
// defaults to skillshare-hub.json at the repo root.
func loadIndexViaSSH(indexURL string) (*indexDocument, error) {
src, err := install.ParseSource(indexURL)
func loadIndexViaSSH(indexURL string, opts install.ParseOptions) (*indexDocument, error) {
src, err := install.ParseSourceWithOptions(indexURL, opts)
if err != nil {
return nil, fmt.Errorf("parse hub source: %w", err)
}
@@ -290,19 +290,19 @@ func loadIndexViaSSH(indexURL string) (*indexDocument, error) {
if rel == "" {
rel = defaultHubIndexFile
}
return readIndexFromGitClone(src.CloneURL, rel)
return readIndexFromGitClone(src.CloneURL, rel, opts)
}
// readIndexFromGitClone shallow-clones cloneURL into a temp dir, reads relPath
// from the clone, and parses it as a hub index document. relPath must stay
// within the repo (no absolute paths or parent traversal).
func readIndexFromGitClone(cloneURL, relPath string) (*indexDocument, error) {
func readIndexFromGitClone(cloneURL, relPath string, opts install.ParseOptions) (*indexDocument, error) {
clean := filepath.Clean(relPath)
if filepath.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
return nil, fmt.Errorf("invalid hub index path: %s", relPath)
}
dir, err := install.ShallowCloneToTemp(cloneURL, "")
dir, err := install.ShallowCloneToTemp(cloneURL, "", opts)
if err != nil {
return nil, fmt.Errorf("clone hub repo: %w", err)
}
@@ -408,17 +408,17 @@ func gitLabWebToAPIRawURL(u *url.URL) (string, bool) {
), true
}
func buildHubRequest(indexURL string) (*http.Request, error) {
func buildHubRequest(indexURL string, opts install.ParseOptions) (*http.Request, error) {
req, err := http.NewRequest("GET", normalizeHubURL(indexURL), nil)
if err != nil {
return nil, err
}
applyHubAuthHeaders(req)
applyHubAuthHeaders(req, opts)
return req, nil
}
func applyHubAuthHeaders(req *http.Request) {
token, username := install.ResolveTokenForURL(req.URL.String())
func applyHubAuthHeaders(req *http.Request, opts install.ParseOptions) {
token, username := install.ResolveTokenForURL(req.URL.String(), opts)
if token == "" {
return
}
+43 -14
View File
@@ -28,7 +28,7 @@ func TestSearchFromIndexURL_LocalFile(t *testing.T) {
]
}`)
results, err := SearchFromIndexURL("react", 20, indexPath)
results, err := SearchFromIndexURL("react", 20, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -51,7 +51,7 @@ func TestSearchFromIndexURL_EmptyQuery(t *testing.T) {
]
}`)
results, err := SearchFromIndexURL("", 20, indexPath)
results, err := SearchFromIndexURL("", 20, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -64,7 +64,7 @@ func TestSearchFromIndexURL_MalformedJSON(t *testing.T) {
dir := t.TempDir()
indexPath := writeTestIndex(t, dir, "index.json", `{not valid json}`)
_, err := SearchFromIndexURL("test", 20, indexPath)
_, err := SearchFromIndexURL("test", 20, indexPath, install.ParseOptions{})
if err == nil {
t.Fatal("expected error for malformed JSON")
}
@@ -83,7 +83,7 @@ func TestSearchFromIndexURL_LimitRespected(t *testing.T) {
]
}`)
results, err := SearchFromIndexURL("", 2, indexPath)
results, err := SearchFromIndexURL("", 2, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -102,7 +102,7 @@ func TestSearchFromIndexURL_SourcePathJoin(t *testing.T) {
]
}`)
results, err := SearchFromIndexURL("", 20, indexPath)
results, err := SearchFromIndexURL("", 20, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -124,7 +124,7 @@ func TestSearchFromIndexURL_NoSourcePath(t *testing.T) {
]
}`)
results, err := SearchFromIndexURL("", 20, indexPath)
results, err := SearchFromIndexURL("", 20, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -137,7 +137,7 @@ func TestSearchFromIndexURL_NoSourcePath(t *testing.T) {
}
func TestSearchFromIndexURL_EmptyURL(t *testing.T) {
_, err := SearchFromIndexURL("test", 20, "")
_, err := SearchFromIndexURL("test", 20, "", install.ParseOptions{})
if err == nil {
t.Fatal("expected error for empty URL")
}
@@ -153,7 +153,7 @@ func TestSearchFromIndexURL_SkipsEmptyName(t *testing.T) {
]
}`)
results, err := SearchFromIndexURL("", 20, indexPath)
results, err := SearchFromIndexURL("", 20, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -173,7 +173,7 @@ func TestSearchFromIndexURL_RiskFields(t *testing.T) {
]
}`)
results, err := SearchFromIndexURL("", 20, indexPath)
results, err := SearchFromIndexURL("", 20, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -445,7 +445,7 @@ func TestBuildHubRequest_GitLabHeaders(t *testing.T) {
t.Setenv("GITLAB_TOKEN", "glpat_test")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
req, err := buildHubRequest("https://gitlab.com/runkids/demo_empty/-/blob/main/skillshare-hub.json")
req, err := buildHubRequest("https://gitlab.com/runkids/demo_empty/-/blob/main/skillshare-hub.json", install.ParseOptions{})
if err != nil {
t.Fatalf("buildHubRequest() error = %v", err)
}
@@ -465,7 +465,7 @@ func TestBuildHubRequest_GitHubHeaders(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "ghp_test")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
req, err := buildHubRequest("https://github.com/acme/skills/blob/main/skillshare-hub.json")
req, err := buildHubRequest("https://github.com/acme/skills/blob/main/skillshare-hub.json", install.ParseOptions{})
if err != nil {
t.Fatalf("buildHubRequest() error = %v", err)
}
@@ -483,7 +483,7 @@ func TestBuildHubRequest_BitbucketBasicAuth(t *testing.T) {
t.Setenv("BITBUCKET_USERNAME", "willie0903")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
req, err := buildHubRequest("https://bitbucket.org/team/repo/raw/main/skillshare-hub.json")
req, err := buildHubRequest("https://bitbucket.org/team/repo/raw/main/skillshare-hub.json", install.ParseOptions{})
if err != nil {
t.Fatalf("buildHubRequest() error = %v", err)
}
@@ -503,7 +503,7 @@ func TestBuildHubRequest_NoToken_NoAuthHeader(t *testing.T) {
t.Setenv("BITBUCKET_TOKEN", "")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
req, err := buildHubRequest("https://gitlab.com/group/repo/-/raw/main/skillshare-hub.json")
req, err := buildHubRequest("https://gitlab.com/group/repo/-/raw/main/skillshare-hub.json", install.ParseOptions{})
if err != nil {
t.Fatalf("buildHubRequest() error = %v", err)
}
@@ -600,7 +600,7 @@ func TestSearchFromIndexURL_PinnedSourceKeepsRef(t *testing.T) {
}]
}`)
results, err := SearchFromIndexURL("", 0, indexPath)
results, err := SearchFromIndexURL("", 0, indexPath, install.ParseOptions{})
if err != nil {
t.Fatalf("SearchFromIndexURL: %v", err)
}
@@ -619,3 +619,32 @@ func TestSearchFromIndexURL_PinnedSourceKeepsRef(t *testing.T) {
t.Errorf("Subdir = %q", src.Subdir)
}
}
func TestBuildHubRequest_ConfiguredHostAuthorization(t *testing.T) {
t.Setenv("CNB_TOKEN", "cnb-test-token")
t.Setenv("GITEA_TOKEN", "gitea-test-token")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
opts := install.ParseOptions{
CNBHosts: []string{"cnb.corp.example"},
GiteaHosts: []string{"forge.corp.example"},
}
for _, tt := range []struct {
url, auth string
}{
{"https://cnb.corp.example/org/repo/raw/main/skillshare-hub.json", "Bearer cnb-test-token"},
{"https://forge.corp.example/org/repo/raw/main/skillshare-hub.json", "Bearer gitea-test-token"},
{"https://cnb.attacker.invalid/org/repo/raw/main/skillshare-hub.json", ""},
{"https://gitea.attacker.invalid/org/repo/raw/main/skillshare-hub.json", ""},
{"https://forge.corp.example.attacker.invalid/org/repo/raw/main/skillshare-hub.json", ""},
} {
t.Run(tt.url, func(t *testing.T) {
req, err := buildHubRequest(tt.url, opts)
if err != nil {
t.Fatal(err)
}
if got := req.Header.Get("Authorization"); got != tt.auth {
t.Fatalf("Authorization = %q, want %q", got, tt.auth)
}
})
}
}
+19 -32
View File
@@ -41,8 +41,8 @@ type SkillPreview struct {
// GitHub-family hosts (github.com and GitHub Enterprise) use the REST Contents
// API at the host's own API base; all other platforms (GitLab, Bitbucket,
// Azure, SSH, …) fall back to a shallow git clone so their SKILL.md renders too.
func FetchPreview(client *http.Client, source, branch string) (*SkillPreview, error) {
src, err := install.ParseSource(source)
func FetchPreview(client *http.Client, source, branch string, opts install.ParseOptions) (*SkillPreview, error) {
src, err := install.ParseSourceWithOptions(source, opts)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrPreviewUnsupported, err)
}
@@ -50,6 +50,7 @@ func FetchPreview(client *http.Client, source, branch string) (*SkillPreview, er
}
func fetchPreviewFromSource(client *http.Client, src *install.Source, source, branch string) (*SkillPreview, error) {
opts := install.ParseOptions{CNBHosts: src.CNBHosts, GiteaHosts: src.GiteaHosts}
if branch == "" {
branch = src.Branch
}
@@ -57,10 +58,10 @@ func fetchPreviewFromSource(client *http.Client, src *install.Source, source, br
if apiBase := src.GitHubAPIBase(); apiBase != "" {
owner, repo := src.GitHubOwner(), src.GitHubRepo()
if owner != "" && repo != "" {
if src.Type == install.SourceTypeGitSSH && previewToken(src.CloneURL, apiBase) == "" {
if src.Type == install.SourceTypeGitSSH && previewToken(apiBase, opts) == "" {
return fetchViaClone(src, source, branch)
}
preview, err := fetchViaContentsAPI(client, apiBase, src.CloneURL, owner, repo, src.Subdir, branch)
preview, err := fetchViaContentsAPI(client, apiBase, owner, repo, src.Subdir, branch, opts)
if err == nil || src.Type != install.SourceTypeGitSSH {
return preview, err
}
@@ -71,10 +72,10 @@ func fetchPreviewFromSource(client *http.Client, src *install.Source, source, br
}
// fetchViaContentsAPI fetches SKILL.md through the GitHub/GHE Contents API at
// the given API base. cloneURL is used only to resolve a host-appropriate auth
// token. The path parameter is the subdirectory within the repo (empty for root).
func fetchViaContentsAPI(client *http.Client, apiBase, cloneURL, owner, repo, path, branch string) (*SkillPreview, error) {
token := previewToken(cloneURL, apiBase)
// the given API base. Authorization is resolved for that exact destination.
// The path parameter is the subdirectory within the repo (empty for root).
func fetchViaContentsAPI(client *http.Client, apiBase, owner, repo, path, branch string, opts install.ParseOptions) (*SkillPreview, error) {
token := previewToken(apiBase, opts)
skillPath := "SKILL.md"
if path != "" && path != "." {
@@ -109,7 +110,7 @@ func fetchViaContentsAPI(client *http.Client, apiBase, cloneURL, owner, repo, pa
// Hub sources use install shorthands (e.g. "owner/repo/critique")
// where the actual file may be at "source/skills/critique/SKILL.md".
if resolved := resolveSkillPath(client, apiBase, token, owner, repo, path, branch); resolved != "" {
return fetchViaContentsAPI(client, apiBase, cloneURL, owner, repo, resolved, branch)
return fetchViaContentsAPI(client, apiBase, owner, repo, resolved, branch, opts)
}
return nil, fmt.Errorf("%w: %s/%s/%s", ErrSkillNotFound, owner, repo, path)
}
@@ -156,7 +157,7 @@ func fetchViaClone(src *install.Source, source, branch string) (*SkillPreview, e
return nil, fmt.Errorf("%w: %s", ErrPreviewUnsupported, source)
}
dir, err := install.ShallowCloneToTemp(src.CloneURL, branch)
dir, err := install.ShallowCloneToTemp(src.CloneURL, branch, install.ParseOptions{CNBHosts: src.CNBHosts, GiteaHosts: src.GiteaHosts})
if err != nil {
return nil, fmt.Errorf("%w: clone %s: %v", ErrPreviewUnsupported, source, err)
}
@@ -259,35 +260,21 @@ func buildPreview(body, source, owner, repo string) *SkillPreview {
return preview
}
// previewToken resolves an auth token for the Contents API request. It prefers
// a host-specific token (GITHUB_TOKEN, GHE token via SKILLSHARE_GIT_TOKEN, …)
// and falls back to `gh auth token` only for github.com.
func previewToken(cloneURL, apiBase string) string {
if t, _ := install.ResolveTokenForURL(cloneURL); t != "" {
// previewToken authorizes the actual Contents API origin, including its scheme
// and port. The GitHub CLI fallback is limited to the public HTTPS API origin.
func previewToken(apiBase string, opts install.ParseOptions) string {
if t, _ := install.ResolveTokenForURL(apiBase, opts); t != "" {
return t
}
if lookupURL := previewTokenLookupURL(cloneURL); lookupURL != "" {
if t, _ := install.ResolveTokenForURL(lookupURL); t != "" {
return t
}
}
if apiBase == "https://api.github.com" {
u, err := url.Parse(apiBase)
if err == nil && strings.EqualFold(u.Scheme, "https") &&
strings.EqualFold(u.Hostname(), "api.github.com") &&
(u.Port() == "" || u.Port() == "443") && u.User == nil {
return ghclient.GetToken()
}
return ""
}
func previewTokenLookupURL(cloneURL string) string {
if _, host, ok := install.SSHIdentity(cloneURL); ok {
return "https://" + host + "/"
}
u, err := url.Parse(strings.TrimSpace(cloneURL))
if err != nil || u.Hostname() == "" {
return ""
}
return "https://" + u.Hostname() + "/"
}
// newContentsRequest builds a GET request for the GitHub/GHE REST API with the
// given token (token may be empty for anonymous requests).
func newContentsRequest(apiURL, token string) (*http.Request, error) {
+82 -5
View File
@@ -4,6 +4,7 @@ import (
"encoding/base64"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
@@ -63,7 +64,7 @@ func TestFetchViaContentsAPI_Success(t *testing.T) {
})
defer srv.Close()
preview, err := fetchViaContentsAPI(srv.Client(), srv.URL, "", "o", "r", "skills/foo", "")
preview, err := fetchViaContentsAPI(srv.Client(), srv.URL, "o", "r", "skills/foo", "", install.ParseOptions{})
if err != nil {
t.Fatalf("fetchViaContentsAPI: %v", err)
}
@@ -100,7 +101,7 @@ func TestFetchViaContentsAPI_TreeFallback(t *testing.T) {
})
defer srv.Close()
preview, err := fetchViaContentsAPI(srv.Client(), srv.URL, "", "o", "r", "critique", "")
preview, err := fetchViaContentsAPI(srv.Client(), srv.URL, "o", "r", "critique", "", install.ParseOptions{})
if err != nil {
t.Fatalf("fetchViaContentsAPI: %v", err)
}
@@ -118,7 +119,7 @@ func TestFetchViaContentsAPI_NotFound(t *testing.T) {
})
defer srv.Close()
_, err := fetchViaContentsAPI(srv.Client(), srv.URL, "", "o", "r", "missing", "")
_, err := fetchViaContentsAPI(srv.Client(), srv.URL, "o", "r", "missing", "", install.ParseOptions{})
if !errors.Is(err, ErrSkillNotFound) {
t.Fatalf("err = %v, want ErrSkillNotFound", err)
}
@@ -240,12 +241,12 @@ func TestFetchPreviewFromSource_SSHContentsAPIFailureFallsBackToClone(t *testing
}
}
func TestPreviewToken_ResolvesEnvForSSHGitHubSource(t *testing.T) {
func TestPreviewToken_ResolvesEnvForPublicGitHubAPI(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "ghp_test")
t.Setenv("GH_TOKEN", "")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
got := previewToken("git@github.com:o/r.git", "https://api.github.com")
got := previewToken("https://api.github.com", install.ParseOptions{})
if got != "ghp_test" {
t.Fatalf("previewToken() = %q, want ghp_test", got)
}
@@ -300,3 +301,79 @@ func writeFile(t *testing.T, root, rel, content string) {
t.Fatalf("write: %v", err)
}
}
type previewCredentialTransport struct {
t *testing.T
host, auth string
}
func (p previewCredentialTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Host != p.host || r.Header.Get("Authorization") != p.auth {
p.t.Fatalf("credential destination = %s, Authorization = %q", r.URL.Host, r.Header.Get("Authorization"))
}
body := `{"stargazers_count":0}`
if strings.Contains(r.URL.Path, "/contents/") {
body = contentsJSON(p.t, sampleSkillMD)
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
func TestFetchPreviewDoesNotAuthorizeProviderLookalikes(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "audit-dummy-token")
t.Setenv("GH_TOKEN", "")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
for _, tt := range []struct {
source, host, auth string
}{
{"https://github.attacker.invalid/o/r", "github.attacker.invalid", ""},
{"https://github.com/o/r", "api.github.com", "token audit-dummy-token"},
{"http://github.com/o/r", "api.github.com", "token audit-dummy-token"},
{"https://github.com:8443/o/r", "api.github.com", "token audit-dummy-token"},
} {
t.Run(tt.host, func(t *testing.T) {
client := &http.Client{Transport: previewCredentialTransport{t, tt.host, tt.auth}}
preview, err := FetchPreview(client, tt.source, "", install.ParseOptions{})
if err != nil {
t.Fatal(err)
}
if preview.Content != sampleSkillMD {
t.Fatalf("preview content = %q, want fixture", preview.Content)
}
})
}
}
func TestContentsPreview_ExactCredentialDestination(t *testing.T) {
t.Setenv("GITHUB_TOKEN", "github-preview-token")
t.Setenv("GH_TOKEN", "")
t.Setenv("CNB_TOKEN", "cnb-preview-token")
t.Setenv("GITEA_TOKEN", "gitea-preview-token")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
opts := install.ParseOptions{
CNBHosts: []string{"cnb.corp.example"},
GiteaHosts: []string{"forge.corp.example"},
}
for _, tt := range []struct {
apiBase, host, auth string
}{
{"https://api.github.com", "api.github.com", "token github-preview-token"},
{"http://api.github.com", "api.github.com", ""},
{"https://api.github.com:8443", "api.github.com:8443", ""},
{"https://cnb.corp.example", "cnb.corp.example", "token cnb-preview-token"},
{"https://forge.corp.example", "forge.corp.example", "token gitea-preview-token"},
{"http://forge.corp.example", "forge.corp.example", ""},
{"https://forge.corp.example:8443", "forge.corp.example:8443", ""},
{"https://gitea.attacker.invalid", "gitea.attacker.invalid", ""},
} {
t.Run(tt.apiBase, func(t *testing.T) {
client := &http.Client{Transport: previewCredentialTransport{t, tt.host, tt.auth}}
preview, err := fetchViaContentsAPI(client, tt.apiBase, "org", "repo", "", "", opts)
if err != nil {
t.Fatal(err)
}
if preview.Content != sampleSkillMD {
t.Fatal("preview did not return the requested skill")
}
})
}
}
+5 -4
View File
@@ -65,8 +65,8 @@ func dashboardSkillResults(results []check.SkillResult) []skillCheckResult {
// checkTrackedRepo checks one tracked repo with the same logic as the CLI:
// auth-aware fetch and a reported dirty-check error.
func checkTrackedRepo(name, repoPath string) repoCheckResult {
out := check.ParallelCheckRepos([]check.RepoCheckInput{{Name: name, RepoPath: repoPath}}, nil)[0]
func checkTrackedRepo(name, repoPath string, parseOpts install.ParseOptions) repoCheckResult {
out := check.ParallelCheckRepos([]check.RepoCheckInput{{Name: name, RepoPath: repoPath, ParseOptions: parseOpts}}, nil)[0]
return repoCheckResult{Name: out.Name, Status: out.Status, Behind: out.Behind, Message: out.Message}
}
@@ -76,6 +76,7 @@ func (s *Server) handleCheck(w http.ResponseWriter, r *http.Request) {
sourceDir := s.skillsSource()
projectRoot := s.projectRoot
walk := s.skillsWalk()
parseOpts := s.parseOpts()
s.mu.RUnlock()
repos, linked := dashboardRepos(sourceDir, walk)
@@ -83,11 +84,11 @@ func (s *Server) handleCheck(w http.ResponseWriter, r *http.Request) {
var repoResults []repoCheckResult
for _, repo := range repos {
repoResults = append(repoResults, checkTrackedRepo(repo, filepath.Join(sourceDir, repo)))
repoResults = append(repoResults, checkTrackedRepo(repo, filepath.Join(sourceDir, repo), parseOpts))
}
// Without a context the check runs to completion, so the error is always nil.
resolved, _ := plan.Run(context.Background(), check.Options{})
resolved, _ := plan.Run(context.Background(), check.Options{ParseOptions: parseOpts})
skillResults := dashboardSkillResults(resolved)
if repoResults == nil {
+3 -2
View File
@@ -32,6 +32,7 @@ func (s *Server) handleCheckStream(w http.ResponseWriter, r *http.Request) {
sourceDir := s.skillsSource()
projectRoot := s.projectRoot
walk := s.skillsWalk()
parseOpts := s.parseOpts()
s.mu.RUnlock()
// Immediate feedback before the potentially slow discovery walk.
@@ -82,12 +83,12 @@ func (s *Server) handleCheckStream(w http.ResponseWriter, r *http.Request) {
default:
}
repoResults = append(repoResults, checkTrackedRepo(repo, filepath.Join(sourceDir, repo)))
repoResults = append(repoResults, checkTrackedRepo(repo, filepath.Join(sourceDir, repo), parseOpts))
checked.Add(1)
}
// --- Phase 2: Check skills by remote (1 work unit per remote) ---
resolved, err := plan.Run(ctx, check.Options{OnRemoteDone: func(int) { checked.Add(1) }})
resolved, err := plan.Run(ctx, check.Options{ParseOptions: parseOpts, OnRemoteDone: func(int) { checked.Add(1) }})
// Stop ticker
close(done)
+6 -6
View File
@@ -223,7 +223,7 @@ func (s *Server) handleGitBranches(w http.ResponseWriter, r *http.Request) {
// Optional: fetch from remote first to discover new branches
if r.URL.Query().Get("fetch") == "true" && git.HasRemote(src) {
if err := git.FetchWithEnv(src, git.AuthEnvForRepo(src)); err != nil {
if err := git.FetchWithEnv(src, git.AuthEnvForRepo(src, s.parseOpts())); err != nil {
writeError(w, http.StatusInternalServerError, "git fetch failed: "+err.Error())
return
}
@@ -319,7 +319,7 @@ func (s *Server) handleGitCheckout(w http.ResponseWriter, r *http.Request) {
// Fetch before checkout to ensure remote refs are up to date
if git.HasRemote(src) {
if err := git.FetchWithEnv(src, git.AuthEnvForRepo(src)); err != nil {
if err := git.FetchWithEnv(src, git.AuthEnvForRepo(src, s.parseOpts())); err != nil {
s.writeOpsLog("checkout", "error", start, map[string]any{
"branch": body.Branch,
"scope": "ui",
@@ -536,7 +536,7 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request) {
if s.rootConfigHistoryGuard(w, src) {
return
}
if err := git.PushRemoteWithAuth(src); err != nil {
if err := git.PushRemoteWithAuth(src, s.parseOpts()); err != nil {
if errors.Is(err, git.ErrPushRejected) {
// The UI offers a pull for this code.
s.writeOpsLog("push", "error", start, args, err.Error())
@@ -557,7 +557,7 @@ func (s *Server) rootConfigHistoryGuard(w http.ResponseWriter, src string) bool
if s.cfg.GitRoot != "root" {
return false
}
if err := git.CheckUnpushedConfigHistory(src); err != nil {
if err := git.CheckUnpushedConfigHistory(src, s.parseOpts()); err != nil {
var historyErr *git.UnpushedConfigHistoryError
if errors.As(err, &historyErr) {
writeCodedError(w, http.StatusConflict, "unpushed_config_history", err.Error(), nil)
@@ -749,7 +749,7 @@ func (s *Server) handlePull(w http.ResponseWriter, r *http.Request) {
return
}
}
info, err = git.PullWithResolution(src, body.Resolution)
info, err = git.PullWithResolution(src, body.Resolution, s.parseOpts())
// A restore failure joins the pull's own error so a conflict is still
// reported as one and the failure is logged below.
var restoreErr error
@@ -760,7 +760,7 @@ func (s *Server) handlePull(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "conflict resolution requires an upstream branch")
return
}
info, err = git.FirstPull(src, body.Force)
info, err = git.FirstPull(src, body.Force, s.parseOpts())
}
if errors.Is(err, git.ErrNoRemoteBranches) {
// Sync both ways pushes on this code, like push --pull.
+18 -3
View File
@@ -1,12 +1,14 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"sync"
"time"
ghclient "skillshare/internal/github"
"skillshare/internal/install"
"skillshare/internal/search"
)
@@ -21,6 +23,15 @@ type previewCacheEntry struct {
expiresAt time.Time
}
type previewCacheKey struct {
source, branch, policy string
}
func previewKey(source, branch string, opts install.ParseOptions) previewCacheKey {
policy, _ := json.Marshal(opts)
return previewCacheKey{source: source, branch: branch, policy: string(policy)}
}
func (s *Server) handlePreview(w http.ResponseWriter, r *http.Request) {
source := r.URL.Query().Get("source")
if source == "" {
@@ -29,8 +40,12 @@ func (s *Server) handlePreview(w http.ResponseWriter, r *http.Request) {
}
branch := r.URL.Query().Get("branch")
// Check cache (include branch in key to avoid cross-branch collisions)
cacheKey := source + "@" + branch
s.mu.RLock()
parseOpts := s.parseOpts()
s.mu.RUnlock()
// Bind cached content to both the requested ref and configured host scope.
cacheKey := previewKey(source, branch, parseOpts)
if entry, ok := previewCache.Load(cacheKey); ok {
ce := entry.(*previewCacheEntry)
if time.Now().Before(ce.expiresAt) {
@@ -41,7 +56,7 @@ func (s *Server) handlePreview(w http.ResponseWriter, r *http.Request) {
}
client := ghclient.NewClient()
preview, err := search.FetchPreview(client, source, branch)
preview, err := search.FetchPreview(client, source, branch, parseOpts)
if err != nil {
var rlErr *ghclient.RateLimitError
if errors.As(err, &rlErr) {
+1 -1
View File
@@ -48,7 +48,7 @@ func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "SSH hub sources must be added first via 'skillshare hub add'")
return
}
results, err = search.SearchFromIndexURL(query, limit, hubParam)
results, err = search.SearchFromIndexURL(query, limit, hubParam, parseOpts)
default:
// GitHub search always needs a limit
if limit <= 0 {
+40
View File
@@ -4,9 +4,12 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"skillshare/internal/config"
"skillshare/internal/search"
)
func TestSavedHubURLSet(t *testing.T) {
@@ -35,3 +38,40 @@ func TestHandleSearch_SSHHubNotSaved_Forbidden(t *testing.T) {
t.Fatalf("expected 403 for unsaved SSH hub, got %d: %s", rr.Code, rr.Body.String())
}
}
func TestHandlePreview_CacheDoesNotOutliveHostAuthorization(t *testing.T) {
t.Setenv("SKILLSHARE_CNB_HOSTS", "")
t.Setenv("SKILLSHARE_GITEA_HOSTS", "")
for _, provider := range []string{"cnb", "gitea"} {
t.Run(provider, func(t *testing.T) {
s, _ := newTestServer(t)
if provider == "cnb" {
s.cfg.CNBHosts = []string{"forge.corp.example"}
} else {
s.cfg.GiteaHosts = []string{"forge.corp.example"}
}
// This deliberately invalid source cannot trigger network I/O on a miss.
source := "invalid-" + strings.ReplaceAll(t.Name(), "/", "-")
key := previewKey(source, "main", s.parseOpts())
previewCache.Store(key, &previewCacheEntry{
data: &search.SkillPreview{Content: "private cached skill"},
expiresAt: time.Now().Add(time.Minute),
})
t.Cleanup(func() { previewCache.Delete(key) })
target := "/api/preview?source=" + url.QueryEscape(source) + "&branch=main"
fetch := func() *httptest.ResponseRecorder {
rr := httptest.NewRecorder()
s.handlePreview(rr, httptest.NewRequest(http.MethodGet, target, nil))
return rr
}
if rr := fetch(); rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "private cached skill") {
t.Fatalf("authorized cache hit = %d: %s", rr.Code, rr.Body.String())
}
s.cfg.CNBHosts = nil
s.cfg.GiteaHosts = nil
if rr := fetch(); rr.Code != http.StatusNotFound || strings.Contains(rr.Body.String(), "private cached skill") {
t.Fatalf("revoked host authorization reused private preview: %d: %s", rr.Code, rr.Body.String())
}
})
}
}
+5 -4
View File
@@ -314,10 +314,11 @@ func (s *Server) updateTrackedRepo(name, repoPath, sourceDir string, force, skip
return *refusal
}
opts := update.TrackedRepoOptions{
SourceDir: sourceDir,
Force: force,
SkipAudit: skipAudit,
Threshold: s.updateAuditThreshold(),
ParseOptions: s.parseOpts(),
SourceDir: sourceDir,
Force: force,
SkipAudit: skipAudit,
Threshold: s.updateAuditThreshold(),
}
if len(follow) > 0 {
opts.Follow = follow[0]
+2 -2
View File
@@ -24,8 +24,8 @@ func rejectCrossSiteWrites(next http.Handler) http.Handler {
})
}
// requireSameOrigin applies the same check to a GET route that changes state, such as an
// update stream that EventSource can only open with GET.
// requireSameOrigin protects sensitive GET routes: update streams and remote
// reads that can send credentials to a request-selected destination.
func requireSameOrigin(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !sameOriginRequest(r) {
+27
View File
@@ -72,3 +72,30 @@ func TestCrossSiteUpdateStreamIsRefused(t *testing.T) {
t.Fatalf("status = %d: %s", rr.Code, rr.Body.String())
}
}
func TestCrossSitePreviewIsRefused(t *testing.T) {
s, _ := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/api/preview?source=https://github.attacker.invalid/demo/skill", nil)
req.Host = "127.0.0.1:19420"
req.Header.Set("Origin", "https://untrusted-page.invalid")
req.Header.Set("Sec-Fetch-Site", "cross-site")
rr := httptest.NewRecorder()
s.servedHandler().ServeHTTP(rr, req)
if rr.Code != http.StatusForbidden {
t.Fatalf("cross-site preview status = %d, want 403: %s", rr.Code, rr.Body.String())
}
}
func TestCrossSiteHubSearchIsRefused(t *testing.T) {
t.Setenv("SKILLSHARE_GIT_TOKEN", "audit-dummy-token")
s, _ := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/api/search?hub=https://untrusted.invalid/index.json", nil)
req.Host = "127.0.0.1:19420"
req.Header.Set("Origin", "https://untrusted-page.invalid")
req.Header.Set("Sec-Fetch-Site", "cross-site")
rr := httptest.NewRecorder()
s.servedHandler().ServeHTTP(rr, req)
if rr.Code != http.StatusForbidden {
t.Fatalf("cross-site hub search status = %d, want 403: %s", rr.Code, rr.Body.String())
}
}
+2 -2
View File
@@ -580,8 +580,8 @@ func (s *Server) registerRoutes() {
s.mux.HandleFunc("DELETE /api/hub/saved/{label}", s.handleDeleteHubSaved)
// Search & Install
s.mux.HandleFunc("GET /api/search", s.handleSearch)
s.mux.HandleFunc("GET /api/preview", s.handlePreview)
s.mux.HandleFunc("GET /api/search", requireSameOrigin(s.handleSearch))
s.mux.HandleFunc("GET /api/preview", requireSameOrigin(s.handlePreview))
s.mux.HandleFunc("POST /api/discover", s.handleDiscover)
s.mux.HandleFunc("POST /api/install", s.handleInstall)
s.mux.HandleFunc("POST /api/install/batch", s.handleInstallBatch)
+95
View File
@@ -13,6 +13,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/install"
"skillshare/internal/skillpkg"
"skillshare/internal/sourcewalk"
)
func writeFile(t *testing.T, path, content string) {
@@ -149,6 +150,100 @@ func TestBuild_SkipsParentOfExcludedNestedSkill(t *testing.T) {
}
}
func TestBuild_RefusesAgentsFallbackAliasesOfExcludedSkills(t *testing.T) {
orig := sourcewalk.TargetDotDirs
sourcewalk.TargetDotDirs = map[string]bool{".agents": true}
defer func() { sourcewalk.TargetDotDirs = orig }()
for _, component := range []string{".agents", "skills"} {
for _, follow := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/follow=%t", component, follow), func(t *testing.T) {
hub := t.TempDir()
src := filepath.Join(hub, "skills")
writeFile(t, filepath.Join(src, "private", "SKILL.md"), skillMD("private"))
writeFile(t, filepath.Join(src, "private", "secret.txt"), "excluded-private-marker")
repo := filepath.Join(src, "_public")
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0o755); err != nil {
t.Fatal(err)
}
link := filepath.Join(repo, ".agents")
if component == "skills" {
if err := os.MkdirAll(link, 0o755); err != nil {
t.Fatal(err)
}
link = filepath.Join(link, "skills")
}
// .agents points to hub; skills points to the skills source.
if err := os.Symlink("../..", link); err != nil {
t.Fatal(err)
}
b := &Builder{Source: src, Target: "claude", Skills: &config.ResourceTargetConfig{Include: []string{"_public__*"}}}
if follow {
b.Walk.Follow = sourcewalk.NewFollow(src, nil)
}
c, err := b.Build()
if err != nil {
t.Fatal(err)
}
if len(c.Skills) != 0 {
t.Errorf("excluded skill published through fallback alias: %v", c.Skills)
}
for _, prefix := range []string{"private", "_public/.agents/skills/private"} {
if _, ok := c.Skill("skill://" + prefix + "/SKILL.md"); ok {
t.Errorf("excluded skill published at %s", prefix)
}
uri := "skill://" + prefix + "/secret.txt"
if c.Revision(uri) != "" {
t.Errorf("excluded file listed at %s", uri)
}
if data, err := c.Read(uri); err == nil || len(data) != 0 {
t.Errorf("Read(%s) = %q, %v; want rejection", uri, data, err)
}
}
})
}
}
}
func TestBuild_ServesRealAgentsFallbackThroughFollowedRepoRoot(t *testing.T) {
orig := sourcewalk.TargetDotDirs
sourcewalk.TargetDotDirs = map[string]bool{".agents": true}
defer func() { sourcewalk.TargetDotDirs = orig }()
for _, followedRoot := range []bool{false, true} {
t.Run(fmt.Sprintf("followed=%t", followedRoot), func(t *testing.T) {
src := t.TempDir()
repo := filepath.Join(src, "_public")
if followedRoot {
repo = t.TempDir()
if err := os.Symlink(repo, filepath.Join(src, "_public")); err != nil {
t.Fatal(err)
}
}
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0o755); err != nil {
t.Fatal(err)
}
writeFile(t, filepath.Join(repo, ".agents", "skills", "public", "SKILL.md"), skillMD("public"))
writeFile(t, filepath.Join(repo, ".agents", "skills", "public", "reference.txt"), "public-marker")
b := &Builder{Source: src, Target: "claude", Skills: &config.ResourceTargetConfig{Include: []string{"_public__*"}}}
if followedRoot {
b.Walk.Follow = sourcewalk.NewFollow(src, nil)
}
c, err := b.Build()
if err != nil {
t.Fatal(err)
}
const prefix = "skill://_public/.agents/skills/public/"
if len(c.Skills) != 1 || find(c, prefix+"SKILL.md") == nil {
t.Fatalf("real fallback not published: skills=%v warnings=%v", c.Skills, c.Skipped)
}
if data, err := c.Read(prefix + "reference.txt"); err != nil || string(data) != "public-marker" {
t.Errorf("Read real fallback = %q, %v", data, err)
}
})
}
}
// A parent and its nested skill list the same files under the same URIs; an
// unchanged tree serves both.
func TestBuild_ServesParentAndNestedSkillTogether(t *testing.T) {
+3 -7
View File
@@ -167,13 +167,8 @@ internal/install/github_download.go writeDownloadedFile os.OpenFile destPath clo
internal/install/gitignore.go writeGitignoreLines os.WriteFile path source-unmigrated
internal/install/install.go <package> os.RemoveAll <ref> source-unmigrated
internal/install/install.go <package> os.RemoveAll <ref> source-unmigrated
internal/install/install_apply.go UpdateAgentFromDiscovery os.MkdirAll filepath.Dir(destFile) agents
internal/install/install_apply.go UpdateAgentFromDiscovery os.MkdirTemp "" tmp
internal/install/install_apply.go UpdateAgentFromDiscovery os.RemoveAll tempDir tmp
internal/install/install_apply.go UpdateAgentFromDiscovery os.Rename tempFile, destFile agents
internal/install/install_apply.go UpdateAgentFromDiscovery os.WriteFile destFile agents
internal/install/install_apply.go installAgentFromDiscoveryInternal os.MkdirAll filepath.Dir(destFile) agents
internal/install/install_apply.go installAgentFromDiscoveryInternal os.WriteFile destFile agents
internal/install/install_apply.go installAgentFromDiscoveryInternal os.MkdirTemp "" tmp
internal/install/install_apply.go installAgentFromDiscoveryInternal os.RemoveAll tempDir tmp
internal/install/install_apply.go installFromDiscoveryInternal os.MkdirAll workDest source-unmigrated
internal/install/install_apply.go installFromDiscoveryInternal os.MkdirTemp "" tmp
internal/install/install_apply.go installFromDiscoveryInternal os.RemoveAll tempDir tmp
@@ -543,3 +538,4 @@ internal/version/check.go saveCacheAt os.WriteFile cachePath config
internal/config/config.go (*Config).Save os.MkdirAll dir config
internal/config/config.go (*Config).Save os.WriteFile path config
internal/plugin/state.go (*Service).saveState os.MkdirAll s.managedRoot() config
internal/testutil/private_git.go ServePrivateGit os.Mkdir filepath.Join(root, "org") test-helper
Can't render this file because it contains an unexpected character in line 23 and column 89.
+13 -5
View File
@@ -38,17 +38,25 @@ var errSkillFound = errors.New("skill found")
// only when no SKILL.md exists elsewhere in the repository outside .git and
// the target dot dirs in dotDirs. Ignore rules are not applied: a repository
// whose authored skills are all ignored must not fall back to its copies.
// The repository root may be linked, but both fallback components must be real
// directories so the fallback cannot follow a nested link out of the repository.
func AgentsSkillsDir(repoRoot string, dotDirs map[string]bool) (string, bool) {
if !dotDirs[".agents"] {
return "", false
}
dir := filepath.Join(repoRoot, ".agents", "skills")
if info, err := os.Lstat(dir); err != nil || !info.IsDir() {
return "", false
// Resolve only the intentionally allowed repository root, then inspect each
// fallback component without following links.
root := utils.ResolveSymlink(repoRoot)
dir := root
for _, component := range [...]string{".agents", "skills"} {
dir = filepath.Join(dir, component)
info, err := os.Lstat(dir)
if err != nil || !info.IsDir() || utils.IsLinkMode(dir, info.Mode()) {
return "", false
}
}
// Scan the resolved root: filepath.Walk does not descend into a root that
// is a link, which would hide the authored skills of a linked repository.
root := utils.ResolveSymlink(repoRoot)
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
@@ -64,7 +72,7 @@ func AgentsSkillsDir(repoRoot string, dotDirs map[string]bool) (string, bool) {
if err != nil {
return "", false
}
return dir, true
return filepath.Join(repoRoot, ".agents", "skills"), true
}
// Options is the operation's traversal policy. The zero value follows no links.
+60
View File
@@ -284,3 +284,63 @@ func TestAgentsSkillsDirThroughLinkedRoot(t *testing.T) {
})
}
}
func TestAgentsSkillsDirRequiresRealDirectories(t *testing.T) {
dotDirs := map[string]bool{".agents": true}
for _, linkedRoot := range []bool{false, true} {
rootName := "real root"
if linkedRoot {
rootName = "linked root"
}
t.Run(rootName, func(t *testing.T) {
for _, tt := range []struct {
name string
component string
link bool
want bool
}{
{name: "real fallback", want: true},
{name: "linked .agents", component: ".agents", link: true},
{name: "linked skills", component: ".agents/skills", link: true},
{name: "file .agents", component: ".agents"},
{name: "file skills", component: ".agents/skills"},
} {
t.Run(tt.name, func(t *testing.T) {
repo := t.TempDir()
if tt.want {
write(t, filepath.Join(repo, ".agents", "skills", "x", "SKILL.md"))
} else {
component := filepath.Join(repo, filepath.FromSlash(tt.component))
if err := os.MkdirAll(filepath.Dir(component), 0755); err != nil {
t.Fatal(err)
}
if tt.link {
outside := t.TempDir()
write(t, filepath.Join(outside, "skills", "x", "SKILL.md"))
target := outside
if tt.component == ".agents/skills" {
target = filepath.Join(outside, "skills")
}
symlink(t, target, component)
} else {
write(t, component)
}
}
root := repo
if linkedRoot {
root = filepath.Join(t.TempDir(), "repo")
symlink(t, repo, root)
}
dir, ok := AgentsSkillsDir(root, dotDirs)
wantDir := ""
if tt.want {
wantDir = filepath.Join(root, ".agents", "skills")
}
if ok != tt.want || dir != wantDir {
t.Fatalf("AgentsSkillsDir() = %q, %v; want %q, %v", dir, ok, wantDir, tt.want)
}
})
}
})
}
}
+84
View File
@@ -0,0 +1,84 @@
package testutil
import (
"fmt"
"io"
"net"
"net/http"
"net/http/cgi"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// ServePrivateGit routes HTTPS Git traffic to a local authenticated smart-HTTP
// backend serving repo at /org/repo.git. It never resolves or dials the requested
// hostname, so configured and lookalike origins both remain entirely local.
func ServePrivateGit(t *testing.T, repo, username, password string) {
t.Helper()
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "org"), 0o755); err != nil {
t.Fatal(err)
}
RunGit(t, root, "clone", "--bare", repo, filepath.Join(root, "org", "repo.git"))
gitPath, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
backend := &cgi.Handler{
Path: gitPath,
Args: []string{"http-backend"},
Env: []string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"},
}
remote := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || user != username || pass != password {
w.Header().Set("WWW-Authenticate", `Basic realm="private repo"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
backend.ServeHTTP(w, r)
}))
t.Cleanup(remote.Close)
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodConnect {
http.Error(w, "CONNECT required", http.StatusMethodNotAllowed)
return
}
upstream, err := net.DialTimeout("tcp", strings.TrimPrefix(remote.URL, "https://"), 5*time.Second)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer upstream.Close()
conn, buffered, err := w.(http.Hijacker).Hijack()
if err != nil {
return
}
defer conn.Close()
deadline := time.Now().Add(10 * time.Second)
_ = conn.SetDeadline(deadline)
_ = upstream.SetDeadline(deadline)
if _, err := fmt.Fprint(conn, "HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil {
return
}
go func() { _, _ = io.Copy(upstream, buffered) }()
_, _ = io.Copy(conn, upstream)
}))
t.Cleanup(proxy.Close)
global := filepath.Join(t.TempDir(), "gitconfig")
RunGit(t, root, "config", "--file", global, "http.proxy", proxy.URL)
t.Setenv("GIT_CONFIG_GLOBAL", global)
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
t.Setenv("GIT_CONFIG_COUNT", "0")
t.Setenv("GIT_SSL_NO_VERIFY", "true")
t.Setenv("GIT_TERMINAL_PROMPT", "0")
t.Setenv("GIT_ASKPASS", "")
t.Setenv("NO_PROXY", "")
t.Setenv("no_proxy", "")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
}
+5 -4
View File
@@ -55,7 +55,8 @@ func (e *Error) Unwrap() error { return e.Err }
type TrackedRepoOptions struct {
// SourceDir is the source root that holds the repo's metadata and accepted
// findings.
SourceDir string
SourceDir string
ParseOptions install.ParseOptions
// Force discards uncommitted changes, pulls with a hard reset and lets
// audit findings through. It never overrides a scan that could not run.
Force bool
@@ -121,7 +122,7 @@ func TrackedRepo(repoPath string, opts TrackedRepoOptions) (*TrackedRepoResult,
return res, nil
}
candidate, err := install.StageGitUpdate(repoPath, opts.Force)
candidate, err := install.StageGitUpdate(repoPath, opts.Force, opts.ParseOptions)
if err != nil {
return res, &Error{Stage: StagePull, Err: err}
}
@@ -131,7 +132,7 @@ func TrackedRepo(repoPath string, opts TrackedRepoOptions) (*TrackedRepoResult,
if opts.Force {
pull = git.ForcePullWithProgress
}
info, err := pull(candidate.Path, git.AuthEnvForRepo(repoPath), opts.OnProgress)
info, err := pull(candidate.Path, git.AuthEnvForRepo(repoPath, opts.ParseOptions), opts.OnProgress)
if err != nil {
return res, &Error{Stage: StagePull, Err: err}
}
@@ -158,7 +159,7 @@ func TrackedRepo(repoPath string, opts TrackedRepoOptions) (*TrackedRepoResult,
}
if !info.UpToDate {
res.Warnings = install.SubmoduleWarnings(repoPath, git.AuthEnvForRepo(repoPath))
res.Warnings = install.SubmoduleWarnings(repoPath, git.AuthEnvForRepo(repoPath, opts.ParseOptions))
}
res.MetadataChanged, res.MetadataErr = refreshMetadata(repoPath, opts)
+3 -1
View File
@@ -17,6 +17,8 @@ Discovery skips target directories such as `.claude/` and `.agents/`, which usua
hold copies of a repository's skills. A repository with no other skills has its
root `.agents/skills/` discovered instead.
The `.agents/skills/` fallback requires both `.agents` and `skills` to be real directories, not symlinks or junctions, even with `follow_source_links: true`. An intentionally followed repository root remains supported. Discovered agent installs and updates reject intermediate or final destination links; audits run before publication, and a blocked audit leaves existing agent contents unchanged.
For an explicit, untracked skill source, `install <source> --dry-run --json`
returns `planned: [{name, path}]`: canonical install names and repository-relative
Git paths (including a selected subdirectory), or `.` for a local skill. Use this
@@ -162,7 +164,7 @@ Tracked custom names must not contain path separators (`/`, `\`) or `..`.
**Security audit:** Install auto-scans skills after download. Blocking follows the active threshold (default `CRITICAL`), while aggregate risk is reported separately for context. Use `--force` to override blocking, `--skip-audit` to skip scanning, or `--audit-threshold` / `--threshold` / `-T` to override threshold per command.
**Private repos (HTTPS):** `install` and `update` auto-detect `GITHUB_TOKEN`, `GITLAB_TOKEN`, `BITBUCKET_TOKEN`, `AZURE_DEVOPS_TOKEN`, `GITEA_TOKEN`, `CNB_TOKEN`, or `SKILLSHARE_GIT_TOKEN` for HTTPS clone/pull. No manual git config needed. SSH works as usual.
**Private repos (HTTPS):** Provider tokens are sent only over HTTPS on the default port (or 443): `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, and `cnb.cool`. Self-hosted Gitea/CNB requires an exact hostname in `gitea_hosts`/`cnb_hosts`, even if its name contains the provider name. For self-hosted GitHub/GitLab or other hosts, use a host-scoped Git credential helper, or set `SKILLSHARE_GIT_TOKEN` only for the intended invocation. That generic fallback can be sent to **any HTTPS source**; provider-looking names do not authorize provider tokens. SSH and host-scoped Git credential helpers work as usual.
**After install:** `skillshare sync`
@@ -18,14 +18,16 @@ skillshare detects tokens from environment variables, with platform-specific var
| Platform | Environment Variable |
|----------|---------------------|
| GitHub / GitHub Enterprise | `GITHUB_TOKEN` |
| GitLab / Self-hosted GitLab | `GITLAB_TOKEN` |
| `github.com` | `GITHUB_TOKEN` |
| `gitlab.com` | `GITLAB_TOKEN` |
| Bitbucket | `BITBUCKET_TOKEN` (+ optional `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` |
| Gitea / Self-hosted Gitea | `GITEA_TOKEN` |
| CNB | `CNB_TOKEN` |
| Any platform (fallback) | `SKILLSHARE_GIT_TOKEN` |
Provider tokens are sent only over HTTPS on the default port (or 443): `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, and `cnb.cool`. Self-hosted Gitea/CNB requires an exact hostname in `gitea_hosts`/`cnb_hosts`, even if its name contains the provider name. For self-hosted GitHub/GitLab or other hosts, use a host-scoped Git credential helper, or set `SKILLSHARE_GIT_TOKEN` only for the intended invocation. That generic fallback can be sent to **any HTTPS source**; provider-looking names do not authorize provider tokens.
```bash
# Option A: Git credential helper (recommended for GitHub)
gh auth login # sets up git credential helper for HTTPS
@@ -80,8 +82,8 @@ skillshare sync # Push to targets
- **Selective install**: `skillshare install your-org/internal-skills --skill code-review` installs only one skill
- **CI/CD token**: In pipelines, set the platform-specific env var (e.g., `GITHUB_TOKEN`) from CI secrets
- **Self-hosted GitLab**: Set `GITLAB_TOKEN` and use HTTPS URL: `skillshare install https://gitlab.internal.com/team/skills.git --track`
- **Self-hosted Gitea**: Set `GITEA_TOKEN`. If the hostname does not contain `gitea`, also list it in [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)
- **Self-hosted GitHub/GitLab**: Use a host-scoped Git credential helper, or provide the token only for this invocation: `SKILLSHARE_GIT_TOKEN=your-token skillshare install https://gitlab.internal.com/team/skills.git --track`. `GITHUB_TOKEN`/`GITLAB_TOKEN` are not sent to self-hosted instances.
- **Self-hosted Gitea**: Set `GITEA_TOKEN` and always list the exact hostname in [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts).
- **Gitee / AtomGit**: Supported via HTTPS URLs with `SKILLSHARE_GIT_TOKEN`
## Related
@@ -197,6 +197,8 @@ See [Reverse Proxy](/docs/reference/commands/ui#reverse-proxy).
GitHub personal access token.
Provider tokens are sent only over HTTPS on the default port (or 443): `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, and `cnb.cool`. Self-hosted Gitea/CNB requires an exact hostname in `gitea_hosts`/`cnb_hosts`, even if its name contains the provider name. For self-hosted GitHub/GitLab or other hosts, use a host-scoped Git credential helper, or set `SKILLSHARE_GIT_TOKEN` only for the intended invocation. That generic fallback can be sent to **any HTTPS source**; provider-looking names do not authorize provider tokens.
**Used for:**
- GitHub API requests (`skillshare search`, `skillshare upgrade`, version check)
- **Git clone authentication** — automatically injected when installing private repos via HTTPS
@@ -353,7 +355,7 @@ skillshare install https://gitea.com/org/skills.git --track
$env:GITEA_TOKEN = "your_token"
```
The token is sent only to the host you install from. A self-hosted instance on a domain without `gitea` in its name needs [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts), otherwise `SKILLSHARE_GIT_TOKEN` is used for it.
Self-hosted Gitea requires an exact hostname in [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) to authorize `GITEA_TOKEN`, even when the name contains `gitea`. Provider authentication requires HTTPS on the default port or 443.
### CNB_TOKEN
+8 -2
View File
@@ -131,6 +131,8 @@ $ skillshare install anthropics/skills
Discovery scans all directories for `SKILL.md` files except `.git` and target directories such as `.claude/` and `.agents/`, which usually hold copies of the repository's skills. Other hidden directories like `.curated/` or `.system/` are scanned, so their skills are discovered automatically. A repository with no other skills has its root `.agents/skills/` scanned instead. When multiple skills are found, the prompt lists skills from the same folder together and shows each one's description and folder; press `/` to narrow a long list.
The `.agents/skills/` fallback requires both `.agents` and `skills` to be real directories, not symlinks or junctions, even with `follow_source_links: true`. An intentionally followed repository root remains supported. Discovered agent installs and updates reject intermediate or final destination links; audits run before publication, and a blocked audit leaves existing agent contents unchanged.
If the repository contains a `.skillignore` file at its root, matching skills are automatically excluded from discovery. See [.skillignore](#skillignore) below.
If a skill's `SKILL.md` includes a `license:` frontmatter field, the license is shown in the selection prompt (e.g., `my-skill (MIT)`) and in the confirmation screen for single-skill installs.
@@ -549,14 +551,18 @@ skillshare install https://github.com/org/private-skills.git --track
| Platform | Env Var | Token Type |
|----------|---------|------------|
| GitHub | `GITHUB_TOKEN` | Personal access token (`repo` scope) |
| GitLab | `GITLAB_TOKEN` | Personal access or CI job token |
| `github.com` | `GITHUB_TOKEN` | Personal access token (`repo` scope) |
| `gitlab.com` | `GITLAB_TOKEN` | Personal access or CI job token |
| Bitbucket | `BITBUCKET_TOKEN` | Repository token, or app password (with `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` | Personal Access Token (Code: Read scope) |
| Gitea | `GITEA_TOKEN` | Access token (repository: Read) |
| CNB | `CNB_TOKEN` | Access token with repository read permission |
| Any host | `SKILLSHARE_GIT_TOKEN` | Generic fallback |
Provider tokens are sent only over HTTPS on the default port (or 443): `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, and `cnb.cool`. Self-hosted Gitea/CNB requires an exact hostname in `gitea_hosts`/`cnb_hosts`, even if its name contains the provider name. For self-hosted GitHub/GitLab or other hosts, use a host-scoped Git credential helper, or set `SKILLSHARE_GIT_TOKEN` only for the intended invocation. That generic fallback can be sent to **any HTTPS source**; provider-looking names do not authorize provider tokens.
Provider tokens are sent only over HTTPS on the default port (or 443): `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, and `cnb.cool`. Self-hosted Gitea/CNB requires an exact hostname in `gitea_hosts`/`cnb_hosts`, even if its name contains the provider name. For self-hosted GitHub/GitLab or other hosts, use a host-scoped Git credential helper, or set `SKILLSHARE_GIT_TOKEN` only for the intended invocation. That generic fallback can be sent to **any HTTPS source**; provider-looking names do not authorize provider tokens.
Platform-specific variables take priority over `SKILLSHARE_GIT_TOKEN`.
The token reaches git through a credential helper scoped to the host, so it never appears in process arguments such as `ps` output. While a token applies to a host, git does not ask your own credential helper or keychain for that host and stores nothing there.
+2
View File
@@ -6,6 +6,8 @@ sidebar_position: 1
Launch the web dashboard for visual skill management.
Remote searches (`GET /api/search`) and install previews (`GET /api/preview`) use the same origin checks as mutations: cross-site browser requests are refused before fetching. Direct clients without browser origin/fetch headers remain supported. GitHub API credentials are restricted to HTTPS `api.github.com` and `raw.githubusercontent.com` on the default port or 443; authorization is removed on cross-origin redirects.
```bash
skillshare ui # Run in the foreground
skillshare ui start # Start (or reuse) a background server
@@ -852,7 +852,7 @@ SKILLSHARE_AZURE_HOSTS=azuredevops.mycompany.com skillshare install \
### `gitea_hosts`
Hostnames of self-hosted Gitea instances. Hosts containing `gitea` in the name, such as `gitea.com` or `gitea.company.com`, are detected automatically. This field is only needed for other custom domains.
Self-hosted Gitea requires an exact hostname in [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) to authorize `GITEA_TOKEN`, even when the name contains `gitea`. Provider authentication requires HTTPS on the default port or 443.
```yaml
gitea_hosts:
@@ -20,14 +20,16 @@ skillshare は環境変数からトークンを検出します。プラットフ
| プラットフォーム | 環境変数 |
|----------|---------------------|
| GitHub / GitHub Enterprise | `GITHUB_TOKEN` |
| GitLab / セルフホストの GitLab | `GITLAB_TOKEN` |
| `github.com` | `GITHUB_TOKEN` |
| `gitlab.com` | `GITLAB_TOKEN` |
| Bitbucket | `BITBUCKET_TOKEN`(+ 任意で `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` |
| Gitea / セルフホストの Gitea | `GITEA_TOKEN` |
| CNB | `CNB_TOKEN` |
| 任意のプラットフォーム(フォールバック) | `SKILLSHARE_GIT_TOKEN` |
プロバイダーのトークンは HTTPS の既定ポート(または 443)でのみ送信されます。対象は `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com`、`cnb.cool` です。セルフホストの Gitea/CNB は、名前にプロバイダー名を含む場合も `gitea_hosts`/`cnb_hosts` に正確なホスト名の登録が必要です。セルフホストの GitHub/GitLab などにはホスト別の Git credential helper を使うか、対象の実行時だけ `SKILLSHARE_GIT_TOKEN` を設定してください。この汎用フォールバックは**任意の HTTPS ソース**に送信されます。名前による判定だけではプロバイダートークンの送信は許可されません。
```bash
# オプション A: Git credential helper(GitHub に推奨)
gh auth login # HTTPS 用の git credential helper をセットアップする
@@ -84,10 +86,8 @@ skillshare sync # Target にプッシュする
は1つの Skill のみをインストールする
- **CI/CD トークン**: パイプラインでは、CI シークレットからプラットフォーム固有の環境変数
(例: `GITHUB_TOKEN`)を設定する
- **セルフホストの GitLab**: `GITLAB_TOKEN` を設定し、HTTPS URL を使う:
`skillshare install https://gitlab.internal.com/team/skills.git --track`
- **セルフホストの Gitea**: `GITEA_TOKEN` を設定する。ホスト名に `gitea` が含まれない場合は、
[`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) にも列挙する
- **セルフホストの GitHub/GitLab**: ホスト別の Git credential helper を使うか、対象の実行時だけ指定します: `SKILLSHARE_GIT_TOKEN=your-token skillshare install https://gitlab.internal.com/team/skills.git --track`。`GITHUB_TOKEN`/`GITLAB_TOKEN` はセルフホストへ送信されません。
- **セルフホストの Gitea**: `GITEA_TOKEN` を設定し、必ず正確なホスト名を [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) に登録します。
- **Gitee / AtomGit**: `SKILLSHARE_GIT_TOKEN` を使った HTTPS URL 経由で対応
## 関連項目
@@ -201,6 +201,8 @@ SKILLSHARE_UI_TRUSTED_ORIGINS=https://tools.example.com skillshare ui --host 0.0
### GITHUB_TOKEN
プロバイダーのトークンは HTTPS の既定ポート(または 443)でのみ送信されます。対象は `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com`、`cnb.cool` です。セルフホストの Gitea/CNB は、名前にプロバイダー名を含む場合も `gitea_hosts`/`cnb_hosts` に正確なホスト名の登録が必要です。セルフホストの GitHub/GitLab などにはホスト別の Git credential helper を使うか、対象の実行時だけ `SKILLSHARE_GIT_TOKEN` を設定してください。この汎用フォールバックは**任意の HTTPS ソース**に送信されます。名前による判定だけではプロバイダートークンの送信は許可されません。
GitHub の personal access token です。
**用途:**
@@ -370,8 +372,7 @@ skillshare install https://gitea.com/org/skills.git --track
$env:GITEA_TOKEN = "your_token"
```
トークンはインストール元のホストにのみ送信されます。名前に `gitea` を含まないドメイン上のセルフ
ホストインスタンスには [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) が必要で、
セルフホストの Gitea は、名前に `gitea` を含む場合も `GITEA_TOKEN` の送信に [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) への正確なホスト名の登録が必要です。プロバイダー認証は HTTPS の既定ポートまたは 443 に限定されます。
それがなければ代わりに `SKILLSHARE_GIT_TOKEN` が使われます。
### CNB_TOKEN
@@ -129,6 +129,8 @@ $ skillshare install anthropics/skills
ディスカバリーは、`.git` と、通常リポジトリの Skill のコピーを置く `.claude/` や `.agents/` などのターゲットディレクトリを除き、すべてのディレクトリを `SKILL.md` ファイルについてスキャンします。`.curated/` や `.system/` のようなその他の隠しディレクトリはスキャンされるため、その中の Skill も自動的に検出されます。ほかに Skill がないリポジトリでは、代わりにルートの `.agents/skills/` がスキャンされます。複数の Skill が見つかった場合、選択プロンプトは同じフォルダの Skill をまとめて並べ、各 Skill の説明とフォルダを表示します。リストが長いときは `/` で絞り込めます。
`.agents/skills/` のフォールバックでは、`.agents` と `skills` の両方が実ディレクトリである必要があります。`follow_source_links: true` でもシンボリックリンクやジャンクションは拒否されます。意図的にたどるリポジトリルートは引き続き対応します。検出した Agent のインストールと更新は保存先の途中または末尾のリンクを拒否し、公開前に監査します。監査でブロックされた場合、既存の Agent の内容は変わりません。
リポジトリのルートに `.skillignore` ファイルがある場合、一致する Skill はディスカバリーから自動的に除外されます。詳細は下記の [.skillignore](#skillignore) を参照してください。
Skill の `SKILL.md` に `license:` フロントマターフィールドが含まれている場合、そのライセンスは選択プロンプト(例: `my-skill (MIT)`)と、単一 Skill インストール時の確認画面に表示されます。
@@ -543,12 +545,16 @@ skillshare install https://github.com/org/private-skills.git --track
| プラットフォーム | 環境変数 | トークンの種類 |
|----------|---------|------------|
| GitHub | `GITHUB_TOKEN` | Personal access token(`repo` スコープ) |
| GitLab | `GITLAB_TOKEN` | Personal access token または CI job token |
| `github.com` | `GITHUB_TOKEN` | Personal access token(`repo` スコープ) |
| `gitlab.com` | `GITLAB_TOKEN` | Personal access token または CI job token |
| Bitbucket | `BITBUCKET_TOKEN` | Repository token、または app password(`BITBUCKET_USERNAME` と併用) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` | Personal Access Token(Code: Read スコープ) |
| 任意のホスト | `SKILLSHARE_GIT_TOKEN` | 汎用フォールバック |
プロバイダーのトークンは HTTPS の既定ポート(または 443)でのみ送信されます。対象は `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com`、`cnb.cool` です。セルフホストの Gitea/CNB は、名前にプロバイダー名を含む場合も `gitea_hosts`/`cnb_hosts` に正確なホスト名の登録が必要です。セルフホストの GitHub/GitLab などにはホスト別の Git credential helper を使うか、対象の実行時だけ `SKILLSHARE_GIT_TOKEN` を設定してください。この汎用フォールバックは**任意の HTTPS ソース**に送信されます。名前による判定だけではプロバイダートークンの送信は許可されません。
プロバイダーのトークンは HTTPS の既定ポート(または 443)でのみ送信されます。対象は `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com`、`cnb.cool` です。セルフホストの Gitea/CNB は、名前にプロバイダー名を含む場合も `gitea_hosts`/`cnb_hosts` に正確なホスト名の登録が必要です。セルフホストの GitHub/GitLab などにはホスト別の Git credential helper を使うか、対象の実行時だけ `SKILLSHARE_GIT_TOKEN` を設定してください。この汎用フォールバックは**任意の HTTPS ソース**に送信されます。名前による判定だけではプロバイダートークンの送信は許可されません。
プラットフォーム固有の環境変数は `SKILLSHARE_GIT_TOKEN` より優先されます。
token はホスト単位の credential helper を通じて git に渡されるため、`ps` の出力などのプロセス引数には現れません。token がホストに適用されている間、git はそのホストについて自分の credential helper やキーチェーンに問い合わせず、何も保存しません。
@@ -6,6 +6,8 @@ sidebar_position: 1
視覚的な Skill 管理のための Web ダッシュボードを起動します。
リモート検索(`GET /api/search`)とインストールのプレビュー(`GET /api/preview`)は変更操作と同じ origin チェックを使い、別サイトからのブラウザー要求は取得前に拒否します。ブラウザーの origin/fetch ヘッダーを持たない直接クライアントは引き続き対応します。GitHub API の認証情報は HTTPS の `api.github.com` と `raw.githubusercontent.com`(既定ポートまたは 443)に限定され、別 origin へのリダイレクト時は認証情報を削除します。
```bash
skillshare ui # フォアグラウンドで実行
skillshare ui start # バックグラウンドサーバーを起動(既存があれば再利用)
@@ -882,8 +882,7 @@ SKILLSHARE_AZURE_HOSTS=azuredevops.mycompany.com skillshare install \
### `gitea_hosts`
セルフホストの Gitea インスタンスのホスト名。`gitea.com` や `gitea.company.com` のように名前に
`gitea` を含むホストは自動的に検出されます。このフィールドは他のカスタムドメインでのみ必要です。
セルフホストの Gitea は、名前に `gitea` を含む場合も `GITEA_TOKEN` の送信に [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) への正確なホスト名の登録が必要です。プロバイダー認証は HTTPS の既定ポートまたは 443 に限定されます。
```yaml
gitea_hosts:
@@ -18,14 +18,16 @@ skillshare는 환경 변수에서 토큰을 감지하며, 플랫폼별 변수가
| 플랫폼 | 환경 변수 |
|----------|---------------------|
| GitHub / GitHub Enterprise | `GITHUB_TOKEN` |
| GitLab / 자체 호스팅 GitLab | `GITLAB_TOKEN` |
| `github.com` | `GITHUB_TOKEN` |
| `gitlab.com` | `GITLAB_TOKEN` |
| Bitbucket | `BITBUCKET_TOKEN` (+ 선택적 `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` |
| Gitea / 자체 호스팅 Gitea | `GITEA_TOKEN` |
| CNB | `CNB_TOKEN` |
| 모든 플랫폼 (대체) | `SKILLSHARE_GIT_TOKEN` |
공급자 토큰은 HTTPS 기본 포트(또는 443)의 `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, `cnb.cool`에만 전송됩니다. 자체 호스팅 Gitea/CNB는 이름에 공급자 이름이 포함되어도 `gitea_hosts`/`cnb_hosts`에 정확한 호스트명을 등록해야 합니다. 자체 호스팅 GitHub/GitLab 등에는 호스트별 Git credential helper를 사용하거나 해당 실행에만 `SKILLSHARE_GIT_TOKEN`을 설정하세요. 이 범용 폴백은 **모든 HTTPS 소스**에 전송될 수 있습니다. 공급자처럼 보이는 이름만으로는 공급자 토큰 전송이 허용되지 않습니다.
```bash
# 옵션 A: Git credential helper (GitHub에 권장)
gh auth login # HTTPS용 git credential helper를 설정합니다
@@ -80,8 +82,8 @@ skillshare sync # Target에 반영
- **선택적 설치**: `skillshare install your-org/internal-skills --skill code-review`는 하나의 Skill만 설치합니다
- **CI/CD 토큰**: 파이프라인에서는 CI 시크릿으로부터 플랫폼별 환경 변수(예: `GITHUB_TOKEN`)를 설정하세요
- **자체 호스팅 GitLab**: `GITLAB_TOKEN`을 설정하고 HTTPS URL을 사용하세요: `skillshare install https://gitlab.internal.com/team/skills.git --track`
- **자체 호스팅 Gitea**: `GITEA_TOKEN`을 설정하세요. 호스트명에 `gitea`가 포함되어 있지 않다면 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)에도 등록하세요
- **자체 호스팅 GitHub/GitLab**: 호스트별 Git credential helper를 사용하거나 해당 실행에만 지정하세요: `SKILLSHARE_GIT_TOKEN=your-token skillshare install https://gitlab.internal.com/team/skills.git --track`. `GITHUB_TOKEN`/`GITLAB_TOKEN`은 자체 호스팅에 전송되지 않습니다.
- **자체 호스팅 Gitea**: `GITEA_TOKEN`을 설정하고 항상 정확한 호스트명을 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)에 등록하세요.
- **Gitee / AtomGit**: `SKILLSHARE_GIT_TOKEN`을 사용한 HTTPS URL로 지원됩니다
## 관련 문서
@@ -190,6 +190,8 @@ SKILLSHARE_UI_TRUSTED_ORIGINS=https://tools.example.com skillshare ui --host 0.0
### GITHUB_TOKEN
공급자 토큰은 HTTPS 기본 포트(또는 443)의 `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, `cnb.cool`에만 전송됩니다. 자체 호스팅 Gitea/CNB는 이름에 공급자 이름이 포함되어도 `gitea_hosts`/`cnb_hosts`에 정확한 호스트명을 등록해야 합니다. 자체 호스팅 GitHub/GitLab 등에는 호스트별 Git credential helper를 사용하거나 해당 실행에만 `SKILLSHARE_GIT_TOKEN`을 설정하세요. 이 범용 폴백은 **모든 HTTPS 소스**에 전송될 수 있습니다. 공급자처럼 보이는 이름만으로는 공급자 토큰 전송이 허용되지 않습니다.
GitHub 개인 액세스 토큰입니다.
**사용처:**
@@ -348,7 +350,7 @@ skillshare install https://gitea.com/org/skills.git --track
$env:GITEA_TOKEN = "your_token"
```
토큰은 설치 대상 호스트에만 전송됩니다. 이름에 `gitea`가 포함되지 않은 자체 호스팅 인스턴스는 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) 설정이 필요하며, 그렇지 않으면 해당 호스트에는 `SKILLSHARE_GIT_TOKEN`이 사용됩니다.
자체 호스팅 Gitea는 이름에 `gitea`가 포함되어도 `GITEA_TOKEN` 전송을 위해 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)에 정확한 호스트명을 등록해야 합니다. 공급자 인증은 HTTPS 기본 포트 또는 443으로 제한됩니다.
### CNB_TOKEN
@@ -129,6 +129,8 @@ $ skillshare install anthropics/skills
Discovery는 `.git`과, 보통 저장소 skill의 복사본을 담는 `.claude/`, `.agents/` 같은 타깃 디렉터리를 제외한 모든 디렉터리에서 `SKILL.md` 파일을 스캔합니다. `.curated/`나 `.system/`과 같은 그 밖의 숨김 디렉터리는 스캔되므로 그 안의 skill도 자동으로 발견됩니다. 다른 skill이 없는 저장소는 대신 루트의 `.agents/skills/`를 스캔합니다. 여러 skill이 발견되면, 선택 화면은 같은 폴더의 skill을 함께 나열하고 각 skill의 설명과 폴더를 보여 줍니다. 목록이 길면 `/`로 필터링할 수 있습니다.
`.agents/skills/` 폴백은 `.agents`와 `skills` 모두 실제 디렉터리여야 하며, `follow_source_links: true`여도 symlink나 junction은 허용하지 않습니다. 의도적으로 따라가는 저장소 루트는 계속 지원됩니다. 발견한 agent 설치 및 업데이트는 중간 또는 최종 대상 링크를 거부하고 게시 전에 감사합니다. 감사가 차단되면 기존 agent 내용은 유지됩니다.
repository 루트에 `.skillignore` 파일이 있으면, 일치하는 skill은 discovery에서 자동으로 제외됩니다. 아래 [.skillignore](#skillignore)를 참고하세요.
skill의 `SKILL.md`에 `license:` frontmatter 필드가 있으면, 선택 화면(예: `my-skill (MIT)`)과 단일 skill 설치의 확인 화면에 라이선스가 표시됩니다.
@@ -543,12 +545,16 @@ skillshare install https://github.com/org/private-skills.git --track
| 플랫폼 | 환경 변수 | 토큰 종류 |
|----------|---------|------------|
| GitHub | `GITHUB_TOKEN` | Personal access token (`repo` scope) |
| GitLab | `GITLAB_TOKEN` | Personal access 또는 CI job token |
| `github.com` | `GITHUB_TOKEN` | Personal access token (`repo` scope) |
| `gitlab.com` | `GITLAB_TOKEN` | Personal access 또는 CI job token |
| Bitbucket | `BITBUCKET_TOKEN` | Repository token, 또는 app password (`BITBUCKET_USERNAME`과 함께) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` | Personal Access Token (Code: Read scope) |
| 모든 호스트 | `SKILLSHARE_GIT_TOKEN` | 범용 폴백 |
공급자 토큰은 HTTPS 기본 포트(또는 443)의 `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, `cnb.cool`에만 전송됩니다. 자체 호스팅 Gitea/CNB는 이름에 공급자 이름이 포함되어도 `gitea_hosts`/`cnb_hosts`에 정확한 호스트명을 등록해야 합니다. 자체 호스팅 GitHub/GitLab 등에는 호스트별 Git credential helper를 사용하거나 해당 실행에만 `SKILLSHARE_GIT_TOKEN`을 설정하세요. 이 범용 폴백은 **모든 HTTPS 소스**에 전송될 수 있습니다. 공급자처럼 보이는 이름만으로는 공급자 토큰 전송이 허용되지 않습니다.
공급자 토큰은 HTTPS 기본 포트(또는 443)의 `github.com`, `gitlab.com`, `bitbucket.org`, `dev.azure.com`, `*.visualstudio.com`, `gitea.com`, `cnb.cool`에만 전송됩니다. 자체 호스팅 Gitea/CNB는 이름에 공급자 이름이 포함되어도 `gitea_hosts`/`cnb_hosts`에 정확한 호스트명을 등록해야 합니다. 자체 호스팅 GitHub/GitLab 등에는 호스트별 Git credential helper를 사용하거나 해당 실행에만 `SKILLSHARE_GIT_TOKEN`을 설정하세요. 이 범용 폴백은 **모든 HTTPS 소스**에 전송될 수 있습니다. 공급자처럼 보이는 이름만으로는 공급자 토큰 전송이 허용되지 않습니다.
플랫폼별 변수가 `SKILLSHARE_GIT_TOKEN`보다 우선합니다.
token은 호스트 범위의 credential helper를 통해 git에 전달되므로 `ps` 출력 같은 프로세스 인자에 나타나지 않습니다. 호스트에 token이 적용되는 동안 git은 해당 호스트에 대해 사용자의 credential helper나 키체인에 묻지 않으며 아무것도 저장하지 않습니다.
@@ -6,6 +6,8 @@ sidebar_position: 1
시각적인 Skill 관리를 위한 웹 대시보드를 실행합니다.
원격 검색(`GET /api/search`)과 설치 미리 보기(`GET /api/preview`)는 변경 작업과 같은 origin 검사를 사용하며, cross-site 브라우저 요청은 가져오기 전에 거부합니다. 브라우저 origin/fetch 헤더가 없는 직접 클라이언트는 계속 지원됩니다. GitHub API 인증 정보는 HTTPS `api.github.com`, `raw.githubusercontent.com`의 기본 포트 또는 443으로 제한되며 cross-origin 리디렉션에서는 제거됩니다.
```bash
skillshare ui # 포그라운드에서 실행
skillshare ui start # 백그라운드 서버 시작(또는 기존 서버 재사용)
@@ -847,7 +847,7 @@ SKILLSHARE_AZURE_HOSTS=azuredevops.mycompany.com skillshare install \
### `gitea_hosts`
Self-hosted Gitea 인스턴스의 호스트명. `gitea.com`이나 `gitea.company.com`처럼 이름에 `gitea`가 포함된 호스트는 자동으로 감지됩니다. 이 필드는 다른 custom 도메인에만 필요합니다.
자체 호스팅 Gitea는 이름에 `gitea`가 포함되어도 `GITEA_TOKEN` 전송을 위해 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)에 정확한 호스트명을 등록해야 합니다. 공급자 인증은 HTTPS 기본 포트 또는 443으로 제한됩니다.
```yaml
gitea_hosts:
@@ -18,14 +18,16 @@ skillshare 会从环境变量中检测 token,平台专属变量的优先级高
| Platform | Environment Variable |
|----------|---------------------|
| GitHub / GitHub Enterprise | `GITHUB_TOKEN` |
| GitLab / Self-hosted GitLab | `GITLAB_TOKEN` |
| `github.com` | `GITHUB_TOKEN` |
| `gitlab.com` | `GITLAB_TOKEN` |
| Bitbucket | `BITBUCKET_TOKEN`(+ 可选的 `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` |
| Gitea / Self-hosted Gitea | `GITEA_TOKEN` |
| CNB | `CNB_TOKEN` |
| 任意平台(fallback) | `SKILLSHARE_GIT_TOKEN` |
平台令牌仅发送到使用 HTTPS 默认端口(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自建 Gitea/CNB 即使名称包含平台名,也必须在 `gitea_hosts`/`cnb_hosts` 中配置准确主机名。自建 GitHub/GitLab 等主机应使用按主机配置的 Git credential helper,或仅为目标调用设置 `SKILLSHARE_GIT_TOKEN`。此通用回退可发送给**任何 HTTPS 来源**;类似平台的名称不会授权发送平台令牌。
```bash
# 选项 A:Git credential helper(推荐用于 GitHub)
gh auth login # 为 HTTPS 设置 git credential helper
@@ -80,8 +82,8 @@ skillshare sync # 推送到 Targets
- **选择性安装**:`skillshare install your-org/internal-skills --skill code-review` 只安装一个 Skill
- **CI/CD token**:在流水线中,通过 CI secrets 设置对应平台的环境变量(例如 `GITHUB_TOKEN`)
- **Self-hosted GitLab**:设置 `GITLAB_TOKEN` 并使用 HTTPS URL:`skillshare install https://gitlab.internal.com/team/skills.git --track`
- **Self-hosted Gitea**:设置 `GITEA_TOKEN`。如果主机名不包含 `gitea`,还需将其列入 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)
- **自建 GitHub/GitLab**:使用按主机配置的 Git credential helper,或仅为此次调用提供令牌:`SKILLSHARE_GIT_TOKEN=your-token skillshare install https://gitlab.internal.com/team/skills.git --track`。`GITHUB_TOKEN`/`GITLAB_TOKEN` 不会发送给自建实例。
- **自建 Gitea**:设置 `GITEA_TOKEN`,并始终将准确主机名列入 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)。
- **Gitee / AtomGit**:通过 HTTPS URL 配合 `SKILLSHARE_GIT_TOKEN` 支持
## Related
@@ -190,6 +190,8 @@ SKILLSHARE_UI_TRUSTED_ORIGINS=https://tools.example.com skillshare ui --host 0.0
### GITHUB_TOKEN
平台令牌仅发送到使用 HTTPS 默认端口(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自建 Gitea/CNB 即使名称包含平台名,也必须在 `gitea_hosts`/`cnb_hosts` 中配置准确主机名。自建 GitHub/GitLab 等主机应使用按主机配置的 Git credential helper,或仅为目标调用设置 `SKILLSHARE_GIT_TOKEN`。此通用回退可发送给**任何 HTTPS 来源**;类似平台的名称不会授权发送平台令牌。
GitHub 个人访问令牌(personal access token)。
**用途:**
@@ -348,7 +350,7 @@ skillshare install https://gitea.com/org/skills.git --track
$env:GITEA_TOKEN = "your_token"
```
该令牌只会发送给你安装所用的主机。名称中不含 `gitea` 的自建实例需要配置 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts),否则将改用 `SKILLSHARE_GIT_TOKEN`。
自建 Gitea 即使名称包含 `gitea`,也必须在 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) 中配置准确主机名才能发送 `GITEA_TOKEN`。平台认证仅支持 HTTPS 默认端口或 443。
### CNB_TOKEN
@@ -129,6 +129,8 @@ $ skillshare install anthropics/skills
Discovery 会扫描所有目录以查找 `SKILL.md` 文件,但会跳过 `.git` 以及 `.claude/`、`.agents/` 等目标目录,这些目录通常存放仓库中 Skill 的副本。其他隐藏目录(如 `.curated/` 或 `.system/`)会被扫描,其中的 Skill 也会被自动发现。如果仓库没有其他 Skill,则改为扫描根目录的 `.agents/skills/`。当发现多个 Skill 时,选择提示会把同一文件夹中的 Skill 排在一起,并显示每个 Skill 的描述和所在文件夹;列表较长时按 `/` 筛选。
`.agents/skills/` 回退要求 `.agents` 和 `skills` 均为真实目录,即使启用 `follow_source_links: true` 也不接受符号链接或 junction。仍支持有意跟随的仓库根目录。发现的 agent 在安装和更新时会拒绝目标路径中间或末尾的链接,并在发布前审核;审核阻止操作时,现有 agent 内容保持不变。
如果仓库根目录下存在 `.skillignore` 文件,匹配的 Skill 会被自动从 discovery 中排除。参见下方的 [.skillignore](#skillignore)。
如果某个 Skill 的 `SKILL.md` 包含 `license:` frontmatter 字段,该 license 会显示在选择提示中(例如 `my-skill (MIT)`),以及单 Skill 安装的确认界面中。
@@ -543,12 +545,16 @@ skillshare install https://github.com/org/private-skills.git --track
| Platform | Env Var | Token Type |
|----------|---------|------------|
| GitHub | `GITHUB_TOKEN` | Personal access token(`repo` scope) |
| GitLab | `GITLAB_TOKEN` | Personal access 或 CI job token |
| `github.com` | `GITHUB_TOKEN` | Personal access token(`repo` scope) |
| `gitlab.com` | `GITLAB_TOKEN` | Personal access 或 CI job token |
| Bitbucket | `BITBUCKET_TOKEN` | Repository token,或 app password(配合 `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` | Personal Access Token(Code: Read scope) |
| Any host | `SKILLSHARE_GIT_TOKEN` | 通用兜底方案 |
平台令牌仅发送到使用 HTTPS 默认端口(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自建 Gitea/CNB 即使名称包含平台名,也必须在 `gitea_hosts`/`cnb_hosts` 中配置准确主机名。自建 GitHub/GitLab 等主机应使用按主机配置的 Git credential helper,或仅为目标调用设置 `SKILLSHARE_GIT_TOKEN`。此通用回退可发送给**任何 HTTPS 来源**;类似平台的名称不会授权发送平台令牌。
平台令牌仅发送到使用 HTTPS 默认端口(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自建 Gitea/CNB 即使名称包含平台名,也必须在 `gitea_hosts`/`cnb_hosts` 中配置准确主机名。自建 GitHub/GitLab 等主机应使用按主机配置的 Git credential helper,或仅为目标调用设置 `SKILLSHARE_GIT_TOKEN`。此通用回退可发送给**任何 HTTPS 来源**;类似平台的名称不会授权发送平台令牌。
平台专属变量的优先级高于 `SKILLSHARE_GIT_TOKEN`。
token 通过限定于该主机的 credential helper 传给 git,因此不会出现在 `ps` 输出等进程参数中。token 作用于某个主机期间,git 不会向你自己的 credential helper 或钥匙串查询该主机,也不会在其中存储任何内容。
@@ -6,6 +6,8 @@ sidebar_position: 1
启动 web dashboard 以可视化管理 skills。
远程搜索(`GET /api/search`)和安装预览(`GET /api/preview`)使用与修改操作相同的来源检查,在获取前拒绝跨站浏览器请求。仍支持不带浏览器 origin/fetch 请求头的直接客户端。GitHub API 凭据仅用于 HTTPS `api.github.com` 和 `raw.githubusercontent.com` 的默认端口或 443;跨来源重定向会移除认证信息。
```bash
skillshare ui # 在前台运行
skillshare ui start # 启动(或复用)一个后台 server
@@ -842,7 +842,7 @@ SKILLSHARE_AZURE_HOSTS=azuredevops.mycompany.com skillshare install \
### `gitea_hosts`
自建 Gitea 实例的主机名。名称中包含 `gitea` 的主机,例如 `gitea.com` 或 `gitea.company.com`,会被自动检测。此字段仅在使用其他自定义域名时才需要。
自建 Gitea 即使名称包含 `gitea`,也必须在 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) 中配置准确主机名才能发送 `GITEA_TOKEN`。平台认证仅支持 HTTPS 默认端口或 443。
```yaml
gitea_hosts:
@@ -18,14 +18,16 @@ skillshare 會從環境變數偵測 token,平台專屬的變數優先於通用
| 平台 | 環境變數 |
|----------|---------------------|
| GitHub / GitHub Enterprise | `GITHUB_TOKEN` |
| GitLab / 自架 GitLab | `GITLAB_TOKEN` |
| `github.com` | `GITHUB_TOKEN` |
| `gitlab.com` | `GITLAB_TOKEN` |
| Bitbucket | `BITBUCKET_TOKEN`(+ 選用的 `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` |
| Gitea / 自架 Gitea | `GITEA_TOKEN` |
| CNB | `CNB_TOKEN` |
| 任何平台(fallback) | `SKILLSHARE_GIT_TOKEN` |
平台權杖僅傳送至使用 HTTPS 預設連接埠(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自架 Gitea/CNB 即使名稱包含平台名,也必須在 `gitea_hosts`/`cnb_hosts` 中設定完整相符的主機名稱。自架 GitHub/GitLab 等主機應使用依主機設定的 Git credential helper,或僅為目標呼叫設定 `SKILLSHARE_GIT_TOKEN`。此通用 fallback 可傳送給**任何 HTTPS 來源**;類似平台的名稱不會授權傳送平台權杖。
```bash
# 選項 A:Git credential helper(建議用於 GitHub)
gh auth login # 為 HTTPS 設定 git credential helper
@@ -80,8 +82,8 @@ skillshare sync # 推送到 targets
- **選擇性安裝**:`skillshare install your-org/internal-skills --skill code-review` 只安裝單一 skill
- **CI/CD token**:在 pipeline 中,從 CI secrets 設定平台專屬的環境變數(例如 `GITHUB_TOKEN`)
- **自架 GitLab**:設定 `GITLAB_TOKEN` 並使用 HTTPS URL:`skillshare install https://gitlab.internal.com/team/skills.git --track`
- **自架 Gitea**:設定 `GITEA_TOKEN`。若主機名稱不含 `gitea`,也需將其列入 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)
- **自架 GitHub/GitLab**:使用依主機設定的 Git credential helper,或僅為這次呼叫提供 token:`SKILLSHARE_GIT_TOKEN=your-token skillshare install https://gitlab.internal.com/team/skills.git --track`。`GITHUB_TOKEN`/`GITLAB_TOKEN` 不會傳送給自架服務。
- **自架 Gitea**:設定 `GITEA_TOKEN`,並一律將確切主機名稱列入 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts)。
- **Gitee / AtomGit**:透過 `SKILLSHARE_GIT_TOKEN` 搭配 HTTPS URL 支援
## 相關
@@ -190,6 +190,8 @@ SKILLSHARE_UI_TRUSTED_ORIGINS=https://tools.example.com skillshare ui --host 0.0
### GITHUB_TOKEN
平台權杖僅傳送至使用 HTTPS 預設連接埠(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自架 Gitea/CNB 即使名稱包含平台名,也必須在 `gitea_hosts`/`cnb_hosts` 中設定完整相符的主機名稱。自架 GitHub/GitLab 等主機應使用依主機設定的 Git credential helper,或僅為目標呼叫設定 `SKILLSHARE_GIT_TOKEN`。此通用 fallback 可傳送給**任何 HTTPS 來源**;類似平台的名稱不會授權傳送平台權杖。
GitHub 個人存取權杖(personal access token)。
**用途:**
@@ -348,7 +350,7 @@ skillshare install https://gitea.com/org/skills.git --track
$env:GITEA_TOKEN = "your_token"
```
此 token 只會傳送給你安裝來源的主機。若自架的執行個體位於名稱中不含 `gitea` 的網域,需要設定 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts),否則會改用 `SKILLSHARE_GIT_TOKEN`。
自架 Gitea 即使名稱包含 `gitea`,也必須在 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) 中設定完整相符的主機名稱才能傳送 `GITEA_TOKEN`。平台認證僅支援 HTTPS 預設連接埠或 443。
### CNB_TOKEN
@@ -129,6 +129,8 @@ $ skillshare install anthropics/skills
Discovery 會掃描所有目錄尋找 `SKILL.md` 檔案,但會跳過 `.git` 以及 `.claude/`、`.agents/` 等 target 目錄,這些目錄通常放的是 repo 中 skills 的副本。其他隱藏目錄(如 `.curated/` 或 `.system/`)會被掃描,其中的 skills 也會被自動發現。如果 repo 沒有其他 skills,則改為掃描根目錄的 `.agents/skills/`。當找到多個 skills 時,選擇提示會把同一個資料夾的 skills 排在一起,並顯示每個 skill 的說明與所在資料夾;清單很長時按 `/` 篩選。
`.agents/skills/` fallback 要求 `.agents` 和 `skills` 均為實際目錄,即使啟用 `follow_source_links: true` 也不接受符號連結或 junction。仍支援刻意跟隨的儲存庫根目錄。探索到的 agent 在安裝及更新時會拒絕目標路徑中間或末尾的連結,並在發佈前稽核;稽核阻擋操作時,現有 agent 內容保持不變。
如果 repository 根目錄有 `.skillignore` 檔案,符合的 skills 會自動從 discovery 中排除。見下方 [.skillignore](#skillignore)。
如果某個 skill 的 `SKILL.md` 包含 `license:` frontmatter 欄位,該授權會顯示在選擇提示中(例如 `my-skill (MIT)`),單一 skill 安裝時也會顯示在確認畫面上。
@@ -543,12 +545,16 @@ skillshare install https://github.com/org/private-skills.git --track
| 平台 | 環境變數 | Token 類型 |
|----------|---------|------------|
| GitHub | `GITHUB_TOKEN` | Personal access token(`repo` scope) |
| GitLab | `GITLAB_TOKEN` | Personal access 或 CI job token |
| `github.com` | `GITHUB_TOKEN` | Personal access token(`repo` scope) |
| `gitlab.com` | `GITLAB_TOKEN` | Personal access 或 CI job token |
| Bitbucket | `BITBUCKET_TOKEN` | Repository token,或 app password(搭配 `BITBUCKET_USERNAME`) |
| Azure DevOps | `AZURE_DEVOPS_TOKEN` | Personal Access Token(Code: Read scope) |
| 任何主機 | `SKILLSHARE_GIT_TOKEN` | 通用後備方案 |
平台權杖僅傳送至使用 HTTPS 預設連接埠(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自架 Gitea/CNB 即使名稱包含平台名,也必須在 `gitea_hosts`/`cnb_hosts` 中設定完整相符的主機名稱。自架 GitHub/GitLab 等主機應使用依主機設定的 Git credential helper,或僅為目標呼叫設定 `SKILLSHARE_GIT_TOKEN`。此通用 fallback 可傳送給**任何 HTTPS 來源**;類似平台的名稱不會授權傳送平台權杖。
平台權杖僅傳送至使用 HTTPS 預設連接埠(或 443)的 `github.com`、`gitlab.com`、`bitbucket.org`、`dev.azure.com`、`*.visualstudio.com`、`gitea.com` 和 `cnb.cool`。自架 Gitea/CNB 即使名稱包含平台名,也必須在 `gitea_hosts`/`cnb_hosts` 中設定完整相符的主機名稱。自架 GitHub/GitLab 等主機應使用依主機設定的 Git credential helper,或僅為目標呼叫設定 `SKILLSHARE_GIT_TOKEN`。此通用 fallback 可傳送給**任何 HTTPS 來源**;類似平台的名稱不會授權傳送平台權杖。
平台專屬的變數優先於 `SKILLSHARE_GIT_TOKEN`。
token 會透過限定於該主機的 credential helper 傳給 git,因此不會出現在 `ps` 輸出等行程參數中。token 套用於某個主機期間,git 不會向你自己的 credential helper 或鑰匙圈查詢該主機,也不會在其中儲存任何內容。
@@ -6,6 +6,8 @@ sidebar_position: 1
啟動用於視覺化 skill 管理的 Web dashboard。
遠端搜尋(`GET /api/search`)和安裝預覽(`GET /api/preview`)使用與修改操作相同的來源檢查,在擷取前拒絕跨站瀏覽器要求。仍支援不帶瀏覽器 origin/fetch 標頭的直接用戶端。GitHub API 憑證僅用於 HTTPS `api.github.com` 和 `raw.githubusercontent.com` 的預設連接埠或 443;跨來源重新導向會移除認證資訊。
```bash
skillshare ui # 在前景執行
skillshare ui start # 啟動(或重用)背景伺服器
@@ -842,7 +842,7 @@ SKILLSHARE_AZURE_HOSTS=azuredevops.mycompany.com skillshare install \
### `gitea_hosts`
自架的 Gitea 實例主機名稱。名稱中包含 `gitea` 的主機,例如 `gitea.com` 或 `gitea.company.com`,會自動被偵測。此欄位只在其他自訂網域時才需要。
自架 Gitea 即使名稱包含 `gitea`,也必須在 [`gitea_hosts`](/docs/reference/targets/configuration#gitea_hosts) 中設定完整相符的主機名稱才能傳送 `GITEA_TOKEN`。平台認證僅支援 HTTPS 預設連接埠或 443。
```yaml
gitea_hosts: