refactor(sandbox): remove token requirement for skill installation from source

Updated the skill installation process to eliminate the need for a token when installing skills from ClawHub, SkillHub, or Git URLs. The source must now be readable anonymously, ensuring that no credentials are sent during the fetch process. Adjusted related documentation and UI components to reflect this change, enhancing the user experience by simplifying the installation workflow.
main
wizardchen 2026-08-25 15:13:20 +08:00 committed by lyingbug
parent 260057b5f4
commit 92fd75f54a
19 changed files with 4148 additions and 893 deletions

View File

@ -391,7 +391,7 @@ if err != nil {
```go
skillID, err := apiClient.InstallSandboxSkillFromSource(
context.Background(), sandboxConfigID, "@owner/slug", "")
context.Background(), sandboxConfigID, "@owner/slug")
if err != nil {
// 处理错误
}

View File

@ -204,7 +204,7 @@ if err != nil {
```go
skillID, err := apiClient.InstallSandboxSkillFromSource(
context.Background(), sandboxConfigID, "@owner/slug", "")
context.Background(), sandboxConfigID, "@owner/slug")
if err != nil {
// Handle error
}

View File

@ -53,17 +53,15 @@ func (c *Client) ListSkills(ctx context.Context, sandboxConfigID string) ([]Skil
// InstallSandboxSkillFromSource installs a skill onto a sandbox config from a
// ClawHub / SkillHub / skills.sh / GitHub / GitLab locator or a direct archive
// URL. The call is accepted asynchronously; follow progress on the skill ID.
// URL. The source must be readable anonymously. The call is accepted
// asynchronously; follow progress on the skill ID.
func (c *Client) InstallSandboxSkillFromSource(
ctx context.Context, configID, source, token string,
ctx context.Context, configID, source string,
) (string, error) {
if configID == "" {
return "", fmt.Errorf("sandbox config ID is required")
}
body := map[string]string{"source": source}
if token != "" {
body["token"] = token
}
path := "/api/v1/sandbox-configs/" + url.PathEscape(configID) + "/skills"
resp, err := c.doRequest(ctx, http.MethodPost, path, body, nil)
if err != nil {

View File

@ -164,7 +164,7 @@ Docker、Local、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接
- skills.sh、GitHub、GitLab 仓库或目录链接
- 直接的 zip / `SKILL.md` URL
私有 SkillHub 可在同一次请求里带 Token,仅用于下载、不会落库。安装仍走原有镜像快照流程。
来源必须可匿名读取,服务端下载时不携带任何凭据;私有仓库请先导出 zip 再上传。安装仍走原有镜像快照流程。
**有沙箱在跑时改不了身份字段。** 身份字段分两组,成因不同但后果都足够严重:

View File

@ -75,7 +75,7 @@ curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills' \
- skills.sh / GitHub / GitLab 仓库或目录链接
- 直接的 zip / `SKILL.md` URL
私有 SkillHub 可带 `token`,仅用于本次下载,服务端不保存。
来源必须可匿名读取:服务端不会为这次下载附带任何凭据,因此私有仓库/私有 registry 需要先自行导出 zip 再上传。
```curl
curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills' \

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1038,7 +1038,7 @@ export function uploadConfigSkill(
export function installConfigSkillFromSource(
configId: string,
payload: { source: string; token?: string },
payload: { source: string },
): Promise<{ data: { skill_id: string } }> {
return post(`/api/v1/sandbox-configs/${configId}/skills`, payload, {
timeout: 2 * 60 * 1000,

View File

@ -83,18 +83,6 @@
</t-button>
</template>
</t-input-adornment>
<div v-if="showRegistryToken" class="skill-token-row">
<p class="skill-token-label">{{ $t('settings.sandbox.skillSourceTokenLabel') }}</p>
<t-input
v-model="sourceToken"
type="password"
size="small"
autocomplete="off"
:placeholder="$t('settings.sandbox.skillSourceTokenPlaceholder')"
:disabled="installBusy"
/>
<p class="skill-token-hint">{{ $t('settings.sandbox.skillSourceTokenHint') }}</p>
</div>
<div class="skill-install-split">
<span>{{ $t('settings.sandbox.skillInstallOr') }}</span>
</div>
@ -333,8 +321,6 @@ const uploading = ref(false)
const installingFromSource = ref(false)
const uploadPercent = ref(0)
const sourceInput = ref('')
const sourceToken = ref('')
const forceRegistryToken = ref(false)
const skills = ref<ConfigSkill[]>([])
const skillImage = ref<SandboxSkillImage | null>(null)
const togglingId = ref('')
@ -369,8 +355,6 @@ const uploadHint = computed(() =>
: t('settings.sandbox.skillUploadHint'),
)
const installBusy = computed(() => uploading.value || installingFromSource.value)
const sourceNeedsRegistryToken = computed(() => looksLikePrivateSkillHub(sourceInput.value))
const showRegistryToken = computed(() => sourceNeedsRegistryToken.value || forceRegistryToken.value)
const deleteHint = computed(() =>
skillRollout.value === 'new_session'
? t('settings.sandbox.skillDeleteHintNewSession')
@ -382,48 +366,6 @@ const runtimeTemplateId = computed(() => {
})
const hasSkillSnapshot = computed(() => Boolean(skillImage.value?.snapshot_id?.trim()))
const PUBLIC_SKILL_HOSTS = new Set([
'github.com',
'www.github.com',
'codeload.github.com',
'gitlab.com',
'www.gitlab.com',
'skills.sh',
'www.skills.sh',
'clawhub.ai',
'www.clawhub.ai',
'clawhub.com',
'www.clawhub.com',
'skillhub.cn',
'www.skillhub.cn',
'api.skillhub.cn',
])
function looksLikePrivateSkillHub(raw: string): boolean {
const input = raw.trim()
if (!input.includes('://')) return false
try {
const parsed = new URL(input)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
return !PUBLIC_SKILL_HOSTS.has(parsed.hostname.toLowerCase())
} catch {
return false
}
}
function isRegistryAuthError(err: unknown): boolean {
const message = err && typeof err === 'object' && 'message' in err
? String((err as { message?: unknown }).message)
: String(err ?? '')
return /\bHTTP 401\b/.test(message) || /\bHTTP 403\b/.test(message)
}
watch(sourceInput, (value) => {
if (!looksLikePrivateSkillHub(value)) {
forceRegistryToken.value = false
}
})
function readLastChatModelID(): string {
try {
return localStorage.getItem(LAST_CHAT_MODEL_KEY) || ''
@ -750,21 +692,14 @@ async function installFromSource() {
installingFromSource.value = true
try {
await persistInstallerModel(installerModelId.value)
const token = showRegistryToken.value ? sourceToken.value.trim() : ''
const res = await installConfigSkillFromSource(props.record.id, {
source,
...(token ? { token } : {}),
})
const res = await installConfigSkillFromSource(props.record.id, { source })
MessagePlugin.success(t('settings.sandbox.skillUploadAccepted'))
sourceInput.value = ''
sourceToken.value = ''
forceRegistryToken.value = false
const skillId = res?.data?.skill_id
await loadSkills()
await refreshImage()
if (skillId) followProgress(skillId)
} catch (e: any) {
if (isRegistryAuthError(e)) forceRegistryToken.value = true
MessagePlugin.error(e?.message || t('settings.sandbox.skillSourceFailed'))
} finally {
installingFromSource.value = false
@ -999,28 +934,6 @@ onUnmounted(() => {
}
}
.skill-token-row {
margin-top: 8px;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 6px;
}
.skill-token-label {
margin: 0;
font-size: 12px;
line-height: 1.4;
color: var(--td-text-color-secondary);
}
.skill-token-hint {
margin: 0;
font-size: 12px;
line-height: 1.4;
color: var(--td-text-color-placeholder);
}
.skill-install-split {
display: flex;
align-items: center;

View File

@ -1282,9 +1282,6 @@ export default {
skillUploadHint: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
skillUploadHintNewSession: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. Already-open sessions keep their current sandbox until they end; only newly started sessions pick up this install.',
skillSourcePlaceholder: 'Paste a URL or {\'@\'}owner/slug',
skillSourceTokenLabel: 'Private SkillHub token',
skillSourceTokenPlaceholder: 'Optional',
skillSourceTokenHint: 'Only needed for a self-hosted or private SkillHub. Used for this download only, not stored.',
skillSourceInstall: 'Install',
skillInstallOr: 'or',
skillSourceFailed: 'Failed to install the skill from the registry',

View File

@ -5121,9 +5121,6 @@ export default {
skillUploadHint: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
skillUploadHintNewSession: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이번에 설치한 스킬은 새로 시작한 세션에만 적용됩니다.',
skillSourcePlaceholder: 'URL 또는 {\'@\'}owner/slug 붙여넣기',
skillSourceTokenLabel: '비공개 SkillHub 토큰',
skillSourceTokenPlaceholder: '선택 사항',
skillSourceTokenHint: '자체 호스팅 또는 비공개 SkillHub에서만 필요합니다. 이번 다운로드에만 사용되며 저장되지 않습니다.',
skillSourceInstall: '설치',
skillInstallOr: '또는',
skillSourceFailed: '레지스트리에서 스킬을 설치하지 못했습니다',

View File

@ -5121,9 +5121,6 @@ export default {
skillUploadHint: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
skillUploadHintNewSession: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык появится только у новых сессий.',
skillSourcePlaceholder: 'Вставьте URL или {\'@\'}owner/slug',
skillSourceTokenLabel: 'Токен закрытого SkillHub',
skillSourceTokenPlaceholder: 'Необязательно',
skillSourceTokenHint: 'Нужен только для собственного или закрытого SkillHub. Используется только для этой загрузки и не сохраняется.',
skillSourceInstall: 'Установить',
skillInstallOr: 'или',
skillSourceFailed: 'Не удалось установить навык из реестра',

View File

@ -5123,9 +5123,6 @@ export default {
skillUploadHint: '安装会在当前镜像上生成新快照,可能需要数分钟。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙箱,会话工作区草稿会在那时清空。',
skillUploadHintNewSession: '安装会在当前镜像上生成新快照,可能需要数分钟。已打开的会话继续使用原沙箱,直到该会话结束;只有新打开的会话才会带上这次安装的技能。',
skillSourcePlaceholder: '粘贴链接或 {\'@\'}owner/slug',
skillSourceTokenLabel: '私有 SkillHub 访问令牌',
skillSourceTokenPlaceholder: '可选',
skillSourceTokenHint: '只发给这个平台,不会保存。公开 ClawHub / GitHub 技能不用填。',
skillSourceInstall: '安装',
skillInstallOr: '或',
skillSourceFailed: '从托管平台安装技能失败',

View File

@ -15,6 +15,7 @@ import (
"sync"
"time"
apperrors "github.com/Tencent/WeKnora/internal/errors"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
@ -71,10 +72,26 @@ type skillSourceHandoff struct {
// InstallSkillFromSource resolves a ClawHub / SkillHub / skills.sh / git /
// direct-zip locator to a skill bundle and runs the same install as an upload.
//
// Every fetch is anonymous. Private registries are deliberately out of scope:
// carrying a credential here would mean deciding, per hop, which of a
// registry's handoff targets may see it, and there is no private registry to
// validate that against yet.
func (s *TenantSkillService) InstallSkillFromSource(
ctx context.Context, tenantID uint64, configID, source, token string,
ctx context.Context, tenantID uint64, configID, source string,
) (string, error) {
archive, err := fetchSkillArchive(ctx, source, token, s.sourceHTTP)
// The config is authorized before the fetch, not by InstallSkill after it.
// The source is a caller-supplied host, so an unknown config ID must not
// be able to spend an outbound request and a body-sized download first.
cfgEntity, err := s.configs.GetByID(ctx, tenantID, configID)
if err != nil {
return "", err
}
if cfgEntity == nil {
return "", apperrors.NewNotFoundError("sandbox config not found")
}
archive, err := fetchSkillArchive(ctx, source, s.sourceHTTP)
if err != nil {
return "", err
}
@ -93,17 +110,46 @@ func skillSourceHTTPClient(override *http.Client) *http.Client {
return skillSourceHTTPDefault
}
func fetchSkillArchive(ctx context.Context, source, token string, client *http.Client) ([]byte, error) {
func fetchSkillArchive(ctx context.Context, source string, client *http.Client) ([]byte, error) {
parsed, err := parseSkillSource(source)
if err != nil {
return nil, err
}
httpClient := skillSourceHTTPClient(client)
body, contentType, err := fetchSkillSourceBytes(ctx, httpClient, parsed, token, 0)
fetched, err := fetchSkillSourceBytes(ctx, httpClient, parsed, 0)
if err != nil {
return nil, err
// A bare "owner/slug" is both a GitHub repo and a registry slug, and
// the paste usually came from the registry listing. Only the failure
// of the first reading tells us which one it was.
alt, ok := registrySlugFallback(source, parsed)
if !ok {
return nil, err
}
altFetched, altErr := fetchSkillSourceBytes(ctx, httpClient, alt, 0)
if altErr != nil {
return nil, err
}
fetched = altFetched
}
return normalizeFetchedSkillArchive(body, contentType, parsed.Subdir)
return normalizeFetchedSkillArchive(fetched.body, fetched.contentType, fetched.subdir)
}
// registrySlugFallback re-reads a shorthand that was taken for a GitHub repo as
// a registry slug. It applies only to a bare "owner/slug": anything carrying a
// ref, a subdirectory or a scheme said what it meant.
func registrySlugFallback(raw string, parsed parsedSkillSource) (parsedSkillSource, bool) {
if parsed.Kind != skillSourceGitHub || parsed.Subdir != "" || parsed.Ref != "HEAD" {
return parsedSkillSource{}, false
}
spec := strings.TrimRight(strings.TrimSpace(raw), "/")
if spec == "" || strings.Contains(spec, "://") || strings.Contains(spec, "@") {
return parsedSkillSource{}, false
}
alt, err := parseRegistrySlug(defaultSkillRegistryOrigin, spec)
if err != nil {
return parsedSkillSource{}, false
}
return alt, true
}
func parseSkillSource(raw string) (parsedSkillSource, error) {
@ -457,6 +503,17 @@ func splitPath(p string) []string {
return out
}
// escapePathSegments escapes a value that spans several path segments, such as
// a "refs/heads/main" ref or a GitLab "group/subgroup" owner, without turning
// its separators into %2F.
func escapePathSegments(p string) string {
parts := strings.Split(p, "/")
for i, part := range parts {
parts[i] = url.PathEscape(part)
}
return strings.Join(parts, "/")
}
func isDirectArchivePath(p string) bool {
lower := strings.ToLower(p)
for _, ext := range []string{".zip", ".tgz", ".tar.gz", ".tar", ".md"} {
@ -494,71 +551,65 @@ func (s parsedSkillSource) fetchURL() (string, error) {
ref = "HEAD"
}
return fmt.Sprintf("https://codeload.github.com/%s/%s/zip/%s",
s.Owner, s.Repo, ref), nil
escapePathSegments(s.Owner), url.PathEscape(s.Repo), escapePathSegments(ref)), nil
case skillSourceGitLab:
ref := s.Ref
if ref == "" {
ref = "HEAD"
}
return fmt.Sprintf("https://gitlab.com/%s/%s/-/archive/%s/%s-%s.zip",
s.Owner, s.Repo, ref, s.Repo, ref), nil
return fmt.Sprintf("https://gitlab.com/%s/%s/-/archive/%s/%s.zip",
escapePathSegments(s.Owner), url.PathEscape(s.Repo),
escapePathSegments(ref), url.PathEscape(s.Repo+"-"+ref)), nil
default:
return "", fmt.Errorf("%w: cannot resolve source", ErrSkillSourceInvalid)
}
}
// fetchedSkillSource is the archive a source resolved to, plus the skill root
// inside it. The subdir is carried out of the fetch rather than re-derived from
// the original locator: a registry handoff to a monorepo zip names the one
// skill it meant, and only the last hop knows it.
type fetchedSkillSource struct {
body []byte
contentType string
subdir string
}
func fetchSkillSourceBytes(
ctx context.Context, client *http.Client, src parsedSkillSource, token string, hop int,
) ([]byte, string, error) {
ctx context.Context, client *http.Client, src parsedSkillSource, hop int,
) (fetchedSkillSource, error) {
if hop > skillSourceMaxHops {
return nil, "", fmt.Errorf("%w: too many source redirects", ErrSkillSourceInvalid)
return fetchedSkillSource{}, fmt.Errorf("%w: too many source redirects", ErrSkillSourceInvalid)
}
target, err := src.fetchURL()
if err != nil {
return nil, "", err
return fetchedSkillSource{}, err
}
body, contentType, err := getSkillURL(ctx, client, target, token, shouldSendSkillToken(src, token))
body, contentType, err := getSkillURL(ctx, client, target)
if err != nil {
return nil, "", err
return fetchedSkillSource{}, err
}
fetched := fetchedSkillSource{body: body, contentType: contentType, subdir: src.Subdir}
if isZipMagic(body) || looksLikeSkillMarkdown(body) {
return body, contentType, nil
return fetched, nil
}
if !looksLikeJSON(contentType, body) {
if isZipPayload(contentType, body) {
return body, contentType, nil
return fetched, nil
}
return nil, "", fmt.Errorf("%w: remote did not return a skill archive", ErrSkillSourceInvalid)
return fetchedSkillSource{}, fmt.Errorf(
"%w: remote did not return a skill archive", ErrSkillSourceInvalid)
}
var handoff skillSourceHandoff
if err := json.Unmarshal(body, &handoff); err != nil {
return nil, "", fmt.Errorf("%w: remote JSON is not a skill archive", ErrSkillSourceInvalid)
return fetchedSkillSource{}, fmt.Errorf(
"%w: remote JSON is not a skill archive", ErrSkillSourceInvalid)
}
next, err := sourceFromHandoff(src, handoff)
if err != nil {
return nil, "", err
return fetchedSkillSource{}, err
}
return fetchSkillSourceBytes(ctx, client, next, token, hop+1)
}
func shouldSendSkillToken(src parsedSkillSource, token string) bool {
if token == "" || src.Kind == skillSourceGitHub || src.Kind == skillSourceGitLab {
return false
}
target, err := src.fetchURL()
if err != nil {
return false
}
host := ""
if u, err := url.Parse(target); err == nil {
host = strings.ToLower(u.Hostname())
}
switch host {
case "github.com", "www.github.com", "codeload.github.com",
"gitlab.com", "www.gitlab.com", "skills.sh", "www.skills.sh":
return false
}
return src.Kind == skillSourceRegistry || src.Kind == skillSourceDirect
return fetchSkillSourceBytes(ctx, client, next, hop+1)
}
func sourceFromHandoff(prev parsedSkillSource, handoff skillSourceHandoff) (parsedSkillSource, error) {
@ -576,9 +627,14 @@ func sourceFromHandoff(prev parsedSkillSource, handoff skillSourceHandoff) (pars
}
archiveURL = strings.TrimRight(prev.Registry, "/") + archiveURL
}
// A handoff that is not a parseable http(s) URL is refused rather than
// passed through as a direct target: SSRF validation normalises a
// scheme-less string by prepending https://, which would turn a malformed
// response into a fetch of a host we never agreed to read.
next, err := parseSkillSourceURL(archiveURL)
if err != nil {
next = parsedSkillSource{Kind: skillSourceDirect, DirectURL: archiveURL}
return parsedSkillSource{}, fmt.Errorf(
"%w: registry archive URL is not usable: %v", ErrSkillSourceInvalid, err)
}
if next.Subdir == "" && strings.TrimSpace(handoff.Path) != "" {
next.Subdir = strings.Trim(handoff.Path, "/")
@ -590,7 +646,7 @@ func sourceFromHandoff(prev parsedSkillSource, handoff skillSourceHandoff) (pars
}
func getSkillURL(
ctx context.Context, client *http.Client, rawURL, token string, sendToken bool,
ctx context.Context, client *http.Client, rawURL string,
) ([]byte, string, error) {
if err := secutils.ValidateURLForSSRF(rawURL); err != nil {
return nil, "", fmt.Errorf("%w: %s", ErrSkillSourceInvalid,
@ -602,9 +658,6 @@ func getSkillURL(
}
req.Header.Set("User-Agent", skillSourceUserAgent)
req.Header.Set("Accept", "application/zip, application/octet-stream, application/json, text/plain;q=0.9, */*;q=0.8")
if sendToken && token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := client.Do(req)
if err != nil {
if errors.Is(err, secutils.ErrSSRFRedirectBlocked) {

View File

@ -5,6 +5,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/Tencent/WeKnora/internal/utils"
@ -155,9 +156,7 @@ func TestSkillHubCNMapsToDownloadAPI(t *testing.T) {
func TestFetchSkillArchiveFromRegistry(t *testing.T) {
archive := zipBundle(t, map[string]string{"SKILL.md": validSkillMD})
var sawAuth string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sawAuth = r.Header.Get("Authorization")
if r.URL.Path != "/api/v1/download" || r.URL.Query().Get("slug") != "owner/demo" {
http.NotFound(w, r)
return
@ -168,15 +167,128 @@ func TestFetchSkillArchiveFromRegistry(t *testing.T) {
t.Cleanup(server.Close)
allowLoopbackSkillFetch(t)
got, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", "sk_test", server.Client())
got, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", server.Client())
require.NoError(t, err)
require.Equal(t, "Bearer sk_test", sawAuth)
bundle, err := ParseSkillBundle(got)
require.NoError(t, err)
require.Equal(t, "pdf-tools", bundle.Name)
}
// Skill sources are read anonymously. Nothing in this flow holds a credential,
// so no hop may present one.
func TestFetchSkillArchiveSendsNoCredentials(t *testing.T) {
archive := zipBundle(t, map[string]string{"SKILL.md": validSkillMD})
var archiveAuth, registryAuth string
var mu sync.Mutex
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
switch r.URL.Path {
case "/api/v1/download":
registryAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(skillSourceHandoff{
ArchiveURL: "http://" + r.Host + "/skill.zip",
})
case "/skill.zip":
archiveAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/zip")
_, _ = w.Write(archive)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(server.Close)
allowLoopbackSkillFetch(t)
_, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", server.Client())
require.NoError(t, err)
require.Empty(t, registryAuth)
require.Empty(t, archiveAuth)
}
// The handoff's path is what names one skill inside a monorepo zip; losing it
// makes a multi-skill repo either ambiguous or wrong.
func TestFetchSkillArchiveUsesHandoffPath(t *testing.T) {
otherSkillMD := strings.Replace(validSkillMD, "name: pdf-tools", "name: csv-tools", 1)
archive := zipBundle(t, map[string]string{
"repo-main/README.md": "# repo",
"repo-main/skills/pdf/SKILL.md": validSkillMD,
"repo-main/skills/pdf/extract.py": "print('pdf')\n",
"repo-main/skills/csv/SKILL.md": otherSkillMD,
"repo-main/skills/csv/transform.py": "print('csv')\n",
})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/download":
_ = json.NewEncoder(w).Encode(skillSourceHandoff{
SourceRef: "public-github",
ArchiveURL: "http://" + r.Host + "/archive.zip",
Path: "skills/csv",
})
case "/archive.zip":
w.Header().Set("Content-Type", "application/zip")
_, _ = w.Write(archive)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(server.Close)
allowLoopbackSkillFetch(t)
got, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", server.Client())
require.NoError(t, err)
bundle, err := ParseSkillBundle(got)
require.NoError(t, err)
require.Equal(t, "csv-tools", bundle.Name)
require.Contains(t, bundle.Files, "transform.py")
require.NotContains(t, bundle.Files, "extract.py")
}
// A malformed handoff is refused: SSRF validation normalises a scheme-less
// string by prepending https://, so passing it through would fetch a host the
// response never legally named.
func TestFetchSkillArchiveRejectsUnusableHandoffURL(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(skillSourceHandoff{ArchiveURL: "evil.example.com/skill.zip"})
}))
t.Cleanup(server.Close)
allowLoopbackSkillFetch(t)
_, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", server.Client())
require.ErrorIs(t, err, ErrSkillSourceInvalid)
require.ErrorContains(t, err, "archive URL is not usable")
}
// A bare "owner/slug" reads as a GitHub repo and as a registry slug. The
// registry is the fallback, but only for a shorthand that named nothing else.
func TestRegistrySlugFallback(t *testing.T) {
bare := "clawhub_pskoett/self-improving-agent"
parsed, err := parseSkillSource(bare)
require.NoError(t, err)
require.Equal(t, skillSourceGitHub, parsed.Kind)
alt, ok := registrySlugFallback(bare, parsed)
require.True(t, ok)
require.Equal(t, skillSourceRegistry, alt.Kind)
require.Equal(t, defaultSkillRegistryOrigin, alt.Registry)
require.Equal(t, bare, alt.Slug)
withSubdir := "vercel-labs/agent-skills@frontend-design"
parsed, err = parseSkillSource(withSubdir)
require.NoError(t, err)
_, ok = registrySlugFallback(withSubdir, parsed)
require.False(t, ok, "a shorthand that named a skill directory meant GitHub")
parsed, err = parseSkillSource("https://github.com/vercel-labs/agent-skills")
require.NoError(t, err)
_, ok = registrySlugFallback("https://github.com/vercel-labs/agent-skills", parsed)
require.False(t, ok, "an explicit GitHub URL is not a registry slug")
}
func TestFetchSkillArchiveFollowsGitHubHandoff(t *testing.T) {
archive := zipBundle(t, map[string]string{
"repo-main/README.md": "# repo",
@ -201,7 +313,7 @@ func TestFetchSkillArchiveFollowsGitHubHandoff(t *testing.T) {
t.Cleanup(server.Close)
allowLoopbackSkillFetch(t)
got, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", "", server.Client())
got, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", server.Client())
require.NoError(t, err)
bundle, err := ParseSkillBundle(got)
require.NoError(t, err)
@ -218,23 +330,13 @@ func TestFetchSkillArchiveFromSkillMarkdown(t *testing.T) {
t.Cleanup(server.Close)
allowLoopbackSkillFetch(t)
got, err := fetchSkillArchive(t.Context(), server.URL+"/SKILL.md", "", server.Client())
got, err := fetchSkillArchive(t.Context(), server.URL+"/SKILL.md", server.Client())
require.NoError(t, err)
bundle, err := ParseSkillBundle(got)
require.NoError(t, err)
require.Equal(t, "pdf-tools", bundle.Name)
}
func TestFetchSkillArchiveDoesNotSendTokenToGitHub(t *testing.T) {
src := parsedSkillSource{
Kind: skillSourceGitHub, Owner: "o", Repo: "r", Ref: "HEAD",
}
require.False(t, shouldSendSkillToken(src, "sk_secret"))
src.Kind = skillSourceRegistry
src.Registry = "https://skillhub.example.com"
require.True(t, shouldSendSkillToken(src, "sk_secret"))
}
func TestParseSkillBundleNestedRemoteArchive(t *testing.T) {
data := zipBundle(t, map[string]string{
"repo-abc/LICENSE": "MIT",
@ -267,7 +369,7 @@ func TestFetchSkillArchiveRejectsNonSkillHTML(t *testing.T) {
t.Cleanup(server.Close)
allowLoopbackSkillFetch(t)
_, err := fetchSkillArchive(t.Context(), server.URL+"/demo.zip", "", server.Client())
_, err := fetchSkillArchive(t.Context(), server.URL+"/demo.zip", server.Client())
require.ErrorIs(t, err, ErrSkillSourceInvalid)
require.True(t, strings.Contains(err.Error(), "skill archive") ||
strings.Contains(err.Error(), "zip skill bundle"))

View File

@ -49,7 +49,7 @@ type sandboxSkillService interface {
) (*types.TenantSkillEntity, error)
InstallSkill(ctx context.Context, tenantID uint64, configID string, archive []byte) (string, error)
InstallSkillFromSource(
ctx context.Context, tenantID uint64, configID, source, token string,
ctx context.Context, tenantID uint64, configID, source string,
) (string, error)
RemoveSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
LastProgress(
@ -190,9 +190,10 @@ func (h *SandboxSkillHandler) Get(c *gin.Context) {
// @Description Install a skill onto this sandbox config's image. Send a zip
// @Description as multipart form field "file", or JSON {"source":"..."} to
// @Description pull from ClawHub, SkillHub, skills.sh, GitHub, GitLab, or a
// @Description direct archive URL. The install boots a sandbox and runs for
// @Description minutes, so the request is only accepted; follow it via the
// @Description install-events stream.
// @Description direct archive URL. The source must be readable anonymously.
// @Description The install boots a sandbox and runs for minutes, so the
// @Description request is only accepted; follow it via the install-events
// @Description stream.
// @Tags SandboxConfig
// @Accept json
// @Accept multipart/form-data
@ -258,11 +259,9 @@ func (h *SandboxSkillHandler) Upload(c *gin.Context) {
type skillSourceRequest struct {
// Source is a ClawHub/SkillHub slug or page URL, a skills.sh / GitHub /
// GitLab locator, or a direct zip/SKILL.md URL.
// GitLab locator, or a direct zip/SKILL.md URL. It must be readable
// anonymously: the fetch carries no credential of any kind.
Source string `json:"source"`
// Token is an optional registry bearer token (private SkillHub). It is
// used only for that fetch and is never stored.
Token string `json:"token"`
}
func (h *SandboxSkillHandler) installFromSource(c *gin.Context) {
@ -283,7 +282,7 @@ func (h *SandboxSkillHandler) installFromSource(c *gin.Context) {
}
skillID, err := h.service.InstallSkillFromSource(
c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), source, req.Token,
c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), source,
)
if err != nil {
respondSkillServiceError(c, err)

View File

@ -38,7 +38,6 @@ type fakeSandboxSkillService struct {
installID string
installErr error
installSource string
installToken string
sourceErr error
removeErr error
@ -124,10 +123,10 @@ func (f *fakeSandboxSkillService) InstallSkill(
}
func (f *fakeSandboxSkillService) InstallSkillFromSource(
_ context.Context, tenantID uint64, configID, source, token string,
_ context.Context, tenantID uint64, configID, source string,
) (string, error) {
f.installTenant, f.installConfig = tenantID, configID
f.installSource, f.installToken = source, token
f.installSource = source
return f.installID, f.sourceErr
}
@ -281,7 +280,7 @@ func TestSandboxSkillInstallFromSourceAcceptedReturnsSkillID(t *testing.T) {
svc := &fakeSandboxSkillService{installID: "skill-9"}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
body := `{"source":"@owner/demo","token":"sk_test"}`
body := `{"source":"@owner/demo"}`
req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/skills",
strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@ -292,7 +291,6 @@ func TestSandboxSkillInstallFromSourceAcceptedReturnsSkillID(t *testing.T) {
require.Equal(t, testSkillTenantID, svc.installTenant)
require.Equal(t, "cfg-a", svc.installConfig)
require.Equal(t, "@owner/demo", svc.installSource)
require.Equal(t, "sk_test", svc.installToken)
require.Nil(t, svc.installBytes, "a source install must not look like an upload")
}

View File

@ -41,7 +41,6 @@ type SkillInfoResponse struct {
// @Produce json
// @Param sandbox_config_id query string false "Sandbox config ID"
// @Success 200 {object} map[string]interface{} "Skills列表"
// @Failure 500 {object} errors.AppError "服务器错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /skills [get]