fix(assets,assessments): sync classic chat precipitated assets into project scope
This commit is contained in:
parent
8e893960a3
commit
41aea97735
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"cyberstrike-ai/internal/authctx"
|
||||||
"cyberstrike-ai/internal/config"
|
"cyberstrike-ai/internal/config"
|
||||||
"cyberstrike-ai/internal/database"
|
"cyberstrike-ai/internal/database"
|
||||||
"cyberstrike-ai/internal/mcp"
|
"cyberstrike-ai/internal/mcp"
|
||||||
|
|
@ -199,6 +200,15 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
|
||||||
if warn := project.SparseBodyWarningIfNeeded(f.Category, f.FactKey, f.Body); warn != "" {
|
if warn := project.SparseBodyWarningIfNeeded(f.Category, f.FactKey, f.Body); warn != "" {
|
||||||
msg += warn
|
msg += warn
|
||||||
}
|
}
|
||||||
|
if principal, hasPrincipal := authctx.PrincipalFromContext(ctx); !hasPrincipal || principal.HasPermission("asset:write") {
|
||||||
|
ownerID := ""
|
||||||
|
allowGlobal := true
|
||||||
|
if hasPrincipal {
|
||||||
|
ownerID = principal.UserID
|
||||||
|
allowGlobal = principal.ScopeFor("asset:write") == database.RBACScopeAll
|
||||||
|
}
|
||||||
|
_, _ = db.SyncFactTargetsToAssets(projectID, created, ownerID, allowGlobal)
|
||||||
|
}
|
||||||
return textResult(msg, false), nil
|
return textResult(msg, false), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -407,6 +407,11 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
|
||||||
if principal, ok := authctx.PrincipalFromContext(ctx); ok {
|
if principal, ok := authctx.PrincipalFromContext(ctx); ok {
|
||||||
_ = db.SetResourceOwner("vulnerability", created.ID, principal.UserID)
|
_ = db.SetResourceOwner("vulnerability", created.ID, principal.UserID)
|
||||||
_ = db.AssignResourceToUser(principal.UserID, "vulnerability", created.ID)
|
_ = db.AssignResourceToUser(principal.UserID, "vulnerability", created.ID)
|
||||||
|
if projectID != "" && principal.HasPermission("asset:write") {
|
||||||
|
_, _ = db.SyncVulnerabilityTargetToAssets(projectID, created.Target, principal.UserID, principal.ScopeFor("asset:write") == database.RBACScopeAll)
|
||||||
|
}
|
||||||
|
} else if projectID != "" {
|
||||||
|
_, _ = db.SyncVulnerabilityTargetToAssets(projectID, created.Target, "", true)
|
||||||
}
|
}
|
||||||
db.NotifyVulnerabilityCreated(created)
|
db.NotifyVulnerabilityCreated(created)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -380,12 +380,16 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
|
||||||
result.Skipped++
|
result.Skipped++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if existingProject.String != asset.ProjectID {
|
existingProj := strings.TrimSpace(existingProject.String)
|
||||||
result.Skipped++
|
if existingProj != asset.ProjectID {
|
||||||
result.ProjectConflicts++
|
if existingProj != "" || asset.ProjectID == "" {
|
||||||
continue
|
result.Skipped++
|
||||||
|
result.ProjectConflicts++
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_, err = tx.Exec(`UPDATE assets SET
|
_, err = tx.Exec(`UPDATE assets SET
|
||||||
|
project_id=CASE WHEN COALESCE(project_id, '')='' AND ?<>'' THEN ? ELSE project_id END,
|
||||||
host=CASE WHEN ?<>'' THEN ? ELSE host END, ip=CASE WHEN ?<>'' THEN ? ELSE ip END,
|
host=CASE WHEN ?<>'' THEN ? ELSE host END, ip=CASE WHEN ?<>'' THEN ? ELSE ip END,
|
||||||
domain=CASE WHEN ?<>'' THEN ? ELSE domain END, protocol=CASE WHEN ?<>'' THEN ? ELSE protocol END,
|
domain=CASE WHEN ?<>'' THEN ? ELSE domain END, protocol=CASE WHEN ?<>'' THEN ? ELSE protocol END,
|
||||||
title=CASE WHEN ?<>'' THEN ? ELSE title END, server=CASE WHEN ?<>'' THEN ? ELSE server END,
|
title=CASE WHEN ?<>'' THEN ? ELSE title END, server=CASE WHEN ?<>'' THEN ? ELSE server END,
|
||||||
|
|
@ -399,6 +403,7 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
|
||||||
criticality=CASE WHEN ?<>'' THEN ? ELSE criticality END,
|
criticality=CASE WHEN ?<>'' THEN ? ELSE criticality END,
|
||||||
tags_json=CASE WHEN ?<>'[]' THEN ? ELSE tags_json END,
|
tags_json=CASE WHEN ?<>'[]' THEN ? ELSE tags_json END,
|
||||||
last_seen_at=?, updated_at=? WHERE id=?`,
|
last_seen_at=?, updated_at=? WHERE id=?`,
|
||||||
|
asset.ProjectID, asset.ProjectID,
|
||||||
asset.Host, asset.Host, asset.IP, asset.IP, asset.Domain, asset.Domain, asset.Protocol, asset.Protocol,
|
asset.Host, asset.Host, asset.IP, asset.IP, asset.Domain, asset.Domain, asset.Protocol, asset.Protocol,
|
||||||
asset.Title, asset.Title, asset.Server, asset.Server, asset.Country, asset.Country, asset.Province, asset.Province,
|
asset.Title, asset.Title, asset.Server, asset.Server, asset.Country, asset.Country, asset.Province, asset.Province,
|
||||||
asset.City, asset.City, asset.Source, asset.Source, asset.SourceQuery, asset.SourceQuery,
|
asset.City, asset.City, asset.Source, asset.Source, asset.SourceQuery, asset.SourceQuery,
|
||||||
|
|
|
||||||
|
|
@ -456,6 +456,12 @@ func (db *DB) SetConversationProjectID(conversationID, projectID string) error {
|
||||||
return fmt.Errorf("设置对话项目失败: %w", err)
|
return fmt.Errorf("设置对话项目失败: %w", err)
|
||||||
}
|
}
|
||||||
if oldProjectID != projectID {
|
if oldProjectID != projectID {
|
||||||
|
if oldProjectID == "" && projectID != "" {
|
||||||
|
_, _ = tx.Exec(
|
||||||
|
`UPDATE assets SET project_id = ?, updated_at = ? WHERE last_scan_conversation_id = ? AND COALESCE(project_id, '') = ''`,
|
||||||
|
projectID, time.Now(), conversationID,
|
||||||
|
)
|
||||||
|
}
|
||||||
rows, err := tx.Query(`SELECT id FROM vulnerabilities WHERE conversation_id = ? AND COALESCE(project_id, '') = ?`, conversationID, oldProjectID)
|
rows, err := tx.Query(`SELECT id FROM vulnerabilities WHERE conversation_id = ? AND COALESCE(project_id, '') = ?`, conversationID, oldProjectID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("查询对话关联漏洞失败: %w", err)
|
return fmt.Errorf("查询对话关联漏洞失败: %w", err)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,484 @@
|
||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cyberstrike-ai/internal/surfaceingest"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxProjectSyncFacts = 500
|
||||||
|
maxProjectSyncExecutions = 80
|
||||||
|
maxProjectSyncUserPrompts = 40
|
||||||
|
maxProjectSyncVulns = 500
|
||||||
|
maxProjectSyncChainNodes = 500
|
||||||
|
)
|
||||||
|
|
||||||
|
type projectScopeJSON struct {
|
||||||
|
Targets []string `json:"targets"`
|
||||||
|
Exclude []string `json:"exclude"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseProjectScopeTargets(raw string) (targets, exclude string) {
|
||||||
|
var payload projectScopeJSON
|
||||||
|
if json.Unmarshal([]byte(strings.TrimSpace(raw)), &payload) != nil {
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
return strings.Join(payload.Targets, "\n"), strings.Join(payload.Exclude, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isStructuredTargetFact(category, factKey string) bool {
|
||||||
|
cat := strings.ToLower(strings.TrimSpace(category))
|
||||||
|
key := strings.ToLower(strings.TrimSpace(factKey))
|
||||||
|
return cat == "target" || cat == "infra" ||
|
||||||
|
strings.HasPrefix(key, "target/") || strings.HasPrefix(key, "infra/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isArtifactOnlyFactKey(factKey string) bool {
|
||||||
|
key := strings.ToLower(strings.TrimSpace(factKey))
|
||||||
|
return strings.HasPrefix(key, "artifact/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractAttackChainTargetMetadata(raw string) string {
|
||||||
|
raw = strings.TrimSpace(raw)
|
||||||
|
if raw == "" || !strings.HasPrefix(raw, "{") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var meta map[string]any
|
||||||
|
if json.Unmarshal([]byte(raw), &meta) != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var parts []string
|
||||||
|
for _, k := range []string{"target", "host", "url", "domain", "ip"} {
|
||||||
|
if v, ok := meta[k].(string); ok && strings.TrimSpace(v) != "" {
|
||||||
|
parts = append(parts, strings.TrimSpace(v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func unwrapStoredToolExecutionText(raw string) string {
|
||||||
|
trimmed := strings.TrimSpace(raw)
|
||||||
|
if trimmed == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(trimmed, "{") {
|
||||||
|
var envelope struct {
|
||||||
|
Content []struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
} `json:"content"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal([]byte(trimmed), &envelope) == nil && len(envelope.Content) > 0 {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, item := range envelope.Content {
|
||||||
|
if item.Text != "" {
|
||||||
|
if b.Len() > 0 {
|
||||||
|
b.WriteByte('\n')
|
||||||
|
}
|
||||||
|
b.WriteString(item.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
func surfaceHitHost(hit surfaceingest.SurfaceHit) string {
|
||||||
|
if hit.Domain != "" {
|
||||||
|
return hit.Domain
|
||||||
|
}
|
||||||
|
return hit.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
func clipSurfaceSource(value string, max int) string {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
runes := []rune(value)
|
||||||
|
if len(runes) <= max {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return string(runes[:max])
|
||||||
|
}
|
||||||
|
|
||||||
|
func isEndpointValidationError(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
text := err.Error()
|
||||||
|
return strings.Contains(text, "invalid HTTP method") || strings.Contains(text, "endpoint path")
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountSharedProjectFacts counts non-deprecated project facts excluding automatic session checkpoints.
|
||||||
|
func (db *DB) CountSharedProjectFacts(projectID string) (int, error) {
|
||||||
|
projectID = strings.TrimSpace(projectID)
|
||||||
|
if db == nil || projectID == "" {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
err := db.QueryRow(
|
||||||
|
`SELECT COUNT(*) FROM project_facts WHERE project_id = ? AND confidence != 'deprecated' AND fact_key NOT LIKE 'note/context-%'`,
|
||||||
|
projectID,
|
||||||
|
).Scan(&count)
|
||||||
|
return count, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *DB) applyProjectSurfaceHits(projectID, source, sourceQuery, ownerUserID string, allowGlobal bool, hits []surfaceingest.SurfaceHit) ([]string, error) {
|
||||||
|
projectID = strings.TrimSpace(projectID)
|
||||||
|
if db == nil || projectID == "" || len(hits) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
scope := RBACScopeAssigned
|
||||||
|
if allowGlobal || strings.TrimSpace(ownerUserID) == "" {
|
||||||
|
scope = RBACScopeAll
|
||||||
|
}
|
||||||
|
access := RBACListAccess{UserID: ownerUserID, Scope: scope}
|
||||||
|
var applied []string
|
||||||
|
for _, hit := range hits {
|
||||||
|
asset := &Asset{
|
||||||
|
ProjectID: projectID,
|
||||||
|
Host: surfaceHitHost(hit),
|
||||||
|
IP: hit.IP,
|
||||||
|
Domain: hit.Domain,
|
||||||
|
Port: hit.Port,
|
||||||
|
Protocol: hit.Protocol,
|
||||||
|
Source: source,
|
||||||
|
SourceQuery: clipSurfaceSource(sourceQuery, 500),
|
||||||
|
Status: "active",
|
||||||
|
}
|
||||||
|
res, err := db.UpsertAssetsInProject([]*Asset{asset}, ownerUserID, allowGlobal, projectID)
|
||||||
|
if err != nil {
|
||||||
|
var invalid *AssetValidationError
|
||||||
|
if errors.As(err, &invalid) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return applied, err
|
||||||
|
}
|
||||||
|
if len(res.AppliedIDs) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
id := res.AppliedIDs[0]
|
||||||
|
applied = append(applied, id)
|
||||||
|
for _, ep := range hit.Endpoints {
|
||||||
|
epErr := db.PutAssetEndpoint(&AssetEndpoint{AssetID: id, Method: ep.Method, Path: ep.Path}, access)
|
||||||
|
if epErr != nil && !isEndpointValidationError(epErr) {
|
||||||
|
return applied, epErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return applied, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *DB) projectSeedsAndExclusions(projectID string) ([]surfaceingest.ScopeSeed, []surfaceingest.ScopeSeed, string) {
|
||||||
|
var scopeTargets, scopeExclude string
|
||||||
|
if proj, err := db.GetProject(projectID); err == nil && proj != nil {
|
||||||
|
scopeTargets, scopeExclude = parseProjectScopeTargets(proj.ScopeJSON)
|
||||||
|
}
|
||||||
|
excluded := surfaceingest.SeedsFromHits(surfaceingest.ExtractDeclaredTargets(scopeExclude))
|
||||||
|
rows, err := db.ListAssetScopeSeeds(5000, AssetListFilter{ProjectID: projectID}, RBACListAccess{Scope: RBACScopeAll})
|
||||||
|
var seeds []surfaceingest.ScopeSeed
|
||||||
|
if err == nil {
|
||||||
|
for _, r := range rows {
|
||||||
|
seeds = append(seeds, surfaceingest.ScopeSeed{Host: r.Host, IP: r.IP, Domain: r.Domain})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if scopeTargets != "" {
|
||||||
|
seeds = append(seeds, surfaceingest.SeedsFromHits(surfaceingest.ExtractDeclaredTargets(scopeTargets))...)
|
||||||
|
}
|
||||||
|
return seeds, excluded, scopeTargets
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncFactTargetsToAssets materializes targets referenced in a saved project fact into the project's asset library.
|
||||||
|
func (db *DB) SyncFactTargetsToAssets(projectID string, fact *ProjectFact, ownerUserID string, allowGlobal bool) ([]string, error) {
|
||||||
|
projectID = strings.TrimSpace(projectID)
|
||||||
|
if db == nil || projectID == "" || fact == nil || fact.Confidence == "deprecated" || IsContextCheckpointKey(fact.FactKey) || isArtifactOnlyFactKey(fact.FactKey) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if proj, err := db.GetProject(projectID); err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
|
||||||
|
var structured, prose []string
|
||||||
|
if isStructuredTargetFact(fact.Category, fact.FactKey) {
|
||||||
|
structured = append(structured, fact.Summary, fact.Body)
|
||||||
|
} else {
|
||||||
|
structured = append(structured, fact.Summary)
|
||||||
|
prose = append(prose, fact.Body)
|
||||||
|
}
|
||||||
|
hits := surfaceingest.ExtractPrecipitatedTargets(structured, prose, seeds, excluded)
|
||||||
|
return db.applyProjectSurfaceHits(projectID, "project_fact", fact.FactKey, ownerUserID, allowGlobal, hits)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncVulnerabilityTargetToAssets materializes a recorded vulnerability's target into the project's asset library.
|
||||||
|
func (db *DB) SyncVulnerabilityTargetToAssets(projectID, target, ownerUserID string, allowGlobal bool) ([]string, error) {
|
||||||
|
projectID = strings.TrimSpace(projectID)
|
||||||
|
target = strings.TrimSpace(target)
|
||||||
|
if db == nil || projectID == "" || target == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if proj, err := db.GetProject(projectID); err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
|
||||||
|
hits := surfaceingest.ExtractPrecipitatedTargets([]string{target}, nil, seeds, excluded)
|
||||||
|
return db.applyProjectSurfaceHits(projectID, "vulnerability", target, ownerUserID, allowGlobal, hits)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IngestBoundConversationSurface writes in-scope discoveries from classic chat or batch tool outputs
|
||||||
|
// into the bound project's shared asset library.
|
||||||
|
func (db *DB) IngestBoundConversationSurface(conversationID, toolName, content, ownerUserID string, allowGlobal bool) (int, error) {
|
||||||
|
conversationID = strings.TrimSpace(conversationID)
|
||||||
|
if db == nil || conversationID == "" || strings.TrimSpace(content) == "" {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
projectID, err := db.GetConversationProjectID(conversationID)
|
||||||
|
if err != nil || strings.TrimSpace(projectID) == "" {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
projectID = strings.TrimSpace(projectID)
|
||||||
|
proj, err := db.GetProject(projectID)
|
||||||
|
if err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
if ownerUserID == "" {
|
||||||
|
_ = db.QueryRow(`SELECT COALESCE(owner_user_id, '') FROM conversations WHERE id = ?`, conversationID).Scan(&ownerUserID)
|
||||||
|
ownerUserID = strings.TrimSpace(ownerUserID)
|
||||||
|
}
|
||||||
|
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
|
||||||
|
// Also seed from explicit targets declared in this conversation's user prompts or target facts.
|
||||||
|
promptRows, err := db.Query(
|
||||||
|
`SELECT content FROM messages WHERE conversation_id = ? AND role = 'user' ORDER BY created_at DESC LIMIT 10`,
|
||||||
|
conversationID,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
var userTexts []string
|
||||||
|
for promptRows.Next() {
|
||||||
|
var body string
|
||||||
|
if promptRows.Scan(&body) == nil && strings.TrimSpace(body) != "" {
|
||||||
|
userTexts = append(userTexts, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = promptRows.Close()
|
||||||
|
if len(userTexts) > 0 {
|
||||||
|
promptHits := surfaceingest.ExtractPrecipitatedTargets(userTexts, nil, seeds, excluded)
|
||||||
|
if len(promptHits) > 0 {
|
||||||
|
_, _ = db.applyProjectSurfaceHits(projectID, "chat", "conversation_prompt", ownerUserID, allowGlobal, promptHits)
|
||||||
|
seeds = append(seeds, surfaceingest.SeedsFromHits(promptHits)...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
factRows, err := db.Query(
|
||||||
|
`SELECT category, fact_key, summary, COALESCE(body, '') FROM project_facts
|
||||||
|
WHERE project_id = ? AND confidence != 'deprecated' AND fact_key NOT LIKE 'note/context-%'
|
||||||
|
ORDER BY updated_at DESC LIMIT 60`,
|
||||||
|
projectID,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
var structured []string
|
||||||
|
for factRows.Next() {
|
||||||
|
var cat, key, summary, body string
|
||||||
|
if factRows.Scan(&cat, &key, &summary, &body) == nil && !isArtifactOnlyFactKey(key) {
|
||||||
|
structured = append(structured, summary)
|
||||||
|
if isStructuredTargetFact(cat, key) {
|
||||||
|
structured = append(structured, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = factRows.Close()
|
||||||
|
if len(structured) > 0 {
|
||||||
|
seeds = append(seeds, surfaceingest.SeedsFromHits(surfaceingest.ExtractPrecipitatedTargets(structured, nil, nil, excluded))...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(seeds) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
hits, _ := surfaceingest.Ingest(content, seeds, excluded)
|
||||||
|
applied, err := db.applyProjectSurfaceHits(projectID, "chat", toolName, ownerUserID, allowGlobal, hits)
|
||||||
|
return len(applied), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncProjectPrecipitatedAssets backfills and synchronizes targets precipitated in classic
|
||||||
|
// conversations (project facts, promoted/cached attack-chain target nodes, vulnerabilities,
|
||||||
|
// scope_json targets, unassigned conversation-scanned assets, and in-scope tool outputs)
|
||||||
|
// into the project's shared asset library.
|
||||||
|
func (db *DB) SyncProjectPrecipitatedAssets(projectID, ownerUserID string, allowGlobal bool) (int, error) {
|
||||||
|
projectID = strings.TrimSpace(projectID)
|
||||||
|
if db == nil || projectID == "" {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
proj, err := db.GetProject(projectID)
|
||||||
|
if err != nil || proj == nil || proj.Status == ProjectStatusArchived {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
ownerUserID = strings.TrimSpace(ownerUserID)
|
||||||
|
adopted := 0
|
||||||
|
|
||||||
|
// 1. Adopt unassigned assets that were scanned in conversations bound to this project.
|
||||||
|
now := time.Now()
|
||||||
|
var adoptRes sql.Result
|
||||||
|
if allowGlobal || ownerUserID == "" {
|
||||||
|
adoptRes, _ = db.Exec(
|
||||||
|
`UPDATE assets SET project_id = ?, updated_at = ?
|
||||||
|
WHERE COALESCE(project_id, '') = '' AND COALESCE(last_scan_conversation_id, '') <> ''
|
||||||
|
AND EXISTS (SELECT 1 FROM conversations c WHERE c.id = assets.last_scan_conversation_id AND c.project_id = ?)`,
|
||||||
|
projectID, now, projectID,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
adoptRes, _ = db.Exec(
|
||||||
|
`UPDATE assets SET project_id = ?, updated_at = ?
|
||||||
|
WHERE COALESCE(project_id, '') = '' AND COALESCE(owner_user_id, '') = ?
|
||||||
|
AND COALESCE(last_scan_conversation_id, '') <> ''
|
||||||
|
AND EXISTS (SELECT 1 FROM conversations c WHERE c.id = assets.last_scan_conversation_id AND c.project_id = ?)`,
|
||||||
|
projectID, now, ownerUserID, projectID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if adoptRes != nil {
|
||||||
|
if n, nErr := adoptRes.RowsAffected(); nErr == nil {
|
||||||
|
adopted += int(n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
seeds, excluded, scopeTargets := db.projectSeedsAndExclusions(projectID)
|
||||||
|
var structuredTexts []string
|
||||||
|
var proseTexts []string
|
||||||
|
if scopeTargets != "" {
|
||||||
|
structuredTexts = append(structuredTexts, scopeTargets)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Collect recorded vulnerabilities in this project.
|
||||||
|
vulnRows, err := db.Query(
|
||||||
|
`SELECT COALESCE(target, ''), COALESCE(targets_json, '') FROM vulnerabilities
|
||||||
|
WHERE project_id = ? AND manually_archived = 0 ORDER BY updated_at DESC LIMIT ?`,
|
||||||
|
projectID, maxProjectSyncVulns,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
for vulnRows.Next() {
|
||||||
|
var target, targetsJSON string
|
||||||
|
if vulnRows.Scan(&target, &targetsJSON) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(target) != "" {
|
||||||
|
structuredTexts = append(structuredTexts, target)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(targetsJSON) != "" && targetsJSON != "[]" {
|
||||||
|
var list []string
|
||||||
|
if json.Unmarshal([]byte(targetsJSON), &list) == nil && len(list) > 0 {
|
||||||
|
structuredTexts = append(structuredTexts, strings.Join(list, "\n"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = vulnRows.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Collect target nodes from conversation attack chains bound to this project.
|
||||||
|
chainRows, err := db.Query(
|
||||||
|
`SELECT acn.node_name, COALESCE(acn.metadata, '')
|
||||||
|
FROM attack_chain_nodes acn
|
||||||
|
INNER JOIN conversations c ON c.id = acn.conversation_id
|
||||||
|
WHERE c.project_id = ? AND LOWER(acn.node_type) = 'target'
|
||||||
|
ORDER BY acn.created_at DESC LIMIT ?`,
|
||||||
|
projectID, maxProjectSyncChainNodes,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
for chainRows.Next() {
|
||||||
|
var name, metadata string
|
||||||
|
if chainRows.Scan(&name, &metadata) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(name) != "" {
|
||||||
|
structuredTexts = append(structuredTexts, name)
|
||||||
|
}
|
||||||
|
if metaTargets := extractAttackChainTargetMetadata(metadata); metaTargets != "" {
|
||||||
|
structuredTexts = append(structuredTexts, metaTargets)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = chainRows.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Collect project blackboard facts.
|
||||||
|
factRows, err := db.Query(
|
||||||
|
`SELECT category, fact_key, summary, COALESCE(body, '')
|
||||||
|
FROM project_facts
|
||||||
|
WHERE project_id = ? AND confidence != 'deprecated'
|
||||||
|
ORDER BY pinned DESC, updated_at DESC LIMIT ?`,
|
||||||
|
projectID, maxProjectSyncFacts,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
for factRows.Next() {
|
||||||
|
var cat, key, summary, body string
|
||||||
|
if factRows.Scan(&cat, &key, &summary, &body) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if IsContextCheckpointKey(key) {
|
||||||
|
if strings.TrimSpace(body) != "" {
|
||||||
|
proseTexts = append(proseTexts, body)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isArtifactOnlyFactKey(key) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isStructuredTargetFact(cat, key) {
|
||||||
|
structuredTexts = append(structuredTexts, summary, body)
|
||||||
|
} else {
|
||||||
|
structuredTexts = append(structuredTexts, summary)
|
||||||
|
if strings.TrimSpace(body) != "" {
|
||||||
|
proseTexts = append(proseTexts, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = factRows.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Collect user prompts and completed tool outputs from bound non-assessment conversations.
|
||||||
|
promptRows, err := db.Query(
|
||||||
|
`SELECT m.content
|
||||||
|
FROM messages m
|
||||||
|
INNER JOIN conversations c ON c.id = m.conversation_id
|
||||||
|
WHERE c.project_id = ? AND m.role = 'user'
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM deep_assessment_sessions das WHERE das.conversation_id = c.id)
|
||||||
|
ORDER BY m.created_at DESC LIMIT ?`,
|
||||||
|
projectID, maxProjectSyncUserPrompts,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
for promptRows.Next() {
|
||||||
|
var content string
|
||||||
|
if promptRows.Scan(&content) == nil && strings.TrimSpace(content) != "" {
|
||||||
|
structuredTexts = append(structuredTexts, content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = promptRows.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
execRows, err := db.Query(
|
||||||
|
`SELECT COALESCE(te.result, '')
|
||||||
|
FROM tool_executions te
|
||||||
|
INNER JOIN conversations c ON c.id = te.conversation_id
|
||||||
|
WHERE c.project_id = ? AND te.status = 'completed' AND COALESCE(te.result, '') <> ''
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM deep_assessment_sessions das WHERE das.conversation_id = c.id)
|
||||||
|
ORDER BY te.created_at DESC LIMIT ?`,
|
||||||
|
projectID, maxProjectSyncExecutions,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
for execRows.Next() {
|
||||||
|
var raw string
|
||||||
|
if execRows.Scan(&raw) == nil {
|
||||||
|
if text := unwrapStoredToolExecutionText(raw); text != "" {
|
||||||
|
proseTexts = append(proseTexts, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = execRows.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
hits := surfaceingest.ExtractPrecipitatedTargets(structuredTexts, proseTexts, seeds, excluded)
|
||||||
|
applied, err := db.applyProjectSurfaceHits(projectID, "project_sync", "project_precipitation", ownerUserID, allowGlobal, hits)
|
||||||
|
if err != nil {
|
||||||
|
return adopted + len(applied), err
|
||||||
|
}
|
||||||
|
return adopted + len(applied), nil
|
||||||
|
}
|
||||||
|
|
@ -248,6 +248,27 @@ func (h *AssetHandler) List(c *gin.Context) {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
syncRequested := strings.TrimSpace(c.Query("sync_project_scope")) == "1" && filter.ProjectID != ""
|
||||||
|
syncedAssets := 0
|
||||||
|
projectFactCount := 0
|
||||||
|
if syncRequested {
|
||||||
|
if session, ok := security.CurrentSession(c); ok {
|
||||||
|
if security.SessionHasPermission(c, "project:read") &&
|
||||||
|
h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", filter.ProjectID) {
|
||||||
|
if security.SessionHasPermission(c, "asset:write") {
|
||||||
|
syncedAssets, _ = h.db.SyncProjectPrecipitatedAssets(
|
||||||
|
filter.ProjectID,
|
||||||
|
session.UserID,
|
||||||
|
session.ScopeFor("asset:write") == database.RBACScopeAll,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
projectFactCount, _ = h.db.CountSharedProjectFacts(filter.ProjectID)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
syncedAssets, _ = h.db.SyncProjectPrecipitatedAssets(filter.ProjectID, "", true)
|
||||||
|
projectFactCount, _ = h.db.CountSharedProjectFacts(filter.ProjectID)
|
||||||
|
}
|
||||||
|
}
|
||||||
assets, total, err := h.db.ListAssets(pageSize, (page-1)*pageSize, filter, assetAccess(c))
|
assets, total, err := h.db.ListAssets(pageSize, (page-1)*pageSize, filter, assetAccess(c))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Error("加载资产失败", zap.Error(err))
|
h.logger.Error("加载资产失败", zap.Error(err))
|
||||||
|
|
@ -258,7 +279,12 @@ func (h *AssetHandler) List(c *gin.Context) {
|
||||||
if totalPages < 1 {
|
if totalPages < 1 {
|
||||||
totalPages = 1
|
totalPages = 1
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"assets": assets, "total": total, "page": page, "page_size": pageSize, "total_pages": totalPages})
|
resp := gin.H{"assets": assets, "total": total, "page": page, "page_size": pageSize, "total_pages": totalPages}
|
||||||
|
if syncRequested {
|
||||||
|
resp["synced_assets"] = syncedAssets
|
||||||
|
resp["project_fact_count"] = projectFactCount
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
func assetListFilterFromQuery(c *gin.Context) (database.AssetListFilter, error) {
|
func assetListFilterFromQuery(c *gin.Context) (database.AssetListFilter, error) {
|
||||||
|
|
|
||||||
|
|
@ -150,6 +150,15 @@ func (h *ConversationHandler) SetConversationProject(c *gin.Context) {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if projectID != "" {
|
||||||
|
if session, ok := security.CurrentSession(c); ok {
|
||||||
|
if security.SessionHasPermission(c, "asset:write") {
|
||||||
|
_, _ = h.db.SyncProjectPrecipitatedAssets(projectID, session.UserID, session.ScopeFor("asset:write") == database.RBACScopeAll)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_, _ = h.db.SyncProjectPrecipitatedAssets(projectID, "", true)
|
||||||
|
}
|
||||||
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true, "projectId": projectID})
|
c.JSON(http.StatusOK, gin.H{"success": true, "projectId": projectID})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -60,6 +60,9 @@ func (h *AgentHandler) syncAssessmentAssets(actor assessmentAssetActor, t *deepa
|
||||||
}
|
}
|
||||||
var ids []string
|
var ids []string
|
||||||
if strings.TrimSpace(t.ProjectID) != "" {
|
if strings.TrimSpace(t.ProjectID) != "" {
|
||||||
|
if strings.TrimSpace(t.CollectionID) == "" && actor.can("asset:write") {
|
||||||
|
_, _ = h.db.SyncProjectPrecipitatedAssets(t.ProjectID, actor.userID, actor.scope("asset:write") == database.RBACScopeAll)
|
||||||
|
}
|
||||||
scoped, err := h.assessmentScopeIDs(actor, t)
|
scoped, err := h.assessmentScopeIDs(actor, t)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
@ -155,29 +158,54 @@ func (h *AgentHandler) assessmentSurfaceSeeds(actor assessmentAssetActor, t *dee
|
||||||
return seeds, nil
|
return seeds, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// IngestMCPSurface is the execution-service entry for a successful MCP result.
|
// IngestMCPSurface is the execution-service entry for a successful MCP or local
|
||||||
// It claims the execution ID before writing. Deep assessment AfterTool uses the
|
// tool result. It claims the execution ID before writing so each receipt is
|
||||||
// same claim, so one receipt is parsed once. Conversations that are not a
|
// parsed at most once across MCP hooks and Deep Assessment AfterTool.
|
||||||
// single assessment task are left unclaimed for a later chat or batch writer.
|
|
||||||
// Local tool output never reaches this hook and is still ingested by AfterTool,
|
|
||||||
// which also keeps the asset-library Signal wake.
|
|
||||||
func (h *AgentHandler) IngestMCPSurface(ctx context.Context, tool, executionID, content string) {
|
func (h *AgentHandler) IngestMCPSurface(ctx context.Context, tool, executionID, content string) {
|
||||||
if h == nil || h.db == nil || h.deepAssessments == nil || h.deepAssessmentRuntime == nil {
|
if h == nil || h.db == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
taskID, ok, err := h.db.AssessmentIDForConversation(mcp.MCPConversationIDFromContext(ctx))
|
convID := strings.TrimSpace(mcp.MCPConversationIDFromContext(ctx))
|
||||||
if err != nil || !ok {
|
if convID == "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
task, err := h.deepAssessments.Store.Get(taskID)
|
if h.deepAssessments != nil && h.deepAssessmentRuntime != nil {
|
||||||
if err != nil || task == nil {
|
taskID, ok, err := h.db.AssessmentIDForConversation(convID)
|
||||||
|
if err == nil && ok {
|
||||||
|
task, getErr := h.deepAssessments.Store.Get(taskID)
|
||||||
|
if getErr != nil || task == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !surfaceingest.Claim(executionID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ingestErr := h.deepAssessmentRuntime.ingestToolSurface(task, tool, agentruntime.ToolResult{Content: content, ExecutionID: executionID}); ingestErr != nil && h.logger != nil {
|
||||||
|
h.logger.Warn("自动写入资产库失败", zap.String("task", task.ID), zap.String("tool", tool), zap.Error(ingestErr))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tool == "create_asset" || tool == "update_asset" || tool == "delete_asset" || tool == "query_assets" || tool == "get_asset" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ownerID := ""
|
||||||
|
allowGlobal := true
|
||||||
|
if principal, hasPrincipal := authctx.PrincipalFromContext(ctx); hasPrincipal {
|
||||||
|
if !principal.HasPermission("asset:write") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ownerID = principal.UserID
|
||||||
|
allowGlobal = principal.ScopeFor("asset:write") == database.RBACScopeAll
|
||||||
|
}
|
||||||
|
projectID, err := h.db.GetConversationProjectID(convID)
|
||||||
|
if err != nil || strings.TrimSpace(projectID) == "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !surfaceingest.Claim(executionID) {
|
if !surfaceingest.Claim(executionID) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err = h.deepAssessmentRuntime.ingestToolSurface(task, tool, agentruntime.ToolResult{Content: content, ExecutionID: executionID}); err != nil && h.logger != nil {
|
if _, err := h.db.IngestBoundConversationSurface(convID, tool, content, ownerID, allowGlobal); err != nil && h.logger != nil {
|
||||||
h.logger.Warn("自动写入资产库失败", zap.String("task", task.ID), zap.String("tool", tool), zap.Error(err))
|
h.logger.Warn("对话工具输出写入项目资产库失败", zap.String("conversation", convID), zap.String("tool", tool), zap.Error(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -195,6 +195,7 @@ func TestDeepAssessmentUnassociatedProjectExtractsDeclaredTargetsAndNormalizesAs
|
||||||
func assessmentAssetRouter(h *AgentHandler, user string) *gin.Engine {
|
func assessmentAssetRouter(h *AgentHandler, user string) *gin.Engine {
|
||||||
gin.SetMode(gin.TestMode)
|
gin.SetMode(gin.TestMode)
|
||||||
router := gin.New()
|
router := gin.New()
|
||||||
|
assetHandler := NewAssetHandler(h.db, h.logger)
|
||||||
router.Use(func(c *gin.Context) {
|
router.Use(func(c *gin.Context) {
|
||||||
c.Set(security.ContextSessionKey, security.Session{
|
c.Set(security.ContextSessionKey, security.Session{
|
||||||
UserID: user,
|
UserID: user,
|
||||||
|
|
@ -206,10 +207,104 @@ func assessmentAssetRouter(h *AgentHandler, user string) *gin.Engine {
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
router.Use(security.RBACMiddleware(h.db))
|
router.Use(security.RBACMiddleware(h.db))
|
||||||
|
router.GET("/api/assets", assetHandler.List)
|
||||||
router.POST("/api/deep-assessments", h.CreateDeepAssessment)
|
router.POST("/api/deep-assessments", h.CreateDeepAssessment)
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestClassicChatPrecipitatedAssetsSyncIntoProjectScopeAndAssessment(t *testing.T) {
|
||||||
|
h, task := deepAssessmentFixture(t)
|
||||||
|
project, err := h.db.CreateProject(&database.Project{Name: "货讯通科技"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// 1. Simulate an unassigned asset created before the conversation was bound to the project.
|
||||||
|
unassigned := &database.Asset{Host: "https://portal.hxt-example.com"}
|
||||||
|
if _, err = h.db.UpsertAssets([]*database.Asset{unassigned}, task.OwnerID, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// 2. Simulate classic chat conversation bound to the project with target facts, attack-chain nodes, vulns, and tool output.
|
||||||
|
conv, err := h.db.CreateConversation("货讯通渗透", database.ConversationCreateMeta{ProjectID: project.ID})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = h.db.SetResourceOwner("conversation", conv.ID, task.OwnerID)
|
||||||
|
if _, err = h.db.UpsertProjectFact(&database.ProjectFact{
|
||||||
|
ProjectID: project.ID,
|
||||||
|
FactKey: "target/primary",
|
||||||
|
Category: "target",
|
||||||
|
Summary: "主域 hxt-example.com,发现 portal.hxt-example.com 与 api.hxt-example.com:8443",
|
||||||
|
Body: "使用 exploit.py 读取 config.json,参考 https://github.com/projectdiscovery/httpx",
|
||||||
|
Confidence: "tentative",
|
||||||
|
SourceConversationID: conv.ID,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = h.db.SaveAttackChainNode(conv.ID, "node_1", "target", "edi.hxt-example.com", "", `{"target":"https://edi.hxt-example.com/ws"}`, 0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = h.db.CreateVulnerability(&database.Vulnerability{
|
||||||
|
ConversationID: conv.ID,
|
||||||
|
ProjectID: project.ID,
|
||||||
|
Title: "订单接口越权",
|
||||||
|
Severity: "high",
|
||||||
|
Target: "https://tms.hxt-example.com/api/orders",
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Selecting the project in CreateDrawer queries GET /api/assets?project_id=...&sync_project_scope=1.
|
||||||
|
router := assessmentAssetRouter(h, task.OwnerID)
|
||||||
|
req := httptest.NewRequest("GET", "/api/assets?project_id="+project.ID+"&page=1&page_size=6&sync_project_scope=1", nil)
|
||||||
|
resp := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(resp, req)
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Fatalf("sync_project_scope status=%d body=%s", resp.Code, resp.Body.String())
|
||||||
|
}
|
||||||
|
var listed struct {
|
||||||
|
Assets []*database.Asset `json:"assets"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(resp.Body.Bytes(), &listed); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if listed.Total < 5 {
|
||||||
|
t.Fatalf("expected >=5 synced project assets, got total=%d assets=%+v", listed.Total, listed.Assets)
|
||||||
|
}
|
||||||
|
for _, want := range []string{"hxt-example.com", "portal.hxt-example.com", "api.hxt-example.com", "edi.hxt-example.com", "tms.hxt-example.com"} {
|
||||||
|
if !assetInProject(t, h.db, project.ID, want) {
|
||||||
|
t.Fatalf("expected classic chat target %s in project asset library", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, noise := range []string{"exploit.py", "config.json", "github.com"} {
|
||||||
|
if assetInProject(t, h.db, project.ID, noise) {
|
||||||
|
t.Fatalf("noise host %s leaked into project asset library", noise)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Creating the deep assessment automatically links all synced project assets.
|
||||||
|
createBody := `{"name":"货讯通深度测评","objective":"全面评估认证与越权风险","project_id":"` + project.ID + `"}`
|
||||||
|
createReq := httptest.NewRequest("POST", "/api/deep-assessments", strings.NewReader(createBody))
|
||||||
|
createReq.Header.Set("Content-Type", "application/json")
|
||||||
|
createResp := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(createResp, createReq)
|
||||||
|
if createResp.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("create deep assessment failed: %d %s", createResp.Code, createResp.Body.String())
|
||||||
|
}
|
||||||
|
var created struct {
|
||||||
|
Task deepassessment.Task `json:"task"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(createResp.Body.Bytes(), &created); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
linked := linkedAssetNames(t, h.db, created.Task.ID)
|
||||||
|
for _, want := range []string{"portal.hxt-example.com", "api.hxt-example.com", "edi.hxt-example.com", "tms.hxt-example.com"} {
|
||||||
|
if !linked[want] {
|
||||||
|
t.Fatalf("expected %s linked to deep assessment, got %v", want, linked)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func linkedAssetNames(t *testing.T, db *database.DB, taskID string) map[string]bool {
|
func linkedAssetNames(t *testing.T, db *database.DB, taskID string) map[string]bool {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
rows, err := db.Query(`SELECT COALESCE(domain,''), COALESCE(ip,''), COALESCE(host,'') FROM assets JOIN deep_assessment_assets a ON a.asset_id=assets.id WHERE a.task_id=?`, taskID)
|
rows, err := db.Query(`SELECT COALESCE(domain,''), COALESCE(ip,''), COALESCE(host,'') FROM assets JOIN deep_assessment_assets a ON a.asset_id=assets.id WHERE a.task_id=?`, taskID)
|
||||||
|
|
|
||||||
|
|
@ -721,5 +721,8 @@ func (h *ProjectHandler) PromoteAttackChain(c *gin.Context) {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if security.SessionHasPermission(c, "asset:write") {
|
||||||
|
_, _ = h.db.SyncProjectPrecipitatedAssets(projectID, session.UserID, session.ScopeFor("asset:write") == database.RBACScopeAll)
|
||||||
|
}
|
||||||
c.JSON(http.StatusOK, result)
|
c.JSON(http.StatusOK, result)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -104,6 +104,23 @@ func (s *ExecutionService) SetSurfaceIngest(fn SurfaceIngestFunc) {
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IngestCompletedSurface dispatches completed tool text (including local host tools)
|
||||||
|
// to the registered surface ingest callback when present.
|
||||||
|
func (s *ExecutionService) IngestCompletedSurface(ctx context.Context, toolName, executionID, plainText string) {
|
||||||
|
if s == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
ingest := s.surfaceIngest
|
||||||
|
s.mu.Unlock()
|
||||||
|
if ingest == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if text := strings.TrimSpace(plainText); text != "" {
|
||||||
|
ingest(ctx, toolName, executionID, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func NewExecutionService(storage MonitorStorage, logger *zap.Logger) *ExecutionService {
|
func NewExecutionService(storage MonitorStorage, logger *zap.Logger) *ExecutionService {
|
||||||
if logger == nil {
|
if logger == nil {
|
||||||
logger = zap.NewNop()
|
logger = zap.NewNop()
|
||||||
|
|
|
||||||
|
|
@ -1150,6 +1150,10 @@ func (s *Server) FinishToolExecution(ctx context.Context, executionID, toolName
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !failed && s.executionService != nil && strings.TrimSpace(resultText) != "" {
|
||||||
|
s.executionService.IngestCompletedSurface(ctx, exec.ToolName, id, resultText)
|
||||||
|
}
|
||||||
|
|
||||||
s.updateStats(exec.ToolName, exec.Status)
|
s.updateStats(exec.ToolName, exec.Status)
|
||||||
|
|
||||||
if s.storage != nil {
|
if s.storage != nil {
|
||||||
|
|
|
||||||
|
|
@ -201,7 +201,7 @@ func BuildAssetLibraryBlock(db *database.DB, projectID string, access database.R
|
||||||
b.WriteString("该项目目前没有可读资产。新发现的目标用 create_asset 写入这个项目。\n")
|
b.WriteString("该项目目前没有可读资产。新发现的目标用 create_asset 写入这个项目。\n")
|
||||||
return b.String(), nil
|
return b.String(), nil
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, "当前可读资产 %d 个。下面最多列出 12 个,其余用 query_assets 按该项目分页读取。\n", total)
|
fmt.Fprintf(&b, "当前可读资产 %d 个。下面最多列出 12 个,其余用 query_assets 按该项目分页读取;新发现的目标用 create_asset 写入这个项目。\n", total)
|
||||||
for _, asset := range assets {
|
for _, asset := range assets {
|
||||||
fmt.Fprintf(&b, "- %s\n", assetLibraryLine(asset))
|
fmt.Fprintf(&b, "- %s\n", assetLibraryLine(asset))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,304 @@
|
||||||
|
package surfaceingest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// nonTargetReferenceDomains lists external documentation, package registry,
|
||||||
|
// scanner, and OOB callback domains commonly cited in security notes or POCs
|
||||||
|
// that must never be auto-materialized as customer project assets.
|
||||||
|
var nonTargetReferenceDomains = []string{
|
||||||
|
"github.com",
|
||||||
|
"githubusercontent.com",
|
||||||
|
"gitlab.com",
|
||||||
|
"owasp.org",
|
||||||
|
"mitre.org",
|
||||||
|
"nist.gov",
|
||||||
|
"cve.org",
|
||||||
|
"portswigger.net",
|
||||||
|
"hacktricks.xyz",
|
||||||
|
"w3.org",
|
||||||
|
"xmlsoap.org",
|
||||||
|
"mozilla.org",
|
||||||
|
"googleapis.com",
|
||||||
|
"gstatic.com",
|
||||||
|
"jsdelivr.net",
|
||||||
|
"unpkg.com",
|
||||||
|
"npmjs.org",
|
||||||
|
"pypi.org",
|
||||||
|
"golang.org",
|
||||||
|
"python.org",
|
||||||
|
"dnslog.cn",
|
||||||
|
"ceye.io",
|
||||||
|
"oastify.com",
|
||||||
|
"oast.pro",
|
||||||
|
"oast.fun",
|
||||||
|
"oast.live",
|
||||||
|
"oast.me",
|
||||||
|
"oast.online",
|
||||||
|
"burpcollaborator.net",
|
||||||
|
"interact.sh",
|
||||||
|
"shodan.io",
|
||||||
|
"fofa.info",
|
||||||
|
"qianxin.com",
|
||||||
|
"360.net",
|
||||||
|
}
|
||||||
|
|
||||||
|
// ambiguousTwoLabelExtensions lists file extensions that collide with ICANN
|
||||||
|
// 2-letter/new TLDs when written bare in prose without scheme or port
|
||||||
|
// (for example "exploit.py", "run.sh", "README.md", "spac.do", "backup.zip").
|
||||||
|
var ambiguousTwoLabelExtensions = map[string]bool{
|
||||||
|
"py": true,
|
||||||
|
"sh": true,
|
||||||
|
"md": true,
|
||||||
|
"rs": true,
|
||||||
|
"pl": true,
|
||||||
|
"cc": true,
|
||||||
|
"so": true,
|
||||||
|
"do": true,
|
||||||
|
"zip": true,
|
||||||
|
"mov": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
var allowedInternalSuffixes = map[string]bool{
|
||||||
|
"test": true,
|
||||||
|
"local": true,
|
||||||
|
"internal": true,
|
||||||
|
"lan": true,
|
||||||
|
"corp": true,
|
||||||
|
"example": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
var publicResolverIPs = map[string]bool{
|
||||||
|
"8.8.8.8": true,
|
||||||
|
"8.8.4.4": true,
|
||||||
|
"1.1.1.1": true,
|
||||||
|
"1.0.0.1": true,
|
||||||
|
"114.114.114.114": true,
|
||||||
|
"223.5.5.5": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsNoiseTarget reports whether a candidate IP or domain is loopback,
|
||||||
|
// link-local/metadata, public DNS, or a known third-party reference/OOB host.
|
||||||
|
func IsNoiseTarget(ip, domain string) bool {
|
||||||
|
if ip != "" {
|
||||||
|
parsed := net.ParseIP(strings.TrimSpace(ip))
|
||||||
|
if parsed == nil ||
|
||||||
|
parsed.IsLoopback() ||
|
||||||
|
parsed.IsUnspecified() ||
|
||||||
|
parsed.IsLinkLocalUnicast() ||
|
||||||
|
parsed.IsLinkLocalMulticast() ||
|
||||||
|
parsed.IsMulticast() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if v4 := parsed.To4(); v4 != nil {
|
||||||
|
if v4[0] == 0 || v4[0] == 127 || v4[0] == 255 || (v4[0] == 169 && v4[1] == 254) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Subnet masks such as 255.255.255.0
|
||||||
|
if v4[0] >= 224 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if publicResolverIPs[parsed.String()] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if domain != "" {
|
||||||
|
lower := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
|
||||||
|
if lower == "" || lower == "localhost" || strings.HasSuffix(lower, ".localhost") || strings.HasSuffix(lower, ".invalid") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, ref := range nonTargetReferenceDomains {
|
||||||
|
if lower == ref || strings.HasSuffix(lower, "."+ref) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func validBarePrecipitatedDomain(domain string) bool {
|
||||||
|
lower := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
|
||||||
|
if lower == "" || IsNoiseTarget("", lower) || !validSurfaceDomain(lower) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
labels := strings.Split(lower, ".")
|
||||||
|
last := labels[len(labels)-1]
|
||||||
|
if len(labels) == 2 && ambiguousTwoLabelExtensions[last] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, icann := publicsuffix.PublicSuffix(lower)
|
||||||
|
if icann {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return allowedInternalSuffixes[last]
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractExplicitServiceTokens extracts only explicit http(s) URLs and host:port
|
||||||
|
// pairs from free-form prose (ignoring bare domain-like words unless seeded).
|
||||||
|
func extractExplicitServiceTokens(text string) []SurfaceHit {
|
||||||
|
if len(text) > surfaceTextLimit {
|
||||||
|
text = text[:surfaceTextLimit]
|
||||||
|
}
|
||||||
|
text = strings.ReplaceAll(text, "\r\n", "\n")
|
||||||
|
builder := &surfaceBuilder{scope: newSurfaceScope(nil, true), hits: map[string]*SurfaceHit{}}
|
||||||
|
lines := strings.Split(text, "\n")
|
||||||
|
if len(lines) > surfaceLineLimit {
|
||||||
|
lines = lines[:surfaceLineLimit]
|
||||||
|
}
|
||||||
|
for _, line := range lines {
|
||||||
|
if len(line) > 4000 {
|
||||||
|
line = line[:4000]
|
||||||
|
}
|
||||||
|
method := surfaceLineMethod(line)
|
||||||
|
urls := surfaceURLPattern.FindAllString(line, 20)
|
||||||
|
for _, raw := range urls {
|
||||||
|
raw = strings.TrimRight(raw, ".,;:")
|
||||||
|
parsed, err := url.Parse(raw)
|
||||||
|
if err != nil || parsed.Hostname() == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parsed.User = nil
|
||||||
|
scheme := strings.ToLower(parsed.Scheme)
|
||||||
|
if scheme != "http" && scheme != "https" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ip, domain, ok := classifySurfaceHost(parsed.Hostname())
|
||||||
|
if !ok || IsNoiseTarget(ip, domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if domain != "" && !validExplicitHostDomain(domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
hit := builder.add(ip, domain, scheme, surfacePort(parsed))
|
||||||
|
if path := cleanSurfacePath(parsed.EscapedPath()); path != "" && path != "/" {
|
||||||
|
builder.addEndpoint(hit, method, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stripped := surfaceURLPattern.ReplaceAllString(line, " ")
|
||||||
|
for _, match := range surfaceHostPattern.FindAllStringSubmatch(stripped, 20) {
|
||||||
|
ip, domain, ok := classifySurfaceHost(match[1])
|
||||||
|
if !ok || IsNoiseTarget(ip, domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if domain != "" && !validExplicitHostDomain(domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
port := atoiPort(match[2])
|
||||||
|
if port <= 0 || port > 65535 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
protocol := ""
|
||||||
|
if port == 443 {
|
||||||
|
protocol = "https"
|
||||||
|
} else if port == 80 {
|
||||||
|
protocol = "http"
|
||||||
|
}
|
||||||
|
builder.add(ip, domain, protocol, port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return builder.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
func validExplicitHostDomain(domain string) bool {
|
||||||
|
lower := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
|
||||||
|
if lower == "" || IsNoiseTarget("", lower) || !validSurfaceDomain(lower) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
labels := strings.Split(lower, ".")
|
||||||
|
last := labels[len(labels)-1]
|
||||||
|
_, icann := publicsuffix.PublicSuffix(lower)
|
||||||
|
return icann || allowedInternalSuffixes[last]
|
||||||
|
}
|
||||||
|
|
||||||
|
func filterStructuredHits(hits []SurfaceHit) []SurfaceHit {
|
||||||
|
out := make([]SurfaceHit, 0, len(hits))
|
||||||
|
for _, hit := range hits {
|
||||||
|
if IsNoiseTarget(hit.IP, hit.Domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if hit.Domain != "" {
|
||||||
|
if hit.Port > 0 || hit.Protocol != "" || len(hit.Endpoints) > 0 {
|
||||||
|
if !validExplicitHostDomain(hit.Domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else if !validBarePrecipitatedDomain(hit.Domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, hit)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExtractPrecipitatedTargets extracts project targets from structured target
|
||||||
|
// records (scope_json targets, target/infra facts, attack-chain target nodes,
|
||||||
|
// vulnerability targets, fact summaries) and then expands in-scope subdomains
|
||||||
|
// and endpoints across prose bodies and tool outputs without adopting unrelated
|
||||||
|
// external hosts or filename tokens.
|
||||||
|
func ExtractPrecipitatedTargets(structuredTexts, proseTexts []string, seeds, excluded []ScopeSeed) []SurfaceHit {
|
||||||
|
merged := map[string]*SurfaceHit{}
|
||||||
|
mergeHits := func(items []SurfaceHit) {
|
||||||
|
for _, item := range items {
|
||||||
|
if IsNoiseTarget(item.IP, item.Domain) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
key := item.key()
|
||||||
|
if existing := merged[key]; existing != nil {
|
||||||
|
for _, ep := range item.Endpoints {
|
||||||
|
appendSurfaceEndpoint(existing, ep)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
copyHit := item
|
||||||
|
if len(item.Endpoints) > 0 {
|
||||||
|
copyHit.Endpoints = append([]SurfaceEndpoint(nil), item.Endpoints...)
|
||||||
|
}
|
||||||
|
merged[key] = ©Hit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, text := range structuredTexts {
|
||||||
|
if strings.TrimSpace(text) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
mergeHits(filterStructuredHits(ExtractDeclaredTargets(text)))
|
||||||
|
}
|
||||||
|
for _, text := range proseTexts {
|
||||||
|
if strings.TrimSpace(text) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
mergeHits(extractExplicitServiceTokens(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
allSeeds := make([]ScopeSeed, 0, len(seeds)+len(merged))
|
||||||
|
allSeeds = append(allSeeds, seeds...)
|
||||||
|
for _, hit := range merged {
|
||||||
|
allSeeds = append(allSeeds, ScopeSeed{IP: hit.IP, Domain: hit.Domain})
|
||||||
|
}
|
||||||
|
if len(allSeeds) > 0 {
|
||||||
|
for _, text := range proseTexts {
|
||||||
|
if strings.TrimSpace(text) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
inScope, _ := ExtractSurface(text, allSeeds)
|
||||||
|
mergeHits(inScope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-run builder.finish()-style specificity collapsing: if host:443 exists,
|
||||||
|
// fold bare host:0 into host:443 so we don't create duplicate port=0 rows.
|
||||||
|
collapsed := &surfaceBuilder{scope: newSurfaceScope(nil, true), hits: map[string]*SurfaceHit{}}
|
||||||
|
for _, hit := range merged {
|
||||||
|
added := collapsed.add(hit.IP, hit.Domain, hit.Protocol, hit.Port)
|
||||||
|
for _, ep := range hit.Endpoints {
|
||||||
|
collapsed.addEndpoint(added, ep.Method, ep.Path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return WithoutExcluded(collapsed.finish(), excluded)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
package surfaceingest
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestExtractPrecipitatedTargetsFiltersNoiseAndKeepsProjectAssets(t *testing.T) {
|
||||||
|
structured := []string{
|
||||||
|
"主域名 cargosmart.com,发现子域 portal.cargosmart.com、https://api.cargosmart.com:8443/v1/auth 和后台 203.0.113.25:8080",
|
||||||
|
"脚本 exploit.py 读取 config.json、web.xml、login.jsp、spac.do,本地 127.0.0.1:4444,参考 https://github.com/projectdiscovery/httpx 与 xxx.dnslog.cn",
|
||||||
|
}
|
||||||
|
prose := []string{
|
||||||
|
"subfinder 结果:edi.cargosmart.com\nhttps://owasp.org/www-project-top-ten/\nhttp://169.254.169.254/latest/meta-data/\nhttps://admin.hxt.com.cn/console\n无关裸词 other-company.org",
|
||||||
|
}
|
||||||
|
excluded := []ScopeSeed{{Domain: "skip.cargosmart.com"}}
|
||||||
|
|
||||||
|
hits := ExtractPrecipitatedTargets(structured, prose, nil, excluded)
|
||||||
|
got := map[string]bool{}
|
||||||
|
for _, hit := range hits {
|
||||||
|
if hit.Domain != "" {
|
||||||
|
got[hit.Domain] = true
|
||||||
|
}
|
||||||
|
if hit.IP != "" {
|
||||||
|
got[hit.IP] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, want := range []string{
|
||||||
|
"cargosmart.com",
|
||||||
|
"portal.cargosmart.com",
|
||||||
|
"api.cargosmart.com",
|
||||||
|
"edi.cargosmart.com",
|
||||||
|
"admin.hxt.com.cn",
|
||||||
|
"203.0.113.25",
|
||||||
|
} {
|
||||||
|
if !got[want] {
|
||||||
|
t.Fatalf("missing expected precipitated target %s in %+v", want, hits)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, unwanted := range []string{
|
||||||
|
"exploit.py",
|
||||||
|
"config.json",
|
||||||
|
"web.xml",
|
||||||
|
"login.jsp",
|
||||||
|
"spac.do",
|
||||||
|
"127.0.0.1",
|
||||||
|
"169.254.169.254",
|
||||||
|
"github.com",
|
||||||
|
"xxx.dnslog.cn",
|
||||||
|
"owasp.org",
|
||||||
|
"other-company.org",
|
||||||
|
} {
|
||||||
|
if got[unwanted] {
|
||||||
|
t.Fatalf("noise token %s leaked into precipitated targets: %+v", unwanted, hits)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -77,7 +77,8 @@ function AssetLibraryWorkspace({ projectId, scope, projectResource, searchParams
|
||||||
const deepId = searchParams.get('id') || '';
|
const deepId = searchParams.get('id') || '';
|
||||||
const scopeQuery = useMemo(() => ({
|
const scopeQuery = useMemo(() => ({
|
||||||
project_id: projectId,
|
project_id: projectId,
|
||||||
project_unassigned: scope === 'unassigned' ? true : undefined
|
project_unassigned: scope === 'unassigned' ? true : undefined,
|
||||||
|
sync_project_scope: projectId ? 1 : undefined
|
||||||
}), [projectId, scope]);
|
}), [projectId, scope]);
|
||||||
|
|
||||||
const [filters, setFilters] = useState(() => ({
|
const [filters, setFilters] = useState(() => ({
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/** 新建深度测评表单:字段与 internal/handler/deep_assessment.go 的创建结构体一致。 */
|
/** 新建深度测评表单:字段与 internal/handler/deep_assessment.go 的创建结构体一致。 */
|
||||||
import { useCallback, useEffect, useId, useRef, useState } from 'react';
|
import { useCallback, useEffect, useId, useRef, useState } from 'react';
|
||||||
import { Banner, Button, Form, Spin, Typography } from '@douyinfe/semi-ui';
|
import { Banner, Button, Form, Spin, Tag, Typography } from '@douyinfe/semi-ui';
|
||||||
import { IconPlus } from '@douyinfe/semi-icons';
|
import { IconPlus } from '@douyinfe/semi-icons';
|
||||||
import { useAuth } from '../../lib/auth';
|
import { useAuth } from '../../lib/auth';
|
||||||
import { api } from '../../lib/http';
|
import { api } from '../../lib/http';
|
||||||
|
|
@ -59,13 +59,29 @@ function assessmentRoleOptions(raw) {
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatScopeAssetLabel(asset) {
|
||||||
|
if (!asset || typeof asset !== 'object') return '';
|
||||||
|
const base = String(asset.domain || asset.ip || asset.host || '').trim();
|
||||||
|
if (!base) return '';
|
||||||
|
const port = Number(asset.port);
|
||||||
|
const hasPortInBase = base.includes(':') && !base.startsWith('[');
|
||||||
|
if (Number.isFinite(port) && port > 0 && !hasPortInBase) {
|
||||||
|
return `${base}:${port}`;
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
function ProjectAssetScope({ projectId }) {
|
function ProjectAssetScope({ projectId }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const assets = useResource(
|
const assets = useResource(
|
||||||
() => api.get('/assets', { project_id: projectId, page: 1, page_size: 1 }),
|
() => api.get('/assets', { project_id: projectId, page: 1, page_size: 6, sync_project_scope: 1 }),
|
||||||
[projectId]
|
[projectId]
|
||||||
);
|
);
|
||||||
const total = Number.isFinite(Number(assets.data?.total)) ? Number(assets.data.total) : null;
|
const total = Number.isFinite(Number(assets.data?.total)) ? Number(assets.data.total) : null;
|
||||||
|
const factCount = Number(assets.data?.project_fact_count) || 0;
|
||||||
|
const previewLabels = (Array.isArray(assets.data?.assets) ? assets.data.assets : [])
|
||||||
|
.map(formatScopeAssetLabel)
|
||||||
|
.filter(Boolean);
|
||||||
let message = t('common.loading', null, '加载中…');
|
let message = t('common.loading', null, '加载中…');
|
||||||
if (!assets.loading && assets.error) {
|
if (!assets.loading && assets.error) {
|
||||||
message = '资产库暂时读不到。保存后仍使用该项目在资产库中的资产。';
|
message = '资产库暂时读不到。保存后仍使用该项目在资产库中的资产。';
|
||||||
|
|
@ -77,6 +93,23 @@ function ProjectAssetScope({ projectId }) {
|
||||||
return (
|
return (
|
||||||
<Form.Slot label={t('deepAssessments.assetScope', null, '资产范围')}>
|
<Form.Slot label={t('deepAssessments.assetScope', null, '资产范围')}>
|
||||||
<Typography.Text type="tertiary" role="status">{message}</Typography.Text>
|
<Typography.Text type="tertiary" role="status">{message}</Typography.Text>
|
||||||
|
{!assets.loading && !assets.error && previewLabels.length > 0 ? (
|
||||||
|
<div className="assessment-scope-preview">
|
||||||
|
{previewLabels.map(label => (
|
||||||
|
<Tag key={label} size="small" color="light-blue">{label}</Tag>
|
||||||
|
))}
|
||||||
|
{total > previewLabels.length ? (
|
||||||
|
<Tag size="small" color="grey">{`+${total - previewLabels.length}`}</Tag>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{!assets.loading && !assets.error && total === 0 && factCount > 0 ? (
|
||||||
|
<div className="assessment-scope-hint">
|
||||||
|
<Typography.Text type="tertiary" size="small">
|
||||||
|
{`该项目已有 ${factCount} 条对话沉淀事实,测评启动时会自动带入上下文。`}
|
||||||
|
</Typography.Text>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</Form.Slot>
|
</Form.Slot>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -206,6 +206,17 @@
|
||||||
padding-bottom: 0;
|
padding-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.assessment-scope-preview {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assessment-scope-hint {
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
.assessment-form-note {
|
.assessment-form-note {
|
||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1542,10 +1542,12 @@ test('deep assessment: create and select a new project without losing the draft'
|
||||||
const emptyScope = '这个项目的资产库还是空的。测评中新发现的目标会写进资产库,对话和批量任务也能看到。';
|
const emptyScope = '这个项目的资产库还是空的。测评中新发现的目标会写进资产库,对话和批量任务也能看到。';
|
||||||
mockApi.respond('GET', '/api/assets', (_, url) => ({
|
mockApi.respond('GET', '/api/assets', (_, url) => ({
|
||||||
json: {
|
json: {
|
||||||
assets: [],
|
assets: url.searchParams.get('project_id') === PROJECT.id
|
||||||
|
? [{ id: 'a1', domain: 'portal.example.com', port: 443 }, { id: 'a2', domain: 'api.example.com', port: 8443 }]
|
||||||
|
: [],
|
||||||
total: url.searchParams.get('project_id') === PROJECT.id ? 3 : 0,
|
total: url.searchParams.get('project_id') === PROJECT.id ? 3 : 0,
|
||||||
page: 1,
|
page: 1,
|
||||||
page_size: 1
|
page_size: 6
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
const main = await visit(page, 'deep-assessments');
|
const main = await visit(page, 'deep-assessments');
|
||||||
|
|
@ -1566,7 +1568,13 @@ test('deep assessment: create and select a new project without losing the draft'
|
||||||
await page.getByRole('option').filter({ hasText: PROJECT.name }).click();
|
await page.getByRole('option').filter({ hasText: PROJECT.name }).click();
|
||||||
await expect(collectionSelect).toHaveCount(0);
|
await expect(collectionSelect).toHaveCount(0);
|
||||||
await expect(drawer.getByRole('status')).toHaveText(sharedScope);
|
await expect(drawer.getByRole('status')).toHaveText(sharedScope);
|
||||||
expect(mockApi.calls('GET', '/api/assets').some(call => new URLSearchParams(call.query).get('project_id') === PROJECT.id)).toBe(true);
|
await expect(drawer.locator('.assessment-scope-preview')).toContainText('portal.example.com:443');
|
||||||
|
await expect(drawer.locator('.assessment-scope-preview')).toContainText('api.example.com:8443');
|
||||||
|
await expect(drawer.locator('.assessment-scope-preview')).toContainText('+1');
|
||||||
|
expect(mockApi.calls('GET', '/api/assets').some(call => {
|
||||||
|
const q = new URLSearchParams(call.query);
|
||||||
|
return q.get('project_id') === PROJECT.id && q.get('sync_project_scope') === '1';
|
||||||
|
})).toBe(true);
|
||||||
expect(mockApi.calls('GET', '/api/assets/collections')).toEqual([]);
|
expect(mockApi.calls('GET', '/api/assets/collections')).toEqual([]);
|
||||||
await createProject.click();
|
await createProject.click();
|
||||||
await expect(projectDrawer).toBeVisible();
|
await expect(projectDrawer).toBeVisible();
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
||||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,Pt as s,R as c,U as l,ft as u,i as d,lt as f,ut as p}from"./semi-65W_4I1v.js";import{F as m,I as h,L as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-DNMXun-U.js";var k=e(t(),1),A=e(n(),1),{Text:j}=r;function M(){let e=m(),{hasPermission:t}=h(),n=t(`agents:write`),r=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>g.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await g.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await g.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await g.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(c,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(u,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),r&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(a,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(l,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(d,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(d.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(d.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(d.Input,{field:`description`,label:`描述`}),(0,A.jsx)(d.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(d.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(d.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,Pt as s,R as c,U as l,ft as u,i as d,lt as f,ut as p}from"./semi-65W_4I1v.js";import{F as m,I as h,L as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-C6SML8F9.js";var k=e(t(),1),A=e(n(),1),{Text:j}=r;function M(){let e=m(),{hasPermission:t}=h(),n=t(`agents:write`),r=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>g.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await g.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await g.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await g.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(c,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(u,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),r&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(a,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(l,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(d,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(d.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(d.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(d.Input,{field:`description`,label:`描述`}),(0,A.jsx)(d.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(d.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(d.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
||||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,R as r}from"./semi-65W_4I1v.js";import{A as i,E as a,F as o}from"./index-DNMXun-U.js";import"./c2-shared-2EAlkwn6.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=t,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:t,ns:i=`tasks`}){let a=o();return(0,c.jsxs)(n,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:a(`c2.tasks.timePresets`,null,`快捷`)}),v.map(n=>(0,c.jsx)(r,{size:`small`,theme:n.value===e?`solid`:`borderless`,type:n.value===e?`primary`:`tertiary`,onClick:()=>t(n.value),children:a(`c2.${i}.preset${n.value===`all`?`All`:n.value}`,null,n.label)},n.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=o();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:a(e),children:i(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,R as r}from"./semi-65W_4I1v.js";import{A as i,E as a,F as o}from"./index-C6SML8F9.js";import"./c2-shared-u6LJyEH4.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=t,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:t,ns:i=`tasks`}){let a=o();return(0,c.jsxs)(n,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:a(`c2.tasks.timePresets`,null,`快捷`)}),v.map(n=>(0,c.jsx)(r,{size:`small`,theme:n.value===e?`solid`:`borderless`,type:n.value===e?`primary`:`tertiary`,onClick:()=>t(n.value),children:a(`c2.${i}.preset${n.value===`all`?`All`:n.value}`,null,n.label)},n.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=o();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:a(e),children:i(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||||
|
|
@ -1 +1 @@
|
||||||
import{L as e,R as t}from"./index-DNMXun-U.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
import{L as e,R as t}from"./index-C6SML8F9.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
||||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,R as s,U as c,lt as l,ut as u}from"./semi-65W_4I1v.js";import{E as d,F as f,I as p,L as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-DNMXun-U.js";var T=e(t(),1),E=e(n(),1),{Text:D}=r;function O(){let e=f(),{hasPermission:t}=p(),n=t(`knowledge:delete`),[r,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>m.get(`/knowledge/retrieval-logs`,{conversationId:r||void 0,limit:k}),[r,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await m.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(s,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(a,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(c,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:r,onChange:O,style:{width:260}}),(0,E.jsx)(c,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,R as s,U as c,lt as l,ut as u}from"./semi-65W_4I1v.js";import{E as d,F as f,I as p,L as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-C6SML8F9.js";var T=e(t(),1),E=e(n(),1),{Text:D}=r;function O(){let e=f(),{hasPermission:t}=p(),n=t(`knowledge:delete`),[r,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>m.get(`/knowledge/retrieval-logs`,{conversationId:r||void 0,limit:k}),[r,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await m.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(s,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(a,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(c,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:r,onChange:O,style:{width:260}}),(0,E.jsx)(c,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
||||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,i}from"./semi-65W_4I1v.js";import{F as a,L as o,c as s,l as c,x as l}from"./index-DNMXun-U.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=a(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await o.put(`/projects/${t.id}`,n):await o.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,i}from"./semi-65W_4I1v.js";import{F as a,L as o,c as s,l as c,x as l}from"./index-C6SML8F9.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=a(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await o.put(`/projects/${t.id}`,n):await o.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,4 +1,4 @@
|
||||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,g as r,t as i,y as a}from"./react-QV7DAAIx.js";import{$ as o,B as s,Ft as c,G as l,I as u,L as d,N as f,R as p,S as m,U as h,c as g,d as _,g as v,h as y,j as ee,k as b,lt as x,m as S,on as C,p as w,s as T,ut as E,y as D}from"./semi-65W_4I1v.js";import{D as O,E as k,F as te,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as R,a as z,b as ne,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as G,u as K,x as ae,y as oe,z as se}from"./index-DNMXun-U.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function Y(e){return JSON.stringify(String(e))}function me(e){let t=String(e);return pe(t)?t:Y(t)}function he(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):Y(String(e));let t=String(e);return pe(t)?t:Y(t)}function ge(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function _e(e,t,n,r){let i=` `.repeat(n),a=me(e);if(ge(t))r.push(`${i}${a}: ${he(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),be(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ve(t,n+2,r)):r.push(`${i}${a}: {}`)}function ve(e,t,n){for(let[r,i]of Object.entries(e))_e(r,i,t,n)}function ye(e,t,n){let r=` `.repeat(t);if(ge(e)){n.push(`${r}- ${he(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),be(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);ge(o)?n.push(`${r}- ${me(a)}: ${he(o)}`):(n.push(`${r}-`),_e(a,o,t+2,n));for(let[e,r]of s)_e(e,r,t+2,n)}function be(e,t,n){for(let r of e)ye(r,t,n)}function xe(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,g as r,t as i,y as a}from"./react-QV7DAAIx.js";import{$ as o,B as s,Ft as c,G as l,I as u,L as d,N as f,R as p,S as m,U as h,c as g,d as _,g as v,h as y,j as ee,k as b,lt as x,m as S,on as C,p as w,s as T,ut as E,y as D}from"./semi-65W_4I1v.js";import{D as O,E as k,F as te,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as R,a as z,b as ne,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as G,u as K,x as ae,y as oe,z as se}from"./index-C6SML8F9.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function Y(e){return JSON.stringify(String(e))}function me(e){let t=String(e);return pe(t)?t:Y(t)}function he(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):Y(String(e));let t=String(e);return pe(t)?t:Y(t)}function ge(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function _e(e,t,n,r){let i=` `.repeat(n),a=me(e);if(ge(t))r.push(`${i}${a}: ${he(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),be(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ve(t,n+2,r)):r.push(`${i}${a}: {}`)}function ve(e,t,n){for(let[r,i]of Object.entries(e))_e(r,i,t,n)}function ye(e,t,n){let r=` `.repeat(t);if(ge(e)){n.push(`${r}- ${he(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),be(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);ge(o)?n.push(`${r}- ${me(a)}: ${he(o)}`):(n.push(`${r}-`),_e(a,o,t+2,n));for(let[e,r]of s)_e(e,r,t+2,n)}function be(e,t,n){for(let r of e)ye(r,t,n)}function xe(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
||||||
`).split(`
|
`).split(`
|
||||||
`))n.push(`# ${e}`.trimEnd());n.length&&n.push(``)}return ge(e)?(n.push(he(e)),`${n.join(`
|
`))n.push(`# ${e}`.trimEnd());n.length&&n.push(``)}return ge(e)?(n.push(he(e)),`${n.join(`
|
||||||
`)}\n`):Array.isArray(e)?(e.length?be(e,0,n):n.push(`[]`),`${n.join(`
|
`)}\n`):Array.isArray(e)?(e.length?be(e,0,n):n.push(`[]`),`${n.join(`
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
||||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,Lt as r,R as i,ut as a}from"./semi-65W_4I1v.js";import{D as o,F as s,I as c,L as l,O as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-DNMXun-U.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=t;function S(){let e=s(),{hasPermission:t}=c(),y=t(`skills:delete`),S=f(()=>l.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await l.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await l.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(i,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(i,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:u(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(i,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(r,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,Lt as r,R as i,ut as a}from"./semi-65W_4I1v.js";import{D as o,F as s,I as c,L as l,O as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-C6SML8F9.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=t;function S(){let e=s(),{hasPermission:t}=c(),y=t(`skills:delete`),S=f(()=>l.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await l.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await l.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(i,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(i,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:u(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(i,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(r,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -18,7 +18,7 @@
|
||||||
} catch (error) { /* first paint fallback */ }
|
} catch (error) { /* first paint fallback */ }
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<script type="module" crossorigin src="/static/app/assets/index-DNMXun-U.js"></script>
|
<script type="module" crossorigin src="/static/app/assets/index-C6SML8F9.js"></script>
|
||||||
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
|
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
|
||||||
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
|
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
|
||||||
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-65W_4I1v.js">
|
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-65W_4I1v.js">
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue