Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Introduce agent-side synchronization of gateway configuration (rules, proxies, providers) for Clash and Surge.

luoleie9a9d1127dc4
diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.go
index ba021a8..d308b55 100644
--- a/apps/agent/internal/agent/runner.go
+++ b/apps/agent/internal/agent/runner.go
@@ -3,6 +3,7 @@ package agent
import (
"bytes"
"context"
+ "crypto/md5"
"encoding/json"
"fmt"
"io"
@@ -43,6 +44,12 @@ type heartbeatPayload struct {
GatewayURL string `json:"gatewayUrl,omitempty"`
}
+type configPayload struct {
+ BackendID int `json:"backendId"`
+ AgentID string `json:"agentId"`
+ Config *domain.GatewayConfigSnapshot `json:"config"`
+}
+
type Runner struct {
cfg config.Config
httpClient *http.Client
@@ -53,6 +60,8 @@ type Runner struct {
queue []domain.TrafficUpdate
flows map[string]trackedFlow
dropped int64
+
+ lastConfigHash string
}
func NewRunner(cfg config.Config) *Runner {
@@ -76,10 +85,11 @@ func (r *Runner) Run(ctx context.Context) {
log.Printf("[agent:%s] starting, backend=%d, gateway_type=%s, server=%s", r.cfg.AgentID, r.cfg.BackendID, r.cfg.GatewayType, r.cfg.ServerAPIBase)
var wg sync.WaitGroup
- wg.Add(3)
+ wg.Add(4)
go r.runCollectorLoop(ctx, &wg)
go r.runReportLoop(ctx, &wg)
go r.runHeartbeatLoop(ctx, &wg)
+ go r.runConfigSyncLoop(ctx, &wg)
<-ctx.Done()
log.Printf("[agent:%s] stopping...", r.cfg.AgentID)
@@ -163,6 +173,61 @@ func (r *Runner) runHeartbeatLoop(ctx context.Context, wg *sync.WaitGroup) {
}
}
+func (r *Runner) runConfigSyncLoop(ctx context.Context, wg *sync.WaitGroup) {
+ defer wg.Done()
+
+ // Initial sync immediately
+ if err := r.syncConfig(ctx); err != nil {
+ log.Printf("[agent:%s] init config sync error: %v", r.cfg.AgentID, err)
+ }
+
+ // Then every 5 minutes (or reuse heartbeat interval)
+ ticker := time.NewTicker(2 * time.Minute)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if err := r.syncConfig(ctx); err != nil {
+ log.Printf("[agent:%s] config sync error: %v", r.cfg.AgentID, err)
+ }
+ }
+ }
+}
+
+func (r *Runner) syncConfig(ctx context.Context) error {
+ snap, err := r.gatewayClient.GetConfigSnapshot(ctx)
+ if err != nil {
+ return err
+ }
+
+ // Calculate a simple hash to avoid sending if unmodified
+ data, _ := json.Marshal(snap)
+ hash := fmt.Sprintf("%x", md5.Sum(data))
+ if hash == r.lastConfigHash {
+ return nil
+ }
+ snap.Hash = hash
+ snap.Timestamp = time.Now().UnixMilli()
+
+ payload := configPayload{
+ BackendID: r.cfg.BackendID,
+ AgentID: r.cfg.AgentID,
+ Config: snap,
+ }
+
+ if err := r.postJSON(ctx, "/agent/config", payload); err != nil {
+ return err
+ }
+
+ r.mu.Lock()
+ r.lastConfigHash = hash
+ r.mu.Unlock()
+ return nil
+}
+
func (r *Runner) ingestSnapshots(snapshots []domain.FlowSnapshot, nowMs int64) {
active := make(map[string]struct{}, len(snapshots))
updates := make([]domain.TrafficUpdate, 0, len(snapshots))
diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.go
index b1ace3a..0007723 100644
--- a/apps/agent/internal/config/config.go
+++ b/apps/agent/internal/config/config.go
@@ -181,11 +181,7 @@ func normalizeGatewayEndpoint(gatewayType, raw string) string {
if gatewayType == "clash" {
trimmed = strings.Replace(trimmed, "ws://", "http://", 1)
trimmed = strings.Replace(trimmed, "wss://", "https://", 1)
- trimmed = strings.TrimSuffix(trimmed, "/connections")
- return trimmed + "/connections"
+ return strings.TrimSuffix(trimmed, "/connections")
}
- if strings.HasSuffix(trimmed, "/v1/requests/recent") {
- return trimmed
- }
- return trimmed + "/v1/requests/recent"
+ return strings.TrimSuffix(trimmed, "/v1/requests/recent")
}
diff --git a/apps/agent/internal/domain/config.go b/apps/agent/internal/domain/config.go
new file mode 100644
index 0000000..7216ad3
--- /dev/null
+++ b/apps/agent/internal/domain/config.go
@@ -0,0 +1,28 @@
+package domain
+
+type GatewayRule struct {
+ Type string `json:"type"`
+ Payload string `json:"payload"`
+ Proxy string `json:"proxy"`
+ Raw string `json:"raw,omitempty"`
+}
+
+type GatewayProxy struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Now string `json:"now,omitempty"`
+}
+
+type GatewayProvider struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Proxies []GatewayProxy `json:"proxies"`
+}
+
+type GatewayConfigSnapshot struct {
+ Rules []GatewayRule `json:"rules"`
+ Proxies map[string]GatewayProxy `json:"proxies"`
+ Providers map[string]GatewayProvider `json:"providers"`
+ Timestamp int64 `json:"timestamp"`
+ Hash string `json:"hash"`
+}
diff --git a/apps/agent/internal/gateway/client.go b/apps/agent/internal/gateway/client.go
index 944f8a4..7ca5cab 100644
--- a/apps/agent/internal/gateway/client.go
+++ b/apps/agent/internal/gateway/client.go
@@ -168,7 +168,7 @@ type surgeRequestsResponse struct {
}
func (c *Client) collectClash(ctx context.Context) ([]domain.FlowSnapshot, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint+"/connections", nil)
if err != nil {
return nil, err
}
@@ -222,7 +222,7 @@ func (c *Client) collectClash(ctx context.Context) ([]domain.FlowSnapshot, error
}
func (c *Client) collectSurge(ctx context.Context) ([]domain.FlowSnapshot, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint+"/v1/requests/recent", nil)
if err != nil {
return nil, err
}
diff --git a/apps/agent/internal/gateway/config.go b/apps/agent/internal/gateway/config.go
new file mode 100644
index 0000000..54b84ad
--- /dev/null
+++ b/apps/agent/internal/gateway/config.go
@@ -0,0 +1,192 @@
+package gateway
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+
+ "github.com/foru17/neko-master/apps/agent/internal/domain"
+)
+
+func (c *Client) GetConfigSnapshot(ctx context.Context) (*domain.GatewayConfigSnapshot, error) {
+ if c.gatewayType == "clash" {
+ return c.getClashConfig(ctx)
+ }
+ return c.getSurgeConfig(ctx)
+}
+
+func (c *Client) getJSON(ctx context.Context, path string, out interface{}) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint+path, nil)
+ if err != nil {
+ return err
+ }
+ if c.token != "" {
+ if c.gatewayType == "surge" {
+ req.Header.Set("X-Key", c.token)
+ } else {
+ req.Header.Set("Authorization", "Bearer "+c.token)
+ }
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
+ return fmt.Errorf("gateway %s returned %d: %s", path, resp.StatusCode, string(msg))
+ }
+
+ return json.NewDecoder(resp.Body).Decode(out)
+}
+
+func (c *Client) getClashConfig(ctx context.Context) (*domain.GatewayConfigSnapshot, error) {
+ var rulesData struct {
+ Rules []struct {
+ Type string `json:"type"`
+ Payload string `json:"payload"`
+ Proxy string `json:"proxy"`
+ } `json:"rules"`
+ }
+ if err := c.getJSON(ctx, "/rules", &rulesData); err != nil {
+ return nil, fmt.Errorf("clash /rules error: %w", err)
+ }
+
+ var proxiesData struct {
+ Proxies map[string]struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Now string `json:"now"`
+ } `json:"proxies"`
+ }
+ if err := c.getJSON(ctx, "/proxies", &proxiesData); err != nil {
+ return nil, fmt.Errorf("clash /proxies error: %w", err)
+ }
+
+ var providersData struct {
+ Providers map[string]struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Proxies []struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Now string `json:"now"`
+ } `json:"proxies"`
+ } `json:"providers"`
+ }
+ if err := c.getJSON(ctx, "/providers/proxies", &providersData); err != nil {
+ fmt.Printf("[agent] warning: /providers/proxies not available: %v\n", err)
+ }
+
+ snap := &domain.GatewayConfigSnapshot{
+ Rules: make([]domain.GatewayRule, len(rulesData.Rules)),
+ Proxies: make(map[string]domain.GatewayProxy),
+ Providers: make(map[string]domain.GatewayProvider),
+ }
+
+ for i, r := range rulesData.Rules {
+ snap.Rules[i] = domain.GatewayRule{
+ Type: r.Type,
+ Payload: r.Payload,
+ Proxy: r.Proxy,
+ }
+ }
+
+ for k, p := range proxiesData.Proxies {
+ snap.Proxies[k] = domain.GatewayProxy{
+ Name: p.Name,
+ Type: p.Type,
+ Now: p.Now,
+ }
+ }
+
+ for k, v := range providersData.Providers {
+ proxies := make([]domain.GatewayProxy, len(v.Proxies))
+ for i, p := range v.Proxies {
+ proxies[i] = domain.GatewayProxy{
+ Name: p.Name,
+ Type: p.Type,
+ Now: p.Now,
+ }
+ }
+ snap.Providers[k] = domain.GatewayProvider{
+ Name: v.Name,
+ Type: v.Type,
+ Proxies: proxies,
+ }
+ }
+
+ return snap, nil
+}
+
+func parseSurgeRuleForAgent(raw string) domain.GatewayRule {
+ // Basic Surge parsing logic. For agent, returning "raw" is often enough as backend parses it.
+ // However master expects { type, payload, proxy } if we can parse it.
+ // But since Master's app.ts does `parseSurgeRule(raw)`, we actually don't need to parse it perfectly here on Agent.
+ // Wait, the master expects:
+ // parsedRules = data.rules.map(raw => {
+ // const parsed = parseSurgeRule(raw);
+ // return parsed ? { type: parsed.type, payload: parsed.payload, policy: parsed.policy, raw } : null;
+ // })
+ // We can just set type: "Surge", raw: raw, but it's better to let master do it, or do it here.
+ // The master's app.ts (modified earlier) uses rules cached and returns them directly:
+ // return { rules: cached.rules || [], _source: 'agent-cache' };
+ // And note that Master's GET /api/gateway/rules for Surge usually parses and returns { type, payload, proxy }.
+ return domain.GatewayRule{
+ Raw: raw,
+ }
+}
+
+func (c *Client) getSurgeConfig(ctx context.Context) (*domain.GatewayConfigSnapshot, error) {
+ var rulesData struct {
+ Rules []string `json:"rules"`
+ }
+ if err := c.getJSON(ctx, "/v1/rules", &rulesData); err != nil {
+ return nil, fmt.Errorf("surge /v1/rules error: %w", err)
+ }
+
+ var policiesData struct {
+ PolicyGroups []string `json:"policy-groups"`
+ Proxies []string `json:"proxies"`
+ }
+ if err := c.getJSON(ctx, "/v1/policies", &policiesData); err != nil {
+ return nil, fmt.Errorf("surge /v1/policies error: %w", err)
+ }
+
+ snap := &domain.GatewayConfigSnapshot{
+ Rules: make([]domain.GatewayRule, len(rulesData.Rules)),
+ Proxies: make(map[string]domain.GatewayProxy),
+ Providers: make(map[string]domain.GatewayProvider),
+ }
+
+ for i, raw := range rulesData.Rules {
+ snap.Rules[i] = parseSurgeRuleForAgent(raw)
+ }
+
+ for _, p := range policiesData.Proxies {
+ snap.Proxies[p] = domain.GatewayProxy{
+ Name: p,
+ Type: "Proxy",
+ }
+ }
+
+ for _, g := range policiesData.PolicyGroups {
+ var groupDetail struct {
+ Type string `json:"type"`
+ Policy string `json:"policy"`
+ }
+ _ = c.getJSON(ctx, "/v1/policies/"+url.PathEscape(g), &groupDetail)
+ snap.Proxies[g] = domain.GatewayProxy{
+ Name: g,
+ Type: groupDetail.Type,
+ Now: groupDetail.Policy,
+ }
+ }
+
+ return snap, nil
+}
diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.ts
index eb00d5c..d346af9 100644
--- a/apps/collector/src/modules/app/app.ts
+++ b/apps/collector/src/modules/app/app.ts
@@ -58,6 +58,18 @@ type AgentTrafficUpdatePayload = {
timestampMs?: number;
};
+type AgentConfigPayload = {
+ backendId?: number | string;
+ agentId?: string;
+ config: {
+ rules: Array<{ type: string; payload: string; proxy: string; raw?: string }>;
+ proxies: Record<string, { name: string; type: string; now?: string }>;
+ providers: Record<string, { proxies: Array<{ name: string; type: string; now?: string }> }>;
+ timestamp: number;
+ hash: string;
+ };
+};
+
type AgentHeartbeatPayload = {
backendId?: number;
agentId?: string;
@@ -580,6 +592,32 @@ export async function createApp(options: AppOptions) {
};
});
+ app.post('/api/agent/config', async (request, reply) => {
+ const body = request.body as AgentConfigPayload;
+ const backendId = parseBackendId(body?.backendId);
+ if (backendId === null) {
+ return reply.status(400).send({ error: 'Invalid backendId' });
+ }
+ if (!isAgentBackendAuthorized(backendId, request, reply)) {
+ return;
+ }
+ const agentId = parseAgentId(body.agentId);
+ if (!agentId) {
+ return reply.status(400).send({ error: 'Invalid agentId' });
+ }
+ if (!isAgentBindingAllowed(backendId, agentId, reply)) {
+ return;
+ }
+
+ if (!body.config) {
+ return reply.status(400).send({ error: 'Missing config payload' });
+ }
+
+ realtimeStore.setAgentConfig(backendId, body.config);
+
+ return { success: true, backendId, hash: body.config.hash };
+ });
+
// Compatibility routes: Gateway APIs
app.get('/api/gateway/proxies', async (request, reply) => {
const backendId = getBackendIdFromQuery(request.query as Record<string, unknown>);
@@ -592,7 +630,11 @@ export async function createApp(options: AppOptions) {
return reply.status(404).send({ error: 'Backend not found' });
}
if (isAgentBackendUrl(backend.url)) {
- return reply.status(400).send({ error: 'Agent mode backend does not support gateway passthrough APIs' });
+ const cached = realtimeStore.getAgentConfig(backendId);
+ if (!cached) {
+ return reply.status(503).send({ error: 'Agent config not yet synced' });
+ }
+ return { proxies: cached.proxies || {}, _source: 'agent-cache' };
}
const gatewayBaseUrl = getGatewayBaseUrl(backend.url);
@@ -677,7 +719,11 @@ export async function createApp(options: AppOptions) {
return reply.status(404).send({ error: 'Backend not found' });
}
if (isAgentBackendUrl(backend.url)) {
- return reply.status(400).send({ error: 'Agent mode backend does not support gateway passthrough APIs' });
+ const cached = realtimeStore.getAgentConfig(backendId);
+ if (!cached) {
+ return reply.status(503).send({ error: 'Agent config not yet synced' });
+ }
+ return { providers: cached.providers || {}, proxies: cached.proxies || {}, _source: 'agent-cache' };
}
const gatewayBaseUrl = getGatewayBaseUrl(backend.url);
@@ -850,7 +896,20 @@ export async function createApp(options: AppOptions) {
return reply.status(404).send({ error: 'Backend not found' });
}
if (isAgentBackendUrl(backend.url)) {
- return reply.status(400).send({ error: 'Agent mode backend does not support gateway passthrough APIs' });
+ const cached = realtimeStore.getAgentConfig(backendId);
+ if (!cached) {
+ return reply.status(503).send({ error: 'Agent config not yet synced' });
+ }
+
+ if (backend.type === 'surge') {
+ const parsedRules = (cached.rules || [])
+ .map(r => r.raw ? parseSurgeRule(r.raw) : null)
+ .filter((r): r is NonNullable<typeof r> => r !== null)
+ .map(r => ({ type: r.type, payload: r.payload, proxy: r.policy, size: 0 }));
+ return { rules: parsedRules, _source: 'agent-cache' };
+ }
+
+ return { rules: cached.rules || [], _source: 'agent-cache' };
}
const gatewayBaseUrl = getGatewayBaseUrl(backend.url);
@@ -948,6 +1007,7 @@ export async function createApp(options: AppOptions) {
'/api/auth/logout', // Add logout as public so we can clear cookies even if invalid
'/api/agent/heartbeat',
'/api/agent/report',
+ '/api/agent/config',
];
// Check if route is public
diff --git a/apps/collector/src/modules/realtime/realtime.store.ts b/apps/collector/src/modules/realtime/realtime.store.ts
index e32d4ad..df552d7 100644
--- a/apps/collector/src/modules/realtime/realtime.store.ts
+++ b/apps/collector/src/modules/realtime/realtime.store.ts
@@ -206,7 +206,16 @@ function sortIPs(data: IPStats[], sortBy: string, sortOrder: 'asc' | 'desc'): IP
});
}
+export type AgentGatewayConfig = {
+ rules: Array<{ type: string; payload: string; proxy: string; raw?: string }>;
+ proxies: Record<string, { name: string; type: string; now?: string }>;
+ providers: Record<string, { proxies: Array<{ name: string; type: string; now?: string }> }>;
+ timestamp: number;
+ hash: string;
+};
+
export class RealtimeStore {
+ private agentConfigByBackend = new Map<number, AgentGatewayConfig>();
public summaryByBackend = new Map<number, SummaryDelta>();
public minuteByBackend = new Map<number, Map<string, MinuteBucket>>();
public domainByBackend = new Map<number, Map<string, DomainDelta>>();
@@ -230,6 +239,14 @@ export class RealtimeStore {
this.maxMinutes = Number.isFinite(maxMinutes) ? Math.max(30, maxMinutes) : 180;
}
+ setAgentConfig(backendId: number, config: AgentGatewayConfig): void {
+ this.agentConfigByBackend.set(backendId, config);
+ }
+
+ getAgentConfig(backendId: number): AgentGatewayConfig | undefined {
+ return this.agentConfigByBackend.get(backendId);
+ }
+
recordTraffic(
backendId: number,
meta: TrafficMeta,
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index 678f9e7..29d14ad 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -167,7 +167,7 @@ export interface GatewayRule {
export interface GatewayRulesResponse {
rules: GatewayRule[];
// Surge specific fields
- _source?: 'surge' | 'clash';
+ _source?: 'surge' | 'clash' | 'agent-cache';
_availablePolicies?: string[];
}