mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-26 18:00:54 +08:00
Merge remote-tracking branch 'upstream/main' into codex/s3-archive-server
This commit is contained in:
@@ -1,2 +1,5 @@
|
||||
*.bat text eol=crlf
|
||||
*.sh text eol=lf
|
||||
scripts/poc/ export-ignore
|
||||
skills/edr-bypass-re/ export-ignore
|
||||
skills/php2shell/ export-ignore
|
||||
|
||||
@@ -71,7 +71,7 @@ jobs:
|
||||
ARTEX_PG_DSN: postgres://artex:testpass@localhost:5432/artextest_race?sslmode=disable
|
||||
|
||||
run: >-
|
||||
go test -race -p 1 ./agent ./cmd/artex ./config ./db ./evidence ./guard
|
||||
go test -race -p 1 ./agent ./archivestore ./cmd/artex ./config ./db ./evidence ./guard
|
||||
./intercept ./llmpool ./llmrec ./mcphttp ./notify ./server ./sidequestion
|
||||
./traffic ./traffic/rewrite
|
||||
|
||||
@@ -149,6 +149,7 @@ jobs:
|
||||
- run: npm run test:polling
|
||||
- run: npm run test:replay
|
||||
- run: npm run test:upload
|
||||
- run: npm run test:i18n
|
||||
- run: npm run build:static
|
||||
|
||||
python:
|
||||
|
||||
@@ -26,6 +26,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
- **Capture-proxy rewrite rules, storage and API**: `GET`, `POST`, `PUT` and `DELETE /api/traffic/rewrite-rules` and `POST /api/traffic/rewrite-rules/{id}/toggle` manage rules that match a request or a response (method, host, URL, headers, body, status) and describe a rewrite (method, path and query, headers, body, status). Rules are validated on save, limited to 100 of which 50 enabled, created disabled, and stored in the new table `traffic_rewrite_rules` (migration `0005_traffic_rewrite_rules.sql`) with `matchers` and `actions` encrypted at rest. The value of an action marked `sensitive` is never returned, and an update sent without it keeps the stored one. The server compiles the enabled rules at startup and after every change and hands the snapshot to the proxy. The proxy applies them from the next entry. See `docs/traffic-rewrite-rules.md`.
|
||||
- **Capture-proxy rewrite rules applied**: the capture proxy applies enabled rules to each HTTP request before it is sent to the target and to each response before it reaches the client. Each action that ran is recorded in the new table `exchange_rewrites` in the same transaction as the exchange, `traffic_get` shows a `REWRITTEN` line, and `traffic_search` never finds a value a rule wrote. SSE status and headers are rewritten at the start of the stream. **WebSocket handshakes are not rewritten**: the capture library runs its hook after the upgrade, so the status and headers cannot be changed, and frames pass unchanged. **Responses of 5 MiB or more** are forwarded unchanged and not recorded in full, because the library does not call the response hook for them. Snapshots of original requests are capped at 1024 entries and 64 MiB. Replays go through the proxy, so the rules apply to them. Archives, a per-replay rule toggle, the web UI and the proof flag come later.
|
||||
- **Bulk finding status** (#298): select findings in the findings table and apply one disposition to all of them, up to 500 per call, in one transaction; each row still goes through the single-decision notification semantics and the change is mirrored onto its exploration node (#289).
|
||||
- **Stream message direction filter** (#379): `GET /api/traffic/stream` and the `traffic_messages` agent tool take an optional `direction` (`c2s` or `s2c`) that lists only one side of a WebSocket or SSE conversation. `total` and `offset` apply to the filtered list, each row keeps its `seq` in the whole stream, and the `meta` row (messages dropped past the recorder limits) stays in a filtered page. Any other value is a 400 (API) or a tool error.
|
||||
- **Traffic replay** (#266): replay a recorded request from the traffic detail with its method, URL, headers and stored body; replay is disabled when only the body preview is loaded.
|
||||
- **Finding proof strength in reports** (#268): the Markdown report and the export show each finding's proof strength next to its verification status.
|
||||
- **Opt-in Keenable web search backend** (#295): the search tool gains Keenable alongside Brave and Tavily; the key is stored encrypted and can be cleared independently.
|
||||
@@ -49,6 +50,15 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Workspace and skill symlink confinement**: workspace file operations, the skill file APIs and the skill loader resolve symlinks in every path component and refuse a target outside their root, so a link planted in the workspace or a skill directory cannot expose another file.
|
||||
- **Target gate behind proxies**: a target approval is name-only whenever a proxy is in the path, including the recording proxy, the global egress proxy and a custom tool's own proxy, so the gate never claims an IP binding the proxy does not enforce.
|
||||
- **Remote MCP response bound**: Streamable HTTP JSON-RPC bodies and SSE data payloads are refused above 8 MiB, so a remote MCP server cannot force an unbounded decode.
|
||||
- **LLM response capture bound**: each recorded provider attempt keeps at most 1 MiB, and a call keeps at most 8 attempts, so a large or retrying stream cannot grow the recorder without bound. The live stream is unchanged.
|
||||
- **Intercept audit ring**: `preToolUse` records allow only after intercept and the target gate decide, so a blocked call no longer leaves a leftover allow row in `Guard.Audit()`.
|
||||
- **DSN password redaction**: `config.Redact` now masks libpq `password=` keywords and `?password=` query values as well as URL userinfo, so a ping-failure log cannot print the database password.
|
||||
- **Asset DSL nesting**: `ParseDSL` refuses queries longer than 4 KiB or nested more than 32 parentheses deep, so a crafted `dsl` cannot grow the goroutine stack without bound.
|
||||
- **Retry-After overflow**: a 429/503 `Retry-After` of huge seconds no longer wraps `time.Duration` into a tiny delay. Values above `MaxDelay` are not retried.
|
||||
- **Conversation message pages**: `GET /api/conversations/{id}/messages` clamps `limit` (200 for history, 1000 for `?since=`), so a huge query cannot load the whole transcript in one response.
|
||||
- **Findings CSV formula cells**: `FindingsCSV` prefixes name, class, summary, task, and other text fields that start with `=`, `+`, `-`, `@`, tab, or CR so Excel/LibreOffice do not evaluate them as formulas when the export is opened.
|
||||
- **Asset service links**: the Services tab only uses an asset URL as `href` when it is `http:` or `https:`. `javascript:`, `data:`, and other schemes render as text.
|
||||
- **Chat session directories**: `ChatAgent.Chat` accepts only `[A-Za-z0-9_-]` session ids (at most 64 bytes) before joining them under `<workDir>/sessions`, so `..` and path separators cannot escape that directory.
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@
|
||||
- **At most 7 open pull requests per contributor.** The repository enforces this with GitHub's pull request creation limit, drafts included: when you reach it, close or merge one before opening another. Review is manual, one change at a time, so a larger batch makes the queue unmanageable and slows everyone down, including you. If you have more changes queued, open one issue that lists them and wait for the current ones to be reviewed.
|
||||
- **One focused change per PR.** If a change has independent parts, split it into a small number of PRs and say in each description what the other parts depend on.
|
||||
- **Describe the change.** State the problem, the behavior change and what you tested. A pull request with no description is a request for changes.
|
||||
- **Provider support stays generic.** Any OpenAI- or Anthropic-compatible endpoint works through a model profile; provider convenience goes in as a neutral preset (name and base URL) or a docs recipe, with no vendor logos, promotional codes, baked vendor endpoints, or vendor-specific environment variables. A new wire format needs a schema migration, a profile save/load test, and a live connection test.
|
||||
|
||||
## Issues
|
||||
|
||||
@@ -12,4 +13,4 @@
|
||||
|
||||
## Security
|
||||
|
||||
- Do not open a public issue for a vulnerability in ARTEX itself. Use the private advisory form in the repository's Security tab.
|
||||
- Do not open a public issue for a vulnerability in ARTEX itself. Follow the [private reporting instructions](SECURITY.md#reporting-a-vulnerability).
|
||||
|
||||
@@ -428,6 +428,14 @@ runtime supports it.
|
||||
`/chat/completions` (or `/responses` for `openai-responses`), so their base **does** end in `/v1`
|
||||
(for example `https://api.openai.com/v1`).
|
||||
|
||||
**OpenAI-compatible gateways**: any provider that serves an OpenAI-style
|
||||
`/v1/chat/completions` endpoint works through the **OpenAI** format — no dedicated format
|
||||
needed. Create a profile with format **OpenAI**, set **Base URL** to the gateway's `/v1`
|
||||
root, paste the key, then click the **↻** button next to *Model* to load the provider's
|
||||
catalog (`GET /v1/models`) and pick a model; models the provider adds later appear on the
|
||||
next refresh. For example, [NotHoly](https://notholy.com) (offensive-security models) uses
|
||||
base URL `https://api.notholy.com/v1` with an API key from its console.
|
||||
|
||||
**Concurrency**: work agents per task, in "System Settings" (default 3).
|
||||
|
||||
**Untrusted-output boundary (on by default)**: tool results for the worker, planner, chat and main
|
||||
|
||||
+7
-1
@@ -14,7 +14,7 @@ Notes:
|
||||
|
||||
**Do not open a public issue for a security vulnerability.**
|
||||
|
||||
Report through **GitHub Security Advisories**: **Security** tab → **Report a vulnerability** in the `BaaRai/ARTEX` repository. This is the only reporting channel.
|
||||
Sign in to GitHub and use the [private vulnerability report form](https://github.com/BaaRai/ARTEX/security/advisories/new). You can also reach it from the repository's **Security and quality** tab under **Advisories** → **Report a vulnerability**. This is the only reporting channel.
|
||||
|
||||
Please include:
|
||||
- A description of the vulnerability and its expected impact.
|
||||
@@ -43,6 +43,12 @@ The enforced trust boundary for asset insertion is `insert_assets`, which runs e
|
||||
|
||||
Accepted gap: when a task has no allow-list, there is no allow rule to apply (block rules still run), and any host carried on an in-scope event that is not blocked enters the graph as an asset. Operators who rely on the scanner's scope rules alone should configure an allow-list per task, or review `output.json` before feeding it to ARTEX. Cross-checking ingested events against ARTEX's own rule set would change what existing scanner configurations mean for those operators, so it is treated as a deliberate design question (see #317), not an accepted vulnerability.
|
||||
|
||||
## Outbound Model Listing (`POST /api/llm/models`)
|
||||
|
||||
`POST /api/llm/models` fetches model lists from the provider endpoint and optional HTTP proxy supplied in the request. By default, ARTEX allows only `http` and `https` URLs whose hosts resolve exclusively to public IP addresses (blocking loopback, RFC1918 private networks, IPv6 unique-local `fc00::/7`, link-local/cloud metadata such as `169.254.169.254`, unspecified, and multicast addresses), and enforces the same checks on redirects and at dial time. The built-in local Ollama default (`http://127.0.0.1:11434/v1`) is permitted only when the request leaves `base_url` empty for the `ollama` provider.
|
||||
|
||||
Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge can allow specific endpoints with `ARTEX_LLM_PRIVATE_ENDPOINTS`, a comma-separated list of exact `host:port` entries (for example, `127.0.0.1:11434,host.docker.internal:11434,192.168.1.10:11434`). A URL whose `host:port` matches an entry may resolve to a loopback or private address while scheme restrictions, link-local/cloud-metadata blocks, and redirect validation still apply; everything else stays refused. Leaving `ARTEX_LLM_PRIVATE_ENDPOINTS` unset or empty keeps the strict public-only policy.
|
||||
|
||||
## What to Expect
|
||||
|
||||
This is an open-source project maintained on a best-effort basis. We aim to acknowledge a report within about a week and keep you updated, but we cannot guarantee specific response or fix timeframes.
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package archivestore
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArchiveStorageEnvironment(t *testing.T) {
|
||||
for _, key := range []string{
|
||||
"ARTEX_ARCHIVE_STORAGE", "ARTEX_ARCHIVE_S3_ENDPOINT", "ARTEX_ARCHIVE_S3_REGION",
|
||||
"ARTEX_ARCHIVE_S3_BUCKET", "ARTEX_ARCHIVE_S3_PREFIX", "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID",
|
||||
"ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_PATH_STYLE",
|
||||
"ARTEX_ARCHIVE_S3_SESSION_TOKEN", "ARTEX_ARCHIVE_S3_SSE", "ARTEX_ARCHIVE_S3_KMS_KEY_ID",
|
||||
} {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
for _, backend := range []string{"", "local"} {
|
||||
t.Setenv("ARTEX_ARCHIVE_STORAGE", backend)
|
||||
if store, err := FromEnv(); err != nil || store != nil {
|
||||
t.Fatalf("local default: %v %v", store, err)
|
||||
}
|
||||
}
|
||||
for _, backend := range []string{"unknown", "s3"} {
|
||||
t.Setenv("ARTEX_ARCHIVE_STORAGE", backend)
|
||||
if _, err := FromEnv(); err == nil {
|
||||
t.Fatalf("%q silently fell back to local", backend)
|
||||
}
|
||||
}
|
||||
t.Setenv("ARTEX_ARCHIVE_S3_ENDPOINT", "http://127.0.0.1:9000")
|
||||
t.Setenv("ARTEX_ARCHIVE_S3_BUCKET", "test-bucket")
|
||||
t.Setenv("ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "test-key")
|
||||
t.Setenv("ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "test-secret")
|
||||
t.Setenv("ARTEX_ARCHIVE_S3_PATH_STYLE", "true")
|
||||
store, err := FromEnv()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if uri := store.URI(1, 2, "checksum"); uri != "s3://test-bucket/artex/tasks/task-1-2-checksum.tar.zst" {
|
||||
t.Fatal("unexpected default object location", uri)
|
||||
}
|
||||
t.Setenv("ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "")
|
||||
if _, err := FromEnv(); err == nil {
|
||||
t.Fatal("missing credentials accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveEndpointValidation(t *testing.T) {
|
||||
config := Config{Bucket: "test", AccessKey: "test-key", SecretKey: "test-secret"}
|
||||
for _, endpoint := range []string{"https://objects.example.test", "http://127.0.0.1:9000", "http://127.0.0.2:9000", "http://[::1]:9000", "http://localhost:9000"} {
|
||||
config.Endpoint = endpoint
|
||||
if _, err := New(config); err != nil {
|
||||
t.Errorf("rejected %s: %v", endpoint, err)
|
||||
}
|
||||
}
|
||||
for _, endpoint := range []string{"http://objects.example.test", "https://user:test-secret@objects.example.test", "https://objects.example.test/bucket", "https://objects.example.test?token=test-secret", "https://objects.example.test#fragment"} {
|
||||
config.Endpoint = endpoint
|
||||
if _, err := New(config); err == nil {
|
||||
t.Error("accepted endpoint with non-loopback HTTP, credentials, path, query or fragment")
|
||||
} else if strings.Contains(err.Error(), "test-secret") {
|
||||
t.Fatal("configuration error disclosed a secret")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveEncryptionConfiguration(t *testing.T) {
|
||||
c := Config{Endpoint: "https://objects.example.test", Bucket: "test", AccessKey: "test", SecretKey: "test"}
|
||||
for _, mode := range []string{"none", "invalid"} {
|
||||
c.SSE = mode
|
||||
if _, err := New(c); err == nil {
|
||||
t.Fatal("unencrypted/invalid mode accepted")
|
||||
}
|
||||
}
|
||||
c.SSE = "AES256"
|
||||
c.KMSKeyID = "alias/archive"
|
||||
if _, err := New(c); err == nil {
|
||||
t.Fatal("KMS key accepted with SSE-S3")
|
||||
}
|
||||
c.SSE = "aws:kms"
|
||||
for _, key := range []string{"alias/archive", "bare-key-id", "arn:aws:kms:us-east-1:123456789012:alias/archive"} {
|
||||
c.KMSKeyID = key
|
||||
if _, err := New(c); err == nil {
|
||||
t.Fatalf("accepted noncanonical KMS key %q", key)
|
||||
}
|
||||
}
|
||||
c.KMSKeyID = "arn:aws:kms:us-east-1:123456789012:key/test-key"
|
||||
if _, err := New(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package archivestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func isolateAWSCredentials(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, key := range []string{
|
||||
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE",
|
||||
"AWS_ROLE_ARN", "AWS_ROLE_SESSION_NAME", "AWS_WEB_IDENTITY_TOKEN_FILE",
|
||||
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
"AWS_CONTAINER_AUTHORIZATION_TOKEN", "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
|
||||
"AWS_EC2_METADATA_SERVICE_ENDPOINT", "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",
|
||||
} {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "credentials"))
|
||||
t.Setenv("AWS_CONFIG_FILE", filepath.Join(dir, "config"))
|
||||
t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
|
||||
}
|
||||
|
||||
func TestArchiveCredentialChain(t *testing.T) {
|
||||
config := Config{Endpoint: "https://objects.example.test", Bucket: "test"}
|
||||
for _, mode := range []string{"explicit-session", "environment", "shared-profile", "ecs", "imds"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
isolateAWSCredentials(t)
|
||||
c := config
|
||||
switch mode {
|
||||
case "explicit-session":
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "other-key")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "other-secret")
|
||||
c.AccessKey, c.SecretKey, c.SessionToken = "fixture-key", "fixture-secret", "fixture-session"
|
||||
case "environment":
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "fixture-key")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "fixture-secret")
|
||||
t.Setenv("AWS_SESSION_TOKEN", "fixture-session")
|
||||
case "shared-profile":
|
||||
t.Setenv("AWS_PROFILE", "archive")
|
||||
data := `[archive]
|
||||
aws_access_key_id=fixture-key
|
||||
aws_secret_access_key=fixture-secret
|
||||
aws_session_token=fixture-session
|
||||
`
|
||||
if err := os.WriteFile(os.Getenv("AWS_SHARED_CREDENTIALS_FILE"), []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "ecs", "imds":
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if mode == "imds" {
|
||||
switch r.URL.Path {
|
||||
case "/latest/api/token":
|
||||
if r.Method != "PUT" {
|
||||
t.Error("IMDS did not use token request")
|
||||
}
|
||||
w.Header().Set("X-aws-ec2-metadata-token-ttl-seconds", "21600")
|
||||
fmt.Fprint(w, "fixture-imds-token")
|
||||
return
|
||||
case "/latest/meta-data/iam/security-credentials/":
|
||||
if r.Header.Get("X-aws-ec2-metadata-token") != "fixture-imds-token" {
|
||||
t.Error("missing IMDSv2 token")
|
||||
}
|
||||
fmt.Fprint(w, "archive-role")
|
||||
return
|
||||
case "/latest/meta-data/iam/security-credentials/archive-role":
|
||||
if r.Header.Get("X-aws-ec2-metadata-token") != "fixture-imds-token" {
|
||||
t.Error("missing IMDSv2 token")
|
||||
}
|
||||
default:
|
||||
t.Errorf("unexpected IMDS request %s", r.URL.Path)
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
} else if r.Header.Get("Authorization") != "fixture-container-token" {
|
||||
t.Error("missing ECS authorization token")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"Code": "Success", "AccessKeyId": "fixture-key", "SecretAccessKey": "fixture-secret",
|
||||
"Token": "fixture-session", "Expiration": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
if mode == "imds" {
|
||||
t.Setenv("AWS_EC2_METADATA_DISABLED", "false")
|
||||
t.Setenv("AWS_EC2_METADATA_V1_DISABLED", "true")
|
||||
t.Setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", srv.URL)
|
||||
} else {
|
||||
t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", srv.URL+"/credentials")
|
||||
t.Setenv("AWS_CONTAINER_AUTHORIZATION_TOKEN", "fixture-container-token")
|
||||
}
|
||||
}
|
||||
store, err := New(c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
credentials, err := store.client.Options().Credentials.Retrieve(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if credentials.AccessKeyID != "fixture-key" || credentials.SecretAccessKey != "fixture-secret" || credentials.SessionToken != "fixture-session" {
|
||||
t.Fatal("wrong credential provider or session token")
|
||||
}
|
||||
if (mode == "imds" || mode == "ecs") && !credentials.CanExpire {
|
||||
t.Fatal("role credentials must remain refreshable")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveIncompleteCredentialOverride(t *testing.T) {
|
||||
isolateAWSCredentials(t)
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "valid-ambient-key")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "valid-ambient-secret")
|
||||
for _, c := range []Config{{AccessKey: "private-value"}, {SecretKey: "private-value"}, {SessionToken: "private-value"}} {
|
||||
c.Endpoint, c.Bucket = "https://objects.example.test", "test"
|
||||
if _, err := New(c); err == nil || strings.Contains(err.Error(), "private-value") {
|
||||
t.Fatalf("partial override must fail without disclosing credentials: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// Package archivestore stores immutable cold-task packages in S3-compatible storage.
|
||||
package archivestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/aws/arn"
|
||||
"github.com/aws/aws-sdk-go-v2/aws/retry"
|
||||
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
|
||||
awsconfig "github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Endpoint, Region, Bucket, Prefix, AccessKey, SecretKey string
|
||||
PathStyle bool
|
||||
SessionToken, SSE, KMSKeyID string
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
client *s3.Client
|
||||
bucket, prefix string
|
||||
encryption types.ServerSideEncryption
|
||||
kmsKeyID string
|
||||
}
|
||||
|
||||
// FromEnv returns nil for the default local backend. A configured but invalid
|
||||
// backend is an error, never a silent fallback to the machine's local disk.
|
||||
func FromEnv() (*Store, error) {
|
||||
switch os.Getenv("ARTEX_ARCHIVE_STORAGE") {
|
||||
case "", "local":
|
||||
return nil, nil
|
||||
case "s3":
|
||||
return New(Config{
|
||||
Endpoint: os.Getenv("ARTEX_ARCHIVE_S3_ENDPOINT"), Region: os.Getenv("ARTEX_ARCHIVE_S3_REGION"),
|
||||
Bucket: os.Getenv("ARTEX_ARCHIVE_S3_BUCKET"), Prefix: os.Getenv("ARTEX_ARCHIVE_S3_PREFIX"),
|
||||
AccessKey: os.Getenv("ARTEX_ARCHIVE_S3_ACCESS_KEY_ID"), SecretKey: os.Getenv("ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY"),
|
||||
PathStyle: os.Getenv("ARTEX_ARCHIVE_S3_PATH_STYLE") == "true",
|
||||
SessionToken: os.Getenv("ARTEX_ARCHIVE_S3_SESSION_TOKEN"),
|
||||
SSE: os.Getenv("ARTEX_ARCHIVE_S3_SSE"), KMSKeyID: os.Getenv("ARTEX_ARCHIVE_S3_KMS_KEY_ID"),
|
||||
})
|
||||
default:
|
||||
return nil, errors.New("ARTEX_ARCHIVE_STORAGE must be local or s3")
|
||||
}
|
||||
}
|
||||
|
||||
func New(c Config) (*Store, error) {
|
||||
u, err := url.Parse(c.Endpoint)
|
||||
loopback := false
|
||||
if err == nil {
|
||||
loopback = u.Hostname() == "localhost"
|
||||
if ip := net.ParseIP(u.Hostname()); ip != nil {
|
||||
loopback = ip.IsLoopback()
|
||||
}
|
||||
}
|
||||
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") ||
|
||||
(u.Scheme != "https" && !(u.Scheme == "http" && loopback)) {
|
||||
return nil, errors.New("archive S3 endpoint must be an HTTPS origin (HTTP allowed only on loopback)")
|
||||
}
|
||||
c.Prefix = strings.Trim(c.Prefix, "/")
|
||||
if c.Prefix == "" {
|
||||
c.Prefix = "artex/tasks"
|
||||
}
|
||||
if path.Clean(c.Prefix) != c.Prefix || strings.Contains(c.Prefix, "..") || strings.ContainsAny(c.Prefix, "\\?#") {
|
||||
return nil, errors.New("invalid archive S3 prefix")
|
||||
}
|
||||
if c.Bucket == "" || strings.ContainsAny(c.Bucket, "/\\:@?# ") {
|
||||
return nil, errors.New("a valid archive S3 bucket is required")
|
||||
}
|
||||
explicitCredentials := c.AccessKey != "" || c.SecretKey != "" || c.SessionToken != ""
|
||||
if explicitCredentials && (c.AccessKey == "" || c.SecretKey == "") {
|
||||
return nil, errors.New("archive S3 access key and secret key must both be set when overriding AWS credentials")
|
||||
}
|
||||
if c.SSE == "" {
|
||||
c.SSE = "AES256"
|
||||
}
|
||||
if c.SSE != "AES256" && c.SSE != "aws:kms" {
|
||||
return nil, errors.New("archive S3 SSE must be AES256 or aws:kms; encryption cannot be disabled")
|
||||
}
|
||||
if c.KMSKeyID != "" && c.SSE != "aws:kms" {
|
||||
return nil, errors.New("archive S3 KMS key requires SSE=aws:kms")
|
||||
}
|
||||
if c.KMSKeyID != "" {
|
||||
key, err := arn.Parse(c.KMSKeyID)
|
||||
if err != nil || key.Service != "kms" || key.Region == "" || key.AccountID == "" ||
|
||||
!strings.HasPrefix(key.Resource, "key/") || len(key.Resource) <= len("key/") {
|
||||
return nil, errors.New("archive S3 KMS key must be a full key ARN, not an alias or bare key ID")
|
||||
}
|
||||
}
|
||||
if c.Region == "" {
|
||||
c.Region = "us-east-1"
|
||||
}
|
||||
// Load shared AWS settings (including custom CAs) for both credential modes.
|
||||
httpClient := awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) {
|
||||
t.ResponseHeaderTimeout = 60 * time.Second
|
||||
})
|
||||
options := []func(*awsconfig.LoadOptions) error{
|
||||
awsconfig.WithRegion(c.Region), awsconfig.WithHTTPClient(httpClient),
|
||||
}
|
||||
if explicitCredentials {
|
||||
options = append(options, awsconfig.WithCredentialsProvider(
|
||||
credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, c.SessionToken)))
|
||||
}
|
||||
cfg, err := awsconfig.LoadDefaultConfig(context.Background(), options...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load archive S3 AWS configuration: %w", err)
|
||||
}
|
||||
// The SDK's default client still follows 307/308. Use its CA-configured
|
||||
// transport, but never redirect a signed archive request to another origin.
|
||||
configuredClient := cfg.HTTPClient.(*awshttp.BuildableClient)
|
||||
cfg.HTTPClient = &http.Client{
|
||||
Transport: configuredClient.GetTransport(), Timeout: configuredClient.GetTimeout(),
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(c.Endpoint)
|
||||
o.UsePathStyle = c.PathStyle
|
||||
o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired
|
||||
o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired
|
||||
})
|
||||
return &Store{client: client, bucket: c.Bucket, prefix: c.Prefix + "/",
|
||||
encryption: types.ServerSideEncryption(c.SSE), kmsKeyID: c.KMSKeyID}, nil
|
||||
}
|
||||
|
||||
func (s *Store) URI(taskID, archiveID int64, checksum string) string {
|
||||
return "s3://" + s.bucket + "/" + s.prefix + fmt.Sprintf("task-%d-%d-%s.tar.zst", taskID, archiveID, checksum)
|
||||
}
|
||||
|
||||
func (s *Store) key(uri string) (string, error) {
|
||||
if s == nil {
|
||||
return "", errors.New("S3 archive storage is not configured")
|
||||
}
|
||||
u, err := url.Parse(uri)
|
||||
if err != nil || u.Scheme != "s3" || u.Host != s.bucket || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return "", errors.New("archive object is outside the configured bucket")
|
||||
}
|
||||
key := strings.TrimPrefix(u.Path, "/")
|
||||
if !strings.HasPrefix(key, s.prefix) || len(key) <= len(s.prefix) || path.Clean(key) != key || strings.Contains(key, "\\") {
|
||||
return "", errors.New("archive object is outside the configured prefix")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func (s *Store) Validate(uri string) error { _, err := s.key(uri); return err }
|
||||
|
||||
// Upload verifies the entire uploaded object by reading it back, including
|
||||
// multipart uploads whose ETag is not a checksum. Callers retain source data
|
||||
// until verification succeeds and PostgreSQL commits the remote location.
|
||||
func (s *Store) Upload(ctx context.Context, uri, filename, checksum string) error {
|
||||
key, err := s.key(uri)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if decoded, err := hex.DecodeString(checksum); err != nil || len(decoded) != sha256.Size {
|
||||
return errors.New("invalid archive SHA-256")
|
||||
}
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
uploader := manager.NewUploader(s.client, func(u *manager.Uploader) {
|
||||
u.PartSize = 8 << 20
|
||||
u.Concurrency = 2
|
||||
u.LeavePartsOnError = true // Abort below with a fresh, bounded cleanup context.
|
||||
u.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired
|
||||
})
|
||||
input := &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket), Key: aws.String(key), Body: f,
|
||||
ContentType: aws.String("application/zstd"), Metadata: map[string]string{"sha256": checksum},
|
||||
ServerSideEncryption: s.encryption,
|
||||
}
|
||||
if s.kmsKeyID != "" {
|
||||
input.SSEKMSKeyId = aws.String(s.kmsKeyID)
|
||||
}
|
||||
result, err := uploader.Upload(ctx, input)
|
||||
if err != nil {
|
||||
uploadErr := fmt.Errorf("upload archive: %w", err)
|
||||
var multipart manager.MultiUploadFailure
|
||||
if errors.As(err, &multipart) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
_, cleanupErr := s.client.AbortMultipartUpload(cleanupCtx, &s3.AbortMultipartUploadInput{
|
||||
Bucket: aws.String(s.bucket), Key: aws.String(key), UploadId: aws.String(multipart.UploadID()),
|
||||
})
|
||||
if cleanupErr != nil {
|
||||
return errors.Join(uploadErr, fmt.Errorf("abort archive multipart upload: %w", cleanupErr))
|
||||
}
|
||||
}
|
||||
return uploadErr
|
||||
}
|
||||
if err := s.readVerified(ctx, key, io.Discard, checksum, info.Size(), true); err != nil {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
// Versioned buckets require deleting the version just uploaded; an
|
||||
// unversioned DELETE would only hide it behind a delete marker.
|
||||
_, cleanupErr := s.client.DeleteObject(cleanupCtx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket), Key: aws.String(key), VersionId: result.VersionID,
|
||||
})
|
||||
if cleanupErr != nil {
|
||||
return errors.Join(err, fmt.Errorf("delete unverified archive: %w", cleanupErr))
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) readVerified(ctx context.Context, key string, out io.Writer, checksum string, expectedSize int64, requireEncryption bool) error {
|
||||
if decoded, err := hex.DecodeString(checksum); err != nil || len(decoded) != sha256.Size {
|
||||
return errors.New("invalid archive SHA-256")
|
||||
}
|
||||
if expectedSize < 0 {
|
||||
return errors.New("invalid archive size")
|
||||
}
|
||||
object, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)})
|
||||
if err != nil {
|
||||
return fmt.Errorf("inspect archive: %w", err)
|
||||
}
|
||||
if requireEncryption && (object.ServerSideEncryption != s.encryption ||
|
||||
(s.encryption == types.ServerSideEncryptionAwsKms && (aws.ToString(object.SSEKMSKeyId) == "" ||
|
||||
(s.kmsKeyID != "" && aws.ToString(object.SSEKMSKeyId) != s.kmsKeyID)))) {
|
||||
return errors.New("remote archive did not confirm the requested server-side encryption; source data retained")
|
||||
}
|
||||
if object.ContentLength == nil || *object.ContentLength != expectedSize || aws.ToString(object.ETag) == "" {
|
||||
return errors.New("remote archive size mismatch or missing ETag; source data retained")
|
||||
}
|
||||
// Commit only complete, validated chunks to the output and hash. A broken
|
||||
// connection can then retry its chunk without duplicating bytes or restarting
|
||||
// a multi-gigabyte read. IfMatch pins every request to the same object.
|
||||
h := sha256.New()
|
||||
for offset := int64(0); offset < expectedSize; {
|
||||
end := offset + min(archiveReadChunkSize, expectedSize-offset) - 1
|
||||
data, err := s.readArchiveChunk(ctx, key, aws.ToString(object.ETag), offset, end, expectedSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := out.Write(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != len(data) {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
_, _ = h.Write(data)
|
||||
offset += int64(len(data))
|
||||
}
|
||||
if !strings.EqualFold(hex.EncodeToString(h.Sum(nil)), checksum) {
|
||||
return errors.New("remote archive size or SHA-256 mismatch; source data retained")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
archiveReadChunkSize = int64(8 << 20)
|
||||
archiveReadAttempts = 5
|
||||
)
|
||||
|
||||
func (s *Store) readArchiveChunk(ctx context.Context, key, etag string, start, end, total int64) ([]byte, error) {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < archiveReadAttempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if attempt > 0 {
|
||||
timer := time.NewTimer((250 * time.Millisecond) << (attempt - 1))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return nil, ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
data, retry, err := s.readArchiveChunkOnce(ctx, key, etag, start, end, total)
|
||||
if err == nil {
|
||||
return data, nil
|
||||
}
|
||||
if !retry {
|
||||
return nil, err
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
return nil, fmt.Errorf("read archive bytes %d-%d after %d attempts: %w", start, end, archiveReadAttempts, lastErr)
|
||||
}
|
||||
|
||||
func (s *Store) readArchiveChunkOnce(ctx context.Context, key, etag string, start, end, total int64) ([]byte, bool, error) {
|
||||
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
object, err := s.client.GetObject(requestCtx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket), Key: aws.String(key), IfMatch: aws.String(etag),
|
||||
Range: aws.String(fmt.Sprintf("bytes=%d-%d", start, end)),
|
||||
}, func(o *s3.Options) {
|
||||
// This loop owns both HTTP and interrupted-body retries: at most five
|
||||
// wire requests per chunk, rather than five times the SDK's attempts.
|
||||
o.RetryMaxAttempts = 1
|
||||
})
|
||||
if err != nil {
|
||||
var networkError net.Error
|
||||
var responseError *awshttp.ResponseError
|
||||
throttled := errors.As(err, &responseError) && responseError.HTTPStatusCode() == http.StatusTooManyRequests
|
||||
shouldRetry := throttled || retry.NewStandard().IsErrorRetryable(err) || errors.As(err, &networkError) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, context.DeadlineExceeded)
|
||||
return nil, shouldRetry, fmt.Errorf("read archive range: %w", err)
|
||||
}
|
||||
defer object.Body.Close()
|
||||
want := end - start + 1
|
||||
if aws.ToString(object.ETag) != etag || aws.ToString(object.ContentRange) != fmt.Sprintf("bytes %d-%d/%d", start, end, total) || object.ContentLength == nil || *object.ContentLength != want {
|
||||
return nil, false, errors.New("remote archive changed or returned an invalid byte range; source data retained")
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(object.Body, want+1))
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
if int64(len(data)) < want {
|
||||
return nil, true, io.ErrUnexpectedEOF
|
||||
}
|
||||
if int64(len(data)) != want {
|
||||
return nil, false, errors.New("remote archive range exceeds its declared size")
|
||||
}
|
||||
return data, false, nil
|
||||
}
|
||||
|
||||
func (s *Store) Download(ctx context.Context, uri, filename, checksum string, size int64) (err error) {
|
||||
key, err := s.key(uri)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size <= 0 {
|
||||
return errors.New("invalid archive size")
|
||||
}
|
||||
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
err = errors.Join(err, f.Close())
|
||||
if err != nil {
|
||||
_ = os.Remove(filename)
|
||||
}
|
||||
}()
|
||||
if err = s.readVerified(ctx, key, f, checksum, size, false); err != nil {
|
||||
return err
|
||||
}
|
||||
return f.Sync()
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, uri string) error {
|
||||
key, err := s.key(uri)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
package archivestore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestS3RoundTripAndIntegrity(t *testing.T) {
|
||||
for _, sse := range []string{"AES256", "aws:kms"} {
|
||||
kms := ""
|
||||
if sse == "aws:kms" {
|
||||
kms = "arn:aws:kms:us-east-1:123456789012:key/test-key"
|
||||
}
|
||||
for _, size := range []int{1024, 10 << 20} {
|
||||
t.Run(sse+"/"+strconv.Itoa(size), func(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var object []byte
|
||||
parts := map[int][]byte{}
|
||||
corrupt, multipart := false, false
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
q := r.URL.Query()
|
||||
if (r.Method == "PUT" && !q.Has("partNumber")) || (r.Method == "POST" && q.Has("uploads")) {
|
||||
if r.Header.Get("X-Amz-Server-Side-Encryption") != sse || r.Header.Get("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id") != kms {
|
||||
t.Error("upload did not explicitly request the configured encryption")
|
||||
}
|
||||
}
|
||||
if r.Method == "HEAD" {
|
||||
if r.Header.Get("X-Amz-Server-Side-Encryption") != "" {
|
||||
t.Error("encryption write header leaked into HEAD")
|
||||
}
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption", sse)
|
||||
if kms != "" {
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", kms)
|
||||
}
|
||||
}
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
switch {
|
||||
case r.Method == "POST" && q.Has("uploads"):
|
||||
multipart = true
|
||||
fmt.Fprint(w, `<InitiateMultipartUploadResult><UploadId>test-upload</UploadId></InitiateMultipartUploadResult>`)
|
||||
case r.Method == "PUT" && q.Has("partNumber"):
|
||||
n, _ := strconv.Atoi(q.Get("partNumber"))
|
||||
parts[n], _ = io.ReadAll(r.Body)
|
||||
case r.Method == "POST" && q.Has("uploadId"):
|
||||
for i := 1; i <= len(parts); i++ {
|
||||
object = append(object, parts[i]...)
|
||||
}
|
||||
fmt.Fprint(w, `<CompleteMultipartUploadResult><ETag>test-etag</ETag></CompleteMultipartUploadResult>`)
|
||||
case r.Method == "PUT":
|
||||
object, _ = io.ReadAll(r.Body)
|
||||
case r.Method == "HEAD":
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(object)))
|
||||
case r.Method == "GET":
|
||||
data := object
|
||||
if corrupt {
|
||||
data = bytes.Clone(object)
|
||||
data[0] ^= 0xff
|
||||
}
|
||||
serveArchiveRange(t, w, r, data)
|
||||
case r.Method == "DELETE":
|
||||
object = nil
|
||||
w.WriteHeader(204)
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL)
|
||||
w.WriteHeader(400)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
store, err := New(Config{Endpoint: srv.URL, Bucket: "test-bucket", Prefix: "test/tasks", AccessKey: "test", SecretKey: "test", PathStyle: true, SSE: sse, KMSKeyID: kms})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := bytes.Repeat([]byte{0x42}, size)
|
||||
h := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(h[:])
|
||||
root := t.TempDir()
|
||||
source := filepath.Join(root, "source")
|
||||
if err := os.WriteFile(source, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
uri := store.URI(1, 2, checksum)
|
||||
ctx := context.Background()
|
||||
if err := store.Upload(ctx, uri, source, checksum); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if multipart != (size > 8<<20) {
|
||||
t.Fatalf("multipart=%v size=%d", multipart, size)
|
||||
}
|
||||
dest := filepath.Join(root, "download")
|
||||
if err := store.Download(ctx, uri, dest, checksum, int64(size)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := os.ReadFile(dest)
|
||||
if !bytes.Equal(got, data) {
|
||||
t.Fatal("download differs")
|
||||
}
|
||||
mu.Lock()
|
||||
corrupt = true
|
||||
mu.Unlock()
|
||||
bad := filepath.Join(root, "bad")
|
||||
if err := store.Download(ctx, uri, bad, checksum, int64(size)); err == nil {
|
||||
t.Fatal("accepted corrupt object")
|
||||
}
|
||||
if _, err := os.Stat(bad); !os.IsNotExist(err) {
|
||||
t.Fatal("left corrupt download")
|
||||
}
|
||||
if err := store.Upload(ctx, uri, source, checksum); err == nil {
|
||||
t.Fatal("upload accepted failed readback")
|
||||
}
|
||||
if err := store.Delete(ctx, uri); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func serveArchiveRange(t *testing.T, w http.ResponseWriter, r *http.Request, data []byte) {
|
||||
t.Helper()
|
||||
var start, end int64
|
||||
if n, err := fmt.Sscanf(r.Header.Get("Range"), "bytes=%d-%d", &start, &end); err != nil || n != 2 || start < 0 || end < start || end >= int64(len(data)) {
|
||||
t.Errorf("invalid range %q", r.Header.Get("Range"))
|
||||
w.WriteHeader(http.StatusRequestedRangeNotSatisfiable)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("If-Match") != `"test-etag"` {
|
||||
t.Errorf("missing object version condition: %q", r.Header.Get("If-Match"))
|
||||
w.WriteHeader(http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10))
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(data)))
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = w.Write(data[start : end+1])
|
||||
}
|
||||
|
||||
func TestS3ReadbackRetriesInterruptedRange(t *testing.T) {
|
||||
data := append(bytes.Repeat([]byte{0x42}, int(archiveReadChunkSize)), bytes.Repeat([]byte{0x73}, 1024)...)
|
||||
var mu sync.Mutex
|
||||
var ranges []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
if r.Method == "HEAD" {
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
return
|
||||
}
|
||||
ranges = append(ranges, r.Header.Get("Range"))
|
||||
if len(ranges) == 2 {
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(int64(len(data))-archiveReadChunkSize, 10))
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", archiveReadChunkSize, len(data)-1, len(data)))
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = w.Write(data[archiveReadChunkSize : archiveReadChunkSize+128]) // Close during a later chunk.
|
||||
return
|
||||
}
|
||||
serveArchiveRange(t, w, r, data)
|
||||
}))
|
||||
defer srv.Close()
|
||||
store := testRangeStore(t, srv.URL)
|
||||
h := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(h[:])
|
||||
dest := filepath.Join(t.TempDir(), "archive")
|
||||
if err := store.Download(context.Background(), store.URI(1, 2, checksum), dest, checksum, int64(len(data))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.ReadFile(dest)
|
||||
if err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("retried download differs: %v", err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(ranges) != 3 || ranges[1] != ranges[2] || ranges[0] != fmt.Sprintf("bytes=0-%d", archiveReadChunkSize-1) || ranges[2] != fmt.Sprintf("bytes=%d-%d", archiveReadChunkSize, len(data)-1) {
|
||||
t.Fatalf("retry did not stay within the interrupted range: %v", ranges)
|
||||
}
|
||||
}
|
||||
|
||||
func testRangeStore(t *testing.T, endpoint string) *Store {
|
||||
t.Helper()
|
||||
s, err := New(Config{Endpoint: endpoint, Bucket: "test-bucket", Prefix: "test/tasks", AccessKey: "test", SecretKey: "test", PathStyle: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestS3ReadbackRejectsInvalidRangesAndExhaustedRetries(t *testing.T) {
|
||||
for _, mode := range []string{"ignored-range", "changed-etag", "changed-object", "truncated"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
data := bytes.Repeat([]byte{0x42}, 1024)
|
||||
var mu sync.Mutex
|
||||
gets := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
if r.Method == "HEAD" {
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
return
|
||||
}
|
||||
gets++
|
||||
if mode == "changed-object" {
|
||||
w.WriteHeader(http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
if mode == "ignored-range" {
|
||||
_, _ = w.Write(data)
|
||||
return
|
||||
}
|
||||
if mode == "changed-etag" {
|
||||
w.Header().Set("ETag", `"different-object"`)
|
||||
}
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(data)-1, len(data)))
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
if mode == "truncated" {
|
||||
_, _ = w.Write(data[:128])
|
||||
} else {
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
store := testRangeStore(t, srv.URL)
|
||||
h := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(h[:])
|
||||
dest := filepath.Join(t.TempDir(), "archive")
|
||||
if err := store.Download(context.Background(), store.URI(1, 2, checksum), dest, checksum, int64(len(data))); err == nil {
|
||||
t.Fatal("accepted invalid or incomplete readback")
|
||||
}
|
||||
if _, err := os.Stat(dest); !os.IsNotExist(err) {
|
||||
t.Fatal("left a failed download on disk")
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
want := 1
|
||||
if mode == "truncated" {
|
||||
want = archiveReadAttempts
|
||||
}
|
||||
if gets != want {
|
||||
t.Fatalf("GET count %d, want %d", gets, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type failedArchiveWriter struct{ err error }
|
||||
|
||||
func (w failedArchiveWriter) Write([]byte) (int, error) { return 0, w.err }
|
||||
|
||||
func TestS3ReadbackPropagatesOutputFailure(t *testing.T) {
|
||||
data := []byte("test archive")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
if r.Method == "HEAD" {
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
return
|
||||
}
|
||||
serveArchiveRange(t, w, r, data)
|
||||
}))
|
||||
defer srv.Close()
|
||||
store := testRangeStore(t, srv.URL)
|
||||
h := sha256.Sum256(data)
|
||||
outputError := errors.New("output disk full")
|
||||
err := store.readVerified(context.Background(), "test/tasks/archive", failedArchiveWriter{outputError}, hex.EncodeToString(h[:]), int64(len(data)), false)
|
||||
if !errors.Is(err, outputError) {
|
||||
t.Fatalf("lost output error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3ReadbackStopsOnCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
data := bytes.Repeat([]byte{0x42}, 1024)
|
||||
gets := make(chan struct{}, archiveReadAttempts+1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
if r.Method == "HEAD" {
|
||||
return
|
||||
}
|
||||
gets <- struct{}{}
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(data)-1, len(data)))
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = w.Write(data[:128])
|
||||
w.(http.Flusher).Flush()
|
||||
cancel()
|
||||
}))
|
||||
defer srv.Close()
|
||||
store := testRangeStore(t, srv.URL)
|
||||
h := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(h[:])
|
||||
dest := filepath.Join(t.TempDir(), "archive")
|
||||
err := store.Download(ctx, store.URI(1, 2, checksum), dest, checksum, int64(len(data)))
|
||||
if !errors.Is(err, context.Canceled) || len(gets) != 1 {
|
||||
t.Fatalf("cancellation was not honored: error=%v GETs=%d", err, len(gets))
|
||||
}
|
||||
if _, err := os.Stat(dest); !os.IsNotExist(err) {
|
||||
t.Fatal("left a cancelled download on disk")
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3RejectsForeignLocations(t *testing.T) {
|
||||
s, err := New(Config{Endpoint: "https://sfo3.digitaloceanspaces.com", Bucket: "allowed", Prefix: "archives/tasks", AccessKey: "test", SecretKey: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, uri := range []string{"s3://other/archives/tasks/a", "s3://allowed/archives/other/a", "s3://allowed/archives/tasks/../a", "s3://allowed/archives/tasks/%2e%2e/a", "s3://allowed/archives/tasks/a?secret=x", "s3://user@allowed/archives/tasks/a", "file:///etc/passwd"} {
|
||||
if err := s.Validate(uri); err == nil {
|
||||
t.Errorf("accepted %s", uri)
|
||||
}
|
||||
}
|
||||
var absent *Store
|
||||
if absent.Validate("s3://allowed/archives/tasks/a") == nil {
|
||||
t.Fatal("missing config accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3UploadRejectsUnconfirmedEncryption(t *testing.T) {
|
||||
for _, mode := range []string{"missing", "different", "kms-without-key"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
data := []byte("private archive")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case "PUT":
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
case "DELETE":
|
||||
w.WriteHeader(204)
|
||||
case "HEAD":
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
if mode != "missing" {
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption", "aws:kms")
|
||||
}
|
||||
default:
|
||||
t.Errorf("content must not be accepted before encryption confirmation: %s", r.Method)
|
||||
w.WriteHeader(400)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
c := Config{Endpoint: srv.URL, Bucket: "test", Prefix: "tasks", AccessKey: "test", SecretKey: "test", PathStyle: true}
|
||||
if mode == "kms-without-key" {
|
||||
c.SSE = "aws:kms"
|
||||
}
|
||||
store, err := New(c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filename := filepath.Join(t.TempDir(), "source")
|
||||
if err := os.WriteFile(filename, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(sum[:])
|
||||
if err := store.Upload(context.Background(), store.URI(1, 2, checksum), filename, checksum); err == nil || !strings.Contains(err.Error(), "encryption") {
|
||||
t.Fatalf("unconfirmed encryption accepted: %v", err)
|
||||
}
|
||||
if got, err := os.ReadFile(filename); err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatal("source was not retained", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3MultipartFailureAbortsUpload(t *testing.T) {
|
||||
var aborted atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
switch {
|
||||
case r.Method == "POST" && q.Has("uploads"):
|
||||
if r.Header.Get("X-Amz-Server-Side-Encryption") != "AES256" {
|
||||
t.Error("multipart encryption missing")
|
||||
}
|
||||
fmt.Fprint(w, `<InitiateMultipartUploadResult><UploadId>failed-upload</UploadId></InitiateMultipartUploadResult>`)
|
||||
case r.Method == "PUT" && q.Has("partNumber"):
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
w.WriteHeader(403)
|
||||
case r.Method == "DELETE" && q.Get("uploadId") == "failed-upload":
|
||||
aborted.Store(true)
|
||||
w.WriteHeader(204)
|
||||
default:
|
||||
t.Errorf("unexpected failed-upload request: %s", r.Method)
|
||||
w.WriteHeader(400)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
store := testRangeStore(t, srv.URL)
|
||||
data := bytes.Repeat([]byte("x"), 9<<20)
|
||||
checksum := sha256.Sum256(data)
|
||||
sum := hex.EncodeToString(checksum[:])
|
||||
filename := filepath.Join(t.TempDir(), "source")
|
||||
if err := os.WriteFile(filename, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Upload(context.Background(), store.URI(1, 2, sum), filename, sum); err == nil {
|
||||
t.Fatal("failed part accepted")
|
||||
}
|
||||
if !aborted.Load() {
|
||||
t.Fatal("failed multipart upload was not aborted")
|
||||
}
|
||||
if info, err := os.Stat(filename); err != nil || info.Size() != int64(len(data)) {
|
||||
t.Fatal("source was not retained", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package archivestore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func archiveSource(t *testing.T, data []byte) (string, string) {
|
||||
t.Helper()
|
||||
filename := filepath.Join(t.TempDir(), "source")
|
||||
if err := os.WriteFile(filename, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
return filename, hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func TestS3VerificationFailureCleansUploadedVersion(t *testing.T) {
|
||||
for _, failure := range []string{"wrong-kms", "checksum", "cancelled", "delete-denied"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
data := []byte("private archive")
|
||||
source, checksum := archiveSource(t, data)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var present, deleted atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case "PUT":
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
present.Store(true)
|
||||
w.Header().Set("X-Amz-Version-Id", "uploaded-version")
|
||||
case "HEAD":
|
||||
w.Header().Set("ETag", `"test-etag"`)
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption", "aws:kms")
|
||||
kms := "arn:aws:kms:us-east-1:123456789012:key/expected"
|
||||
if failure == "wrong-kms" {
|
||||
kms = "arn:aws:kms:us-east-1:123456789012:key/different"
|
||||
}
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", kms)
|
||||
if failure == "cancelled" {
|
||||
cancel()
|
||||
}
|
||||
case "GET":
|
||||
corrupt := bytes.Clone(data)
|
||||
corrupt[0] ^= 0xff
|
||||
serveArchiveRange(t, w, r, corrupt)
|
||||
case "DELETE":
|
||||
if r.URL.Query().Get("versionId") != "uploaded-version" {
|
||||
t.Error("cleanup did not target uploaded version")
|
||||
}
|
||||
deleted.Store(true)
|
||||
if failure == "delete-denied" {
|
||||
w.WriteHeader(403)
|
||||
return
|
||||
}
|
||||
present.Store(false)
|
||||
w.WriteHeader(204)
|
||||
default:
|
||||
t.Errorf("unexpected request %s", r.Method)
|
||||
w.WriteHeader(400)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
store, err := New(Config{Endpoint: srv.URL, Bucket: "test", AccessKey: "test", SecretKey: "test", PathStyle: true,
|
||||
SSE: "aws:kms", KMSKeyID: "arn:aws:kms:us-east-1:123456789012:key/expected"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = store.Upload(ctx, store.URI(1, 2, checksum), source, checksum)
|
||||
if err == nil {
|
||||
t.Fatal("accepted failed verification")
|
||||
}
|
||||
if failure == "wrong-kms" && !strings.Contains(err.Error(), "encryption") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if failure == "cancelled" && !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if failure == "delete-denied" && (!strings.Contains(err.Error(), "SHA-256") || !strings.Contains(err.Error(), "delete unverified archive")) {
|
||||
t.Fatalf("verification and cleanup errors must both survive: %v", err)
|
||||
}
|
||||
if !deleted.Load() || present.Load() != (failure == "delete-denied") {
|
||||
t.Fatal("unverified object cleanup was not attempted/completed")
|
||||
}
|
||||
if got, readErr := os.ReadFile(source); readErr != nil || !bytes.Equal(got, data) {
|
||||
t.Fatal("source changed", readErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3CancelledMultipartAbortsWithFreshContext(t *testing.T) {
|
||||
for _, denyAbort := range []bool{false, true} {
|
||||
t.Run(strconv.FormatBool(denyAbort), func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var aborted atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
switch {
|
||||
case r.Method == "POST" && q.Has("uploads"):
|
||||
fmt.Fprint(w, `<InitiateMultipartUploadResult><UploadId>cancelled-upload</UploadId></InitiateMultipartUploadResult>`)
|
||||
case r.Method == "PUT" && q.Has("partNumber"):
|
||||
cancel()
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
w.WriteHeader(403)
|
||||
case r.Method == "DELETE" && q.Get("uploadId") == "cancelled-upload":
|
||||
aborted.Store(true)
|
||||
if denyAbort {
|
||||
w.WriteHeader(403)
|
||||
} else {
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
default:
|
||||
t.Errorf("unexpected request %s", r.Method)
|
||||
w.WriteHeader(400)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
data := bytes.Repeat([]byte("x"), 9<<20)
|
||||
source, sum := archiveSource(t, data)
|
||||
store := testRangeStore(t, srv.URL)
|
||||
err := store.Upload(ctx, store.URI(1, 2, sum), source, sum)
|
||||
if !errors.Is(err, context.Canceled) || !aborted.Load() {
|
||||
t.Fatalf("cancelled upload not aborted: %v", err)
|
||||
}
|
||||
if denyAbort && !strings.Contains(err.Error(), "abort archive multipart upload") {
|
||||
t.Fatalf("cleanup failure lost: %v", err)
|
||||
}
|
||||
if got, readErr := os.ReadFile(source); readErr != nil || !bytes.Equal(got, data) {
|
||||
t.Fatal("source changed", readErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3SignedRequestsNeverFollowRedirects(t *testing.T) {
|
||||
var reached atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached.Add(1); w.WriteHeader(204) }))
|
||||
defer target.Close()
|
||||
for _, status := range []int{301, 302, 303, 307, 308} {
|
||||
t.Run(strconv.Itoa(status), func(t *testing.T) {
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") == "" || r.Header.Get("X-Amz-Security-Token") != "fixture-session" {
|
||||
t.Error("fixture request must be signed with session credentials")
|
||||
}
|
||||
w.Header().Set("Location", target.URL+"/redirected")
|
||||
w.WriteHeader(status)
|
||||
}))
|
||||
defer origin.Close()
|
||||
store, err := New(Config{Endpoint: origin.URL, Bucket: "test", AccessKey: "test", SecretKey: "test", SessionToken: "fixture-session", PathStyle: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Delete(context.Background(), store.URI(1, 2, "test")); err == nil {
|
||||
t.Fatal("redirect accepted")
|
||||
}
|
||||
if reached.Load() != 0 {
|
||||
t.Fatal("signed request followed redirect")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3CustomCABundleForBothCredentialModes(t *testing.T) {
|
||||
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }))
|
||||
defer srv.Close()
|
||||
for _, explicit := range []bool{false, true} {
|
||||
t.Run(strconv.FormatBool(explicit), func(t *testing.T) {
|
||||
isolateAWSCredentials(t)
|
||||
ca := filepath.Join(t.TempDir(), "ca.pem")
|
||||
if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("AWS_CA_BUNDLE", ca)
|
||||
c := Config{Endpoint: srv.URL, Bucket: "test", PathStyle: true}
|
||||
if explicit {
|
||||
c.AccessKey, c.SecretKey = "fixture", "fixture"
|
||||
} else {
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "fixture")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "fixture")
|
||||
}
|
||||
store, err := New(c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Delete(context.Background(), store.URI(1, 2, "test")); err != nil {
|
||||
t.Fatalf("configured CA not used: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3RangeRetriesHaveOneWireAttemptEach(t *testing.T) {
|
||||
for _, status := range []int{403, 429, 503} {
|
||||
t.Run(strconv.Itoa(status), func(t *testing.T) {
|
||||
var gets atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gets.Add(1)
|
||||
w.WriteHeader(status)
|
||||
}))
|
||||
defer srv.Close()
|
||||
store := testRangeStore(t, srv.URL)
|
||||
if _, err := store.readArchiveChunk(context.Background(), "key", `"etag"`, 0, 9, 10); err == nil {
|
||||
t.Fatal("failed request accepted")
|
||||
}
|
||||
want := int32(archiveReadAttempts)
|
||||
if status == 403 {
|
||||
want = 1
|
||||
}
|
||||
if got := gets.Load(); got != want {
|
||||
t.Fatalf("wire requests=%d want=%d", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// artex-archive-check tests the configured object store without touching tasks.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/archivestore"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := check(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func check() error {
|
||||
s, err := archivestore.FromEnv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil {
|
||||
return fmt.Errorf("S3 archive storage is not configured")
|
||||
}
|
||||
dir, err := os.MkdirTemp("", "artex-archive-check-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
data := []byte("ARTEX object storage connectivity check " + time.Now().UTC().Format(time.RFC3339Nano))
|
||||
h := sha256.Sum256(data)
|
||||
checksum := hex.EncodeToString(h[:])
|
||||
uri := s.URI(0, time.Now().UnixNano(), checksum)
|
||||
file := filepath.Join(dir, "check")
|
||||
if err := os.WriteFile(file, data, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
defer func() {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err := s.Delete(cleanup, uri); err != nil {
|
||||
log.Printf("test object cleanup failed for %s: %v", uri, err)
|
||||
}
|
||||
}()
|
||||
if err := s.Upload(ctx, uri, file, checksum); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Download(ctx, uri, filepath.Join(dir, "download"), checksum, int64(len(data))); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Delete(ctx, uri); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("S3 upload, full SHA-256 verification, download and delete passed")
|
||||
return nil
|
||||
}
|
||||
+22
-7
@@ -10,6 +10,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -209,16 +210,30 @@ func (d Database) buildDSN() string {
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// String is a redacted view of the resolved DSN (password masked) for logging.
|
||||
// libpqPassword matches a libpq keyword DSN password field, including quoted
|
||||
// values. pgx accepts this form as well as the URL form.
|
||||
var libpqPassword = regexp.MustCompile(`(?i)\b(password)\s*=\s*(?:'[^']*'|"[^"]*"|\S*)`)
|
||||
|
||||
// Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo
|
||||
// passwords, `?password=` query values, and libpq `password=` keywords.
|
||||
// Unrecognised input still runs the keyword mask so a parse failure cannot
|
||||
// print the secret.
|
||||
func Redact(dsn string) string {
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
if dsn == "" {
|
||||
return dsn
|
||||
}
|
||||
if u.User != nil {
|
||||
if _, hasPw := u.User.Password(); hasPw {
|
||||
u.User = url.UserPassword(u.User.Username(), "****")
|
||||
if u, err := url.Parse(dsn); err == nil && (u.Scheme == "postgres" || u.Scheme == "postgresql") {
|
||||
if u.User != nil {
|
||||
if _, hasPw := u.User.Password(); hasPw {
|
||||
u.User = url.UserPassword(u.User.Username(), "****")
|
||||
}
|
||||
}
|
||||
q := u.Query()
|
||||
if q.Has("password") {
|
||||
q.Set("password", "****")
|
||||
u.RawQuery = q.Encode()
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
return fmt.Sprintf("%s", u.String())
|
||||
return libpqPassword.ReplaceAllString(dsn, `${1}=****`)
|
||||
}
|
||||
|
||||
@@ -44,6 +44,22 @@ func TestPostgresDSNPrecedence(t *testing.T) {
|
||||
|
||||
// A config file that exists but is not valid JSON must fail loudly, not run with
|
||||
// defaults (or report "no database config") as if the file were absent.
|
||||
func TestRedactMasksEveryDSNPasswordForm(t *testing.T) {
|
||||
cases := []struct{ in, secret string }{
|
||||
{"postgres://u:secret@localhost:5432/d?sslmode=require", "secret"},
|
||||
{"postgresql://localhost/d?password=secret&sslmode=require", "secret"},
|
||||
{"host=localhost user=u password=secret dbname=d", "secret"},
|
||||
{"host=localhost password='p a ss' dbname=d", "p a ss"},
|
||||
{"not a dsn password=stillsecret", "stillsecret"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := Redact(c.in)
|
||||
if strings.Contains(got, c.secret) {
|
||||
t.Errorf("Redact(%q)=%q still contains %q", c.in, got, c.secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedConfigIsAnError(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "config.json")
|
||||
// What install.sh used to write for a password containing a double quote.
|
||||
|
||||
+19
-1
@@ -136,9 +136,15 @@ func tokenize(s string) ([]tok, error) {
|
||||
// and_expr = atom (AND atom)*
|
||||
// atom = FIELD | BARE | '(' expr ')'
|
||||
|
||||
const (
|
||||
dslMaxLen = 4096
|
||||
dslMaxDepth = 32
|
||||
)
|
||||
|
||||
type dslParser struct {
|
||||
tokens []tok
|
||||
pos int
|
||||
depth int
|
||||
}
|
||||
|
||||
func (p *dslParser) peek() tok {
|
||||
@@ -201,8 +207,13 @@ func (p *dslParser) parseAtom() (*astNode, error) {
|
||||
p.consume()
|
||||
return leafNode(*t.expr), nil
|
||||
case tkLP:
|
||||
if p.depth >= dslMaxDepth {
|
||||
return nil, fmt.Errorf("DSL syntax error: nested parentheses too deep")
|
||||
}
|
||||
p.depth++
|
||||
p.consume()
|
||||
node, err := p.parseOr()
|
||||
p.depth--
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -234,6 +245,9 @@ func ParseDSL(s string) (*astNode, error) {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if len(s) > dslMaxLen {
|
||||
return nil, fmt.Errorf("DSL query is too long")
|
||||
}
|
||||
tokens, err := tokenize(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -288,7 +302,11 @@ func (b *whereBuilder) build(node *astNode) (string, error) {
|
||||
}
|
||||
parts = append(parts, "("+clause+")")
|
||||
}
|
||||
return strings.Join(parts, " OR "), nil
|
||||
// The whole disjunction must be parenthesised: callers append their own
|
||||
// clauses with AND (the task scope in QueryDSLInScope, the type filter),
|
||||
// and AND binds tighter than OR, so "(a) OR (b) AND scope" would let the
|
||||
// first branch escape the scope.
|
||||
return "(" + strings.Join(parts, " OR ") + ")", nil
|
||||
case "leaf":
|
||||
return b.buildLeaf(*node.expr)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseDSLRejectsDeepNesting(t *testing.T) {
|
||||
deep := strings.Repeat("(", dslMaxDepth+1) + "a" + strings.Repeat(")", dslMaxDepth+1)
|
||||
if _, err := ParseDSL(deep); err == nil {
|
||||
t.Fatal("deep nesting accepted")
|
||||
}
|
||||
ok := strings.Repeat("(", dslMaxDepth) + "a" + strings.Repeat(")", dslMaxDepth)
|
||||
if _, err := ParseDSL(ok); err != nil {
|
||||
t.Fatalf("depth %d refused: %v", dslMaxDepth, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDSLRejectsOversize(t *testing.T) {
|
||||
if _, err := ParseDSL(strings.Repeat("a", dslMaxLen+1)); err == nil {
|
||||
t.Fatal("oversize query accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A top-level OR must be parenthesised as a whole. QueryDSLInScope appends the
|
||||
// task-scope clause with AND, and AND binds tighter than OR, so an unparenthesised
|
||||
// disjunction lets the first branch return rows from outside the task scope.
|
||||
func TestBuildDSLWhereWrapsOr(t *testing.T) {
|
||||
node, err := ParseDSL("domain=alpha OR domain=beta")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
where, _, err := buildDSLWhereBase(node, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(where, "((") || !strings.HasSuffix(where, "))") {
|
||||
t.Fatalf("compiled to %q: the whole OR group must be parenthesised", where)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQueryDSLInScopeOrDoesNotEscape is the behavioural form: an OR query whose
|
||||
// first branch matches every row must not return an asset outside the task scope.
|
||||
func TestQueryDSLInScopeOrDoesNotEscape(t *testing.T) {
|
||||
d, assets, _ := testSetup(t)
|
||||
t.Cleanup(func() { d.Close() })
|
||||
|
||||
task, err := d.CreateTask("or scope", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { cleanupErr(t, "task", d.DeleteTask(task.ID)) })
|
||||
|
||||
stamp := time.Now().UnixNano()
|
||||
root := fmt.Sprintf("in%d.invalid", stamp)
|
||||
out := fmt.Sprintf("x%d.invalid", stamp)
|
||||
marker := fmt.Sprintf("or%d", stamp)
|
||||
|
||||
if err := assets.upsertTaskScope(TaskScope{TaskID: task.ID, Kind: "root_domain", Domain: root}); err != nil {
|
||||
t.Fatalf("seed scope: %v", err)
|
||||
}
|
||||
|
||||
var inID, outID int64
|
||||
for _, r := range []struct {
|
||||
domain, root string
|
||||
id *int64
|
||||
}{
|
||||
{"a." + root, root, &inID},
|
||||
{out, out, &outID},
|
||||
} {
|
||||
if err := d.QueryRow(`INSERT INTO assets(type,domain,root_domain,page_title,last_seen)
|
||||
VALUES ('subdomain',$1,$2,$3,now()) RETURNING id`, r.domain, r.root, marker).Scan(r.id); err != nil {
|
||||
t.Fatalf("insert %s: %v", r.domain, err)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cleanupExec(t, d, `DELETE FROM assets WHERE id=ANY($1::bigint[])`, []int64{inID, outID})
|
||||
})
|
||||
|
||||
// The bare marker matches both rows; the second branch names the out-of-scope
|
||||
// host. Only the in-scope row may come back.
|
||||
got, err := assets.QueryDSLInScope(marker+" OR domain="+out, "", task.ID, 50, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var sawIn, sawOut bool
|
||||
for _, a := range got {
|
||||
switch a.ID {
|
||||
case inID:
|
||||
sawIn = true
|
||||
case outID:
|
||||
sawOut = true
|
||||
}
|
||||
}
|
||||
if !sawIn {
|
||||
t.Fatalf("in-scope asset %d missing from %+v", inID, got)
|
||||
}
|
||||
if sawOut {
|
||||
t.Fatalf("out-of-scope asset %d leaked through an OR query", outID)
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -250,8 +250,15 @@ func (g *Governor) reserve(h *hostState) time.Duration {
|
||||
// asks for more than MaxDelay.
|
||||
func (g *Governor) backoff(h http.Header, attempt int) (d time.Duration, ok bool) {
|
||||
v := strings.TrimSpace(h.Get("Retry-After"))
|
||||
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
|
||||
return time.Duration(n) * time.Second, time.Duration(n)*time.Second <= g.p.MaxDelay
|
||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 0 {
|
||||
maxSec := int64(g.p.MaxDelay / time.Second)
|
||||
if maxSec < 0 {
|
||||
maxSec = 0
|
||||
}
|
||||
if n > maxSec {
|
||||
return 0, false
|
||||
}
|
||||
return time.Duration(n) * time.Second, true
|
||||
}
|
||||
if t, err := http.ParseTime(v); err == nil {
|
||||
return max(time.Until(t), 0), time.Until(t) <= g.p.MaxDelay
|
||||
|
||||
@@ -145,6 +145,10 @@ func TestBackoff(t *testing.T) {
|
||||
if d, ok := g.backoff(h, 0); !ok || d <= 0 || d > 2*time.Second {
|
||||
t.Fatalf("HTTP-date Retry-After: %s, %v", d, ok)
|
||||
}
|
||||
// A huge second count used to wrap Duration and look like an immediate retry.
|
||||
if d, ok := g.backoff(http.Header{"Retry-After": {"9223372036854775807"}}, 0); ok || d != 0 {
|
||||
t.Fatalf("overflow Retry-After: %s %v, want refuse", d, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDedupeAndCache(t *testing.T) {
|
||||
|
||||
@@ -4,6 +4,11 @@ go 1.26.10
|
||||
|
||||
require (
|
||||
github.com/Autumn-27/norma v0.4.11
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.5
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.13
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.13
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
@@ -22,6 +27,20 @@ require (
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.2.1 // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect
|
||||
github.com/aws/smithy-go v1.28.7 // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/creack/pty v1.1.24 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
|
||||
@@ -4,6 +4,44 @@ github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eT
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.5/go.mod h1:iNIkogrRvFwm+1OQIUOP2lPBtlXZboOIUWiCa+pHEMw=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 h1:MW0Iql1SOTgQPj8mCxrU/eH/K/AIDWi08ItOsXaWRLU=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25/go.mod h1:+ucVYmHYB3JqVueY0E1RHahdXAnKQbIHqybSbvOUbOM=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.13 h1:u52x6ISQOx172tpwM0VRxhJzEsTJYpMcEYUGM2A1wrw=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.13/go.mod h1:/ixtz6XPHb42zekjQ0LqD9XjTpTysNWhIGwufY1OzI4=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.13 h1:j4z41OtspmQ3ftQycaDunJ26b69a9SHfaSVUPqgRv8k=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.13/go.mod h1:SgPA1oS3b+dlMxZb618jDmGNscpXSCaxz15igS52OlE=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 h1:iXjy2SFhGYNB1jWZBhQqq8HbhsbPF23w+/zbMvPXsTg=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5/go.mod h1:k0RUiBnyXU0AXRJ9tJmY2jQke6XUIX2PNVnWtvgaPtc=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19 h1:+JWfo9Mkg5HWwDwnpRPu7WNiiyEmiQRTaNSFsZ/1KIY=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19/go.mod h1:l4/tI+TfymypMqq2oRCkhMAB7Gi7nlt5JaoUUz+cUbI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9 h1:GACgECI422Xt5n4Pojr3O0aocPv8lfH4PJe2Aon5Wv8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9/go.mod h1:lPfnRkHpn1qWZJLbVEw10rIqSuCee1pNQTyGkUjAYh8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8 h1:RS1Wt+K0r4X0ci9Vf4JYTUfHzsQihYA2LgGJeEneKpk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8/go.mod h1:adMnTy5kyoUW86jhXnGSVc/mvMQI4GZd1qYWMeaS8M8=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 h1:to7+Vr3rLkpYRwVKJ5QRriI0eE306vrVN/6TnVHgxvY=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6/go.mod h1:Jc89ASa2k7HMAskj3bSnt8bf+k+p2IApzkoXnEjkgUw=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 h1:WZLC+k/CZx11kZGQDqu9mpA8yhiXGX2I//jhuJE1FDo=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.12.1/go.mod h1:wxAk0D2oVBSjuXEIzvcKxTZfM90zticdAbh/VD42L0Y=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 h1:4VB/dnDo7pmXSLQMszSoBzWndENuc7mzwTpD6lQn77A=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.1/go.mod h1:UGsEYgWz4Gi+46vDQ5zkFLqUgJziyOE2SXjZjgmfmHc=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 h1:w8yui2ZqdHmGwVBDGvazoIvKw/DnLENBLkYnN8q8iqo=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1/go.mod h1:gJSdIY6YUzDvqQLcMtPVZgBRHrFwzHryvpE8Igzbxps=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw=
|
||||
github.com/aws/smithy-go v1.28.7 h1:h/n1SHrwVtaDYLz8mR1/Kq4Xh4RaFbFW7bOYckg9mfE=
|
||||
github.com/aws/smithy-go v1.28.7/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
||||
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
||||
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
|
||||
|
||||
+4
-4
@@ -15,12 +15,12 @@ import (
|
||||
func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
|
||||
ic := intercept.New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{
|
||||
{ID: 1, Name: "no force push", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "string",
|
||||
{ID: 1, Name: "no force flag", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "string",
|
||||
Pattern: "--force", Action: "deny", Message: "force push is forbidden"},
|
||||
{ID: 2, Name: "argv allow curl", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
|
||||
Pattern: `["curl"]`, Action: "allow"},
|
||||
{ID: 3, Name: "argv allow git push", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
|
||||
Pattern: `["git","push"]`, Action: "allow"},
|
||||
{ID: 3, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
|
||||
Pattern: `["nmap"]`, Action: "allow"},
|
||||
})
|
||||
g := NewWithInterceptor(ic)
|
||||
gate := &fakeGate{t: t, check: unpinnedOnce, request: func(int, []intercept.TargetRequest, *intercept.Decision) intercept.TargetResult {
|
||||
@@ -29,7 +29,7 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
|
||||
g.gate = gate
|
||||
ctx := gateOn(context.Background(), "7", time.Minute)
|
||||
|
||||
if block, msg := pre(g, ctx, "Bash", `{"command":"git push --force origin"}`); !block || !strings.Contains(msg, "force push is forbidden") {
|
||||
if block, msg := pre(g, ctx, "Bash", `{"command":"nmap --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") {
|
||||
t.Fatalf("deny over argv allow: block=%v msg=%q", block, msg)
|
||||
}
|
||||
if gate.checks != 0 {
|
||||
|
||||
+27
-18
@@ -82,31 +82,40 @@ func (g *Guard) setGate(ic *intercept.Interceptor) {
|
||||
func (g *Guard) Hooks() *hook.Registry { return g.reg }
|
||||
|
||||
func (g *Guard) preToolUse(ctx context.Context, ev hook.Event) hook.Result {
|
||||
cmd := toolAuditCommand(ev)
|
||||
res := g.applyIntercept(ctx, ev, cmd)
|
||||
if g.targetOnly {
|
||||
// Not recorded: the audit ring is for the gated worker and chat calls.
|
||||
return g.applyIntercept(ctx, ev)
|
||||
// Not recorded on a pass: the audit ring is for the gated worker and chat
|
||||
// calls. A block still writes through block().
|
||||
return res
|
||||
}
|
||||
// Extract the shell-command surface for the audit log: Bash + the interactive-shell
|
||||
// tools (shell_open's command, shell_send's text). Destructive/exfil gating is no
|
||||
// longer hard-coded here — it now lives in the DB intercept rules, evaluated by
|
||||
// applyIntercept below. Other tools record an empty command.
|
||||
var cmd string
|
||||
// Record the final decision only. An allow written before applyIntercept
|
||||
// stayed in the ring when the call was later blocked, so Audit() showed a
|
||||
// call as allowed that never ran.
|
||||
if res.Decision != "block" {
|
||||
g.record(ev.ToolName, "allow", "", cmd)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// toolAuditCommand is the shell-command surface for the audit log: Bash and
|
||||
// shell_open's command, shell_send's text. Other tools record an empty command.
|
||||
func toolAuditCommand(ev hook.Event) string {
|
||||
switch ev.ToolName {
|
||||
case "Bash", "shell_open":
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
_ = json.Unmarshal(ev.Input, &in)
|
||||
cmd = in.Command
|
||||
return in.Command
|
||||
case "shell_send":
|
||||
var in struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
_ = json.Unmarshal(ev.Input, &in)
|
||||
cmd = in.Text
|
||||
return in.Text
|
||||
}
|
||||
g.record(ev.ToolName, "allow", "", cmd)
|
||||
return g.applyIntercept(ctx, ev)
|
||||
return ""
|
||||
}
|
||||
|
||||
// targetGate is the approval gate for asset targets, as the guard uses it.
|
||||
@@ -138,7 +147,7 @@ func (g *Guard) gateScope(ctx context.Context) (intercept.TargetScope, bool) {
|
||||
// is on: a deny blocks first, before any target request exists; an allow by a
|
||||
// rule or by the judge does not satisfy the gate; an ask and an unpinned target
|
||||
// share one approval request.
|
||||
func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result {
|
||||
func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event, cmd string) hook.Result {
|
||||
if g.targetOnly && g.interceptor != nil {
|
||||
// The planner and the main agent run Bash too (#124, F11): the built-in
|
||||
// deny rules apply to them, before the target gate. User rules and the
|
||||
@@ -146,7 +155,7 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result {
|
||||
if dec, ok := g.interceptor.MatchBuiltin(ev.ToolName, ev.Input); ok {
|
||||
ctx = intercept.WithCall(ctx, ev.ToolName, ev.Input)
|
||||
g.interceptor.Log(ctx, intercept.ConvIDFromContext(ctx), dec, ev.ToolName, ev.Input, "denied")
|
||||
return g.block(ev.ToolName, systemBlockMessage(dec.Message), "")
|
||||
return g.block(ev.ToolName, systemBlockMessage(dec.Message), cmd)
|
||||
}
|
||||
}
|
||||
scope, gated := g.gateScope(ctx)
|
||||
@@ -168,13 +177,13 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result {
|
||||
if dec.Action == "deny" {
|
||||
// Note: a deny hit does not block for approval; it directly logs a denied entry (visible on the history / task interception pages).
|
||||
g.interceptor.Log(ctx, intercept.ConvIDFromContext(ctx), dec, ev.ToolName, ev.Input, "denied")
|
||||
return g.block(ev.ToolName, systemBlockMessage(dec.Message), "")
|
||||
return g.block(ev.ToolName, systemBlockMessage(dec.Message), cmd)
|
||||
}
|
||||
var unpinned []intercept.TargetRequest
|
||||
if gated {
|
||||
var res intercept.TargetResult
|
||||
if unpinned, res = g.gate.CheckTargets(ctx, scope, ev.ToolName, ev.Input); res.Code != "" {
|
||||
return g.block(ev.ToolName, TargetBlockMessage(res), "")
|
||||
return g.block(ev.ToolName, TargetBlockMessage(res), cmd)
|
||||
}
|
||||
}
|
||||
var ask *intercept.Decision
|
||||
@@ -187,14 +196,14 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result {
|
||||
// immediately without creating a pending record — avoids orphaned DB entries
|
||||
// and makes execOne complete fast, reducing the race against drainSynthetic.
|
||||
if ctx.Err() != nil {
|
||||
return g.block(ev.ToolName, systemBlockMessage("work cancelled; platform safety controls blocked execution"), "")
|
||||
return g.block(ev.ToolName, systemBlockMessage("work cancelled; platform safety controls blocked execution"), cmd)
|
||||
}
|
||||
ask = &dec
|
||||
}
|
||||
if len(unpinned) > 0 {
|
||||
res, merged := g.requestTargets(ctx, scope, ev, unpinned, ask)
|
||||
if res.Code != "" {
|
||||
return g.block(ev.ToolName, TargetBlockMessage(res), "")
|
||||
return g.block(ev.ToolName, TargetBlockMessage(res), cmd)
|
||||
}
|
||||
if merged {
|
||||
// The approval of the target request answered the ask as well.
|
||||
@@ -204,7 +213,7 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result {
|
||||
if ask != nil {
|
||||
convID := intercept.ConvIDFromContext(ctx)
|
||||
if !g.interceptor.HandleAsk(ctx, convID, dec, ev.ToolName, ev.Input) {
|
||||
return g.block(ev.ToolName, systemBlockMessage("manual approval not granted (user rejected or approval timed out)"), "")
|
||||
return g.block(ev.ToolName, systemBlockMessage("manual approval not granted (user rejected or approval timed out)"), cmd)
|
||||
}
|
||||
}
|
||||
return hook.Result{}
|
||||
|
||||
@@ -41,6 +41,34 @@ func TestPreToolUsePassthrough(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A deny must not leave a prior allow row in the audit ring.
|
||||
func TestPreToolUseAuditIsFinalDecision(t *testing.T) {
|
||||
ic := intercept.New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{{
|
||||
ID: 1, Name: "deny nmap", Enabled: true, Priority: 10,
|
||||
MatchTarget: "tool_input", MatchType: "string", Action: "deny",
|
||||
Pattern: "nmap", Message: "no nmap",
|
||||
}})
|
||||
g := NewWithInterceptor(ic)
|
||||
input, _ := json.Marshal(map[string]string{"command": "nmap -sV x"})
|
||||
block, _, _ := g.Hooks().PreToolUse(context.Background(), "Bash", input)
|
||||
if !block {
|
||||
t.Fatal("expected block")
|
||||
}
|
||||
audit := g.Audit()
|
||||
if len(audit) != 1 || audit[0].Action != "block" || audit[0].Tool != "Bash" {
|
||||
t.Fatalf("audit=%+v, want a single block", audit)
|
||||
}
|
||||
if audit[0].Command != "nmap -sV x" {
|
||||
t.Fatalf("block command=%q, want the denied command", audit[0].Command)
|
||||
}
|
||||
for _, e := range audit {
|
||||
if e.Action == "allow" {
|
||||
t.Fatalf("blocked call still has an allow row: %+v", audit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The target-only guard (planner, main agent) runs the built-in deny rules and
|
||||
// the target gate: no user intercept rule, no fallback judge, no audit-ring entry
|
||||
// for a call that passes (in production the built-in rules come from the store,
|
||||
|
||||
@@ -530,7 +530,9 @@ func TestGateOffLeavesEveryBranchUnchanged(t *testing.T) {
|
||||
for name, ctx := range off {
|
||||
before := len(g.rows())
|
||||
// 1. A tool outside the enabled set: passes, nothing is written.
|
||||
for _, c := range []struct{ tool, input string }{{"Monitor", curl(deny)}, {"mcp__scan__run", `{"target":"203.0.113.7","note":"` + deny + `"}`}} {
|
||||
// Monitor and ExecuteExtraTool are in the default set now, so use read-only
|
||||
// tools and an MCP name (inner names are not in the set).
|
||||
for _, c := range []struct{ tool, input string }{{"list_assets", curl(deny)}, {"mcp__scan__run", `{"target":"203.0.113.7","note":"` + deny + `"}`}} {
|
||||
if block, msg := pre(guard, ctx, c.tool, c.input); block {
|
||||
t.Fatalf("%s: %s blocked: %s", name, c.tool, msg)
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ var alwaysAllowDenylist = func() map[string]bool {
|
||||
// package managers and build tools: run package scripts and hooks
|
||||
"npm npx pnpm yarn bunx corepack pip pipx uv uvx poetry conda composer gem bundle bundler rake cargo go " +
|
||||
"mvn gradle dotnet apt apt-get dpkg dnf yum rpm pacman apk brew snap flatpak",
|
||||
// version control and build generators: run hooks, aliases and script files
|
||||
"git cmake ctest cpack",
|
||||
// orchestration: run images, playbooks and plans
|
||||
"docker docker-compose podman nerdctl kubectl helm ansible ansible-playbook terraform pulumi vagrant",
|
||||
// destructive
|
||||
|
||||
@@ -13,12 +13,13 @@ func TestArgvAllowDenylist(t *testing.T) {
|
||||
"python", "python3", "python3.11", "/usr/bin/python3.11", "php8.2", "ruby3.2", "perl5", "pip3",
|
||||
"env", "/usr/bin/env", "bash", "/bin/sh", "find", "rm", "mkfs", "mkfs.ext4", "/sbin/mkfs.xfs",
|
||||
"docker", "kubectl", "npm", "sudo", "xargs", "Rscript", ".",
|
||||
"git", "/usr/bin/git", "cmake", "cmake3", "/usr/bin/cmake", "ctest", "cpack",
|
||||
} {
|
||||
if !ArgvAllowDenied(prog) {
|
||||
t.Errorf("%q is not denied", prog)
|
||||
}
|
||||
}
|
||||
for _, prog := range []string{"nmap", "git", "/usr/bin/git", "curl", "ls", "gh", "x", "7z", "pythonic"} {
|
||||
for _, prog := range []string{"nmap", "curl", "ls", "gh", "x", "7z", "pythonic"} {
|
||||
if ArgvAllowDenied(prog) {
|
||||
t.Errorf("%q is denied, want allowable", prog)
|
||||
}
|
||||
@@ -30,8 +31,8 @@ func TestAlwaysAllowPrefix(t *testing.T) {
|
||||
b, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
return b
|
||||
}
|
||||
if got, err := AlwaysAllowPrefix("Bash", bash("git push --force origin main")); err != nil || !slices.Equal(got, []string{"git", "push"}) {
|
||||
t.Fatalf("git push: %q %v", got, err)
|
||||
if got, err := AlwaysAllowPrefix("Bash", bash("gh pr list --limit 5")); err != nil || !slices.Equal(got, []string{"gh", "pr", "list"}) {
|
||||
t.Fatalf("gh pr list: %q %v", got, err)
|
||||
}
|
||||
if got, err := AlwaysAllowPrefix("Bash", bash("nmap -p 80 10.0.0.1")); err != nil || !slices.Equal(got, []string{"nmap"}) {
|
||||
t.Fatalf("nmap: %q %v", got, err)
|
||||
@@ -40,10 +41,10 @@ func TestAlwaysAllowPrefix(t *testing.T) {
|
||||
tool string
|
||||
input []byte
|
||||
}{
|
||||
"not Bash": {"shell_open", bash("git push")},
|
||||
"compound": {"Bash", bash("git push; id")},
|
||||
"substitution": {"Bash", bash("git push $(id)")},
|
||||
"redirection": {"Bash", bash("git push > out")},
|
||||
"not Bash": {"shell_open", bash("gh pr list")},
|
||||
"compound": {"Bash", bash("gh pr list; id")},
|
||||
"substitution": {"Bash", bash("gh pr list $(id)")},
|
||||
"redirection": {"Bash", bash("gh pr list > out")},
|
||||
"empty": {"Bash", bash("")},
|
||||
"no command": {"Bash", []byte(`{}`)},
|
||||
"not json": {"Bash", []byte(`not json`)},
|
||||
@@ -52,6 +53,11 @@ func TestAlwaysAllowPrefix(t *testing.T) {
|
||||
"find": {"Bash", bash("find . -exec sh -c id ;")},
|
||||
"rm": {"Bash", bash("rm -rf /")},
|
||||
"docker": {"Bash", bash("docker run --privileged x")},
|
||||
"git": {"Bash", bash("git status")},
|
||||
"path to git": {"Bash", bash("/usr/bin/git status")},
|
||||
"git config": {"Bash", bash("git config user.name x")},
|
||||
"cmake": {"Bash", bash("cmake --version")},
|
||||
"ctest": {"Bash", bash("ctest -N")},
|
||||
} {
|
||||
if got, err := AlwaysAllowPrefix(c.tool, c.input); err == nil {
|
||||
t.Errorf("%s: prefix %q, want a refusal", name, got)
|
||||
@@ -59,6 +65,20 @@ func TestAlwaysAllowPrefix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The arity table is keyed by program name, so a path-qualified binary derives
|
||||
// the same prefix length as the bare name.
|
||||
func TestArgvPrefixLenUsesBasename(t *testing.T) {
|
||||
if got := argvPrefixLen([]string{"/usr/bin/gh", "pr", "list"}); got != 3 {
|
||||
t.Errorf("path-qualified gh prefix length = %d, want 3", got)
|
||||
}
|
||||
if got := argvPrefixLen([]string{"/usr/bin/git", "status"}); got != 2 {
|
||||
t.Errorf("path-qualified git prefix length = %d, want 2", got)
|
||||
}
|
||||
if got, err := ArgvPrefix("/usr/bin/gh pr list"); err != nil || !slices.Equal(got, []string{"/usr/bin/gh", "pr", "list"}) {
|
||||
t.Errorf("path-qualified gh prefix = %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The denylist neutralises argv allow rules at matching time (a rule created
|
||||
// before the denylist, or written straight into the database), and only them:
|
||||
// an argv deny or ask rule for the same program still matches.
|
||||
|
||||
+9
-1
@@ -25,9 +25,17 @@ var argvArity = map[string]int{
|
||||
}
|
||||
|
||||
// argvPrefixLen returns the number of leading tokens that form the prefix.
|
||||
// The arity table is keyed by program name, so a path-qualified binary
|
||||
// (/usr/bin/git) uses the same arity as the bare name.
|
||||
func argvPrefixLen(tokens []string) int {
|
||||
if len(tokens) == 0 {
|
||||
return 0
|
||||
}
|
||||
key := make([]string, len(tokens))
|
||||
copy(key, tokens)
|
||||
key[0] = argvProgramName(tokens[0])
|
||||
for n := len(tokens); n > 0; n-- {
|
||||
if a, ok := argvArity[strings.Join(tokens[:n], " ")]; ok {
|
||||
if a, ok := argvArity[strings.Join(key[:n], " ")]; ok {
|
||||
return min(a, len(tokens))
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,291 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func bashInput(cmd string) []byte {
|
||||
b, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
return b
|
||||
}
|
||||
|
||||
func matchSingleArgvRule(action, pattern, toolName string, input []byte) (Decision, bool) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{{
|
||||
ID: 1,
|
||||
Name: action + " " + pattern,
|
||||
Enabled: true,
|
||||
Priority: 100,
|
||||
MatchTarget: "tool_input",
|
||||
MatchType: "argv",
|
||||
Pattern: pattern,
|
||||
Action: action,
|
||||
}})
|
||||
return ic.Match(toolName, input)
|
||||
}
|
||||
|
||||
func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) {
|
||||
nmapShouldMatch := []struct {
|
||||
name string
|
||||
cmd string
|
||||
}{
|
||||
{"plain", "nmap -p 80 x"},
|
||||
{"command wrapper", "command nmap -p 80 x"},
|
||||
{"command double dash", "command -- nmap -p 80 x"},
|
||||
{"command -p", "command -p nmap -p 80 x"},
|
||||
{"path qualified", "/usr/bin/nmap -p 80 x"},
|
||||
{"sudo", "sudo nmap -p 80 x"},
|
||||
{"sudo with flags and assign", "sudo -u root -n FOO=1 nmap -p 80 x"},
|
||||
{"doas", "doas -u root nmap -p 80 x"},
|
||||
{"env with assign", "env FOO=1 nmap -p 80 x"},
|
||||
{"env with flags", "env -i -u HOME -C /tmp -S arg FOO=1 nmap -p 80 x"},
|
||||
{"env with expansion in assign", "env FOO=$(id) nmap -p 80 x"},
|
||||
{"env -S separate", "env -S 'nmap -p 80 x'"},
|
||||
{"env -S attached", "env -S'nmap -p 80 x'"},
|
||||
{"env --split-string equals", "env --split-string='nmap -p 80 x'"},
|
||||
{"env --split-string separate", "env --split-string 'nmap -p 80 x'"},
|
||||
{"env -S with env flags", "env -S '-i FOO=1 nmap -p 80 x'"},
|
||||
{"timeout", "timeout 30 nmap -p 80 x"},
|
||||
{"timeout with flags", "timeout -k 5 -s KILL 30 nmap -p 80 x"},
|
||||
{"nohup", "nohup nmap -p 80 x"},
|
||||
{"setsid", "setsid -f nmap -p 80 x"},
|
||||
{"stdbuf", "stdbuf -oL -eL nmap -p 80 x"},
|
||||
{"nice -n", "nice -n 10 nmap -p 80 x"},
|
||||
{"nice numeric flag", "nice -10 nmap -p 80 x"},
|
||||
{"ionice", "ionice -c 3 nmap -p 80 x"},
|
||||
{"taskset", "taskset -c 0-1 nmap -p 80 x"},
|
||||
{"chrt", "chrt -f 50 nmap -p 80 x"},
|
||||
{"watch", "watch -n 5 nmap -p 80 x"},
|
||||
{"watch -d permanent", "watch -d permanent nmap -p 80 x"},
|
||||
{"flock", "flock -n /tmp/lock nmap -p 80 x"},
|
||||
{"flock -c after lockfile", "flock /tmp/lock -c 'nmap -p 80 x'"},
|
||||
{"flock -c before lockfile", "flock -n -c 'nmap -p 80 x' /tmp/lock"},
|
||||
{"strace", "strace -f -o /tmp/trace nmap -p 80 x"},
|
||||
{"ltrace", "ltrace -f -o /tmp/ltrace nmap -p 80 x"},
|
||||
{"xargs", "echo 10.0.0.1 | xargs -n 1 nmap -p 80"},
|
||||
{"xargs -I", "xargs -I{} nmap -p 80 {}"},
|
||||
{"xargs -l bare", "xargs -l nmap"},
|
||||
{"xargs -l5 attached", "xargs -l5 nmap"},
|
||||
{"xargs -l 5 separate", "xargs -l 5 nmap"},
|
||||
{"find -exec", `find . -maxdepth 0 -exec nmap -p 80 x \;`},
|
||||
{"find -execdir", `find . -execdir nmap -p 80 x \;`},
|
||||
{"find -ok", `find . -ok nmap -p 80 x \;`},
|
||||
{"find -okdir plus", `find . -okdir nmap -p 80 x +`},
|
||||
{"find multiple -exec clauses", `find . -exec echo {} \; -exec nmap -p 80 {} \;`},
|
||||
{"find -exec shell wrapper", `find . -exec sh -ec 'nmap -p 80 x' \;`},
|
||||
{"parallel bare", "parallel nmap"},
|
||||
{"parallel with jobs and :::", "parallel -j 4 nmap -p 80 {} ::: 10.0.0.1"},
|
||||
{"parallel quoted shell string", "parallel -j 4 'nmap -p 80 {}' ::: 10.0.0.1"},
|
||||
{"parallel no command ::: bare", "parallel ::: nmap"},
|
||||
{"parallel no command ::: quoted line", `parallel ::: "nmap -p 80 x"`},
|
||||
{"parallel no command -j2 ::: bare", "parallel -j2 ::: nmap"},
|
||||
{"parallel no command ::: multiple lines", "parallel ::: echo nmap"},
|
||||
{"parallel --link ::: nmap", "parallel --link ::: nmap"},
|
||||
{"parallel --xargs ::: nmap", "parallel --xargs ::: nmap"},
|
||||
{"parallel unknown no-arg long opt", "parallel --future-flag ::: nmap"},
|
||||
{"parallel unknown value long opt", "parallel --future-val 42 nmap -p 80 x"},
|
||||
{"sudo unknown flag over-approximated", "sudo --unknown-flag nmap -p 80 x"},
|
||||
{"env unknown flag over-approximated", "env -Z nmap -p 80 x"},
|
||||
{"busybox", "busybox nmap -p 80 x"},
|
||||
{"busybox sh -c", "busybox sh -c 'nmap -p 80 x'"},
|
||||
{"chroot", "chroot / nmap -p 80 x"},
|
||||
{"chroot with userspec", "chroot --userspec=0:0 /mnt nmap -p 80 x"},
|
||||
{"exec", "exec -- nmap -p 80 x"},
|
||||
{"exec -a", "exec -a fake nmap -p 80 x"},
|
||||
{"semicolon list", "nmap -p 80 x; true"},
|
||||
{"and list", "true && nmap -p 80 x"},
|
||||
{"or list", "false || nmap -p 80 x"},
|
||||
{"pipeline", "nmap -p 80 x | tee out"},
|
||||
{"subshell", "(nmap -p 80 x)"},
|
||||
{"redirect", "nmap -p 80 x > out"},
|
||||
{"background", "nmap -p 80 x &"},
|
||||
{"prefix assign", "FOO=1 nmap -p 80 x"},
|
||||
{"expansion in later arg", "nmap $(id)"},
|
||||
{"param expansion in later arg", "nmap $TARGET"},
|
||||
{"command subst inside echo", "echo $(nmap -p 80 x)"},
|
||||
{"bash -c single quoted", "bash -c 'nmap -p 80 x'"},
|
||||
{"bash -x -c", "bash -x -c 'nmap -p 80 x'"},
|
||||
{"bash -lc", "bash -lc 'nmap -p 80 x'"},
|
||||
{"bash -ec", "bash -ec 'nmap -p 80 x'"},
|
||||
{"bash -o pipefail -c", "bash -o pipefail -c 'nmap -p 80 x'"},
|
||||
{"bash +o pipefail -c", "bash +o pipefail -c 'nmap -p 80 x'"},
|
||||
{"bash -O extglob -c", "bash -O extglob -c 'nmap -p 80 x'"},
|
||||
{"bash --norc -c", "bash --norc -c 'nmap -p 80 x'"},
|
||||
{"bash --noprofile --rcfile /dev/null -c --", "bash --noprofile --rcfile /dev/null -c -- 'nmap -p 80 x'"},
|
||||
{"sh -c double quoted", `sh -c "nmap -p 80 x"`},
|
||||
{"zsh -c", "zsh -c 'nmap -p 80 x'"},
|
||||
{"dash -c", "dash -c 'nmap -p 80 x'"},
|
||||
{"ksh -c", "ksh -c 'nmap -p 80 x'"},
|
||||
{"fish -c", "fish -c 'nmap -p 80 x'"},
|
||||
{"fish --command", "fish --command='nmap -p 80 x'"},
|
||||
{"path qualified bash -c", "/bin/bash -c 'nmap -p 80 x'"},
|
||||
{"eval quoted", "eval 'nmap -p 80 x'"},
|
||||
{"eval separate args", "eval nmap -p 80 x"},
|
||||
{"eval with trailing subst", "eval nmap $(id)"},
|
||||
{"stacked wrappers", "sudo env FOO=1 timeout 30 nohup command /usr/bin/nmap -p 80 x"},
|
||||
{"nested payload depth 2", `bash -c "sh -c 'nmap -p 80 x'"`},
|
||||
{"nested payload depth 3", `bash -c "sh -c \"eval 'nmap -p 80 x'\""`},
|
||||
{"bad nested payload does not block later call", `bash -c "if then"; nmap -p 80 x`},
|
||||
}
|
||||
|
||||
for _, action := range []string{"deny", "ask"} {
|
||||
for _, tc := range nmapShouldMatch {
|
||||
t.Run(action+"/match/"+tc.name, func(t *testing.T) {
|
||||
dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd))
|
||||
if !ok || dec.Action != action {
|
||||
t.Errorf("%s [\"nmap\"] on %q: got (%+v, %v), want match with action %q", action, tc.cmd, dec, ok, action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
nmapShouldNotMatch := []struct {
|
||||
name string
|
||||
cmd string
|
||||
}{
|
||||
{"argument to echo", "echo nmap"},
|
||||
{"prefix of other binary", "nmapx"},
|
||||
{"argument in pipeline", "echo x | grep nmap"},
|
||||
{"command -v lookup", "command -v nmap"},
|
||||
{"command -V lookup", "command -V nmap"},
|
||||
{"sudo -l list", "sudo -l nmap"},
|
||||
{"sudo -e edit", "sudo -e nmap"},
|
||||
{"env no command", "env FOO=1"},
|
||||
{"ionice pid mode", "ionice -p 1234"},
|
||||
{"taskset pid mode", "taskset -p 1234"},
|
||||
{"chrt pid mode", "chrt -p 1234"},
|
||||
{"xargs -l echo nmap does not match nmap", "xargs -l echo nmap"},
|
||||
{"shell unknown option before -c", "bash --unknown-opt -c 'nmap -p 80 x'"},
|
||||
{"shell opaque option before -c", "bash $OPT -c 'nmap -p 80 x'"},
|
||||
{"shell script mode with -x", "bash -x nmap"},
|
||||
{"shell script file", "bash nmap"},
|
||||
{"shell -- before -c treats -c as script", "bash -- -c 'nmap -p 80 x'"},
|
||||
{"find -exec echo nmap", `find . -exec echo nmap \;`},
|
||||
{"parallel echo with nmap input", "parallel echo ::: nmap"},
|
||||
{"parallel no command ::: echo nmap quoted", `parallel ::: "echo nmap"`},
|
||||
{"parallel echo nmap ::: x", "parallel echo nmap ::: x"},
|
||||
{"parallel --link echo nmap ::: x", "parallel --link echo nmap ::: x"},
|
||||
{"parallel :::: file input", "parallel :::: nmap"},
|
||||
{"parallel :::+ separator", "parallel :::+ nmap"},
|
||||
{"chroot without command", "chroot /"},
|
||||
{"busybox list mode", "busybox --list"},
|
||||
{"eval opaque leading arg", "eval $CMD nmap"},
|
||||
{"opaque command token", "$CMD -p 80 x"},
|
||||
{"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`},
|
||||
{"unparsable single quote", "nmap 'unterminated"},
|
||||
{"unparsable subst", "nmap $("},
|
||||
{"empty command", ""},
|
||||
}
|
||||
|
||||
for _, action := range []string{"deny", "ask"} {
|
||||
for _, tc := range nmapShouldNotMatch {
|
||||
t.Run(action+"/nomatch/"+tc.name, func(t *testing.T) {
|
||||
if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd)); ok {
|
||||
t.Errorf("%s [\"nmap\"] on %q unexpectedly matched: %+v", action, tc.cmd, dec)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Non-Bash tool never matches argv rules.
|
||||
if dec, ok := matchSingleArgvRule("deny", `["nmap"]`, "shell_open", bashInput("nmap -p 80 x")); ok {
|
||||
t.Errorf("non-Bash tool matched deny rule: %+v", dec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArgvDenyMultiTokenAndPathRules(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
pattern string
|
||||
cmd string
|
||||
want bool
|
||||
}{
|
||||
{"git config path qualified with flag", `["git","config"]`, "/usr/bin/git config --list", true},
|
||||
{"git config via command", `["git","config"]`, "command git config --list", true},
|
||||
{"git config via sudo", `["git","config"]`, "sudo git config user.name foo", true},
|
||||
{"git config opaque subcommand", `["git","config"]`, "git $SUB --list", false},
|
||||
{"git status does not match git config", `["git","config"]`, "git status", false},
|
||||
{"exact path rule matches exact path", `["/usr/bin/nmap"]`, "/usr/bin/nmap -p 80 x", true},
|
||||
{"exact path rule does not match bare name", `["/usr/bin/nmap"]`, "nmap -p 80 x", false},
|
||||
{"exact path rule does not match other path", `["/usr/bin/nmap"]`, "/opt/bin/nmap -p 80 x", false},
|
||||
{"builtin wrapper matches echo", `["echo"]`, "builtin -- echo hi", true},
|
||||
{"xargs with no command does not invent echo", `["echo"]`, "xargs -n 1", false},
|
||||
{"wrapper itself can still be denied", `["sudo"]`, "sudo nmap -p 80 x", true},
|
||||
{"shell itself can still be denied", `["bash"]`, "bash -c 'echo hi'", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, got := matchSingleArgvRule("deny", tc.pattern, "Bash", bashInput(tc.cmd))
|
||||
if got != tc.want {
|
||||
t.Errorf("deny %s on %q = %v, want %v", tc.pattern, tc.cmd, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestArgvAllowRemainsStrict(t *testing.T) {
|
||||
cases := []struct {
|
||||
cmd string
|
||||
want bool
|
||||
}{
|
||||
{"nmap -p 80 x", true},
|
||||
{"command nmap x", false},
|
||||
{"nmap x; true", false},
|
||||
{"bash -c 'nmap x'", false},
|
||||
{"/usr/bin/nmap x", false},
|
||||
{"sudo nmap x", false},
|
||||
{"env FOO=1 nmap x", false},
|
||||
{"nmap $(id)", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.cmd, func(t *testing.T) {
|
||||
_, got := matchSingleArgvRule("allow", `["nmap"]`, "Bash", bashInput(tc.cmd))
|
||||
if got != tc.want {
|
||||
t.Errorf("allow [\"nmap\"] on %q = %v, want %v", tc.cmd, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) {
|
||||
inputs := [][]byte{
|
||||
nil,
|
||||
[]byte(``),
|
||||
[]byte(`not json`),
|
||||
[]byte(`{}`),
|
||||
bashInput(`nmap 'unterminated`),
|
||||
bashInput(`nmap $(`),
|
||||
bashInput(`if then fi; (( (`),
|
||||
bashInput(`bash -c "unterminated`),
|
||||
bashInput(`eval "((("`),
|
||||
}
|
||||
for _, action := range []string{"deny", "ask", "allow"} {
|
||||
for _, in := range inputs {
|
||||
if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", in); ok {
|
||||
t.Errorf("%s matched malformed input %q: %+v", action, string(in), dec)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestArgvPriorityPreservedWithCompoundDeny(t *testing.T) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{
|
||||
{ID: 1, Name: "allow simple nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"},
|
||||
{ID: 2, Name: "deny compound nmap", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"},
|
||||
})
|
||||
|
||||
// Simple command hits the higher-priority allow rule.
|
||||
dec, ok := ic.Match("Bash", bashInput("nmap -p 80 x"))
|
||||
if !ok || dec.Action != "allow" || dec.RuleID != 1 {
|
||||
t.Fatalf("simple nmap: got (%+v, %v), want allow rule 1", dec, ok)
|
||||
}
|
||||
// Compound command fails the strict allow rule and falls through to the deny rule.
|
||||
dec, ok = ic.Match("Bash", bashInput("nmap -p 80 x; true"))
|
||||
if !ok || dec.Action != "deny" || dec.RuleID != 2 {
|
||||
t.Fatalf("compound nmap: got (%+v, %v), want deny rule 2", dec, ok)
|
||||
}
|
||||
}
|
||||
@@ -214,20 +214,20 @@ func TestParseArgvPattern(t *testing.T) {
|
||||
func TestArgvAllowBelowDeny(t *testing.T) {
|
||||
ic := New(nil)
|
||||
ic.SetRulesForTest([]db.InterceptRule{
|
||||
{ID: 1, Name: "no force push", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "regex",
|
||||
{ID: 1, Name: "no force flag", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "regex",
|
||||
Pattern: `--force`, Action: "deny"},
|
||||
{ID: 2, Name: "argv allow git push", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
|
||||
Pattern: `["git","push"]`, Action: "allow"},
|
||||
{ID: 2, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
|
||||
Pattern: `["nmap"]`, Action: "allow"},
|
||||
})
|
||||
dec, ok := ic.Match("Bash", []byte(`{"command":"git push --force"}`))
|
||||
dec, ok := ic.Match("Bash", []byte(`{"command":"nmap --force 10.0.0.1"}`))
|
||||
if !ok || dec.Action != "deny" || dec.RuleID != 1 {
|
||||
t.Fatalf("force push: %+v %v, want the deny rule", dec, ok)
|
||||
t.Fatalf("force flag: %+v %v, want the deny rule", dec, ok)
|
||||
}
|
||||
dec, ok = ic.Match("Bash", []byte(`{"command":"git push origin"}`))
|
||||
dec, ok = ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1"}`))
|
||||
if !ok || dec.Action != "allow" || dec.RuleID != 2 {
|
||||
t.Fatalf("push: %+v %v, want the argv allow", dec, ok)
|
||||
t.Fatalf("nmap: %+v %v, want the argv allow", dec, ok)
|
||||
}
|
||||
if _, ok := ic.Match("Bash", []byte(`{"command":"git push; id"}`)); ok {
|
||||
if _, ok := ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1; id"}`)); ok {
|
||||
t.Fatal("a compound command matched the argv rule")
|
||||
}
|
||||
if _, ok := compileRule(db.InterceptRule{MatchType: "argv", Pattern: `["-x"]`}); ok {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package intercept
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestDefaultEnabledToolsCoverExecutors pins the tools that must be gated when no
|
||||
// intercept_enabled_tools setting has been saved. ExecuteExtraTool and Monitor
|
||||
// dispatch MCP / deferred tools and background commands, so leaving them out let
|
||||
// those calls bypass every rule.
|
||||
func TestDefaultEnabledToolsCoverExecutors(t *testing.T) {
|
||||
got := map[string]bool{}
|
||||
for _, name := range defaultEnabledTools {
|
||||
got[name] = true
|
||||
}
|
||||
for _, want := range []string{"Bash", "Write", "Edit", "MultiEdit", "ExecuteExtraTool", "Monitor"} {
|
||||
if !got[want] {
|
||||
t.Errorf("defaultEnabledTools must include %q", want)
|
||||
}
|
||||
}
|
||||
for _, readOnly := range []string{"list_assets", "traffic_search", "Read"} {
|
||||
if got[readOnly] {
|
||||
t.Errorf("defaultEnabledTools must not gate the read-only tool %q by default", readOnly)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnabledToolsFromSettingNeverDisablesTheGate: an unset or malformed setting
|
||||
// must keep the defaults, not turn the rule system off.
|
||||
func TestEnabledToolsFromSettingNeverDisablesTheGate(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
val string
|
||||
ok bool
|
||||
}{
|
||||
{"unset", "", false},
|
||||
{"malformed", "{not json", true},
|
||||
{"wrong shape", `"Bash"`, true},
|
||||
} {
|
||||
got := enabledToolsFromSetting(tc.val, tc.ok)
|
||||
if !got["Bash"] || !got["ExecuteExtraTool"] || !got["Monitor"] {
|
||||
t.Errorf("%s: enabled tools %v, want the defaults", tc.name, got)
|
||||
}
|
||||
}
|
||||
// A valid explicit list replaces the defaults.
|
||||
got := enabledToolsFromSetting(`["Bash"]`, true)
|
||||
if !got["Bash"] || got["WebFetch"] {
|
||||
t.Fatalf("explicit list: %v, want only Bash", got)
|
||||
}
|
||||
}
|
||||
+53
-24
@@ -211,6 +211,9 @@ type Interceptor struct {
|
||||
// upstreamProxy reports whether target traffic leaves through an upstream
|
||||
// egress proxy (nil = no). Injected by the server layer.
|
||||
upstreamProxy func() bool
|
||||
// toolProxy reports whether one tool's own configuration routes its traffic
|
||||
// through a proxy (nil = no). Injected by the server layer.
|
||||
toolProxy func(string) bool
|
||||
// derivedExempt lists the endpoints of the platform's own services (nil =
|
||||
// none). Injected by the server layer. See SetDerivedExemptions.
|
||||
derivedExempt func() []string
|
||||
@@ -234,6 +237,15 @@ func (i *Interceptor) SetUpstreamProxyCheck(f func() bool) {
|
||||
i.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetToolProxyCheck installs the function that reports whether a tool sends its
|
||||
// own traffic through a proxy. The proxy then chooses the address it connects
|
||||
// to, so a target approval for that call is name-only. Passing nil disables it.
|
||||
func (i *Interceptor) SetToolProxyCheck(f func(string) bool) {
|
||||
i.mu.Lock()
|
||||
i.toolProxy = f
|
||||
i.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetReviewer installs the LLM fallback judge callback. Passing nil disables it.
|
||||
func (i *Interceptor) SetReviewer(r Reviewer) {
|
||||
i.mu.Lock()
|
||||
@@ -254,6 +266,10 @@ var defaultEnabledTools = []string{
|
||||
"Bash", "WebFetch", "web_search",
|
||||
"shell_open", "shell_send",
|
||||
"Write", "Edit", "MultiEdit",
|
||||
// ExecuteExtraTool dispatches MCP and deferred tools, and Monitor starts a
|
||||
// background command; both execute third-party or shell commands, so they
|
||||
// belong in the default gate with the rest.
|
||||
"ExecuteExtraTool", "Monitor",
|
||||
}
|
||||
|
||||
// New creates an Interceptor backed by d. The rule cache is lazy-loaded on
|
||||
@@ -293,27 +309,32 @@ func (i *Interceptor) loadLocked() error {
|
||||
|
||||
// Load enabled-tools set from settings, falling back to hard-coded defaults.
|
||||
val, ok, _ := i.db.GetSetting("intercept_enabled_tools")
|
||||
if !ok {
|
||||
m := make(map[string]bool, len(defaultEnabledTools))
|
||||
for _, n := range defaultEnabledTools {
|
||||
m[n] = true
|
||||
}
|
||||
i.enabledTools = m
|
||||
} else {
|
||||
var names []string
|
||||
if json.Unmarshal([]byte(val), &names) != nil {
|
||||
i.enabledTools = map[string]bool{}
|
||||
} else {
|
||||
m := make(map[string]bool, len(names))
|
||||
for _, n := range names {
|
||||
m[n] = true
|
||||
}
|
||||
i.enabledTools = m
|
||||
}
|
||||
}
|
||||
i.enabledTools = enabledToolsFromSetting(val, ok)
|
||||
return nil
|
||||
}
|
||||
|
||||
// enabledToolsFromSetting maps the stored intercept_enabled_tools value to the
|
||||
// gate's set. A malformed value must not silently disable the gate, so it falls
|
||||
// back to the same defaults as an unset setting.
|
||||
func enabledToolsFromSetting(val string, ok bool) map[string]bool {
|
||||
m := make(map[string]bool, len(defaultEnabledTools))
|
||||
for _, n := range defaultEnabledTools {
|
||||
m[n] = true
|
||||
}
|
||||
if !ok {
|
||||
return m
|
||||
}
|
||||
var names []string
|
||||
if json.Unmarshal([]byte(val), &names) != nil {
|
||||
return m
|
||||
}
|
||||
m = make(map[string]bool, len(names))
|
||||
for _, n := range names {
|
||||
m[n] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (i *Interceptor) rules() ([]compiledRule, error) {
|
||||
i.mu.RLock()
|
||||
if i.cached != nil {
|
||||
@@ -369,7 +390,7 @@ func (i *Interceptor) GetEnabledTools() ([]string, error) {
|
||||
}
|
||||
var names []string
|
||||
if err := json.Unmarshal([]byte(val), &names); err != nil {
|
||||
return []string{}, nil
|
||||
return nil, fmt.Errorf("intercept_enabled_tools is not valid JSON: %w", err)
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
@@ -753,12 +774,20 @@ func (i *Interceptor) SetRulesForTest(rules []db.InterceptRule) {
|
||||
func ruleMatches(r compiledRule, toolName string, input []byte) bool {
|
||||
if r.MatchType == "argv" {
|
||||
// Bash only, on the parsed command; match_target is always tool_input.
|
||||
// The denylist neutralises allow rules only: an argv deny or ask rule
|
||||
// for a denylisted program still matches.
|
||||
if r.Action == "allow" && CheckArgvAllow(r.argv) != nil {
|
||||
return false
|
||||
// Allow rules stay strictly limited to a single simple command with
|
||||
// exact derived prefix and denylist enforcement. Deny and ask rules
|
||||
// walk every call in a compound Bash command, stripping known wrappers
|
||||
// and recursing into eval / shell -c payloads.
|
||||
if r.Action == "allow" {
|
||||
if CheckArgvAllow(r.argv) != nil {
|
||||
return false
|
||||
}
|
||||
return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input)
|
||||
}
|
||||
return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input)
|
||||
if r.Action == "deny" || r.Action == "ask" {
|
||||
return r.MatchTarget == "tool_input" && argvCompoundMatches(r.argv, toolName, input)
|
||||
}
|
||||
return false
|
||||
}
|
||||
var subject string
|
||||
switch r.MatchTarget {
|
||||
|
||||
@@ -165,6 +165,18 @@ func (i *Interceptor) loadExemptions() (exemptions, error) {
|
||||
return ex, nil
|
||||
}
|
||||
|
||||
// IsNonPublicAddr reports whether addr is private (RFC1918, fc00::/7 unique
|
||||
// local), loopback, link-local (including 169.254.169.254 and fe80::/10),
|
||||
// unspecified, multicast, or a known instance-metadata address.
|
||||
// Invalid addresses are treated as non-public (fail closed).
|
||||
func IsNonPublicAddr(addr netip.Addr) bool {
|
||||
if !addr.IsValid() {
|
||||
return true
|
||||
}
|
||||
addr = addr.Unmap().WithZone("")
|
||||
return addr.IsPrivate() || ValidateExemptionHost(addr.String()) != nil
|
||||
}
|
||||
|
||||
// voidsExemption reports whether one resolved address voids a stored
|
||||
// exemption on a name: a private address (10/8, 172.16/12, 192.168/16, the
|
||||
// unique local range fc00::/7), or one that is never exempt as a literal
|
||||
@@ -175,6 +187,5 @@ func voidsExemption(ip string) bool {
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
a = a.Unmap().WithZone("")
|
||||
return a.IsPrivate() || ValidateExemptionHost(a.String()) != nil
|
||||
return IsNonPublicAddr(a)
|
||||
}
|
||||
|
||||
@@ -208,11 +208,13 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
|
||||
i.mu.RLock()
|
||||
proxied := i.upstreamProxy
|
||||
toolProxy := i.toolProxy
|
||||
i.mu.RUnlock()
|
||||
// Behind the upstream proxy the proxy chooses the address it connects to, so
|
||||
// every pin is name-only for this call, whatever the pin row says: the proxy
|
||||
// can be turned on after a pin was approved.
|
||||
nameOnly := proxied != nil && proxied()
|
||||
// Behind a proxy the proxy chooses the address it connects to, so every pin
|
||||
// is name-only for this call, whatever the pin row says: the proxy can be
|
||||
// turned on after a pin was approved. The recording proxy, the global egress
|
||||
// proxy and a custom tool's own proxy all count.
|
||||
nameOnly := (proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool))
|
||||
|
||||
var unpinned []TargetRequest
|
||||
var uses []func()
|
||||
|
||||
@@ -975,6 +975,31 @@ func TestUpstreamProxyMakesPinsNameOnlyAtCallTime(t *testing.T) {
|
||||
g.passes("name-only pin, no proxy", g.fetch(appURL))
|
||||
}
|
||||
|
||||
// A custom tool that carries its own proxy cannot enforce an approved IP, so
|
||||
// its pins are name-only at call time, the same as behind the upstream proxy.
|
||||
func TestToolProxyMakesPinsNameOnlyAtCallTime(t *testing.T) {
|
||||
g := newGate(t)
|
||||
proxied := false
|
||||
g.ic.SetToolProxyCheck(func(string) bool { return proxied })
|
||||
const tool = "my_http_tool"
|
||||
const input = `{"url":"https://app.example.com/login"}`
|
||||
g.res.set("app.example.com", "203.0.113.7")
|
||||
g.pin("app.example.com", 443, "203.0.113.7")
|
||||
|
||||
// The address changes. A direct call asks.
|
||||
g.res.set("app.example.com", "198.51.100.99")
|
||||
g.expire()
|
||||
g.requests("changed address, direct tool", g.check(tool, input))
|
||||
|
||||
// The same pin covers the name for the proxied tool, and the first-use row
|
||||
// records that the connection was not bound.
|
||||
proxied = true
|
||||
g.passes("changed address, proxied tool", g.check(tool, input))
|
||||
if got := g.store.outcomes(); len(got) != 1 || got[0] != "allowed/pin_match" || !g.store.logged[0].Audit.Targets[0].NameOnlyEffective {
|
||||
t.Fatalf("rows %v, target %+v; want a name-only first use", got, g.store.logged[0].Audit.Targets[0])
|
||||
}
|
||||
}
|
||||
|
||||
// The first call that a pin version covers is logged once per process.
|
||||
func TestPinFirstUseLoggedOncePerVersion(t *testing.T) {
|
||||
g := newGate(t)
|
||||
|
||||
+23
-2
@@ -35,8 +35,17 @@ type Capture struct {
|
||||
type attempt struct {
|
||||
status int
|
||||
body strings.Builder
|
||||
full bool // true once body hit maxAttemptBody; further reads are not stored
|
||||
}
|
||||
|
||||
// maxAttemptBody is the captured size of one HTTP attempt. The stream still
|
||||
// reaches the caller in full; only the in-memory mirror stops.
|
||||
const maxAttemptBody = 1 << 20 // 1 MiB
|
||||
|
||||
// maxCaptureAttempts is how many HTTP attempts one Capture keeps. Further
|
||||
// attempts pass through unread into the mirror.
|
||||
const maxCaptureAttempts = 8
|
||||
|
||||
// NewCapture returns a context carrying a fresh Capture, plus the Capture itself.
|
||||
func NewCapture(ctx context.Context) (context.Context, *Capture) {
|
||||
c := &Capture{}
|
||||
@@ -74,8 +83,12 @@ func (c *Capture) TeeResponse(status int, rc io.ReadCloser) io.ReadCloser {
|
||||
if c == nil || rc == nil {
|
||||
return rc
|
||||
}
|
||||
a := &attempt{status: status}
|
||||
c.mu.Lock()
|
||||
if len(c.attempts) >= maxCaptureAttempts {
|
||||
c.mu.Unlock()
|
||||
return rc
|
||||
}
|
||||
a := &attempt{status: status}
|
||||
c.attempts = append(c.attempts, a)
|
||||
c.mu.Unlock()
|
||||
return &teeBody{rc: rc, c: c, a: a}
|
||||
@@ -153,7 +166,15 @@ func (t *teeBody) Read(p []byte) (int, error) {
|
||||
n, err := t.rc.Read(p)
|
||||
if n > 0 {
|
||||
t.c.mu.Lock()
|
||||
t.a.body.Write(p[:n])
|
||||
if !t.a.full {
|
||||
remain := maxAttemptBody - t.a.body.Len()
|
||||
if n > remain {
|
||||
t.a.body.Write(p[:remain])
|
||||
t.a.full = true
|
||||
} else {
|
||||
t.a.body.Write(p[:n])
|
||||
}
|
||||
}
|
||||
t.c.mu.Unlock()
|
||||
}
|
||||
return n, err
|
||||
|
||||
@@ -95,6 +95,30 @@ func TestCaptureRetriedAttemptsAreAllKept(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureCapsAttemptBodyAndCount(t *testing.T) {
|
||||
_, c := NewCapture(context.Background())
|
||||
payload := strings.Repeat("a", maxAttemptBody+4096)
|
||||
body := c.TeeResponse(200, io.NopCloser(strings.NewReader(payload)))
|
||||
got, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
if len(got) != len(payload) {
|
||||
t.Fatalf("tee truncated the caller stream: %d want %d", len(got), len(payload))
|
||||
}
|
||||
if n := len(c.RawResponse()); n != maxAttemptBody {
|
||||
t.Fatalf("captured %d bytes, want cap %d", n, maxAttemptBody)
|
||||
}
|
||||
|
||||
for i := 1; i < maxCaptureAttempts+3; i++ {
|
||||
rc := c.TeeResponse(200, io.NopCloser(strings.NewReader("x")))
|
||||
_, _ = io.ReadAll(rc)
|
||||
}
|
||||
if n := len(c.Attempts()); n != maxCaptureAttempts {
|
||||
t.Fatalf("attempts %d, want %d", n, maxCaptureAttempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureEmptyWhenNoHTTPHappened(t *testing.T) {
|
||||
_, c := NewCapture(context.Background())
|
||||
if c.RawRequest() != "" || c.RawResponse() != "" {
|
||||
|
||||
+114
-14
@@ -17,6 +17,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
@@ -31,6 +32,10 @@ import (
|
||||
const protocolVersion = "2025-11-25"
|
||||
const legacySSEProtocolVersion = "2024-11-05"
|
||||
|
||||
// mcpMaxRPCBytes is the largest JSON-RPC response (JSON body or SSE data
|
||||
// payload) the client will buffer. A remote MCP server is untrusted.
|
||||
const mcpMaxRPCBytes = 8 << 20
|
||||
|
||||
// ToolName mirrors mcp.ToolName so remote tools share the mcp__server__tool scheme.
|
||||
func ToolName(server, name string) string { return "mcp__" + server + "__" + name }
|
||||
|
||||
@@ -97,6 +102,66 @@ func normalizeHeaders(headers map[string]string) (map[string]string, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// originKey returns the scheme, host and effective port of u, in a form two
|
||||
// URLs can be compared with. Empty means u is not an absolute http(s) URL with
|
||||
// a host.
|
||||
func originKey(u *url.URL) string {
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
scheme := strings.ToLower(u.Scheme)
|
||||
var port string
|
||||
switch scheme {
|
||||
case "http":
|
||||
port = "80"
|
||||
case "https":
|
||||
port = "443"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
host := strings.ToLower(u.Hostname())
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
if p := u.Port(); p != "" {
|
||||
port = p
|
||||
}
|
||||
return scheme + "://" + net.JoinHostPort(host, port)
|
||||
}
|
||||
|
||||
// sameOrigin reports whether u has the same scheme, host and effective port as
|
||||
// base.
|
||||
func sameOrigin(base, u *url.URL) bool {
|
||||
key := originKey(base)
|
||||
return key != "" && key == originKey(u)
|
||||
}
|
||||
|
||||
// redirectPolicy refuses a redirect that leaves the origin of the configured
|
||||
// endpoint, so a remote MCP server cannot retarget authenticated requests.
|
||||
func redirectPolicy(base *url.URL) func(*http.Request, []*http.Request) error {
|
||||
return func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return errors.New("mcp: stopped after 10 redirects")
|
||||
}
|
||||
if !sameOrigin(base, req.URL) {
|
||||
return fmt.Errorf("mcp: refusing a redirect to another origin: %s", req.URL.Redacted())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// parseMCPURL parses and validates a configured MCP endpoint URL.
|
||||
func parseMCPURL(raw string) (*url.URL, error) {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp url: %w", err)
|
||||
}
|
||||
if originKey(u) == "" {
|
||||
return nil, fmt.Errorf("mcp url must be an absolute http or https URL with a host: %q", raw)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// New connects to a remote MCP endpoint and performs the initialize handshake.
|
||||
// headers are sent on every request (Authorization, custom API keys, …).
|
||||
// When insecure is true, TLS certificate verification is skipped so servers that
|
||||
@@ -113,7 +178,11 @@ func New(ctx context.Context, server, url string, headers map[string]string, ins
|
||||
if timeoutSeconds > 0 {
|
||||
timeout = time.Duration(timeoutSeconds) * time.Second
|
||||
}
|
||||
hc := &http.Client{Timeout: timeout}
|
||||
base, err := parseMCPURL(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hc := &http.Client{Timeout: timeout, CheckRedirect: redirectPolicy(base)}
|
||||
if insecure {
|
||||
hc.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
|
||||
}
|
||||
@@ -138,7 +207,11 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hc := &http.Client{} // the SSE stream is intentionally long-lived.
|
||||
base, err := parseMCPURL(sseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hc := &http.Client{CheckRedirect: redirectPolicy(base)} // the SSE stream is intentionally long-lived.
|
||||
if insecure {
|
||||
hc.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
|
||||
}
|
||||
@@ -163,7 +236,7 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin
|
||||
return nil, fmt.Errorf("mcp sse http %d: %s", resp.StatusCode, readSnippet(resp.Body))
|
||||
}
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
endpoint, err := readSSEEndpoint(reader, sseURL)
|
||||
endpoint, err := readSSEEndpoint(reader, base)
|
||||
if err != nil {
|
||||
resp.Body.Close()
|
||||
cancel()
|
||||
@@ -191,7 +264,11 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func readSSEEndpoint(r *bufio.Reader, base string) (string, error) {
|
||||
// readSSEEndpoint reads the message endpoint announced by the SSE stream. The
|
||||
// endpoint must stay on the origin of the configured SSE URL: the POSTs that
|
||||
// follow carry the operator's headers, and a remote server must not be able to
|
||||
// retarget them.
|
||||
func readSSEEndpoint(r *bufio.Reader, base *url.URL) (string, error) {
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
@@ -209,14 +286,17 @@ func readSSEEndpoint(r *bufio.Reader, base string) (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("mcp sse endpoint URL: %w", err)
|
||||
}
|
||||
if !u.IsAbs() {
|
||||
b, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
candidate = b.ResolveReference(u).String()
|
||||
if u.User != nil {
|
||||
return "", errors.New("mcp sse endpoint must not carry userinfo")
|
||||
}
|
||||
return candidate, nil
|
||||
abs := u
|
||||
if !u.IsAbs() {
|
||||
abs = base.ResolveReference(u)
|
||||
}
|
||||
if !sameOrigin(base, abs) {
|
||||
return "", fmt.Errorf("mcp sse endpoint %q is not on the configured origin", abs.Redacted())
|
||||
}
|
||||
return abs.String(), nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,10 +432,14 @@ func (c *Client) wrap(rt remoteTool) actool.CoreTool {
|
||||
if err := json.Unmarshal(raw, &res); err != nil {
|
||||
return actool.Errorf("Error: bad MCP response: " + err.Error()), nil
|
||||
}
|
||||
var text string
|
||||
var b strings.Builder
|
||||
for _, blk := range res.Content {
|
||||
text += blk.Text
|
||||
b.WriteString(blk.Text)
|
||||
if b.Len() > mcpMaxRPCBytes {
|
||||
break
|
||||
}
|
||||
}
|
||||
text := b.String()
|
||||
// Consistent with built-in/custom tools: oversized output goes through Capture —
|
||||
// truncated at the session's MaxOutputChars (default 30000), and when
|
||||
// ToolOutputDir is configured the full output spills to disk leaving only the
|
||||
@@ -510,8 +594,21 @@ func (c *Client) roundTrip(ctx context.Context, body rpcRequest, expectResp bool
|
||||
if strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||
return parseSSE(resp.Body, body.ID)
|
||||
}
|
||||
return decodeRPC(resp.Body)
|
||||
}
|
||||
|
||||
// decodeRPC reads one JSON-RPC response, refusing a body larger than
|
||||
// mcpMaxRPCBytes so a remote server cannot force an unbounded allocation.
|
||||
func decodeRPC(r io.Reader) (*rpcResponse, error) {
|
||||
data, err := io.ReadAll(io.LimitReader(r, mcpMaxRPCBytes+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: read json response: %w", err)
|
||||
}
|
||||
if len(data) > mcpMaxRPCBytes {
|
||||
return nil, fmt.Errorf("mcp: json response exceeds %d bytes", mcpMaxRPCBytes)
|
||||
}
|
||||
var out rpcResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
if err := json.Unmarshal(data, &out); err != nil {
|
||||
return nil, fmt.Errorf("mcp: decode json response: %w", err)
|
||||
}
|
||||
return &out, nil
|
||||
@@ -602,6 +699,9 @@ func parseSSE(r io.Reader, wantID int) (*rpcResponse, error) {
|
||||
}
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
dataBuf.WriteString(strings.TrimSpace(line[len("data:"):]))
|
||||
if dataBuf.Len() > mcpMaxRPCBytes {
|
||||
return nil, fmt.Errorf("mcp: sse payload exceeds %d bytes", mcpMaxRPCBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
if resp, ok := flush(); ok {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package mcphttp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -105,3 +107,134 @@ func TestLegacySSEClientDiscoverAndCall(t *testing.T) {
|
||||
t.Fatalf("Call() = %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadSSEEndpointSameOrigin(t *testing.T) {
|
||||
base, err := url.Parse("https://mcp.example.com:8443/sse")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read := func(line string) (string, error) {
|
||||
stream := "event: endpoint\ndata: " + line + "\n\n"
|
||||
return readSSEEndpoint(bufio.NewReader(strings.NewReader(stream)), base)
|
||||
}
|
||||
for _, line := range []string{
|
||||
"/message?sessionId=1",
|
||||
"https://mcp.example.com:8443/message",
|
||||
"HTTPS://MCP.EXAMPLE.COM:8443/message",
|
||||
"//mcp.example.com:8443/message",
|
||||
} {
|
||||
got, err := read(line)
|
||||
if err != nil {
|
||||
t.Errorf("%q: %v", line, err)
|
||||
continue
|
||||
}
|
||||
u, err := url.Parse(got)
|
||||
if err != nil || !sameOrigin(base, u) {
|
||||
t.Errorf("%q: resolved to %q, not the configured origin", line, got)
|
||||
}
|
||||
}
|
||||
for _, line := range []string{
|
||||
"https://evil.example/message",
|
||||
"http://mcp.example.com:8443/message",
|
||||
"https://mcp.example.com:444/message",
|
||||
"//evil.example/message",
|
||||
"http://user:pass@mcp.example.com:8443/message",
|
||||
"ftp://mcp.example.com/message",
|
||||
} {
|
||||
if got, err := read(line); err == nil {
|
||||
t.Errorf("%q: accepted as %q, want a refusal", line, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadSSEEndpointDefaultPort(t *testing.T) {
|
||||
base, err := url.Parse("https://mcp.example.com/sse")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stream := "data: https://mcp.example.com:443/message\n\n"
|
||||
if _, err := readSSEEndpoint(bufio.NewReader(strings.NewReader(stream)), base); err != nil {
|
||||
t.Fatalf("explicit default port refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMCPURL(t *testing.T) {
|
||||
for _, raw := range []string{"ftp://x/y", "not-a-url", "http:///nohost", ""} {
|
||||
if _, err := parseMCPURL(raw); err == nil {
|
||||
t.Errorf("%q accepted, want a refusal", raw)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{"http://x/y", "https://x:8443/y"} {
|
||||
if _, err := parseMCPURL(raw); err != nil {
|
||||
t.Errorf("%q refused: %v", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacySSERefusesCrossOriginEndpoint(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
fmt.Fprint(w, "event: endpoint\ndata: http://evil.invalid/message\n\n")
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := NewSSE(ctx, "test", srv.URL+"/sse", nil, false); err == nil {
|
||||
t.Fatal("cross-origin SSE endpoint accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPClientRefusesCrossOriginRedirect(t *testing.T) {
|
||||
var hits int
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
}))
|
||||
defer target.Close()
|
||||
src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, target.URL+"/steal", http.StatusFound)
|
||||
}))
|
||||
defer src.Close()
|
||||
|
||||
base, err := url.Parse(src.URL + "/sse")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hc := &http.Client{CheckRedirect: redirectPolicy(base)}
|
||||
resp, err := hc.Get(src.URL + "/sse")
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
t.Fatal("cross-origin redirect accepted")
|
||||
}
|
||||
if hits != 0 {
|
||||
t.Fatalf("redirect target was reached %d times", hits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPClientAllowsSameOriginRedirect(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/sse", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/sse2", http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/sse2", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
base, err := url.Parse(srv.URL + "/sse")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hc := &http.Client{CheckRedirect: redirectPolicy(base)}
|
||||
resp, err := hc.Get(srv.URL + "/sse")
|
||||
if err != nil {
|
||||
t.Fatalf("same-origin redirect refused: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -233,3 +234,28 @@ func TestStreamableClientVersionRejectionForms(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRPCCapsBody(t *testing.T) {
|
||||
ok := `{"jsonrpc":"2.0","id":1,"result":{}}`
|
||||
got, err := decodeRPC(strings.NewReader(ok))
|
||||
if err != nil || got == nil || got.ID != 1 {
|
||||
t.Fatalf("small body: got=%+v err=%v", got, err)
|
||||
}
|
||||
if _, err := decodeRPC(strings.NewReader(strings.Repeat("x", mcpMaxRPCBytes+1))); err == nil {
|
||||
t.Fatal("oversize body must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSSECapsPayload(t *testing.T) {
|
||||
chunk := strings.Repeat("a", 64*1024)
|
||||
var b strings.Builder
|
||||
for b.Len() <= mcpMaxRPCBytes {
|
||||
b.WriteString("data: ")
|
||||
b.WriteString(chunk)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
b.WriteByte('\n')
|
||||
if _, err := parseSSE(strings.NewReader(b.String()), 1); err == nil {
|
||||
t.Fatal("oversize SSE payload must fail")
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.Cor
|
||||
for _, n := range names {
|
||||
nameSet[n] = true
|
||||
}
|
||||
if allReg, err := skill.LoadDir(skillDir); err == nil && allReg != nil {
|
||||
if allReg, err := loadSkillsConfined(skillDir); err == nil && allReg != nil {
|
||||
reg = skill.NewRegistry()
|
||||
for _, s := range allReg.List() {
|
||||
// match by directory name (Base of Dir), not by skill display Name
|
||||
|
||||
+2
-2
@@ -283,11 +283,11 @@ func extractToken(r *http.Request) string {
|
||||
}
|
||||
|
||||
// requireAuth wraps h with JWT validation.
|
||||
// /api/auth/* and /api/health are exempt.
|
||||
// /api/auth/*, /api/health and /api/ready are exempt.
|
||||
func (s *Server) requireAuth(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/api/auth/") || p == "/api/health" {
|
||||
if strings.HasPrefix(p, "/api/auth/") || p == "/api/health" || p == "/api/ready" {
|
||||
h.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
+17
-4
@@ -311,16 +311,16 @@ func (s *Server) pgConversationMessages(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
limit := atoiDefault(q.Get("limit"), 200)
|
||||
s.chatMu.Lock()
|
||||
running := s.chatBusy[s.convBusyKey(c.ID)]
|
||||
s.chatMu.Unlock()
|
||||
|
||||
// Incremental tail: ?since=N returns steps after id N (ASC) — used by the live
|
||||
// poll and the post-send fetch. A generous cap so a burst is never dropped.
|
||||
// poll and the post-send fetch. Capped so a huge limit cannot materialise the
|
||||
// whole transcript in one response.
|
||||
if sv := q.Get("since"); sv != "" {
|
||||
since, _ := strconv.ParseInt(sv, 10, 64)
|
||||
items, cursor, err := pg.ConvActivityList(c.ID, since, max(limit, 1000))
|
||||
items, cursor, err := pg.ConvActivityList(c.ID, since, 1000)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
@@ -333,7 +333,7 @@ func (s *Server) pgConversationMessages(w http.ResponseWriter, r *http.Request)
|
||||
// the page of older steps ending before id N. hasMore lets the client stop
|
||||
// loading earlier history once the top of the thread is reached.
|
||||
before, _ := strconv.ParseInt(q.Get("before"), 10, 64)
|
||||
items, hasMore, err := pg.ConvActivityPage(c.ID, before, limit)
|
||||
items, hasMore, err := pg.ConvActivityPage(c.ID, before, convMessageLimit(q.Get("limit"), 200, 200))
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
@@ -345,6 +345,19 @@ func (s *Server) pgConversationMessages(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, 200, map[string]any{"items": activityDTOs(items), "cursor": cursor, "running": running, "hasMore": hasMore})
|
||||
}
|
||||
|
||||
// convMessageLimit clamps a page size. Missing or invalid values use def; the
|
||||
// result is at most cap so a huge query cannot materialise the whole transcript.
|
||||
func convMessageLimit(raw string, maxN, def int) int {
|
||||
n := atoiDefault(raw, def)
|
||||
if n < 1 {
|
||||
n = def
|
||||
}
|
||||
if n > maxN {
|
||||
n = maxN
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// pgConversationMsgDetail lazily returns one step's full detail blob.
|
||||
func (s *Server) pgConversationMsgDetail(w http.ResponseWriter, r *http.Request) {
|
||||
pg, c, ok := s.convByID(w, r)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestConvMessageLimit(t *testing.T) {
|
||||
if got := convMessageLimit("", 200, 200); got != 200 {
|
||||
t.Fatalf("default: %d", got)
|
||||
}
|
||||
if got := convMessageLimit("50", 200, 200); got != 50 {
|
||||
t.Fatalf("50: %d", got)
|
||||
}
|
||||
if got := convMessageLimit("2147483646", 200, 200); got != 200 {
|
||||
t.Fatalf("huge history: %d", got)
|
||||
}
|
||||
if got := convMessageLimit("2147483646", 1000, 1000); got != 1000 {
|
||||
t.Fatalf("huge since: %d", got)
|
||||
}
|
||||
if got := convMessageLimit("-1", 200, 200); got != 200 {
|
||||
t.Fatalf("negative: %d", got)
|
||||
}
|
||||
}
|
||||
+23
-10
@@ -1182,6 +1182,27 @@ func (e *Engine) runWorkerStep(ctx context.Context, t *Task, name string, worker
|
||||
return e.runIntent(ctx, t, name, worker, intent, token, "", "")
|
||||
}
|
||||
|
||||
// intentWorkContext resolves the cached per-task exec context and returns a
|
||||
// per-intent child context with the rotated LLM profile pin attached (#85,
|
||||
// #376). Attaching the pin after execContextFor ensures a cached e.execCtx
|
||||
// does not drop it; attaching it after the paused/deleting check ensures a
|
||||
// rolled-back claim never advances the rotation counter.
|
||||
func (e *Engine) intentWorkContext(ctx context.Context, t *Task) (ectx, workCtx context.Context, workCancel context.CancelCauseFunc, ok bool) {
|
||||
ectx = e.clockCtx(e.execContextFor(ctx, t.ID), t, false) // cancellable by Pause; carries the task deadline
|
||||
if ectx.Err() != nil || e.IsDeleting(t.ID) {
|
||||
return ectx, nil, nil, false
|
||||
}
|
||||
// per-work child context so the planner's kill_work can stop just this work.
|
||||
workCtx, workCancel = context.WithCancelCause(ectx)
|
||||
// Per-intent LLM rotation (#85): each claimed worker intent runs on the
|
||||
// next chain head. The pin travels through the run context into the
|
||||
// provider resolver; non-worker roles and failover keep the active head.
|
||||
if head, pinned := t.nextRotatedProfile(); pinned {
|
||||
workCtx = withLLMProfilePin(workCtx, head)
|
||||
}
|
||||
return ectx, workCtx, workCancel, true
|
||||
}
|
||||
|
||||
// runIntent executes and fully settles one already-claimed (state=running) intent.
|
||||
// Both the pool worker loop (via runWorkerStep) and the human-message handler (via
|
||||
// runDetachedIntent, a dedicated goroutine outside the worker pool) call it, so the
|
||||
@@ -1194,25 +1215,17 @@ func (e *Engine) runWorkerStep(ctx context.Context, t *Task, name string, worker
|
||||
// while the worker is busy, and every intent state write below is fenced on it,
|
||||
// so a worker whose claim was taken over cannot overwrite the new claimer.
|
||||
func (e *Engine) runIntent(ctx context.Context, t *Task, name string, worker *agent.Worker, intent *db.Node, token, requestID, message string) bool {
|
||||
// Per-intent LLM rotation (#85): each claimed worker intent runs on the
|
||||
// next chain head. The pin travels through the run context into the
|
||||
// provider resolver; non-worker roles and failover keep the active head.
|
||||
if head, ok := t.nextRotatedProfile(); ok {
|
||||
ctx = withLLMProfilePin(ctx, head)
|
||||
}
|
||||
hasChatMessage := message != ""
|
||||
e.stampFirstRun(t) // first real execution → stamp first_run_at + compute the deadline (only for tasks with a timeout)
|
||||
e.touch(t.ID)
|
||||
emit := func(r db.Activity) { e.emitActivity(t, r) }
|
||||
ectx := e.clockCtx(e.execContextFor(ctx, t.ID), t, false) // cancellable by Pause; carries the task deadline
|
||||
if ectx.Err() != nil || e.IsDeleting(t.ID) {
|
||||
ectx, workCtx, workCancel, ok := e.intentWorkContext(ctx, t)
|
||||
if !ok {
|
||||
if err := t.Store.SettleIntentClaim(intent.ID, token, "open"); err != nil {
|
||||
log.Printf("[worker %s] task %s intent #%d claim rollback failed: %v", name, t.ID, intent.ID, err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
// per-work child context so the planner's kill_work can stop just this work.
|
||||
workCtx, workCancel := context.WithCancelCause(ectx)
|
||||
e.registerWork(intent.ID, workCancel)
|
||||
stopHeartbeat := startClaimHeartbeat(t.Store, db.IntentClaimHeartbeatInterval, name, intent.ID, token, workCancel)
|
||||
// wrap the guard hooks so steer_work can inject a mid-run course-correction
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func TestValidateArgvRuleReq(t *testing.T) {
|
||||
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["git","push"]`, Action: "allow"}
|
||||
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}
|
||||
if err := validateInterceptRuleReq(base); err != nil {
|
||||
t.Fatalf("valid argv rule refused: %v", err)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ func TestValidateArgvRuleReq(t *testing.T) {
|
||||
"tool_name target": func(r *interceptRuleReq) { r.MatchTarget = "tool_name" },
|
||||
"empty pattern": func(r *interceptRuleReq) { r.Pattern = "" },
|
||||
"empty token": func(r *interceptRuleReq) { r.Pattern = `["git",""]` },
|
||||
"flag token": func(r *interceptRuleReq) { r.Pattern = `["git","-C"]` },
|
||||
"flag token": func(r *interceptRuleReq) { r.Pattern = `["nmap","-C"]` },
|
||||
"metacharacter": func(r *interceptRuleReq) { r.Pattern = `["nmap;id"]` },
|
||||
"nine tokens": func(r *interceptRuleReq) { r.Pattern = `["a","b","c","d","e","f","g","h","i"]` },
|
||||
"not an array": func(r *interceptRuleReq) { r.Pattern = `git push` },
|
||||
@@ -31,7 +31,7 @@ func TestValidateArgvRuleReq(t *testing.T) {
|
||||
// The manual rule form refuses an argv allow rule for a denylisted program,
|
||||
// with the message of the "always allow" endpoint; deny and ask stay creatable.
|
||||
func TestValidateArgvAllowDenylist(t *testing.T) {
|
||||
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`} {
|
||||
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`} {
|
||||
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
|
||||
tokens, _ := intercept.ParseArgvPattern(pattern)
|
||||
want := intercept.CheckArgvAllow(tokens)
|
||||
@@ -45,7 +45,7 @@ func TestValidateArgvAllowDenylist(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, pattern := range []string{`["nmap"]`, `["git","push"]`} {
|
||||
for _, pattern := range []string{`["nmap"]`, `["curl"]`} {
|
||||
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
|
||||
if err := validateInterceptRuleReq(req); err != nil {
|
||||
t.Errorf("allow %s refused: %v", pattern, err)
|
||||
|
||||
@@ -130,6 +130,7 @@ func TestStoredProfileKeyOnlyForStoredEndpoint(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
s.allowLoopbackModels = true
|
||||
s.cfgMu.Lock()
|
||||
s.llmCfg = agent.Config{} // no global key to fall back on
|
||||
s.cfgMu.Unlock()
|
||||
|
||||
@@ -0,0 +1,920 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
)
|
||||
|
||||
func dialTestServerForHosts(routes map[string]string, fallback func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
if target, ok := routes[strings.ToLower(addr)]; ok {
|
||||
return (&net.Dialer{}).DialContext(ctx, network, target)
|
||||
}
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err == nil {
|
||||
if target, ok := routes[strings.ToLower(host)]; ok {
|
||||
return (&net.Dialer{}).DialContext(ctx, network, target)
|
||||
}
|
||||
}
|
||||
return fallback(ctx, network, addr)
|
||||
}
|
||||
}
|
||||
|
||||
// newTestTLSServer starts an HTTPS httptest server with a leaf certificate
|
||||
// valid for dnsNames and returns the server and a CertPool trusting it.
|
||||
func newTestTLSServer(t *testing.T, dnsNames []string, h http.Handler) (*httptest.Server, *x509.CertPool) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: dnsNames[0]},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
DNSNames: dnsNames,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cert, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(cert)
|
||||
|
||||
srv := httptest.NewUnstartedServer(h)
|
||||
srv.TLS = &tls.Config{
|
||||
Certificates: []tls.Certificate{{
|
||||
Certificate: [][]byte{der},
|
||||
PrivateKey: key,
|
||||
}},
|
||||
}
|
||||
srv.StartTLS()
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, pool
|
||||
}
|
||||
|
||||
func TestLLMModelsRefusesLoopbackBeforeRequest(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
var hits atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte("internal secret body"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
// Strict production default: no test seams set.
|
||||
s := &Server{}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
provider string
|
||||
apiKey string
|
||||
}{
|
||||
{"openai", "openai", "sk-test"},
|
||||
{"anthropic", "anthropic", "sk-test"},
|
||||
{"ollama_keyless", "ollama", ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": tc.provider,
|
||||
"base_url": srv.URL,
|
||||
"api_key": tc.apiKey,
|
||||
})
|
||||
if hits.Load() != 0 {
|
||||
t.Fatalf("loopback server was contacted (%d hits)", hits.Load())
|
||||
}
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false, got %v", resp)
|
||||
}
|
||||
errMsg, _ := resp["error"].(string)
|
||||
if errMsg == "" {
|
||||
t.Fatalf("expected non-empty refusal error, got %v", resp)
|
||||
}
|
||||
if strings.Contains(errMsg, "127.0.0.1") || strings.Contains(errMsg, "internal secret") {
|
||||
t.Fatalf("error leaked address or body: %q", errMsg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsDefaultOllamaAllowedWithoutSeam(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
|
||||
// 1. Caller-supplied DefaultOllamaBaseURL ("http://127.0.0.1:11434/v1") must
|
||||
// still be refused with no test seams and no allow-list entry.
|
||||
bare := &Server{}
|
||||
supplied := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": agent.DefaultOllamaBaseURL,
|
||||
"api_key": "",
|
||||
})
|
||||
if supplied["ok"] != false {
|
||||
t.Fatalf("caller-supplied %s must be refused, got %v", agent.DefaultOllamaBaseURL, supplied)
|
||||
}
|
||||
if errMsg, _ := supplied["error"].(string); !strings.Contains(errMsg, "not allowed") || strings.Contains(errMsg, "127.0.0.1") {
|
||||
t.Fatalf("unexpected refusal for caller-supplied ollama URL: %q", errMsg)
|
||||
}
|
||||
|
||||
// 2. Empty base_url with provider="ollama" uses the code-owned default and
|
||||
// must NOT be refused by URL validation or dial control even with no test seam.
|
||||
var ollamaHits atomic.Int32
|
||||
fakeOllama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ollamaHits.Add(1)
|
||||
if r.URL.Path != "/v1/models" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"llama3.2"}]}`))
|
||||
}))
|
||||
t.Cleanup(fakeOllama.Close)
|
||||
|
||||
// Verify the production guard allows dialing only 127.0.0.1:11434 (not other loopback ports).
|
||||
s := &Server{}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"127.0.0.1:11434": fakeOllama.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
})
|
||||
if ollamaHits.Load() != 1 {
|
||||
t.Fatalf("expected default ollama endpoint to be contacted once, got %d", ollamaHits.Load())
|
||||
}
|
||||
if resp["ok"] != true {
|
||||
t.Fatalf("expected ok=true for default ollama without allowLoopbackModels, got %v", resp)
|
||||
}
|
||||
rawModels, _ := resp["models"].([]any)
|
||||
if len(rawModels) != 1 || rawModels[0] != "llama3.2" {
|
||||
t.Fatalf("unexpected models: %v", rawModels)
|
||||
}
|
||||
|
||||
// Also verify a completely bare Server (zero seams at all) does not refuse
|
||||
// {"provider":"ollama","base_url":""} at validation or dial Control.
|
||||
bareResp := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
})
|
||||
if bareResp["ok"] == false {
|
||||
errMsg, _ := bareResp["error"].(string)
|
||||
if strings.Contains(errMsg, "not allowed") {
|
||||
t.Fatalf("bare Server refused code-owned default Ollama URL: %q", errMsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsPrivateEndpointsAllowList(t *testing.T) {
|
||||
var allowedHits atomic.Int32
|
||||
allowedSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
allowedHits.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"local-llama"}]}`))
|
||||
}))
|
||||
t.Cleanup(allowedSrv.Close)
|
||||
|
||||
var otherPortHits atomic.Int32
|
||||
otherPortSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
otherPortHits.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"wrong-port"}]}`))
|
||||
}))
|
||||
t.Cleanup(otherPortSrv.Close)
|
||||
|
||||
// 1. No allow-list entry -> refused with bare Server (zero test seams).
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
bare := &Server{}
|
||||
noEntry := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": allowedSrv.URL,
|
||||
"api_key": "",
|
||||
})
|
||||
if allowedHits.Load() != 0 || noEntry["ok"] != false {
|
||||
t.Fatalf("expected refusal with empty %s, hits=%d resp=%v", LLMPrivateEndpointsEnv, allowedHits.Load(), noEntry)
|
||||
}
|
||||
|
||||
// 2. Allow-listed exact host:port works end-to-end with bare Server (real production dialer + guard).
|
||||
t.Setenv(LLMPrivateEndpointsEnv, allowedSrv.Listener.Addr().String()+",host.docker.internal:11434")
|
||||
okResp := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": allowedSrv.URL,
|
||||
"api_key": "",
|
||||
})
|
||||
if allowedHits.Load() != 1 || okResp["ok"] != true {
|
||||
t.Fatalf("allow-listed endpoint should work, hits=%d resp=%v", allowedHits.Load(), okResp)
|
||||
}
|
||||
rawModels, _ := okResp["models"].([]any)
|
||||
if len(rawModels) != 1 || rawModels[0] != "local-llama" {
|
||||
t.Fatalf("unexpected models from allow-listed endpoint: %v", rawModels)
|
||||
}
|
||||
|
||||
// 3. Same host on a different port stays refused.
|
||||
diffPort := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": otherPortSrv.URL,
|
||||
"api_key": "",
|
||||
})
|
||||
if otherPortHits.Load() != 0 || diffPort["ok"] != false {
|
||||
t.Fatalf("same host on another port must be refused, hits=%d resp=%v", otherPortHits.Load(), diffPort)
|
||||
}
|
||||
|
||||
// 4. Allow-listed hostname resolving to RFC1918 works on its exact port,
|
||||
// stays refused on another port, and still validates scheme & redirects.
|
||||
var dockerHits atomic.Int32
|
||||
dockerSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
dockerHits.Add(1)
|
||||
if r.URL.Path == "/redirect/v1/models" {
|
||||
http.Redirect(w, r, otherPortSrv.URL+"/secret", http.StatusFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"docker-qwen"}]}`))
|
||||
}))
|
||||
t.Cleanup(dockerSrv.Close)
|
||||
|
||||
s := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "host.docker.internal" {
|
||||
return []netip.Addr{netip.MustParseAddr("192.168.65.254")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"host.docker.internal:11434": dockerSrv.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
dockerOK := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": "http://host.docker.internal:11434",
|
||||
"api_key": "",
|
||||
})
|
||||
if dockerHits.Load() != 1 || dockerOK["ok"] != true {
|
||||
t.Fatalf("allow-listed docker host should work, hits=%d resp=%v", dockerHits.Load(), dockerOK)
|
||||
}
|
||||
|
||||
dockerWrongPort := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": "http://host.docker.internal:8080",
|
||||
"api_key": "",
|
||||
})
|
||||
if dockerWrongPort["ok"] != false {
|
||||
t.Fatalf("docker host on wrong port must be refused: %v", dockerWrongPort)
|
||||
}
|
||||
|
||||
dockerBadScheme := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": "ftp://host.docker.internal:11434",
|
||||
"api_key": "",
|
||||
})
|
||||
if dockerBadScheme["ok"] != false {
|
||||
t.Fatalf("disallowed scheme on allow-listed host must be refused: %v", dockerBadScheme)
|
||||
}
|
||||
|
||||
dockerBadRedirect := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "ollama",
|
||||
"base_url": "http://host.docker.internal:11434/redirect",
|
||||
"api_key": "",
|
||||
})
|
||||
if otherPortHits.Load() != 0 || dockerBadRedirect["ok"] != false {
|
||||
t.Fatalf("redirect from allow-listed host to non-listed loopback port must be refused, hits=%d resp=%v", otherPortHits.Load(), dockerBadRedirect)
|
||||
}
|
||||
|
||||
// 5. Cloud metadata remains refused even if mistakenly added to the env var.
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "169.254.169.254:80,[fd00:ec2::254]:80")
|
||||
for _, metaURL := range []string{"http://169.254.169.254/latest/meta-data/", "http://[fd00:ec2::254]/latest/meta-data/"} {
|
||||
metaResp := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": metaURL,
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if metaResp["ok"] != false {
|
||||
t.Fatalf("metadata URL %s must stay refused even if listed: %v", metaURL, metaResp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsRefusesMetadataAndRestrictedAddresses(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
s := &Server{}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
baseURL string
|
||||
noLeak string
|
||||
}{
|
||||
{"aws_metadata", "http://169.254.169.254/latest/meta-data/", "169.254.169.254"},
|
||||
{"rfc1918_10", "http://10.0.0.1/v1", "10.0.0.1"},
|
||||
{"rfc1918_172", "http://172.16.0.1/v1", "172.16.0.1"},
|
||||
{"rfc1918_192", "http://192.168.1.1/v1", "192.168.1.1"},
|
||||
{"unique_local_v6", "http://[fc00::1]/v1", "fc00::1"},
|
||||
{"unique_local_fd", "http://[fd12:3456::1]/v1", "fd12:3456::1"},
|
||||
{"unspecified_v4", "http://0.0.0.0/v1", "0.0.0.0"},
|
||||
{"unspecified_v6", "http://[::]/v1", "::"},
|
||||
{"loopback_v6", "http://[::1]:8080/v1", "::1"},
|
||||
{"link_local_v6", "http://[fe80::1]/v1", "fe80::1"},
|
||||
{"v4_mapped_loopback", "http://[::ffff:127.0.0.1]/v1", "127.0.0.1"},
|
||||
{"v4_mapped_metadata", "http://[::ffff:169.254.169.254]/v1", "169.254.169.254"},
|
||||
{"aws_imds_v6", "http://[fd00:ec2::254]/latest/meta-data/", "fd00:ec2::254"},
|
||||
{"alibaba_metadata", "http://100.100.100.200/latest/meta-data/", "100.100.100.200"},
|
||||
{"decimal_loopback", "http://2130706433/v1", "127.0.0.1"},
|
||||
{"hex_metadata", "http://0xa9.254.0xa9fe/latest/meta-data/", "169.254.169.254"},
|
||||
{"localhost", "http://localhost:8080/v1", "127.0.0.1"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": tc.baseURL,
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false for %s, got %v", tc.baseURL, resp)
|
||||
}
|
||||
errMsg, _ := resp["error"].(string)
|
||||
if errMsg == "" {
|
||||
t.Fatalf("expected error message for %s", tc.baseURL)
|
||||
}
|
||||
if tc.noLeak != "" && strings.Contains(errMsg, tc.noLeak) {
|
||||
t.Fatalf("error leaked address %q: %q", tc.noLeak, errMsg)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Resolved DNS addresses must be checked and must never leak into the error.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
addrs []netip.Addr
|
||||
noLeak string
|
||||
}{
|
||||
{"dns_private", []netip.Addr{netip.MustParseAddr("10.23.45.67")}, "10.23.45.67"},
|
||||
{"dns_metadata", []netip.Addr{netip.MustParseAddr("169.254.169.254")}, "169.254.169.254"},
|
||||
{"dns_unique_local", []netip.Addr{netip.MustParseAddr("fd00::42")}, "fd00::42"},
|
||||
{"dns_mixed_public_and_loopback", []netip.Addr{netip.MustParseAddr("93.184.216.34"), netip.MustParseAddr("127.0.0.1")}, "127.0.0.1"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rs := &Server{
|
||||
modelLookupIP: func(_ context.Context, _ string) ([]netip.Addr, error) {
|
||||
return tc.addrs, nil
|
||||
},
|
||||
}
|
||||
resp := postJSON(t, rs.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://internal.example/v1",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false, got %v", resp)
|
||||
}
|
||||
errMsg, _ := resp["error"].(string)
|
||||
if errMsg == "" || strings.Contains(errMsg, tc.noLeak) {
|
||||
t.Fatalf("unexpected error %q (must be non-empty and not contain %q)", errMsg, tc.noLeak)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsRefusesDisallowedSchemes(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
s := &Server{}
|
||||
for _, raw := range []string{
|
||||
"file:///etc/passwd",
|
||||
"ftp://api.example.com/v1",
|
||||
"gopher://api.example.com:70/1",
|
||||
"javascript:alert(1)",
|
||||
} {
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": raw,
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("scheme %q was not refused: %v", raw, resp)
|
||||
}
|
||||
if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "http or https") {
|
||||
t.Fatalf("scheme %q: expected http/https refusal, got %q", raw, errMsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsRefusesRestrictedProxyAndTargetThroughProxy(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
var proxyHits atomic.Int32
|
||||
proxySrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
proxyHits.Add(1)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"proxied"}]}`))
|
||||
}))
|
||||
t.Cleanup(proxySrv.Close)
|
||||
|
||||
// 1. Loopback proxy is refused before any request is sent.
|
||||
s := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "api.public.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
}
|
||||
if host == "private-proxy.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("10.99.0.1")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
proxy string
|
||||
noLeak string
|
||||
}{
|
||||
{"loopback_proxy", proxySrv.URL, "127.0.0.1"},
|
||||
{"metadata_proxy", "http://169.254.169.254:80", "169.254.169.254"},
|
||||
{"socks5_proxy", "socks5://api.public.example:1080", ""},
|
||||
{"dns_private_proxy", "http://private-proxy.example:3128", "10.99.0.1"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://api.public.example/v1",
|
||||
"proxy": tc.proxy,
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if proxyHits.Load() != 0 {
|
||||
t.Fatalf("proxy was contacted (%d hits)", proxyHits.Load())
|
||||
}
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false, got %v", resp)
|
||||
}
|
||||
errMsg, _ := resp["error"].(string)
|
||||
if errMsg == "" || (tc.noLeak != "" && strings.Contains(errMsg, tc.noLeak)) {
|
||||
t.Fatalf("unexpected error %q (must not leak %q)", errMsg, tc.noLeak)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Valid public proxy + refused target: target must be rejected before the proxy is contacted.
|
||||
s2 := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "proxy.public.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.35")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
s2.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"proxy.public.example": proxySrv.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s2).blockDial}).DialContext,
|
||||
)
|
||||
resp := postJSON(t, s2.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://169.254.169.254/latest/meta-data/",
|
||||
"proxy": "http://proxy.public.example:8080",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if proxyHits.Load() != 0 {
|
||||
t.Fatalf("proxy was contacted for refused target (%d hits)", proxyHits.Load())
|
||||
}
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false, got %v", resp)
|
||||
}
|
||||
if errMsg, _ := resp["error"].(string); strings.Contains(errMsg, "169.254.169.254") {
|
||||
t.Fatalf("error leaked metadata address: %q", errMsg)
|
||||
}
|
||||
|
||||
// 3. Valid public proxy + public target that returns 302 to 127.0.0.1:
|
||||
// the proxy must see the first request only, never the redirect target.
|
||||
var proxyReqs []string
|
||||
redirProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
proxyReqs = append(proxyReqs, r.URL.String())
|
||||
http.Redirect(w, r, "http://127.0.0.1:9999/secret", http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(redirProxy.Close)
|
||||
|
||||
s3 := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
switch host {
|
||||
case "proxy.public.example":
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.35")}, nil
|
||||
case "api.public.example":
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
default:
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
}
|
||||
},
|
||||
}
|
||||
s3.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"proxy.public.example": redirProxy.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s3).blockDial}).DialContext,
|
||||
)
|
||||
resp3 := postJSON(t, s3.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://api.public.example/v1",
|
||||
"proxy": "http://proxy.public.example:8080",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if len(proxyReqs) != 1 || proxyReqs[0] != "http://api.public.example/v1/models" {
|
||||
t.Fatalf("proxy received unexpected requests: %v", proxyReqs)
|
||||
}
|
||||
if resp3["ok"] != false {
|
||||
t.Fatalf("expected ok=false for proxied redirect to loopback, got %v", resp3)
|
||||
}
|
||||
if errMsg, _ := resp3["error"].(string); errMsg == "" || strings.Contains(errMsg, "127.0.0.1") {
|
||||
t.Fatalf("unexpected error %q (must not leak 127.0.0.1)", errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsRefusesRedirectToLoopbackAndRestrictedHost(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
var targetHits atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
targetHits.Add(1)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte("loopback secret"))
|
||||
}))
|
||||
t.Cleanup(target.Close)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
location string
|
||||
noLeak string
|
||||
}{
|
||||
{"redirect_to_loopback", target.URL + "/secret", "127.0.0.1"},
|
||||
{"redirect_to_metadata", "http://169.254.169.254/latest/meta-data/", "169.254.169.254"},
|
||||
{"redirect_to_private_dns", "http://internal.example/secret", "10.44.55.66"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
targetHits.Store(0)
|
||||
var redirHits atomic.Int32
|
||||
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
redirHits.Add(1)
|
||||
http.Redirect(w, r, tc.location, http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(redirector.Close)
|
||||
|
||||
s := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
switch host {
|
||||
case "public.example":
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
case "internal.example":
|
||||
return []netip.Addr{netip.MustParseAddr("10.44.55.66")}, nil
|
||||
default:
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"public.example": redirector.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://public.example/v1",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if redirHits.Load() != 1 {
|
||||
t.Fatalf("expected redirector to be hit once, got %d", redirHits.Load())
|
||||
}
|
||||
if targetHits.Load() != 0 {
|
||||
t.Fatalf("redirect target on loopback was contacted (%d hits)", targetHits.Load())
|
||||
}
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false, got %v", resp)
|
||||
}
|
||||
errMsg, _ := resp["error"].(string)
|
||||
if errMsg == "" {
|
||||
t.Fatalf("expected refusal error, got %v", resp)
|
||||
}
|
||||
if strings.Contains(errMsg, tc.noLeak) || strings.Contains(errMsg, "loopback secret") {
|
||||
t.Fatalf("error leaked address or body: %q", errMsg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsRedirectSchemePolicyAndCap(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
|
||||
t.Run("http_to_https_same_host_allowed", func(t *testing.T) {
|
||||
httpsSrv, pool := newTestTLSServer(t, []string{"public.example"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"upgraded-model"}]}`))
|
||||
}))
|
||||
httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "https://public.example/v1/models", http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(httpSrv.Close)
|
||||
|
||||
s := &Server{
|
||||
modelRootCAs: pool,
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "public.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{
|
||||
"public.example:80": httpSrv.Listener.Addr().String(),
|
||||
"public.example:443": httpsSrv.Listener.Addr().String(),
|
||||
},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://public.example/v1",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if resp["ok"] != true {
|
||||
t.Fatalf("expected same-host http->https upgrade to succeed, got %v", resp)
|
||||
}
|
||||
rawModels, _ := resp["models"].([]any)
|
||||
if len(rawModels) != 1 || rawModels[0] != "upgraded-model" {
|
||||
t.Fatalf("unexpected models after upgrade: %v", rawModels)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("https_to_http_downgrade_refused", func(t *testing.T) {
|
||||
var httpHits atomic.Int32
|
||||
httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
httpHits.Add(1)
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"downgraded"}]}`))
|
||||
}))
|
||||
t.Cleanup(httpSrv.Close)
|
||||
|
||||
httpsSrv, pool := newTestTLSServer(t, []string{"public.example"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "http://public.example/v1/models", http.StatusFound)
|
||||
}))
|
||||
|
||||
s := &Server{
|
||||
modelRootCAs: pool,
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "public.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{
|
||||
"public.example:80": httpSrv.Listener.Addr().String(),
|
||||
"public.example:443": httpsSrv.Listener.Addr().String(),
|
||||
},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "https://public.example/v1",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if httpHits.Load() != 0 {
|
||||
t.Fatalf("downgraded HTTP endpoint was contacted (%d hits)", httpHits.Load())
|
||||
}
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false on https->http downgrade, got %v", resp)
|
||||
}
|
||||
if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "scheme") {
|
||||
t.Fatalf("expected scheme refusal error, got %q", errMsg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("http_to_https_cross_host_refused", func(t *testing.T) {
|
||||
var otherHits atomic.Int32
|
||||
httpsOther, pool := newTestTLSServer(t, []string{"other.public.example"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
otherHits.Add(1)
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"other"}]}`))
|
||||
}))
|
||||
httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "https://other.public.example/v1/models", http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(httpSrv.Close)
|
||||
|
||||
s := &Server{
|
||||
modelRootCAs: pool,
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
switch host {
|
||||
case "public.example":
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
case "other.public.example":
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.35")}, nil
|
||||
default:
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{
|
||||
"public.example:80": httpSrv.Listener.Addr().String(),
|
||||
"other.public.example:443": httpsOther.Listener.Addr().String(),
|
||||
},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://public.example/v1",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if otherHits.Load() != 0 {
|
||||
t.Fatalf("cross-host HTTPS redirect target was contacted (%d hits)", otherHits.Load())
|
||||
}
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false on cross-host scheme change, got %v", resp)
|
||||
}
|
||||
if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "scheme") {
|
||||
t.Fatalf("expected scheme refusal error, got %q", errMsg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("http_to_file_refused", func(t *testing.T) {
|
||||
httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "file:///etc/passwd", http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(httpSrv.Close)
|
||||
|
||||
s := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "public.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"public.example": httpSrv.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://public.example/v1",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false on file:// redirect, got %v", resp)
|
||||
}
|
||||
if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "scheme") {
|
||||
t.Fatalf("expected scheme refusal error, got %q", errMsg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("too_many_redirects", func(t *testing.T) {
|
||||
var hops atomic.Int32
|
||||
looper := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := hops.Add(1)
|
||||
http.Redirect(w, r, "/v1/models?hop="+string(rune('0'+n)), http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(looper.Close)
|
||||
|
||||
s := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "public.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"public.example": looper.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://public.example/v1",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false on redirect loop, got %v", resp)
|
||||
}
|
||||
if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "too many redirects") {
|
||||
t.Fatalf("expected too many redirects error, got %q", errMsg)
|
||||
}
|
||||
if hops.Load() > int32(maxModelRedirects) {
|
||||
t.Fatalf("followed %d redirects, cap is %d", hops.Load(), maxModelRedirects)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestLLMModelsChecksEveryCandidateURL(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
var flip atomic.Bool
|
||||
var seenPaths []string
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
seenPaths = append(seenPaths, r.URL.Path)
|
||||
if r.URL.Path == "/anthropic/v1/models" {
|
||||
// Flip DNS to a private address before candidate 2 is tried.
|
||||
flip.Store(true)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"should-not-reach"}]}`))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
s := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host != "rebind.example" {
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
}
|
||||
if flip.Load() {
|
||||
return []netip.Addr{netip.MustParseAddr("10.77.88.99")}, nil
|
||||
}
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"rebind.example": upstream.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "anthropic",
|
||||
"base_url": "http://rebind.example/anthropic",
|
||||
"api_key": "sk-test",
|
||||
})
|
||||
if resp["ok"] != false {
|
||||
t.Fatalf("expected ok=false when second candidate resolves to private IP, got %v", resp)
|
||||
}
|
||||
if len(seenPaths) != 1 || seenPaths[0] != "/anthropic/v1/models" {
|
||||
t.Fatalf("expected only first candidate to be sent, got %v", seenPaths)
|
||||
}
|
||||
if errMsg, _ := resp["error"].(string); errMsg == "" || strings.Contains(errMsg, "10.77.88.99") {
|
||||
t.Fatalf("unexpected error %q (must not leak resolved IP)", errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMModelsPublicEndpointWorks(t *testing.T) {
|
||||
t.Setenv(LLMPrivateEndpointsEnv, "")
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/v1/models" {
|
||||
// Also verify a safe same-scheme redirect to a public host succeeds.
|
||||
http.Redirect(w, r, "http://api.public.example/v2/models", http.StatusFound)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/v2/models" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer sk-public" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"gpt-4o"},{"id":"o3"}]}`))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
s := &Server{
|
||||
modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if host == "api.public.example" {
|
||||
return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil
|
||||
}
|
||||
return nil, &net.DNSError{Err: "no such host", Name: host}
|
||||
},
|
||||
}
|
||||
s.modelDialContext = dialTestServerForHosts(
|
||||
map[string]string{"api.public.example": upstream.Listener.Addr().String()},
|
||||
(&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext,
|
||||
)
|
||||
|
||||
resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{
|
||||
"provider": "openai",
|
||||
"base_url": "http://api.public.example/v1",
|
||||
"api_key": "sk-public",
|
||||
})
|
||||
if resp["ok"] != true {
|
||||
t.Fatalf("expected ok=true for normal public endpoint, got %v", resp)
|
||||
}
|
||||
rawModels, _ := resp["models"].([]any)
|
||||
if len(rawModels) != 2 || rawModels[0] != "gpt-4o" || rawModels[1] != "o3" {
|
||||
t.Fatalf("unexpected models: %v", rawModels)
|
||||
}
|
||||
}
|
||||
@@ -202,6 +202,7 @@ func TestOllamaListModels(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
s.allowLoopbackModels = true
|
||||
|
||||
call := func(baseURL string) (bool, []string) {
|
||||
body, _ := json.Marshal(map[string]any{"provider": "ollama", "base_url": baseURL, "api_key": ""})
|
||||
|
||||
+35
-2
@@ -430,8 +430,11 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
|
||||
log.Printf("[llmusage] create table: %v", err)
|
||||
}
|
||||
m := &Manager{dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg)}
|
||||
// Behind the global egress proxy a target approval is name-only.
|
||||
m.interceptor.SetUpstreamProxyCheck(func() bool { return m.GlobalProxy() != "" })
|
||||
// Behind any proxy in the path (the recording proxy, the global egress proxy,
|
||||
// or a custom tool's own proxy) the proxy chooses the address, so a target
|
||||
// approval is name-only.
|
||||
m.interceptor.SetUpstreamProxyCheck(func() bool { return m.ProxyAddr() != "" })
|
||||
m.interceptor.SetToolProxyCheck(m.toolUsesProxy)
|
||||
// The platform's own endpoints need no target approval.
|
||||
m.interceptor.SetDerivedExemptions(m.targetGateEndpoints)
|
||||
if proxyAddr != "" {
|
||||
@@ -832,6 +835,36 @@ func (m *Manager) ProxyAddr() string {
|
||||
return m.globalProxy
|
||||
}
|
||||
|
||||
// toolUsesProxy reports whether a custom tool's own configuration sends its
|
||||
// traffic through a proxy. That call cannot enforce an approved IP, so the
|
||||
// target gate treats its pins as name-only. A recording-proxy tool is also
|
||||
// covered by ProxyAddr() when capture is on; the per-tool check covers a
|
||||
// tool-specific proxy while capture is off.
|
||||
func (m *Manager) toolUsesProxy(key string) bool {
|
||||
if m.pg == nil {
|
||||
return false
|
||||
}
|
||||
t, err := m.pg.GetTool(key)
|
||||
if err != nil {
|
||||
// A failed read cannot prove the call is direct; treat it as proxied.
|
||||
return true
|
||||
}
|
||||
if t == nil || t.Kind != "http" {
|
||||
return false
|
||||
}
|
||||
var spec struct {
|
||||
Proxy string `json:"proxy"`
|
||||
UseRecordingProxy bool `json:"use_recording_proxy"`
|
||||
}
|
||||
if json.Unmarshal(t.Exec, &spec) != nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(spec.Proxy) != "" {
|
||||
return true
|
||||
}
|
||||
return spec.UseRecordingProxy && m.ProxyAddr() != ""
|
||||
}
|
||||
|
||||
// ProxyCACert returns the CA cert path agents must trust to verify HTTPS through
|
||||
// the egress proxy. Non-empty ONLY when traffic capture is on (the MITM re-signs
|
||||
// certs): the global proxy used directly (capture off) is a plain forwarder that
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
// ProxyAddr is the one source of truth for "is there a proxy in the path":
|
||||
// the recording proxy while capture is on, the global proxy otherwise.
|
||||
func TestProxyAddrCoversRecordingAndGlobal(t *testing.T) {
|
||||
m := &Manager{}
|
||||
if got := m.ProxyAddr(); got != "" {
|
||||
t.Fatalf("empty manager ProxyAddr = %q", got)
|
||||
}
|
||||
m.globalProxy = "http://127.0.0.1:9"
|
||||
if got := m.ProxyAddr(); got != m.globalProxy {
|
||||
t.Fatalf("global ProxyAddr = %q", got)
|
||||
}
|
||||
|
||||
tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tr.Close()
|
||||
m.traffic = tr
|
||||
m.trafficOn = true
|
||||
if got := m.ProxyAddr(); got == "" {
|
||||
t.Fatal("recording proxy not returned by ProxyAddr")
|
||||
}
|
||||
}
|
||||
|
||||
// A custom http tool with its own proxy cannot enforce an approved IP; a
|
||||
// recording-proxy tool counts only when a proxy address is actually in the path.
|
||||
func TestToolUsesProxy(t *testing.T) {
|
||||
g := newGateServer(t)
|
||||
pg := g.m.pg
|
||||
suffix := fmt.Sprintf("_%d", time.Now().UnixNano())
|
||||
add := func(key, kind string, exec map[string]any) string {
|
||||
t.Helper()
|
||||
key += suffix
|
||||
raw, err := json.Marshal(exec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pg.CreateCustomTool(&db.Tool{Key: key, Kind: kind, Enabled: true, Exec: raw}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.DeleteCustomTool(key) })
|
||||
return key
|
||||
}
|
||||
|
||||
proxied := add("t_proxy_http", "http", map[string]any{
|
||||
"url": "http://example.com/", "proxy": "http://127.0.0.1:9"})
|
||||
direct := add("t_direct_http", "http", map[string]any{"url": "http://example.com/"})
|
||||
recording := add("t_rec_http", "http", map[string]any{
|
||||
"url": "http://example.com/", "use_recording_proxy": true})
|
||||
command := add("t_proxy_cmd", "command", map[string]any{
|
||||
"command": "curl http://example.com/", "proxy": "http://127.0.0.1:9"})
|
||||
|
||||
if !g.m.toolUsesProxy(proxied) {
|
||||
t.Fatal("per-tool proxy not detected")
|
||||
}
|
||||
if g.m.toolUsesProxy(direct) {
|
||||
t.Fatal("direct http tool reported as proxied")
|
||||
}
|
||||
if g.m.toolUsesProxy(recording) {
|
||||
t.Fatal("recording tool reported as proxied with capture off and no global proxy")
|
||||
}
|
||||
if g.m.toolUsesProxy(command) {
|
||||
t.Fatal("command tool reported as proxied")
|
||||
}
|
||||
if g.m.toolUsesProxy("t_missing" + suffix) {
|
||||
t.Fatal("missing tool reported as proxied")
|
||||
}
|
||||
|
||||
// With a proxy address in the path, the recording flag counts.
|
||||
g.m.globalProxy = "http://127.0.0.1:9"
|
||||
if !g.m.toolUsesProxy(recording) {
|
||||
t.Fatal("recording tool not proxied with a global proxy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/Autumn-27/norma/skill"
|
||||
)
|
||||
|
||||
var errPathEscape = errors.New("invalid path")
|
||||
|
||||
// confinedPath holds the canonicalized result of resolving a user-supplied
|
||||
// relative path inside a root directory.
|
||||
type confinedPath struct {
|
||||
realRoot string // canonical root directory after symlink evaluation
|
||||
realPath string // resolved target path (deepest existing ancestor resolved + non-existent remainder)
|
||||
entryPath string // resolved parent + final segment (differs from realPath when final segment is a symlink)
|
||||
exists bool // whether the target itself exists on disk (and, if a symlink, its target exists)
|
||||
}
|
||||
|
||||
// isWithinRoot reports whether target is equal to or strictly beneath realRoot.
|
||||
// Both paths must be cleaned and canonicalized in the same coordinate space.
|
||||
func isWithinRoot(realRoot, target string) bool {
|
||||
realRoot = filepath.Clean(realRoot)
|
||||
target = filepath.Clean(target)
|
||||
if target == realRoot {
|
||||
return true
|
||||
}
|
||||
rel, err := filepath.Rel(realRoot, target)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if rel == "." {
|
||||
return true
|
||||
}
|
||||
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// resolveRealRoot returns the cleaned, symlink-evaluated absolute path of root.
|
||||
func resolveRealRoot(root string) (string, error) {
|
||||
absRoot, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
realRoot, err := filepath.EvalSymlinks(absRoot)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Clean(realRoot), nil
|
||||
}
|
||||
|
||||
// splitRelSegments validates and splits a relative path into individual safe
|
||||
// path segments. It rejects NUL bytes, volume prefixes, ".." segments, and
|
||||
// (unless trimLeadingSlash is true) leading separators.
|
||||
func splitRelSegments(rel string, trimLeadingSlash bool) ([]string, error) {
|
||||
if strings.ContainsRune(rel, 0) {
|
||||
return nil, errPathEscape
|
||||
}
|
||||
rel = strings.TrimSpace(rel)
|
||||
// Reject Windows drive-letter prefixes (e.g. "C:foo" or "C:/foo").
|
||||
if filepath.VolumeName(rel) != "" {
|
||||
return nil, errPathEscape
|
||||
}
|
||||
// Normalize backslashes so "..\foo" is caught uniformly across platforms.
|
||||
slashed := strings.ReplaceAll(rel, "\\", "/")
|
||||
if trimLeadingSlash {
|
||||
slashed = strings.TrimLeft(slashed, "/")
|
||||
} else if strings.HasPrefix(slashed, "/") {
|
||||
return nil, errPathEscape
|
||||
}
|
||||
if slashed == "" || slashed == "." {
|
||||
return nil, nil
|
||||
}
|
||||
rawSegs := strings.Split(slashed, "/")
|
||||
segs := make([]string, 0, len(rawSegs))
|
||||
for _, seg := range rawSegs {
|
||||
if seg == "" || seg == "." {
|
||||
continue
|
||||
}
|
||||
if seg == ".." {
|
||||
return nil, errPathEscape
|
||||
}
|
||||
segs = append(segs, seg)
|
||||
}
|
||||
return segs, nil
|
||||
}
|
||||
|
||||
func isNotDirErr(err error) bool {
|
||||
return errors.Is(err, syscall.ENOTDIR)
|
||||
}
|
||||
|
||||
// resolveWithinRoot resolves rel beneath root, walking each path component so
|
||||
// that symlinks in any component are evaluated and verified to stay within root.
|
||||
//
|
||||
// For paths that do not exist yet (write, upload, mkdir), the deepest existing
|
||||
// ancestor is resolved via Lstat + EvalSymlinks, then the remaining non-existent
|
||||
// components are re-joined and checked against realRoot.
|
||||
//
|
||||
// Broken symlinks, symlink loops, ".." segments, and any symlink whose target
|
||||
// escapes root return errPathEscape. Symlinks whose resolved target stays inside
|
||||
// root are permitted.
|
||||
func resolveWithinRoot(root, rel string, trimLeadingSlash bool) (confinedPath, error) {
|
||||
realRoot, err := resolveRealRoot(root)
|
||||
if err != nil {
|
||||
return confinedPath{}, err
|
||||
}
|
||||
segs, err := splitRelSegments(rel, trimLeadingSlash)
|
||||
if err != nil {
|
||||
return confinedPath{}, err
|
||||
}
|
||||
if len(segs) == 0 {
|
||||
return confinedPath{
|
||||
realRoot: realRoot,
|
||||
realPath: realRoot,
|
||||
entryPath: realRoot,
|
||||
exists: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
cur := realRoot
|
||||
for i, seg := range segs {
|
||||
candidate := filepath.Join(cur, seg)
|
||||
fi, err := os.Lstat(candidate)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) || isNotDirErr(err) {
|
||||
// cur is the deepest existing ancestor (already verified within realRoot).
|
||||
// Re-join the remaining non-existent segments and verify confinement.
|
||||
rem := make([]string, 0, 1+len(segs)-i)
|
||||
rem = append(rem, cur)
|
||||
rem = append(rem, segs[i:]...)
|
||||
full := filepath.Clean(filepath.Join(rem...))
|
||||
if !isWithinRoot(realRoot, full) {
|
||||
return confinedPath{}, errPathEscape
|
||||
}
|
||||
return confinedPath{
|
||||
realRoot: realRoot,
|
||||
realPath: full,
|
||||
entryPath: full,
|
||||
exists: false,
|
||||
}, nil
|
||||
}
|
||||
return confinedPath{}, errPathEscape
|
||||
}
|
||||
|
||||
if fi.Mode()&os.ModeSymlink != 0 {
|
||||
target, evalErr := filepath.EvalSymlinks(candidate)
|
||||
if evalErr != nil {
|
||||
// Broken symlink, symlink loop, or unreadable symlink target.
|
||||
return confinedPath{}, errPathEscape
|
||||
}
|
||||
target = filepath.Clean(target)
|
||||
if !isWithinRoot(realRoot, target) {
|
||||
return confinedPath{}, errPathEscape
|
||||
}
|
||||
if i == len(segs)-1 {
|
||||
return confinedPath{
|
||||
realRoot: realRoot,
|
||||
realPath: target,
|
||||
entryPath: candidate,
|
||||
exists: true,
|
||||
}, nil
|
||||
}
|
||||
cur = target
|
||||
continue
|
||||
}
|
||||
|
||||
cur = candidate
|
||||
}
|
||||
|
||||
if !isWithinRoot(realRoot, cur) {
|
||||
return confinedPath{}, errPathEscape
|
||||
}
|
||||
return confinedPath{
|
||||
realRoot: realRoot,
|
||||
realPath: cur,
|
||||
entryPath: cur,
|
||||
exists: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// resolveSkillDir resolves <skillDir>/<name> and ensures it does not escape skillDir.
|
||||
// If skillDir itself does not exist yet, it returns (confinedPath{exists: false}, nil)
|
||||
// so read/delete handlers can return 404 rather than 400.
|
||||
func resolveSkillDir(skillDir, name string) (confinedPath, error) {
|
||||
cp, err := resolveWithinRoot(skillDir, name, false)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return confinedPath{exists: false}, nil
|
||||
}
|
||||
return confinedPath{}, errPathEscape
|
||||
}
|
||||
return cp, nil
|
||||
}
|
||||
|
||||
// resolveSkillFile resolves <skillDir>/<name>/<relFile>, confining both the
|
||||
// skill directory under skillDir and the file under that skill's directory.
|
||||
func resolveSkillFile(skillDir, name, relFile string) (skillExists bool, cp confinedPath, err error) {
|
||||
dirCP, err := resolveSkillDir(skillDir, name)
|
||||
if err != nil {
|
||||
return false, confinedPath{}, err
|
||||
}
|
||||
if !dirCP.exists {
|
||||
return false, confinedPath{}, nil
|
||||
}
|
||||
fi, statErr := os.Stat(dirCP.realPath)
|
||||
if statErr != nil || !fi.IsDir() {
|
||||
return false, confinedPath{}, nil
|
||||
}
|
||||
fileCP, err := resolveWithinRoot(dirCP.realPath, relFile, false)
|
||||
if err != nil {
|
||||
return true, confinedPath{}, errPathEscape
|
||||
}
|
||||
return true, fileCP, nil
|
||||
}
|
||||
|
||||
// loadSkillsConfined loads skills from dir using skill.LoadDir while refusing
|
||||
// to follow symlinks whose real target leaves dir (or leaves its skill
|
||||
// subdirectory for <dir>/<name>/SKILL.md).
|
||||
func loadSkillsConfined(dir string) (*skill.Registry, error) {
|
||||
realRoot, err := resolveRealRoot(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := os.ReadDir(realRoot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type safeEntry struct {
|
||||
isDir bool
|
||||
entryName string
|
||||
sourcePath string
|
||||
}
|
||||
|
||||
hasUnsafe := false
|
||||
var safe []safeEntry
|
||||
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
switch {
|
||||
case e.IsDir():
|
||||
// os.ReadDir reports e.IsDir() == false for symlinks, so <realRoot>/<name>
|
||||
// is a real directory under realRoot. Verify its SKILL.md stays inside it.
|
||||
skillRoot := filepath.Join(realRoot, name)
|
||||
cp, rerr := resolveWithinRoot(skillRoot, "SKILL.md", false)
|
||||
if rerr != nil {
|
||||
hasUnsafe = true
|
||||
continue
|
||||
}
|
||||
if !cp.exists {
|
||||
continue
|
||||
}
|
||||
if fi, serr := os.Stat(cp.realPath); serr != nil || fi.IsDir() {
|
||||
continue
|
||||
}
|
||||
safe = append(safe, safeEntry{
|
||||
isDir: true,
|
||||
entryName: name,
|
||||
sourcePath: cp.realPath,
|
||||
})
|
||||
case strings.HasSuffix(name, ".md"):
|
||||
cp, rerr := resolveWithinRoot(realRoot, name, false)
|
||||
if rerr != nil {
|
||||
hasUnsafe = true
|
||||
continue
|
||||
}
|
||||
if !cp.exists {
|
||||
continue
|
||||
}
|
||||
if fi, serr := os.Stat(cp.realPath); serr != nil || fi.IsDir() {
|
||||
continue
|
||||
}
|
||||
safe = append(safe, safeEntry{
|
||||
isDir: false,
|
||||
entryName: name,
|
||||
sourcePath: cp.realPath,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Fast path: every skill file candidate in dir is safely confined.
|
||||
if !hasUnsafe {
|
||||
return skill.LoadDir(dir)
|
||||
}
|
||||
|
||||
// Safe fallback: stage only verified files into a temporary directory so
|
||||
// skill.LoadDir never opens or reads escaping/broken/looping symlinks, then
|
||||
// restore each Skill.Dir to match dir.
|
||||
if len(safe) == 0 {
|
||||
return skill.NewRegistry(), nil
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "artex-skills-*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
|
||||
for _, item := range safe {
|
||||
data, rerr := os.ReadFile(item.sourcePath)
|
||||
if rerr != nil {
|
||||
continue
|
||||
}
|
||||
if item.isDir {
|
||||
sub := filepath.Join(tmp, item.entryName)
|
||||
if err := os.MkdirAll(sub, 0o755); err != nil {
|
||||
continue
|
||||
}
|
||||
_ = os.WriteFile(filepath.Join(sub, "SKILL.md"), data, 0o600)
|
||||
} else {
|
||||
_ = os.WriteFile(filepath.Join(tmp, item.entryName), data, 0o600)
|
||||
}
|
||||
}
|
||||
|
||||
loaded, err := skill.LoadDir(tmp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := skill.NewRegistry()
|
||||
for _, sk := range loaded.List() {
|
||||
if sk.Dir == tmp {
|
||||
sk.Dir = dir
|
||||
} else if rel, relErr := filepath.Rel(tmp, sk.Dir); relErr == nil && rel != "." {
|
||||
sk.Dir = filepath.Join(dir, rel)
|
||||
}
|
||||
out.Add(sk)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// safeFSErr formats a filesystem error without leaking absolute paths.
|
||||
func safeFSErr(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
var pe *os.PathError
|
||||
if errors.As(err, &pe) && pe.Err != nil {
|
||||
if pe.Op != "" {
|
||||
return pe.Op + ": " + pe.Err.Error()
|
||||
}
|
||||
return pe.Err.Error()
|
||||
}
|
||||
var le *os.LinkError
|
||||
if errors.As(err, &le) && le.Err != nil {
|
||||
if le.Op != "" {
|
||||
return le.Op + ": " + le.Err.Error()
|
||||
}
|
||||
return le.Err.Error()
|
||||
}
|
||||
var se *os.SyscallError
|
||||
if errors.As(err, &se) && se.Err != nil {
|
||||
return se.Err.Error()
|
||||
}
|
||||
return "filesystem error"
|
||||
}
|
||||
+22
-13
@@ -98,12 +98,16 @@ func (s *Server) toolCreateSkill() actool.CoreTool {
|
||||
if strings.TrimSpace(a.Description) == "" {
|
||||
return actool.Errorf("description is required"), nil
|
||||
}
|
||||
path := filepath.Join(s.skillDir, a.Name)
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
dirCP, err := resolveSkillDir(s.skillDir, a.Name)
|
||||
if err != nil {
|
||||
return actool.Errorf("invalid skill path"), nil
|
||||
}
|
||||
if dirCP.exists {
|
||||
return actool.Errorf("skill already exists: " + a.Name), nil
|
||||
}
|
||||
path := filepath.Join(s.skillDir, a.Name)
|
||||
if err := os.MkdirAll(path, 0o755); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
return actool.Errorf(safeFSErr(err)), nil
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("---\n")
|
||||
@@ -117,7 +121,7 @@ func (s *Server) toolCreateSkill() actool.CoreTool {
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(path, "SKILL.md"), []byte(b.String()), 0o644); err != nil {
|
||||
_ = os.RemoveAll(path)
|
||||
return actool.Errorf(err.Error()), nil
|
||||
return actool.Errorf(safeFSErr(err)), nil
|
||||
}
|
||||
return actool.Text("skill created: " + a.Name), nil
|
||||
})
|
||||
@@ -137,10 +141,6 @@ func (s *Server) toolUpdateSkillFile() actool.CoreTool {
|
||||
if !validSkillName(a.Name) {
|
||||
return actool.Errorf("invalid skill name"), nil
|
||||
}
|
||||
skillPath := filepath.Join(s.skillDir, a.Name)
|
||||
if _, err := os.Stat(skillPath); os.IsNotExist(err) {
|
||||
return actool.Errorf("skill does not exist: " + a.Name), nil
|
||||
}
|
||||
rel := strings.TrimSpace(a.File)
|
||||
if rel == "" {
|
||||
rel = "SKILL.md"
|
||||
@@ -149,12 +149,21 @@ func (s *Server) toolUpdateSkillFile() actool.CoreTool {
|
||||
if msg != "" {
|
||||
return actool.Errorf("illegal path: " + msg), nil
|
||||
}
|
||||
full := filepath.Join(skillPath, clean)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
skillExists, cp, err := resolveSkillFile(s.skillDir, a.Name, clean)
|
||||
if err != nil {
|
||||
return actool.Errorf("illegal path: invalid path"), nil
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(a.Content), 0o644); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
if !skillExists {
|
||||
return actool.Errorf("skill does not exist: " + a.Name), nil
|
||||
}
|
||||
if cp.realPath == cp.realRoot {
|
||||
return actool.Errorf("illegal path: invalid path"), nil
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(cp.realPath), 0o755); err != nil {
|
||||
return actool.Errorf(safeFSErr(err)), nil
|
||||
}
|
||||
if err := os.WriteFile(cp.realPath, []byte(a.Content), 0o644); err != nil {
|
||||
return actool.Errorf(safeFSErr(err)), nil
|
||||
}
|
||||
return actool.Text("skill file written: " + a.Name + "/" + clean), nil
|
||||
})
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
readyCacheTTL = time.Second
|
||||
readyPingTimeout = time.Second
|
||||
)
|
||||
|
||||
var errNoPostgres = errors.New("PostgreSQL is not configured")
|
||||
|
||||
type readyCache struct {
|
||||
mu sync.Mutex
|
||||
checked time.Time
|
||||
ready bool
|
||||
pending chan struct{}
|
||||
}
|
||||
|
||||
func (c *readyCache) check(ctx context.Context, ping func(context.Context) error) bool {
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
if !c.checked.IsZero() && time.Since(c.checked) < readyCacheTTL {
|
||||
ready := c.ready
|
||||
c.mu.Unlock()
|
||||
return ready
|
||||
}
|
||||
if done := c.pending; done != nil {
|
||||
c.mu.Unlock()
|
||||
select {
|
||||
case <-done:
|
||||
c.mu.Lock()
|
||||
ready := c.ready
|
||||
c.mu.Unlock()
|
||||
return ready
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
done := make(chan struct{})
|
||||
c.pending = done
|
||||
c.mu.Unlock()
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(context.Background(), readyPingTimeout)
|
||||
err := ping(pingCtx)
|
||||
cancel()
|
||||
|
||||
c.mu.Lock()
|
||||
c.ready = err == nil
|
||||
c.checked = time.Now()
|
||||
c.pending = nil
|
||||
close(done)
|
||||
ready := c.ready
|
||||
c.mu.Unlock()
|
||||
return ready
|
||||
}
|
||||
|
||||
// ready reports PostgreSQL reachability without exposing connection details.
|
||||
// Its cached ping is bounded to one second and never runs application work.
|
||||
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
|
||||
ready := s.readyPG.check(r.Context(), func(ctx context.Context) error {
|
||||
if s.m == nil || s.m.pg == nil {
|
||||
return errNoPostgres
|
||||
}
|
||||
return s.m.pg.PingContext(ctx)
|
||||
})
|
||||
status := http.StatusServiceUnavailable
|
||||
if ready {
|
||||
status = http.StatusOK
|
||||
}
|
||||
writeJSON(w, status, map[string]bool{"ready": ready})
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
type readyTestConnector struct {
|
||||
ping func(context.Context) error
|
||||
}
|
||||
|
||||
func (c readyTestConnector) Connect(context.Context) (driver.Conn, error) {
|
||||
return readyTestConn{ping: c.ping}, nil
|
||||
}
|
||||
|
||||
func (c readyTestConnector) Driver() driver.Driver { return readyTestDriver{} }
|
||||
|
||||
type readyTestDriver struct{}
|
||||
|
||||
func (readyTestDriver) Open(string) (driver.Conn, error) {
|
||||
return nil, errors.New("ready test driver must be opened through its connector")
|
||||
}
|
||||
|
||||
type readyTestConn struct {
|
||||
ping func(context.Context) error
|
||||
}
|
||||
|
||||
func (readyTestConn) Prepare(string) (driver.Stmt, error) {
|
||||
return nil, errors.New("not supported")
|
||||
}
|
||||
func (readyTestConn) Close() error { return nil }
|
||||
func (readyTestConn) Begin() (driver.Tx, error) { return nil, errors.New("not supported") }
|
||||
func (c readyTestConn) Ping(ctx context.Context) error {
|
||||
return c.ping(ctx)
|
||||
}
|
||||
|
||||
func newReadyServer(t *testing.T, ping func(context.Context) error) (*Server, *sql.DB) {
|
||||
t.Helper()
|
||||
sqlDB := sql.OpenDB(readyTestConnector{ping: ping})
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
return &Server{m: &Manager{pg: &db.DB{DB: sqlDB}}}, sqlDB
|
||||
}
|
||||
|
||||
func readyRequest(h http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
|
||||
return rec
|
||||
}
|
||||
|
||||
func assertReadyResponse(t *testing.T, rec *httptest.ResponseRecorder, status int, ready bool) {
|
||||
t.Helper()
|
||||
if rec.Code != status {
|
||||
t.Fatalf("status = %d, want %d; body=%s", rec.Code, status, rec.Body.String())
|
||||
}
|
||||
var body map[string]bool
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode body %q: %v", rec.Body.String(), err)
|
||||
}
|
||||
if len(body) != 1 || body["ready"] != ready {
|
||||
t.Fatalf("body = %s, want only ready:%t", rec.Body.String(), ready)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadyRouteAvailabilityAndCompatibility(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
s, _ := newReadyServer(t, func(context.Context) error {
|
||||
calls.Add(1)
|
||||
return nil
|
||||
})
|
||||
h := s.Handler()
|
||||
|
||||
assertReadyResponse(t, readyRequest(h, http.MethodGet, "/api/ready"), http.StatusOK, true)
|
||||
if got := readyRequest(h, http.MethodGet, "/api/health"); got.Code != http.StatusOK || strings.TrimSpace(got.Body.String()) != `{"ok":true}` {
|
||||
t.Fatalf("unauthenticated health = %d %s, want 200 {\"ok\":true}", got.Code, got.Body.String())
|
||||
}
|
||||
if got := readyRequest(h, http.MethodGet, "/api/stats"); got.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated stats = %d, want %d", got.Code, http.StatusUnauthorized)
|
||||
}
|
||||
if got := calls.Load(); got != 1 {
|
||||
t.Fatalf("database ping count = %d after readiness and liveness requests, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadyOutageRecoveryAndErrorRedaction(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
var available atomic.Bool
|
||||
s, _ := newReadyServer(t, func(context.Context) error {
|
||||
calls.Add(1)
|
||||
if !available.Load() {
|
||||
return errors.New("secret PostgreSQL connection details")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
h := s.Handler()
|
||||
|
||||
first := readyRequest(h, http.MethodGet, "/api/ready")
|
||||
assertReadyResponse(t, first, http.StatusServiceUnavailable, false)
|
||||
if strings.Contains(first.Body.String(), "secret") {
|
||||
t.Fatalf("readiness response exposed database error: %s", first.Body.String())
|
||||
}
|
||||
|
||||
available.Store(true)
|
||||
s.readyPG.mu.Lock()
|
||||
s.readyPG.checked = time.Now().Add(-2 * readyCacheTTL)
|
||||
s.readyPG.mu.Unlock()
|
||||
assertReadyResponse(t, readyRequest(h, http.MethodGet, "/api/ready"), http.StatusOK, true)
|
||||
if got := calls.Load(); got != 2 {
|
||||
t.Fatalf("database ping count = %d, want outage and recovery checks", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadyClosedDatabaseReturnsUnavailable(t *testing.T) {
|
||||
s, sqlDB := newReadyServer(t, func(context.Context) error { return nil })
|
||||
if err := sqlDB.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertReadyResponse(t, readyRequest(s.Handler(), http.MethodGet, "/api/ready"), http.StatusServiceUnavailable, false)
|
||||
}
|
||||
|
||||
func TestReadyPingTimeout(t *testing.T) {
|
||||
var cache readyCache
|
||||
started := make(chan struct{})
|
||||
start := time.Now()
|
||||
ready := cache.check(context.Background(), func(ctx context.Context) error {
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
})
|
||||
if ready {
|
||||
t.Fatal("timed-out ping reported ready")
|
||||
}
|
||||
<-started
|
||||
if elapsed := time.Since(start); elapsed < readyPingTimeout || elapsed > 2*readyPingTimeout {
|
||||
t.Fatalf("ping timeout elapsed %s, want about %s", elapsed, readyPingTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
type readyWaitContext struct {
|
||||
context.Context
|
||||
waiting chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (c *readyWaitContext) Done() <-chan struct{} {
|
||||
c.once.Do(func() { close(c.waiting) })
|
||||
return c.Context.Done()
|
||||
}
|
||||
|
||||
func TestReadyCanceledWaiterDoesNotCancelSharedPing(t *testing.T) {
|
||||
var cache readyCache
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
pingResult := make(chan bool, 1)
|
||||
go func() {
|
||||
pingResult <- cache.check(context.Background(), func(context.Context) error {
|
||||
close(started)
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
<-started
|
||||
|
||||
waitCtx, cancel := context.WithCancel(context.Background())
|
||||
waitingCtx := &readyWaitContext{Context: waitCtx, waiting: make(chan struct{})}
|
||||
waiterResult := make(chan bool, 1)
|
||||
go func() { waiterResult <- cache.check(waitingCtx, func(context.Context) error { return nil }) }()
|
||||
<-waitingCtx.waiting
|
||||
cancel()
|
||||
select {
|
||||
case ready := <-waiterResult:
|
||||
if ready {
|
||||
t.Fatal("canceled waiter reported ready")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("canceled waiter did not return promptly")
|
||||
}
|
||||
|
||||
close(release)
|
||||
if ready := <-pingResult; !ready {
|
||||
t.Fatal("canceling a waiter canceled the shared ping")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadyConcurrentRequestsShareOnePing(t *testing.T) {
|
||||
var cache readyCache
|
||||
var calls atomic.Int32
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
ping := func(context.Context) error {
|
||||
calls.Add(1)
|
||||
close(started)
|
||||
<-release
|
||||
return nil
|
||||
}
|
||||
|
||||
const callers = 20
|
||||
results := make([]bool, callers)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
results[0] = cache.check(context.Background(), ping)
|
||||
}()
|
||||
<-started
|
||||
|
||||
for i := 1; i < callers; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
results[i] = cache.check(context.Background(), ping)
|
||||
}(i)
|
||||
}
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
close(release)
|
||||
wg.Wait()
|
||||
if got := calls.Load(); got != 1 {
|
||||
t.Fatalf("database ping count = %d for %d callers, want 1", got, callers)
|
||||
}
|
||||
for i, ready := range results {
|
||||
if !ready {
|
||||
t.Errorf("caller %d reported not ready", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
-3
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -66,6 +67,14 @@ type Server struct {
|
||||
authHashKey string
|
||||
authVersionKey string
|
||||
|
||||
// Test-only seams for pgListModels SSRF checks. All remain zero/nil in
|
||||
// production (strict public-only default; only exact host:port entries in
|
||||
// ARTEX_LLM_PRIVATE_ENDPOINTS may resolve to private addresses).
|
||||
allowLoopbackModels bool
|
||||
modelLookupIP func(ctx context.Context, host string) ([]netip.Addr, error)
|
||||
modelDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
modelRootCAs *x509.CertPool
|
||||
|
||||
loginLimit *loginLimiter // per-IP attempt limit on POST /api/auth/login
|
||||
pwdLimit *loginLimiter // attempt limit on POST /api/auth/change-password (IP + session token)
|
||||
trustedProxies []netip.Prefix // ARTEX_TRUSTED_PROXIES; see clientIP
|
||||
@@ -75,6 +84,8 @@ type Server struct {
|
||||
// free slots off the same snapshot and over-promote past the limit.
|
||||
concMu sync.Mutex
|
||||
|
||||
readyPG readyCache
|
||||
|
||||
cfgMu sync.Mutex
|
||||
chatAgent *agent.ChatAgent // conversational runner for the chat page; nil w/o LLM
|
||||
// llmProv is the fully-decorated global provider (recorder + failover chain)
|
||||
@@ -748,6 +759,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("POST /api/auth/change-password", s.authChangePassword)
|
||||
|
||||
mux.HandleFunc("GET /api/health", s.health)
|
||||
mux.HandleFunc("GET /api/ready", s.ready)
|
||||
mux.HandleFunc("GET /api/stats", s.stats)
|
||||
mux.HandleFunc("GET /api/logs", s.getLogs)
|
||||
mux.HandleFunc("GET /api/logs/history", s.getLogsHistory)
|
||||
@@ -1050,7 +1062,14 @@ func (s *Server) Handler() http.Handler {
|
||||
api := cors(s.requireAuth(mux))
|
||||
root := http.NewServeMux()
|
||||
root.Handle("/api/", api)
|
||||
root.Handle("/", s.webuiHandler())
|
||||
webui := s.webuiHandler()
|
||||
root.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
// Keep the operator console out of cross-origin frames and referrers.
|
||||
w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'")
|
||||
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
webui.ServeHTTP(w, r)
|
||||
})
|
||||
return limitRequestBody(root)
|
||||
}
|
||||
|
||||
@@ -3669,7 +3688,8 @@ func (s *Server) getTrafficExchange(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// getTrafficStream returns one page of a WebSocket/SSE exchange's messages in
|
||||
// order (limit 1..200, default 50).
|
||||
// order (limit 1..200, default 50). direction=c2s or s2c keeps one side of the
|
||||
// conversation (plus the meta limit marker); any other non-empty value is a 400.
|
||||
func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
@@ -3684,7 +3704,12 @@ func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
offset, _ := strconv.Atoi(q.Get("offset"))
|
||||
limit, _ := strconv.Atoi(q.Get("limit"))
|
||||
msgs, total, err := tr.StreamMessages(id, offset, limit)
|
||||
direction := strings.ToLower(strings.TrimSpace(q.Get("direction")))
|
||||
msgs, total, err := tr.StreamMessagesByDirection(id, direction, offset, limit)
|
||||
if errors.Is(err, traffic.ErrBadStreamDirection) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
|
||||
+427
-47
@@ -4,13 +4,16 @@ import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
@@ -18,6 +21,8 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"text/template"
|
||||
"text/template/parse"
|
||||
"time"
|
||||
@@ -26,6 +31,7 @@ import (
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/notify"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
"github.com/Autumn-27/norma/skill"
|
||||
@@ -1156,7 +1162,7 @@ type skillFileNode struct {
|
||||
|
||||
func (s *Server) fsListSkills(w http.ResponseWriter, r *http.Request) {
|
||||
_ = os.MkdirAll(s.skillDir, 0o755)
|
||||
allReg, _ := skill.LoadDir(s.skillDir)
|
||||
allReg, _ := loadSkillsConfined(s.skillDir)
|
||||
metaByDir := map[string]skill.Skill{}
|
||||
if allReg != nil {
|
||||
for _, sk := range allReg.List() {
|
||||
@@ -1167,7 +1173,7 @@ func (s *Server) fsListSkills(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
entries, err := os.ReadDir(s.skillDir)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
// Usage is best-effort decoration: a ledger read failure leaves the counts at
|
||||
@@ -1275,13 +1281,18 @@ func (s *Server) fsCreateSkill(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, "description is required")
|
||||
return
|
||||
}
|
||||
skillPath := filepath.Join(s.skillDir, body.Name)
|
||||
if _, err := os.Stat(skillPath); err == nil {
|
||||
dirCP, err := resolveSkillDir(s.skillDir, body.Name)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if dirCP.exists {
|
||||
writeErr(w, 409, "skill already exists")
|
||||
return
|
||||
}
|
||||
skillPath := filepath.Join(s.skillDir, body.Name)
|
||||
if err := os.MkdirAll(skillPath, 0o755); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
// Build a spec-compliant SKILL.md (agentskills.io format):
|
||||
@@ -1317,7 +1328,7 @@ func (s *Server) fsCreateSkill(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(skillPath, "SKILL.md"), []byte(sb.String()), 0o644); err != nil {
|
||||
_ = os.RemoveAll(skillPath)
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
// Verify with the real parser: a description containing ": " (or any value that
|
||||
@@ -1352,19 +1363,31 @@ func (s *Server) fsUpdateSkillMeta(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
skillMD := filepath.Join(s.skillDir, name, "SKILL.md")
|
||||
raw, err := os.ReadFile(skillMD)
|
||||
skillExists, cp, err := resolveSkillFile(s.skillDir, name, "SKILL.md")
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if !skillExists || !cp.exists {
|
||||
writeErr(w, 404, "skill not found")
|
||||
return
|
||||
}
|
||||
raw, err := os.ReadFile(cp.realPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
writeErr(w, 404, "skill not found")
|
||||
return
|
||||
}
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
updated, err := rewriteSkillFrontmatter(raw, body.MCPs, body.Description, body.License, body.Compatibility)
|
||||
if err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(skillMD, updated, 0o644); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
if err := os.WriteFile(cp.realPath, updated, 0o644); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
@@ -1383,9 +1406,9 @@ func yamlScalar(s string) string {
|
||||
// verifySkillFile re-loads a written SKILL.md with the real skill parser and
|
||||
// asserts the name and the mcps list survived the round trip.
|
||||
func verifySkillFile(skillPath, wantName string, wantMCPs []string) error {
|
||||
reg, err := skill.LoadDir(skillPath)
|
||||
reg, err := loadSkillsConfined(skillPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load: %w", err)
|
||||
return fmt.Errorf("load: %s", safeFSErr(err))
|
||||
}
|
||||
for _, s := range reg.List() {
|
||||
if s.Dir == "" {
|
||||
@@ -1399,14 +1422,14 @@ func verifySkillFile(skillPath, wantName string, wantMCPs []string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("no skill loaded from %s", skillPath)
|
||||
return fmt.Errorf("no skill loaded from %s", filepath.Base(skillPath))
|
||||
}
|
||||
|
||||
// warnBrokenSkills logs skills whose parsed name does not match their directory
|
||||
// name: the signature of frontmatter that failed to parse and silently fell back
|
||||
// (fields empty, mcps gate lost). Best-effort, startup only.
|
||||
func warnBrokenSkills(dir string) {
|
||||
reg, err := skill.LoadDir(dir)
|
||||
reg, err := loadSkillsConfined(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -1601,9 +1624,14 @@ func (s *Server) fsUploadSkill(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
dirCP, err := resolveSkillDir(s.skillDir, name)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
skillPath := filepath.Join(s.skillDir, name)
|
||||
overwrite := r.URL.Query().Get("overwrite") == "true"
|
||||
if _, err := os.Stat(skillPath); err == nil && !overwrite {
|
||||
if dirCP.exists && !overwrite {
|
||||
writeErr(w, 409, "skill already exists: "+name+" (retry after confirming if you want to overwrite)")
|
||||
return
|
||||
}
|
||||
@@ -1708,13 +1736,20 @@ func (s *Server) fsDeleteSkill(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, "invalid skill name")
|
||||
return
|
||||
}
|
||||
dirCP, err := resolveSkillDir(s.skillDir, name)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if err := pg.DeleteSkillVisibility(name); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(s.skillDir, name)); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
if dirCP.exists {
|
||||
if err := os.RemoveAll(dirCP.entryPath); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": name})
|
||||
}
|
||||
@@ -1816,14 +1851,23 @@ func (s *Server) fsListFiles(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, "invalid skill name")
|
||||
return
|
||||
}
|
||||
dirPath := filepath.Join(s.skillDir, name)
|
||||
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
|
||||
dirCP, err := resolveSkillDir(s.skillDir, name)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if !dirCP.exists {
|
||||
writeErr(w, 404, "skill not found")
|
||||
return
|
||||
}
|
||||
files, err := walkSkillFiles(dirPath)
|
||||
fi, err := os.Stat(dirCP.realPath)
|
||||
if err != nil || !fi.IsDir() {
|
||||
writeErr(w, 404, "skill not found")
|
||||
return
|
||||
}
|
||||
files, err := walkSkillFiles(dirCP.realPath)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
if files == nil {
|
||||
@@ -1843,13 +1887,22 @@ func (s *Server) fsReadFile(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, errMsg)
|
||||
return
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(s.skillDir, name, file))
|
||||
skillExists, cp, err := resolveSkillFile(s.skillDir, name, file)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if !skillExists || !cp.exists {
|
||||
writeErr(w, 404, "file not found")
|
||||
return
|
||||
}
|
||||
data, err := os.ReadFile(cp.realPath)
|
||||
if os.IsNotExist(err) {
|
||||
writeErr(w, 404, "file not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"content": string(data), "file": file})
|
||||
@@ -1873,19 +1926,26 @@ func (s *Server) fsWriteFile(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
skillPath := filepath.Join(s.skillDir, name)
|
||||
if _, err := os.Stat(skillPath); os.IsNotExist(err) {
|
||||
skillExists, cp, err := resolveSkillFile(s.skillDir, name, file)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if !skillExists {
|
||||
writeErr(w, 404, "skill not found")
|
||||
return
|
||||
}
|
||||
fullPath := filepath.Join(skillPath, file)
|
||||
// create parent subdirectory if needed (e.g. scripts/, references/, assets/)
|
||||
if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
if cp.realPath == cp.realRoot {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(fullPath, []byte(body.Content), 0o644); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
// create parent subdirectory if needed (e.g. scripts/, references/, assets/)
|
||||
if err := os.MkdirAll(filepath.Dir(cp.realPath), 0o755); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(cp.realPath, []byte(body.Content), 0o644); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
@@ -1909,13 +1969,21 @@ func (s *Server) fsCreateDir(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, errMsg)
|
||||
return
|
||||
}
|
||||
skillPath := filepath.Join(s.skillDir, name)
|
||||
if _, err := os.Stat(skillPath); os.IsNotExist(err) {
|
||||
skillExists, cp, err := resolveSkillFile(s.skillDir, name, dir)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if !skillExists {
|
||||
writeErr(w, 404, "skill not found")
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(skillPath, dir), 0o755); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
if cp.realPath == cp.realRoot {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(cp.realPath, 0o755); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, map[string]any{"dir": dir})
|
||||
@@ -1932,13 +2000,21 @@ func (s *Server) fsDeletePath(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, errMsg)
|
||||
return
|
||||
}
|
||||
fullPath := filepath.Join(s.skillDir, name, file)
|
||||
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
|
||||
skillExists, cp, err := resolveSkillFile(s.skillDir, name, file)
|
||||
if err != nil {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if !skillExists || !cp.exists {
|
||||
writeErr(w, 404, "not found")
|
||||
return
|
||||
}
|
||||
if err := os.RemoveAll(fullPath); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
if cp.realPath == cp.realRoot {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if err := os.RemoveAll(cp.entryPath); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": file})
|
||||
@@ -2236,6 +2312,224 @@ func (s *Server) pgLLMPoolReset(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, s.llmPoolStatus())
|
||||
}
|
||||
|
||||
const maxModelRedirects = 5
|
||||
|
||||
// LLMPrivateEndpointsEnv is an opt-in comma-separated allow-list of exact
|
||||
// host:port entries (for example "127.0.0.1:11434,host.docker.internal:11434")
|
||||
// that POST /api/llm/models may contact on loopback or private addresses.
|
||||
// Unset or empty enforces the strict public-only policy.
|
||||
const LLMPrivateEndpointsEnv = "ARTEX_LLM_PRIVATE_ENDPOINTS"
|
||||
|
||||
type modelURLRefusalError struct {
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e *modelURLRefusalError) Error() string { return e.msg }
|
||||
|
||||
func normalizeModelHost(host string) (kind, normalized string, ok bool) {
|
||||
host = strings.TrimSpace(host)
|
||||
if host == "" {
|
||||
return "", "", false
|
||||
}
|
||||
if addr, err := netip.ParseAddr(host); err == nil {
|
||||
return intercept.TargetIP, addr.Unmap().WithZone("").String(), true
|
||||
}
|
||||
t, ok := intercept.NormalizeTarget(host)
|
||||
if !ok || t.Kind == intercept.TargetCIDR || t.Host == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return t.Kind, t.Host, true
|
||||
}
|
||||
|
||||
func urlEffectivePort(u *url.URL) (int, bool) {
|
||||
if p := u.Port(); p != "" {
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil || n < 1 || n > 65535 {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
switch strings.ToLower(u.Scheme) {
|
||||
case "http":
|
||||
return 80, true
|
||||
case "https":
|
||||
return 443, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func parsePrivateModelEndpoints(raw string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, entry := range strings.Split(raw, ",") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if entry == "" {
|
||||
continue
|
||||
}
|
||||
host, portStr, err := net.SplitHostPort(entry)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
continue
|
||||
}
|
||||
_, normHost, ok := normalizeModelHost(host)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out[net.JoinHostPort(normHost, strconv.Itoa(port))] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func sameRedirectHost(a, b *url.URL) bool {
|
||||
ha := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(a.Hostname())), ".")
|
||||
hb := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(b.Hostname())), ".")
|
||||
return ha != "" && ha == hb
|
||||
}
|
||||
|
||||
func (s *Server) isBlockedModelAddr(addr netip.Addr, allowPrivate bool) bool {
|
||||
if !addr.IsValid() {
|
||||
return true
|
||||
}
|
||||
addr = addr.Unmap().WithZone("")
|
||||
if s != nil && s.allowLoopbackModels && addr.IsLoopback() {
|
||||
return false
|
||||
}
|
||||
if !intercept.IsNonPublicAddr(addr) {
|
||||
return false
|
||||
}
|
||||
if allowPrivate {
|
||||
// Allow-listed self-hosted endpoints may resolve to loopback or RFC1918 /
|
||||
// unique-local private addresses, but never link-local, unspecified,
|
||||
// multicast, or instance-metadata addresses (such as 169.254.169.254 or
|
||||
// fd00:ec2::254).
|
||||
if addr.IsLoopback() {
|
||||
return false
|
||||
}
|
||||
if addr.IsPrivate() && intercept.ValidateExemptionHost(addr.String()) == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) lookupModelIPs(ctx context.Context, host string) ([]netip.Addr, error) {
|
||||
if s != nil && s.modelLookupIP != nil {
|
||||
return s.modelLookupIP(ctx, host)
|
||||
}
|
||||
return net.DefaultResolver.LookupNetIP(ctx, "ip", host)
|
||||
}
|
||||
|
||||
type modelURLGuard struct {
|
||||
s *Server
|
||||
privateEndpoints map[string]bool
|
||||
mu sync.Mutex
|
||||
allowedDialAddrs map[string]bool
|
||||
}
|
||||
|
||||
func newModelURLGuard(s *Server) *modelURLGuard {
|
||||
return &modelURLGuard{
|
||||
s: s,
|
||||
privateEndpoints: parsePrivateModelEndpoints(os.Getenv(LLMPrivateEndpointsEnv)),
|
||||
}
|
||||
}
|
||||
|
||||
func (g *modelURLGuard) allowDialAddr(addr netip.Addr, port int) {
|
||||
if !addr.IsValid() || port < 1 || port > 65535 {
|
||||
return
|
||||
}
|
||||
key := net.JoinHostPort(addr.Unmap().WithZone("").String(), strconv.Itoa(port))
|
||||
g.mu.Lock()
|
||||
if g.allowedDialAddrs == nil {
|
||||
g.allowedDialAddrs = map[string]bool{}
|
||||
}
|
||||
g.allowedDialAddrs[key] = true
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *modelURLGuard) isAllowedDialAddr(addr netip.Addr, port string) bool {
|
||||
key := net.JoinHostPort(addr.Unmap().WithZone("").String(), port)
|
||||
g.mu.Lock()
|
||||
ok := g.allowedDialAddrs[key]
|
||||
g.mu.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
func (g *modelURLGuard) blockDial(_, address string, _ syscall.RawConn) error {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return &modelURLRefusalError{msg: "target address is not allowed"}
|
||||
}
|
||||
addr, err := netip.ParseAddr(host)
|
||||
if err != nil {
|
||||
return &modelURLRefusalError{msg: "target address is not allowed"}
|
||||
}
|
||||
allowPrivate := g.isAllowedDialAddr(addr, port)
|
||||
if g.s.isBlockedModelAddr(addr, allowPrivate) {
|
||||
return &modelURLRefusalError{msg: "target address is not allowed"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateURL validates a base_url candidate, proxy URL, or redirect target for
|
||||
// POST /api/llm/models. Only http and https URLs are permitted; hosts must
|
||||
// resolve strictly to public addresses unless their exact host:port is listed
|
||||
// in ARTEX_LLM_PRIVATE_ENDPOINTS. Errors never include resolved IP addresses.
|
||||
func (g *modelURLGuard) validateURL(ctx context.Context, rawURL, role string) (*url.URL, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL", role)}
|
||||
}
|
||||
scheme := strings.ToLower(u.Scheme)
|
||||
if scheme != "http" && scheme != "https" {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL must use http or https", role)}
|
||||
}
|
||||
if u.Opaque != "" {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL", role)}
|
||||
}
|
||||
port, ok := urlEffectivePort(u)
|
||||
if !ok {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL", role)}
|
||||
}
|
||||
kind, normHost, ok := normalizeModelHost(u.Hostname())
|
||||
if !ok {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL host", role)}
|
||||
}
|
||||
hostPort := net.JoinHostPort(normHost, strconv.Itoa(port))
|
||||
allowPrivate := g.privateEndpoints[hostPort]
|
||||
|
||||
if kind == intercept.TargetIP {
|
||||
addr, err := netip.ParseAddr(normHost)
|
||||
if err != nil || g.s.isBlockedModelAddr(addr, allowPrivate) {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL host is not allowed", role)}
|
||||
}
|
||||
if allowPrivate {
|
||||
g.allowDialAddr(addr, port)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
if !allowPrivate && !(g.s != nil && g.s.allowLoopbackModels) && (normHost == "localhost" || strings.HasSuffix(normHost, ".localhost")) {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL host is not allowed", role)}
|
||||
}
|
||||
addrs, err := g.s.lookupModelIPs(ctx, normHost)
|
||||
if err != nil || len(addrs) == 0 {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("failed to resolve %s host", role)}
|
||||
}
|
||||
for _, addr := range addrs {
|
||||
if g.s.isBlockedModelAddr(addr, allowPrivate) {
|
||||
return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL host is not allowed", role)}
|
||||
}
|
||||
}
|
||||
if allowPrivate {
|
||||
for _, addr := range addrs {
|
||||
g.allowDialAddr(addr, port)
|
||||
}
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// pgListModels fetches available models from the provider's API endpoint.
|
||||
// Supports OpenAI-format (GET /models), Anthropic-format (GET /v1/models) and
|
||||
// Ollama (keyless OpenAI-compatible GET /v1/models on the local server); for
|
||||
@@ -2285,7 +2579,9 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
baseURL := strings.TrimRight(strings.TrimSpace(req.BaseURL), "/")
|
||||
rawBaseURL := strings.TrimSpace(req.BaseURL)
|
||||
baseURL := strings.TrimRight(rawBaseURL, "/")
|
||||
defaultOllama := provider == "ollama" && rawBaseURL == ""
|
||||
|
||||
// Candidate endpoints to try in order. Some Anthropic-compatible providers
|
||||
// (e.g. DeepSeek) implement /v1/messages under an /anthropic path but expose
|
||||
@@ -2349,19 +2645,98 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// Build HTTP client with optional proxy.
|
||||
transport := &http.Transport{}
|
||||
// Validate proxy and every candidate URL before sending any request.
|
||||
// Pre-request validation is required in addition to the dial-time guard
|
||||
// because a caller-supplied HTTP proxy fetches the target URL itself.
|
||||
guard := newModelURLGuard(s)
|
||||
var proxyURL *url.URL
|
||||
if p := strings.TrimSpace(req.Proxy); p != "" {
|
||||
if pu, err := url.Parse(p); err == nil {
|
||||
transport.Proxy = http.ProxyURL(pu)
|
||||
var err error
|
||||
proxyURL, err = guard.validateURL(r.Context(), p, "proxy")
|
||||
if err != nil {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
client := &http.Client{Transport: transport, Timeout: 30 * time.Second}
|
||||
if defaultOllama {
|
||||
// The built-in Ollama default is code-owned, not caller input: allow
|
||||
// dialing its exact host:port without relaxing caller-supplied URLs.
|
||||
if du, err := url.Parse(agent.DefaultOllamaBaseURL); err == nil {
|
||||
if addr, err := netip.ParseAddr(du.Hostname()); err == nil {
|
||||
if port, ok := urlEffectivePort(du); ok {
|
||||
guard.allowDialAddr(addr, port)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, c := range candidates {
|
||||
if _, err := guard.validateURL(r.Context(), c.url, "endpoint"); err != nil {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build HTTP client with strict dial guard, redirect validation, and optional proxy.
|
||||
var transport *http.Transport
|
||||
if base, ok := http.DefaultTransport.(*http.Transport); ok {
|
||||
transport = base.Clone()
|
||||
} else {
|
||||
transport = &http.Transport{}
|
||||
}
|
||||
transport.Proxy = nil
|
||||
if proxyURL != nil {
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
}
|
||||
if s.modelRootCAs != nil {
|
||||
if transport.TLSClientConfig == nil {
|
||||
transport.TLSClientConfig = &tls.Config{}
|
||||
} else {
|
||||
transport.TLSClientConfig = transport.TLSClientConfig.Clone()
|
||||
}
|
||||
transport.TLSClientConfig.RootCAs = s.modelRootCAs
|
||||
}
|
||||
dialCtx := (&net.Dialer{Timeout: 10 * time.Second, Control: guard.blockDial}).DialContext
|
||||
if s.modelDialContext != nil {
|
||||
dialCtx = s.modelDialContext
|
||||
}
|
||||
transport.DialContext = dialCtx
|
||||
defer transport.CloseIdleConnections()
|
||||
|
||||
client := &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: 30 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxModelRedirects {
|
||||
return &modelURLRefusalError{msg: "too many redirects"}
|
||||
}
|
||||
if len(via) > 0 {
|
||||
prev := via[len(via)-1].URL
|
||||
prevScheme := strings.ToLower(prev.Scheme)
|
||||
nextScheme := strings.ToLower(req.URL.Scheme)
|
||||
if nextScheme != prevScheme {
|
||||
if !(prevScheme == "http" && nextScheme == "https" && sameRedirectHost(prev, req.URL)) {
|
||||
return &modelURLRefusalError{msg: "redirect scheme change is not allowed"}
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := guard.validateURL(req.Context(), req.URL.String(), "redirect"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// Try each candidate; return the first that yields a non-empty model list.
|
||||
var lastErr string
|
||||
emptyOK := false
|
||||
for _, c := range candidates {
|
||||
for i, c := range candidates {
|
||||
if i > 0 && !defaultOllama {
|
||||
if _, err := guard.validateURL(r.Context(), c.url, "endpoint"); err != nil {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
httpReq, err := http.NewRequestWithContext(r.Context(), http.MethodGet, c.url, nil)
|
||||
if err != nil {
|
||||
lastErr = "failed to build request: " + err.Error()
|
||||
@@ -2370,6 +2745,11 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) {
|
||||
httpReq.Header = c.hdr
|
||||
resp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
var refusal *modelURLRefusalError
|
||||
if errors.As(err, &refusal) {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": refusal.Error()})
|
||||
return
|
||||
}
|
||||
lastErr = "request failed: " + err.Error()
|
||||
continue
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,12 +3,14 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"iter"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
@@ -211,3 +213,180 @@ func TestNextRotatedProfileRoundRobin(t *testing.T) {
|
||||
t.Fatal("disabled rotation must not assign a pin")
|
||||
}
|
||||
}
|
||||
|
||||
type pinCapture struct {
|
||||
id int64
|
||||
ok bool
|
||||
}
|
||||
|
||||
type pinCaptureProvider struct {
|
||||
mu sync.Mutex
|
||||
seen []pinCapture
|
||||
}
|
||||
|
||||
func (p *pinCaptureProvider) record(ctx context.Context) {
|
||||
id, ok := llmProfilePinFrom(ctx)
|
||||
p.mu.Lock()
|
||||
p.seen = append(p.seen, pinCapture{id: id, ok: ok})
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
func (p *pinCaptureProvider) Stream(ctx context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
|
||||
p.record(ctx)
|
||||
return func(yield func(llm.StreamEvent, error) bool) {
|
||||
if !yield(llm.StreamEvent{Type: llm.SETextDelta, Text: "done"}, nil) {
|
||||
return
|
||||
}
|
||||
if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "end_turn"}, nil) {
|
||||
return
|
||||
}
|
||||
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *pinCaptureProvider) Complete(ctx context.Context, _ llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
|
||||
p.record(ctx)
|
||||
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("done")}}, "end_turn", llm.Usage{}, nil
|
||||
}
|
||||
|
||||
// Regression test for #376 (DB-free): warming e.execContextFor first (as the
|
||||
// planner does) must not drop the per-intent LLM profile pin on subsequent
|
||||
// worker intents, and a paused/deleting rollback must not advance rotation.
|
||||
func TestIntentWorkContextRotatesWithCachedExecCtx(t *testing.T) {
|
||||
const (
|
||||
taskID = "77"
|
||||
profileA = int64(101)
|
||||
profileB = int64(202)
|
||||
)
|
||||
e := NewEngine(nil)
|
||||
tk := &Task{ID: taskID, LLMProfileIDs: []int64{profileA, profileB}, LLMRotate: true}
|
||||
|
||||
// Warm the per-task cached execCtx, simulating the planner running first.
|
||||
warm := e.execContextFor(context.Background(), taskID)
|
||||
if warm == nil || warm.Err() != nil {
|
||||
t.Fatalf("warm execContextFor returned invalid ctx: %v", warm)
|
||||
}
|
||||
|
||||
// A paused task must roll back without advancing the rotation counter.
|
||||
e.Pause(taskID, agent.AbortPausedByUser)
|
||||
if _, _, _, ok := e.intentWorkContext(context.Background(), tk); ok {
|
||||
t.Fatal("paused task unexpectedly yielded a work context")
|
||||
}
|
||||
e.Resume(tk)
|
||||
// Re-warm cached execCtx after resume (again simulating planner before worker).
|
||||
_ = e.execContextFor(context.Background(), taskID)
|
||||
|
||||
// A deleting task must also roll back without advancing the rotation counter.
|
||||
e.BeginDelete(taskID)
|
||||
if _, _, _, ok := e.intentWorkContext(context.Background(), tk); ok {
|
||||
t.Fatal("deleting task unexpectedly yielded a work context")
|
||||
}
|
||||
e.AbortDelete(taskID, false)
|
||||
|
||||
// Two consecutive claimed intents must carry distinct rotated pins (A then B).
|
||||
_, workA, cancelA, ok := e.intentWorkContext(context.Background(), tk)
|
||||
if !ok {
|
||||
t.Fatal("first intentWorkContext failed")
|
||||
}
|
||||
defer cancelA(nil)
|
||||
gotA, okA := llmProfilePinFrom(workA)
|
||||
if !okA || gotA != profileA {
|
||||
t.Fatalf("first workCtx pin = (%d, %v), want (%d, true)", gotA, okA, profileA)
|
||||
}
|
||||
|
||||
_, workB, cancelB, ok := e.intentWorkContext(context.Background(), tk)
|
||||
if !ok {
|
||||
t.Fatal("second intentWorkContext failed")
|
||||
}
|
||||
defer cancelB(nil)
|
||||
gotB, okB := llmProfilePinFrom(workB)
|
||||
if !okB || gotB != profileB {
|
||||
t.Fatalf("second workCtx pin = (%d, %v), want (%d, true)", gotB, okB, profileB)
|
||||
}
|
||||
if gotA == gotB {
|
||||
t.Fatalf("expected distinct pinned profile IDs, both were %d", gotA)
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #376 (end-to-end through runIntent): warm execContextFor
|
||||
// first (simulating the planner running before workers), then run two intents
|
||||
// through runIntent and assert the two work contexts carry distinct pinned
|
||||
// profile IDs (A then B).
|
||||
func TestRunIntentRotatesPinnedProfileWithCachedExecCtx(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
ids := make([]int64, 0, 2)
|
||||
for i := 0; i < 2; i++ {
|
||||
id, err := m.pg.SaveProfile(&db.LLMProfile{
|
||||
Name: fmt.Sprintf("runintent-rotate-%d-%d", time.Now().UnixNano(), i),
|
||||
Format: "openai",
|
||||
BaseURL: "http://127.0.0.1:1/v1",
|
||||
Model: "test",
|
||||
APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
defer m.pg.DeleteProfile(id)
|
||||
}
|
||||
|
||||
on := true
|
||||
task, err := m.CreateTaskWithOptions("runIntent rotation", "verify pin survives cached execCtx", db.TaskCreateOptions{
|
||||
LLMProfileIDs: ids,
|
||||
LLMRotate: &on,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.DeleteTask(task.ID, DeleteTaskOptions{})
|
||||
|
||||
e := NewEngine(m)
|
||||
// Warm the per-task cached execCtx before any worker intent runs.
|
||||
_ = e.execContextFor(context.Background(), task.ID)
|
||||
|
||||
// Verify paused rollback through runIntent does not advance rotation.
|
||||
if _, err := task.Store.AddIntent(map[string]any{"summary": "rolled back while paused"}, 1, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pausedIntent, pausedToken := e.claimNext(task, "work#0")
|
||||
if pausedIntent == nil {
|
||||
t.Fatal("failed to claim intent for paused rollback check")
|
||||
}
|
||||
e.Pause(task.ID, agent.AbortPausedByUser)
|
||||
probe := &pinCaptureProvider{}
|
||||
worker := agent.NewWorker(probe, "test-model", m.dir, nil, 0, 2)
|
||||
e.runIntent(context.Background(), task, "work#0", worker, pausedIntent, pausedToken, "", "")
|
||||
if len(probe.seen) != 0 {
|
||||
t.Fatalf("paused runIntent called provider %d times, want 0", len(probe.seen))
|
||||
}
|
||||
e.Resume(task)
|
||||
// Re-warm cached execCtx after resume (simulating planner before workers).
|
||||
_ = e.execContextFor(context.Background(), task.ID)
|
||||
|
||||
// Run two intents through runIntent and assert distinct pins: ids[0] then ids[1].
|
||||
if _, err := task.Store.AddIntent(map[string]any{"summary": "rotate intent 2"}, 1, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, wantID := range ids {
|
||||
name := fmt.Sprintf("work#%d", i+1)
|
||||
intent, token := e.claimNext(task, name)
|
||||
if intent == nil {
|
||||
t.Fatalf("intent %d not claimed", i+1)
|
||||
}
|
||||
p := &pinCaptureProvider{}
|
||||
w := agent.NewWorker(p, "test-model", m.dir, nil, 0, 2)
|
||||
e.runIntent(context.Background(), task, name, w, intent, token, "", "")
|
||||
if len(p.seen) == 0 {
|
||||
t.Fatalf("intent %d: provider was not called", i+1)
|
||||
}
|
||||
got := p.seen[0]
|
||||
if !got.ok || got.id != wantID {
|
||||
t.Fatalf("intent %d: workCtx pin = (%d, %v), want (%d, true)", i+1, got.id, got.ok, wantID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -87,3 +88,65 @@ VALUES('1-0001',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we
|
||||
t.Fatalf("exchange = %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrafficStreamRouteDirection(t *testing.T) {
|
||||
s, request := ingestServer(t)
|
||||
db := s.m.Traffic().DB()
|
||||
if _, err := db.Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
|
||||
VALUES('1-0002',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'websocket',0,0,'')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// seq 1 c2s, 2 s2c, 3 c2s, 4 s2c, 5 meta.
|
||||
for i, dir := range []string{"c2s", "s2c", "c2s", "s2c", "meta"} {
|
||||
kind := 1
|
||||
if dir == "meta" {
|
||||
kind = 0
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,size,payload) VALUES('1-0002',?,1,?,?,1,'x')`, i+1, dir, kind); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type page struct {
|
||||
Items []struct {
|
||||
Seq int64 `json:"seq"`
|
||||
Direction string `json:"direction"`
|
||||
} `json:"items"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
get := func(query string) page {
|
||||
t.Helper()
|
||||
w := request("GET", "/api/traffic/stream?exchange=1-0002"+query, "")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("GET %s = %d %s", query, w.Code, w.Body)
|
||||
}
|
||||
var p page
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
seqs := func(p page) []int64 {
|
||||
out := []int64{}
|
||||
for _, it := range p.Items {
|
||||
out = append(out, it.Seq)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
if p := get(""); p.Total != 5 || len(p.Items) != 5 {
|
||||
t.Fatalf("unfiltered = %+v", p)
|
||||
}
|
||||
if p := get("&direction=c2s"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[1 3 5]" {
|
||||
t.Fatalf("c2s = total %d seqs %v, want 3 and [1 3 5]", p.Total, seqs(p))
|
||||
}
|
||||
if p := get("&direction=S2C"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[2 4 5]" {
|
||||
t.Fatalf("S2C = total %d seqs %v, want 3 and [2 4 5]", p.Total, seqs(p))
|
||||
}
|
||||
if p := get("&direction=s2c&offset=1&limit=1"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[4]" {
|
||||
t.Fatalf("s2c offset=1 limit=1 = total %d seqs %v, want 3 and [4]", p.Total, seqs(p))
|
||||
}
|
||||
if w := request("GET", "/api/traffic/stream?exchange=1-0002&direction=meta", ""); w.Code != 400 {
|
||||
t.Fatalf("direction=meta = %d %s, want 400", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConsoleBrowserProtections(t *testing.T) {
|
||||
handler := (&Server{}).Handler()
|
||||
headers := map[string]string{
|
||||
"Content-Security-Policy": "frame-ancestors 'self'",
|
||||
"X-Frame-Options": "SAMEORIGIN",
|
||||
"Referrer-Policy": "same-origin",
|
||||
}
|
||||
|
||||
for _, path := range []string{"/", "/settings/"} {
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
sent := res.Result().Header
|
||||
for name, want := range headers {
|
||||
if got := sent.Get(name); got != want {
|
||||
t.Errorf("%s: %s = %q, want %q", path, name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/api/health", nil))
|
||||
if res.Code != http.StatusOK {
|
||||
t.Fatalf("health: status = %d, want %d", res.Code, http.StatusOK)
|
||||
}
|
||||
sent := res.Result().Header
|
||||
for name := range headers {
|
||||
if got := sent.Get(name); got != "" {
|
||||
t.Errorf("health: unexpected %s = %q", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
-34
@@ -23,23 +23,68 @@ const (
|
||||
maxWorkspaceUpload = 512 << 20 // 512 MiB per upload request
|
||||
)
|
||||
|
||||
// wsResolveConfined maps a user-supplied relative path to a canonicalized path
|
||||
// inside the work dir, resolving symlinks in every component and rejecting any
|
||||
// traversal, broken symlink, symlink loop, or target that escapes s.m.dir.
|
||||
func (s *Server) wsResolveConfined(rel string) (confinedPath, bool) {
|
||||
cp, err := resolveWithinRoot(s.m.dir, rel, true)
|
||||
if err != nil {
|
||||
return confinedPath{}, false
|
||||
}
|
||||
if workspacePathDenied(cp.realRoot, cp.realPath) {
|
||||
return confinedPath{}, false
|
||||
}
|
||||
return cp, true
|
||||
}
|
||||
|
||||
// workspaceDeniedPrefixes are platform-internal subtrees under the data dir
|
||||
// that the workspace file manager must not expose. traffic/_ca holds the
|
||||
// capture proxy CA private key; traffic/_index holds the SQLite exchange index.
|
||||
var workspaceDeniedPrefixes = []string{"traffic/_ca", "traffic/_index"}
|
||||
|
||||
// workspacePathDenied reports whether realPath lands in a platform-internal
|
||||
// subtree. It compares the canonicalized path relative to the real root, so a
|
||||
// symlink alias cannot reach a denied directory. Segments are lower-cased and
|
||||
// trailing dots/spaces are trimmed because Windows resolves those spellings to
|
||||
// the same directory.
|
||||
func workspacePathDenied(realRoot, realPath string) bool {
|
||||
rel, err := filepath.Rel(realRoot, realPath)
|
||||
if err != nil {
|
||||
return true // fail closed
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
|
||||
return true // outside the root: fail closed
|
||||
}
|
||||
segs := strings.Split(rel, "/")
|
||||
for i, seg := range segs {
|
||||
segs[i] = strings.ToLower(strings.TrimRight(seg, ". "))
|
||||
}
|
||||
rel = strings.Join(segs, "/")
|
||||
for _, prefix := range workspaceDeniedPrefixes {
|
||||
if rel == prefix || strings.HasPrefix(rel, prefix+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// wsResolve maps a user-supplied relative path to an absolute path INSIDE the work
|
||||
// dir. It returns ok=false if the path would escape the root. filepath.Clean on a
|
||||
// rooted copy collapses any ".." so nothing can climb above the root.
|
||||
// dir. It returns ok=false if the path would escape the root (including via symlinks).
|
||||
func (s *Server) wsResolve(rel string) (string, bool) {
|
||||
base := filepath.Clean(s.m.dir)
|
||||
rel = strings.TrimPrefix(strings.TrimSpace(rel), "/")
|
||||
clean := filepath.Clean("/" + rel) // e.g. "/a/../../etc" → "/etc" (still rooted at "/")
|
||||
abs := filepath.Clean(filepath.Join(base, clean))
|
||||
if abs != base && !strings.HasPrefix(abs, base+string(os.PathSeparator)) {
|
||||
cp, ok := s.wsResolveConfined(rel)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
return abs, true
|
||||
return cp.realPath, true
|
||||
}
|
||||
|
||||
// wsRel renders an absolute path back as a workspace-relative path (forward slashes).
|
||||
func (s *Server) wsRel(abs string) string {
|
||||
base := filepath.Clean(s.m.dir)
|
||||
base, err := resolveRealRoot(s.m.dir)
|
||||
if err != nil {
|
||||
base = filepath.Clean(s.m.dir)
|
||||
}
|
||||
rel, err := filepath.Rel(base, abs)
|
||||
if err != nil || rel == "." {
|
||||
return ""
|
||||
@@ -57,11 +102,12 @@ type wsEntry struct {
|
||||
|
||||
// GET /api/workspace/list?path=<rel>
|
||||
func (s *Server) wsList(w http.ResponseWriter, r *http.Request) {
|
||||
abs, ok := s.wsResolve(r.URL.Query().Get("path"))
|
||||
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
||||
if !ok {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
abs := cp.realPath
|
||||
fi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
writeErr(w, 404, "path does not exist")
|
||||
@@ -73,7 +119,7 @@ func (s *Server) wsList(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ents, err := os.ReadDir(abs)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
out := make([]wsEntry, 0, len(ents))
|
||||
@@ -103,11 +149,12 @@ func (s *Server) wsList(w http.ResponseWriter, r *http.Request) {
|
||||
// GET /api/workspace/read?path=<rel> — inline text for view/edit. Binary or oversize
|
||||
// files return {binary:true}/{too_large:true} with no content (use download instead).
|
||||
func (s *Server) wsRead(w http.ResponseWriter, r *http.Request) {
|
||||
abs, ok := s.wsResolve(r.URL.Query().Get("path"))
|
||||
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
||||
if !ok {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
abs := cp.realPath
|
||||
fi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
writeErr(w, 404, "file does not exist")
|
||||
@@ -123,7 +170,7 @@ func (s *Server) wsRead(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
data, err := os.ReadFile(abs)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) {
|
||||
@@ -143,21 +190,22 @@ func (s *Server) wsWrite(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
abs, ok := s.wsResolve(req.Path)
|
||||
if !ok || abs == filepath.Clean(s.m.dir) {
|
||||
cp, ok := s.wsResolveConfined(req.Path)
|
||||
if !ok || cp.realPath == cp.realRoot {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
abs := cp.realPath
|
||||
if fi, err := os.Stat(abs); err == nil && fi.IsDir() {
|
||||
writeErr(w, 400, "target is a directory")
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(abs, []byte(req.Content), 0o644); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "path": s.wsRel(abs)})
|
||||
@@ -172,13 +220,14 @@ func (s *Server) wsMkdir(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
abs, ok := s.wsResolve(req.Path)
|
||||
if !ok || abs == filepath.Clean(s.m.dir) {
|
||||
cp, ok := s.wsResolveConfined(req.Path)
|
||||
if !ok || cp.realPath == cp.realRoot {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
abs := cp.realPath
|
||||
if err := os.MkdirAll(abs, 0o755); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "path": s.wsRel(abs)})
|
||||
@@ -187,21 +236,21 @@ func (s *Server) wsMkdir(w http.ResponseWriter, r *http.Request) {
|
||||
// DELETE /api/workspace/delete?path=<rel> — removes a file or a directory tree
|
||||
// (confined to the work dir; the root itself can't be deleted).
|
||||
func (s *Server) wsDelete(w http.ResponseWriter, r *http.Request) {
|
||||
abs, ok := s.wsResolve(r.URL.Query().Get("path"))
|
||||
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
||||
if !ok {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if abs == filepath.Clean(s.m.dir) {
|
||||
if cp.realPath == cp.realRoot {
|
||||
writeErr(w, 400, "cannot delete the workspace root directory")
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(abs); err != nil {
|
||||
if !cp.exists {
|
||||
writeErr(w, 404, "path does not exist")
|
||||
return
|
||||
}
|
||||
if err := os.RemoveAll(abs); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
if err := os.RemoveAll(cp.entryPath); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
@@ -209,17 +258,18 @@ func (s *Server) wsDelete(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// GET /api/workspace/download?path=<rel> — stream a file as an attachment.
|
||||
func (s *Server) wsDownload(w http.ResponseWriter, r *http.Request) {
|
||||
abs, ok := s.wsResolve(r.URL.Query().Get("path"))
|
||||
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
||||
if !ok {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
abs := cp.realPath
|
||||
fi, err := os.Stat(abs)
|
||||
if err != nil || fi.IsDir() {
|
||||
writeErr(w, 404, "file does not exist")
|
||||
return
|
||||
}
|
||||
name := filepath.Base(abs)
|
||||
name := filepath.Base(cp.entryPath)
|
||||
// RFC 5987 filename* keeps non-ASCII names intact; plain filename is the fallback.
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\""+sanitizeFilename(name)+"\"; filename*=UTF-8''"+url.PathEscape(name))
|
||||
http.ServeFile(w, r, abs)
|
||||
@@ -227,12 +277,12 @@ func (s *Server) wsDownload(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// POST /api/workspace/upload?path=<dir> — multipart form field "file" (one or more).
|
||||
func (s *Server) wsUpload(w http.ResponseWriter, r *http.Request) {
|
||||
dirAbs, ok := s.wsResolve(r.URL.Query().Get("path"))
|
||||
dir, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
||||
if !ok {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if fi, err := os.Stat(dirAbs); err != nil || !fi.IsDir() {
|
||||
if fi, err := os.Stat(dir.realPath); err != nil || !fi.IsDir() {
|
||||
writeErr(w, 400, "target directory does not exist")
|
||||
return
|
||||
}
|
||||
@@ -246,18 +296,24 @@ func (s *Server) wsUpload(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, "missing upload file (form field file)")
|
||||
return
|
||||
}
|
||||
dirRel := s.wsRel(dir.realPath)
|
||||
saved := 0
|
||||
for _, hdr := range files {
|
||||
name := filepath.Base(hdr.Filename) // strip any path component
|
||||
if name == "" || name == "." || name == ".." {
|
||||
continue
|
||||
}
|
||||
destAbs, okd := s.wsResolve(filepath.Join(s.wsRel(dirAbs), name))
|
||||
if !okd {
|
||||
continue
|
||||
destRel := name
|
||||
if dirRel != "" {
|
||||
destRel = dirRel + "/" + name
|
||||
}
|
||||
if err := saveUpload(hdr, destAbs); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
dest, okd := s.wsResolveConfined(destRel)
|
||||
if !okd || dest.realPath == dest.realRoot {
|
||||
writeErr(w, 400, "invalid path")
|
||||
return
|
||||
}
|
||||
if err := saveUpload(hdr, dest.realPath); err != nil {
|
||||
writeErr(w, 500, safeFSErr(err))
|
||||
return
|
||||
}
|
||||
saved++
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWorkspaceDeniesPlatformPaths(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, p := range []string{"traffic/_ca", "traffic/_index", "traffic/host", "other"} {
|
||||
if err := os.MkdirAll(filepath.Join(dir, p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
key := filepath.Join(dir, "traffic", "_ca", "mitmproxy-ca.pem")
|
||||
if err := os.WriteFile(key, []byte("key"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{m: &Manager{dir: dir}}
|
||||
|
||||
for _, rel := range []string{
|
||||
"traffic/_ca",
|
||||
"traffic/_ca/mitmproxy-ca.pem",
|
||||
"traffic/_index",
|
||||
"traffic/_index/index.sqlite",
|
||||
"TRAFFIC/_CA/mitmproxy-ca.pem",
|
||||
"traffic/_ca.",
|
||||
"traffic/_ca./mitmproxy-ca.pem",
|
||||
} {
|
||||
if _, ok := s.wsResolveConfined(rel); ok {
|
||||
t.Errorf("%q resolved, want a refusal", rel)
|
||||
}
|
||||
}
|
||||
|
||||
for _, rel := range []string{"", "traffic", "traffic/host", "traffic/_caX", "other"} {
|
||||
if _, ok := s.wsResolveConfined(rel); !ok {
|
||||
t.Errorf("%q refused, want a resolution", rel)
|
||||
}
|
||||
}
|
||||
|
||||
link := filepath.Join(dir, "alias")
|
||||
if err := os.Symlink(filepath.Join(dir, "traffic", "_ca"), link); err == nil {
|
||||
if _, ok := s.wsResolveConfined("alias/mitmproxy-ca.pem"); ok {
|
||||
t.Error("symlink alias to traffic/_ca resolved")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspacePathDenied(t *testing.T) {
|
||||
root := filepath.Clean("/data")
|
||||
for _, tc := range []struct {
|
||||
path string
|
||||
want bool
|
||||
}{
|
||||
{"/data/traffic/_ca", true},
|
||||
{"/data/traffic/_ca/x", true},
|
||||
{"/data/traffic/_index/index.sqlite", true},
|
||||
{"/data/traffic/_caX", false},
|
||||
{"/data/traffic", false},
|
||||
{"/data/other", false},
|
||||
{"/elsewhere/traffic/_ca", true}, // outside the root: fail closed
|
||||
} {
|
||||
if got := workspacePathDenied(root, filepath.FromSlash(tc.path)); got != tc.want {
|
||||
t.Errorf("workspacePathDenied(%q) = %v, want %v", tc.path, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
-2
@@ -528,6 +528,37 @@ type StreamMessage struct {
|
||||
// most streamPreview (4 KiB); a longer one lives in the blob store and the row
|
||||
// carries its hash for the rest (traffic_blob, GET /api/traffic/blob).
|
||||
func (t *Traffic) StreamMessages(exchangeID string, offset, limit int) ([]StreamMessage, int, error) {
|
||||
return t.StreamMessagesByDirection(exchangeID, "", offset, limit)
|
||||
}
|
||||
|
||||
// ErrBadStreamDirection is returned by StreamMessagesByDirection for a
|
||||
// direction other than "", "c2s" or "s2c".
|
||||
var ErrBadStreamDirection = errors.New(`direction must be "c2s", "s2c" or empty`)
|
||||
|
||||
// streamDirectionFilter returns the SQL condition (after exchange_id=?) and its
|
||||
// argument for a direction filter. A filtered page keeps the 'meta' limit
|
||||
// marker, so a reader never misses that messages were dropped.
|
||||
func streamDirectionFilter(direction string) (cond string, args []any, err error) {
|
||||
switch direction {
|
||||
case "":
|
||||
return "", nil, nil
|
||||
case "c2s", "s2c":
|
||||
return ` AND direction IN (?, 'meta')`, []any{direction}, nil
|
||||
default:
|
||||
return "", nil, ErrBadStreamDirection
|
||||
}
|
||||
}
|
||||
|
||||
// StreamMessagesByDirection is StreamMessages restricted to one direction:
|
||||
// "c2s" (client to server), "s2c" (server to client), or "" for both. total
|
||||
// counts only the matching rows, so offset pages through the filtered list.
|
||||
// The 'meta' row (messages dropped past the recorder's limits) is kept in a
|
||||
// filtered page. Seq stays the message's position in the whole stream.
|
||||
func (t *Traffic) StreamMessagesByDirection(exchangeID, direction string, offset, limit int) ([]StreamMessage, int, error) {
|
||||
cond, dirArgs, err := streamDirectionFilter(direction)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
@@ -538,11 +569,12 @@ func (t *Traffic) StreamMessages(exchangeID string, offset, limit int) ([]Stream
|
||||
offset = 0
|
||||
}
|
||||
var total int
|
||||
if err := t.db.QueryRow(`SELECT COUNT(*) FROM stream_messages WHERE exchange_id=?`, exchangeID).Scan(&total); err != nil {
|
||||
args := append([]any{exchangeID}, dirArgs...)
|
||||
if err := t.db.QueryRow(`SELECT COUNT(*) FROM stream_messages WHERE exchange_id=?`+cond, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
rows, err := t.db.Query(`SELECT seq,ts,direction,kind,event,event_id,retry,size,payload,payload_blob,truncated
|
||||
FROM stream_messages WHERE exchange_id=? ORDER BY seq LIMIT ? OFFSET ?`, exchangeID, limit, offset)
|
||||
FROM stream_messages WHERE exchange_id=?`+cond+` ORDER BY seq LIMIT ? OFFSET ?`, append(args, limit, offset)...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package traffic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// directionStream records c2s "q0","q1",... and s2c "a0","a1",... interleaved
|
||||
// (q0 a0 q1 a1 ...) on one WebSocket exchange and returns its id.
|
||||
func directionStream(t *testing.T, pairs int) (*Traffic, string) {
|
||||
t.Helper()
|
||||
tr, s, f := unitStream(t, "direction.test")
|
||||
for i := 0; i < pairs; i++ {
|
||||
addWS(f, true, websocket.TextMessage, []byte("q"+string(rune('0'+i))))
|
||||
addWS(f, false, websocket.TextMessage, []byte("a"+string(rune('0'+i))))
|
||||
}
|
||||
s.WebSocketMessage(f)
|
||||
s.WebSocketEnd(f)
|
||||
return tr, onlyExchange(t, tr)
|
||||
}
|
||||
|
||||
func TestStreamMessagesByDirection(t *testing.T) {
|
||||
tr, id := directionStream(t, 3)
|
||||
|
||||
all, total, err := tr.StreamMessagesByDirection(id, "", 0, 50)
|
||||
if err != nil || total != 6 || len(all) != 6 {
|
||||
t.Fatalf("unfiltered: %d of %d, err %v; want 6 of 6", len(all), total, err)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
dir string
|
||||
payloads []string
|
||||
seqs []int64
|
||||
}{
|
||||
{"c2s", []string{"q0", "q1", "q2"}, []int64{1, 3, 5}},
|
||||
{"s2c", []string{"a0", "a1", "a2"}, []int64{2, 4, 6}},
|
||||
} {
|
||||
msgs, total, err := tr.StreamMessagesByDirection(id, tc.dir, 0, 50)
|
||||
if err != nil || total != 3 || len(msgs) != 3 {
|
||||
t.Fatalf("%s: %d of %d, err %v; want 3 of 3", tc.dir, len(msgs), total, err)
|
||||
}
|
||||
for i, m := range msgs {
|
||||
// Seq stays the position in the whole stream, so a filtered row
|
||||
// can be matched against the unfiltered conversation.
|
||||
if m.Direction != tc.dir || m.Payload != tc.payloads[i] || m.Seq != tc.seqs[i] {
|
||||
t.Fatalf("%s message %d = %+v, want payload %q seq %d", tc.dir, i, m, tc.payloads[i], tc.seqs[i])
|
||||
}
|
||||
}
|
||||
// offset and total apply to the filtered list.
|
||||
page, total, err := tr.StreamMessagesByDirection(id, tc.dir, 1, 1)
|
||||
if err != nil || total != 3 || len(page) != 1 || page[0].Payload != tc.payloads[1] {
|
||||
t.Fatalf("%s offset=1 limit=1: %+v total %d err %v; want %q", tc.dir, page, total, err, tc.payloads[1])
|
||||
}
|
||||
}
|
||||
|
||||
// StreamMessages is the unfiltered form.
|
||||
if msgs, total, err := tr.StreamMessages(id, 0, 50); err != nil || total != 6 || len(msgs) != 6 {
|
||||
t.Fatalf("StreamMessages: %d of %d, err %v", len(msgs), total, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamMessagesByDirectionRejectsUnknown(t *testing.T) {
|
||||
tr, id := directionStream(t, 1)
|
||||
for _, dir := range []string{"meta", "both", "C2S", "c2s' OR 1=1 --"} {
|
||||
if _, _, err := tr.StreamMessagesByDirection(id, dir, 0, 50); !errors.Is(err, ErrBadStreamDirection) {
|
||||
t.Fatalf("direction %q: err %v, want ErrBadStreamDirection", dir, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A filtered page keeps the meta row, so dropped messages are never hidden.
|
||||
func TestStreamMessagesByDirectionKeepsMetaRow(t *testing.T) {
|
||||
tr, s, f := unitStream(t, "direction-meta.test")
|
||||
for i := 0; i < maxStreamMessages+4; i++ {
|
||||
addWS(f, i%2 == 0, websocket.TextMessage, []byte("m"))
|
||||
}
|
||||
s.WebSocketMessage(f)
|
||||
s.WebSocketEnd(f)
|
||||
id := onlyExchange(t, tr)
|
||||
|
||||
_, total, err := tr.StreamMessagesByDirection(id, "s2c", 0, 1)
|
||||
if err != nil || total != maxStreamMessages/2+1 {
|
||||
t.Fatalf("s2c total %d err %v, want %d messages and the meta row", total, err, maxStreamMessages/2+1)
|
||||
}
|
||||
last, _, err := tr.StreamMessagesByDirection(id, "s2c", total-1, 1)
|
||||
if err != nil || len(last) != 1 || last[0].Type != "meta" {
|
||||
t.Fatalf("last s2c row %+v err %v, want the meta row", last, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrafficMessagesToolDirection(t *testing.T) {
|
||||
tr, id := directionStream(t, 2)
|
||||
|
||||
out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":"s2c"}`)
|
||||
if !strings.HasPrefix(out, "[messages 1-2 of 2]") || !strings.Contains(out, `"a0"`) || !strings.Contains(out, `"a1"`) || strings.Contains(out, `"q0"`) {
|
||||
t.Fatalf("s2c output:\n%s", out)
|
||||
}
|
||||
out = toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":" C2S "}`)
|
||||
if !strings.HasPrefix(out, "[messages 1-2 of 2]") || !strings.Contains(out, `"q1"`) || strings.Contains(out, `"a1"`) {
|
||||
t.Fatalf("c2s output (case and spaces normalized):\n%s", out)
|
||||
}
|
||||
if out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`"}`); !strings.HasPrefix(out, "[messages 1-4 of 4]") {
|
||||
t.Fatalf("no direction output:\n%s", out)
|
||||
}
|
||||
if out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":"sideways"}`); !strings.Contains(out, "direction must be") {
|
||||
t.Fatalf("bad direction output:\n%s", out)
|
||||
}
|
||||
if out := toolText(t, tr, "traffic_messages", `{"id":"nope","direction":"c2s"}`); !strings.Contains(out, "No c2s stream messages") {
|
||||
t.Fatalf("empty filtered output:\n%s", out)
|
||||
}
|
||||
}
|
||||
+14
-8
@@ -2353,13 +2353,14 @@ func (t *Traffic) Tools() []actool.CoreTool {
|
||||
|
||||
messages := actool.Build(actool.Spec{
|
||||
Name: "traffic_messages",
|
||||
Description: "List the messages of one captured WebSocket or SSE (Server-Sent Events) record in order: direction (c2s client→server, s2c server→client), type (text/binary/event, or meta when the recorder dropped messages past its limits), size and a preview of at most 1KB (binary as hex). A payload stored as a blob carries its hash; read the rest with traffic_blob. Returns 20 messages by default, at most 50; use offset to page.",
|
||||
Description: "List the messages of one captured WebSocket or SSE (Server-Sent Events) record in order: direction (c2s client→server, s2c server→client), type (text/binary/event, or meta when the recorder dropped messages past its limits), size and a preview of at most 1KB (binary as hex). A payload stored as a blob carries its hash; read the rest with traffic_blob. Set direction to c2s or s2c to list only one side of the conversation (the meta row is kept). Returns 20 messages by default, at most 50; use offset to page.",
|
||||
Schema: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"id": map[string]any{"type": "string", "description": "the record id from traffic_search (a WebSocket status-101 or SSE record)"},
|
||||
"offset": map[string]any{"type": "integer", "description": "number of messages to skip, default 0"},
|
||||
"limit": map[string]any{"type": "integer", "description": "messages to return, default 20, max 50"},
|
||||
"id": map[string]any{"type": "string", "description": "the record id from traffic_search (a WebSocket status-101 or SSE record)"},
|
||||
"direction": map[string]any{"type": "string", "enum": []any{"c2s", "s2c"}, "description": "only messages in this direction: c2s (client→server) or s2c (server→client); omit for both"},
|
||||
"offset": map[string]any{"type": "integer", "description": "number of messages to skip within the (filtered) list, default 0"},
|
||||
"limit": map[string]any{"type": "integer", "description": "messages to return, default 20, max 50"},
|
||||
},
|
||||
"required": []any{"id"},
|
||||
},
|
||||
@@ -2367,9 +2368,10 @@ func (t *Traffic) Tools() []actool.CoreTool {
|
||||
Permissions: allow,
|
||||
Run: func(_ context.Context, in json.RawMessage, _ *actool.ToolContext) (actool.Result, error) {
|
||||
var a struct {
|
||||
ID string
|
||||
Offset int
|
||||
Limit int
|
||||
ID string
|
||||
Direction string
|
||||
Offset int
|
||||
Limit int
|
||||
}
|
||||
_ = json.Unmarshal(in, &a)
|
||||
if strings.TrimSpace(a.ID) == "" {
|
||||
@@ -2384,11 +2386,15 @@ func (t *Traffic) Tools() []actool.CoreTool {
|
||||
if a.Offset < 0 {
|
||||
a.Offset = 0
|
||||
}
|
||||
msgs, total, err := t.StreamMessages(a.ID, a.Offset, a.Limit)
|
||||
a.Direction = strings.ToLower(strings.TrimSpace(a.Direction))
|
||||
msgs, total, err := t.StreamMessagesByDirection(a.ID, a.Direction, a.Offset, a.Limit)
|
||||
if err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
if total == 0 {
|
||||
if a.Direction != "" {
|
||||
return actool.Text(fmt.Sprintf("No %s stream messages recorded for this id (not a WebSocket/SSE record, or no message was sent in that direction).", a.Direction)), nil
|
||||
}
|
||||
return actool.Text("No stream messages recorded for this id (not a WebSocket/SSE record, or no message was exchanged)."), nil
|
||||
}
|
||||
type liteMsg struct {
|
||||
|
||||
+2
-1
@@ -15,7 +15,8 @@
|
||||
"generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts",
|
||||
"test:polling": "node --test scripts/polling.test.mjs",
|
||||
"test:replay": "node --test scripts/replay.test.mjs",
|
||||
"test:upload": "node --test scripts/upload.test.mjs"
|
||||
"test:upload": "node --test scripts/upload.test.mjs",
|
||||
"test:i18n": "node scripts/check-i18n.mjs"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{js,ts,jsx,tsx}": [
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// Every literal t("...") / t('...') key must exist in the locale dictionary
|
||||
// with the same {placeholders}. Dynamic keys (variables, template literals
|
||||
// with ${}) are skipped: there is nothing to compare them against.
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const dict = JSON.parse(readFileSync(join(root, "src/i18n/locales/tr.json"), "utf8"));
|
||||
|
||||
const files = [];
|
||||
function walk(dir) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const p = join(dir, name);
|
||||
const st = statSync(p);
|
||||
if (st.isDirectory()) walk(p);
|
||||
else if (/\.(ts|tsx)$/.test(name)) files.push(p);
|
||||
}
|
||||
}
|
||||
walk(join(root, "src"));
|
||||
|
||||
const calls = new Map(); // key -> first file that uses it
|
||||
const literalCall = /(?:^|[^\w$.])t\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/gm;
|
||||
for (const file of files) {
|
||||
const src = readFileSync(file, "utf8");
|
||||
for (const m of src.matchAll(literalCall)) {
|
||||
const key =
|
||||
m[1] !== undefined ? JSON.parse(`"${m[1]}"`) : m[2].replace(/\\(['\\])/g, "$1");
|
||||
if (!calls.has(key)) calls.set(key, file.slice(root.length + 1));
|
||||
}
|
||||
}
|
||||
|
||||
function placeholders(s) {
|
||||
return [...s.matchAll(/\{(\w+)\}/g)]
|
||||
.map((m) => m[1])
|
||||
.sort()
|
||||
.join(",");
|
||||
}
|
||||
|
||||
const missing = [];
|
||||
const mismatch = [];
|
||||
for (const [key, file] of calls) {
|
||||
if (!Object.prototype.hasOwnProperty.call(dict, key)) {
|
||||
missing.push(`${file}: ${JSON.stringify(key)}`);
|
||||
continue;
|
||||
}
|
||||
if (placeholders(dict[key]) !== placeholders(key)) {
|
||||
mismatch.push(`${JSON.stringify(key)}: source {${placeholders(key)}} dict {${placeholders(dict[key])}}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length || mismatch.length) {
|
||||
if (missing.length) {
|
||||
console.error(`Missing tr.json entries (${missing.length}):\n${missing.join("\n")}`);
|
||||
}
|
||||
if (mismatch.length) {
|
||||
console.error(`Placeholder mismatches (${mismatch.length}):\n${mismatch.join("\n")}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`i18n: ${calls.size} literal keys checked against ${Object.keys(dict).length} tr.json entries`,
|
||||
);
|
||||
@@ -21,6 +21,9 @@ function setup(mock = false) {
|
||||
require(name) {
|
||||
if (name === "@/lib/mock/enabled") return { MOCK: mock };
|
||||
if (name === "@/lib/mock/handler") return { mockHandle: () => assert.fail("unexpected mock request") };
|
||||
// English passthrough: assertions below match the source (English) messages.
|
||||
if (name === "@/i18n")
|
||||
return { t: (key, vars) => key.replace(/\{(\w+)\}/g, (m, k) => (vars && k in vars ? String(vars[k]) : m)) };
|
||||
throw new Error("Unexpected import: " + name);
|
||||
},
|
||||
FormData: class {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
@@ -55,14 +56,14 @@ export default function LoginPage() {
|
||||
.then(({ initialized }) => {
|
||||
if (!initialized) router.replace("/setup");
|
||||
})
|
||||
.catch(() => setError("Unable to connect to the backend service"))
|
||||
.catch(() => setError(t("Unable to connect to the backend service")))
|
||||
.finally(() => setChecking(false));
|
||||
}, [router]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!agreed) {
|
||||
setError("Please read and agree to the Terms of Use first");
|
||||
setError(t("Please read and agree to the Terms of Use first"));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@@ -72,7 +73,7 @@ export default function LoginPage() {
|
||||
auth.setToken(token);
|
||||
window.location.replace("/function/tasks");
|
||||
} catch {
|
||||
setError("Incorrect username or password");
|
||||
setError(t("Incorrect username or password"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -80,12 +81,16 @@ export default function LoginPage() {
|
||||
|
||||
if (checking) {
|
||||
return (
|
||||
<div role="status" className="flex min-h-dvh items-center justify-center text-muted-foreground">
|
||||
Checking login state…
|
||||
// Prerendered in the build-time locale; the reader's locale may differ for this brief state.
|
||||
<div role="status" className="flex min-h-dvh items-center justify-center text-muted-foreground" suppressHydrationWarning>
|
||||
{t("Checking login state…")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Keep the agreement sentence whole: the link text is placed through a placeholder so the word order can follow the locale.
|
||||
const [agreeBefore, agreeAfter = ""] = t("I have read and agree to {terms}").split("{terms}");
|
||||
|
||||
return (
|
||||
<div className="flex h-dvh">
|
||||
{/* Left panel */}
|
||||
@@ -103,22 +108,24 @@ export default function LoginPage() {
|
||||
<div className="flex w-full items-center justify-center bg-background p-8 lg:w-2/3">
|
||||
<div className="w-full max-w-md space-y-10 py-24 lg:py-32">
|
||||
<div className="space-y-4 text-center">
|
||||
<h2 className="text-2xl font-medium tracking-tight">Sign in</h2>
|
||||
<p className="mx-auto max-w-xl text-muted-foreground">Welcome back — enter your password to continue using ARTEX</p>
|
||||
<h2 className="text-2xl font-medium tracking-tight">{t("Sign in")}</h2>
|
||||
<p className="mx-auto max-w-xl text-muted-foreground">
|
||||
{t("Welcome back — enter your password to continue using ARTEX")}
|
||||
</p>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input id="username" value="ARTEX" readOnly className="bg-muted text-muted-foreground" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Label htmlFor="password">{t("Password")}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Enter your password"
|
||||
placeholder={t("Enter your password")}
|
||||
autoFocus
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
@@ -131,19 +138,20 @@ export default function LoginPage() {
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<Label htmlFor="agree-terms" className="text-sm font-normal leading-relaxed text-muted-foreground">
|
||||
I have read and agree to
|
||||
{agreeBefore}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTermsOpen(true)}
|
||||
className="mx-0.5 font-medium text-primary underline-offset-4 hover:underline"
|
||||
>
|
||||
Terms of Use
|
||||
{t("Terms of Use")}
|
||||
</button>
|
||||
{agreeAfter}
|
||||
</Label>
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
<Button type="submit" className="w-full" disabled={loading || !password || !agreed}>
|
||||
{loading ? "Signing in..." : "Sign in"}
|
||||
{loading ? t("Signing in...") : t("Sign in")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
@@ -156,9 +164,9 @@ export default function LoginPage() {
|
||||
<ShieldCheck className="size-5" />
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
<DialogTitle className="text-base">ARTEX Terms of Use and Disclaimer</DialogTitle>
|
||||
<DialogTitle className="text-base">{t("ARTEX Terms of Use and Disclaimer")}</DialogTitle>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Version v1.1 · Effective 2026-10-11 · Please read all the following terms in full before signing in
|
||||
{t("Version v1.1 · Effective 2026-10-11 · Please read all the following terms in full before signing in")}
|
||||
</p>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
@@ -169,11 +177,14 @@ export default function LoginPage() {
|
||||
className="max-h-[60vh] space-y-5 overflow-y-auto px-6 py-5 text-sm leading-relaxed text-muted-foreground"
|
||||
>
|
||||
<p className="rounded-lg border bg-muted/40 p-3 text-foreground/80">
|
||||
This Terms of Use and Disclaimer (the "Statement") is the agreement between you and the ARTEX
|
||||
project authors and contributors regarding your use of this software. Please read it carefully and fully understand each provision before use, especially the disclaimer, liability-limitation, and prohibition clauses highlighted in bold or color blocks.
|
||||
{t(
|
||||
'This Terms of Use and Disclaimer (the "Statement") is the agreement between you and the ARTEX project authors and contributors regarding your use of this software. Please read it carefully and fully understand each provision before use, especially the disclaimer, liability-limitation, and prohibition clauses highlighted in bold or color blocks.',
|
||||
)}
|
||||
<span className="font-medium text-foreground">
|
||||
{" "}
|
||||
Once you download, install, access, or use this software in any way, you are deemed to have read, understood, and agreed to be bound by all of this Statement.
|
||||
{t(
|
||||
"Once you download, install, access, or use this software in any way, you are deemed to have read, understood, and agreed to be bound by all of this Statement.",
|
||||
)}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
@@ -182,12 +193,12 @@ export default function LoginPage() {
|
||||
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
|
||||
1
|
||||
</span>
|
||||
Article 1 · Definitions and Open-Source License
|
||||
{t("Article 1 · Definitions and Open-Source License")}
|
||||
</h4>
|
||||
<p className="pl-7">
|
||||
This software (ARTEX) is an open-source program released under the GNU Affero General Public License
|
||||
v3.0 (AGPL-3.0). You may freely use, copy, modify, and distribute it under that license; however, any derivative work (including online services provided to third parties over a network) must likewise be open-sourced under
|
||||
the AGPL-3.0 license with the complete corresponding source code made public to its users. The full AGPL-3.0 terms are governed by the accompanying LICENSE file.
|
||||
{t(
|
||||
"This software (ARTEX) is an open-source program released under the GNU Affero General Public License v3.0 (AGPL-3.0). You may freely use, copy, modify, and distribute it under that license; however, any derivative work (including online services provided to third parties over a network) must likewise be open-sourced under the AGPL-3.0 license with the complete corresponding source code made public to its users. The full AGPL-3.0 terms are governed by the accompanying LICENSE file.",
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -196,10 +207,12 @@ export default function LoginPage() {
|
||||
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
|
||||
2
|
||||
</span>
|
||||
Article 2 · Permitted Scope of Use
|
||||
{t("Article 2 · Permitted Scope of Use")}
|
||||
</h4>
|
||||
<p className="pl-7">
|
||||
This software is a security-testing platform. You may use it for: personal study, code research, and technical verification in environments you set up yourself; security testing of systems you own; security testing of third-party systems when you hold the owner's explicit authorization; and testing within the written scope of a bug bounty or vulnerability disclosure program, in compliance with that program's rules of engagement. You are responsible for obtaining and keeping proof of authorization, for staying inside the authorized scope, and for the safety and proportionality of every action the software takes on your behalf.
|
||||
{t(
|
||||
"This software is a security-testing platform. You may use it for: personal study, code research, and technical verification in environments you set up yourself; security testing of systems you own; security testing of third-party systems when you hold the owner's explicit authorization; and testing within the written scope of a bug bounty or vulnerability disclosure program, in compliance with that program's rules of engagement. You are responsible for obtaining and keeping proof of authorization, for staying inside the authorized scope, and for the safety and proportionality of every action the software takes on your behalf.",
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -209,15 +222,29 @@ export default function LoginPage() {
|
||||
3
|
||||
</span>
|
||||
<AlertTriangle className="size-4" />
|
||||
Article 3 · Prohibited Conduct
|
||||
{t("Article 3 · Prohibited Conduct")}
|
||||
</h4>
|
||||
<ul className="ml-7 list-decimal space-y-1.5 rounded-lg border border-destructive/20 bg-destructive/5 p-3 pl-8 text-foreground/80 marker:text-destructive/70">
|
||||
<li>
|
||||
Strictly forbidden: scanning, probing, exploiting, or attacking any system whose owner has not explicitly authorized you to test it, or exceeding the authorized scope or a program's rules of engagement once granted;
|
||||
{t(
|
||||
"Strictly forbidden: scanning, probing, exploiting, or attacking any system whose owner has not explicitly authorized you to test it, or exceeding the authorized scope or a program's rules of engagement once granted;",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
"Strictly forbidden: using this software for illegal intrusion, data theft, extortion, denial of service (DoS/DDoS), or any destructive or criminal activity;",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
"Strictly forbidden: removing, tampering with, or circumventing any copyright, license, or security notice in this software or its output;",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
"Strictly forbidden: engaging in any conduct that violates the laws, regulations, or regulatory rules of your country or region.",
|
||||
)}
|
||||
</li>
|
||||
<li>Strictly forbidden: using this software for illegal intrusion, data theft, extortion, denial of service (DoS/DDoS), or any destructive or criminal activity;</li>
|
||||
<li>Strictly forbidden: removing, tampering with, or circumventing any copyright, license, or security notice in this software or its output;</li>
|
||||
<li>Strictly forbidden: engaging in any conduct that violates the laws, regulations, or regulatory rules of your country or region.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -226,11 +253,12 @@ export default function LoginPage() {
|
||||
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
|
||||
4
|
||||
</span>
|
||||
Article 4 · Intellectual Property
|
||||
{t("Article 4 · Intellectual Property")}
|
||||
</h4>
|
||||
<p className="pl-7">
|
||||
The copyright and related intellectual property of this software belong to the project authors and contributors, who grant
|
||||
you the corresponding rights within the scope of the AGPL-3.0 license. Beyond the rights expressly granted by that license, this Statement grants you no other rights, expressly or by implication.
|
||||
{t(
|
||||
"The copyright and related intellectual property of this software belong to the project authors and contributors, who grant you the corresponding rights within the scope of the AGPL-3.0 license. Beyond the rights expressly granted by that license, this Statement grants you no other rights, expressly or by implication.",
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -239,10 +267,12 @@ export default function LoginPage() {
|
||||
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
|
||||
5
|
||||
</span>
|
||||
Article 5 · Data and Privacy
|
||||
{t("Article 5 · Data and Privacy")}
|
||||
</h4>
|
||||
<p className="pl-7">
|
||||
This software is a self-deployable open-source program; the authors run no centralized service and neither collect nor upload your usage data. All data you generate, process, or touch while using it stays under your control, and you are responsible for its legality and security; any consequence of improper data handling is yours to bear.
|
||||
{t(
|
||||
"This software is a self-deployable open-source program; the authors run no centralized service and neither collect nor upload your usage data. All data you generate, process, or touch while using it stays under your control, and you are responsible for its legality and security; any consequence of improper data handling is yours to bear.",
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -251,13 +281,17 @@ export default function LoginPage() {
|
||||
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
|
||||
6
|
||||
</span>
|
||||
Article 6 · Compliance and Legal Liability
|
||||
{t("Article 6 · Compliance and Legal Liability")}
|
||||
</h4>
|
||||
<p className="pl-7">
|
||||
You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).
|
||||
{t(
|
||||
"You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).",
|
||||
)}
|
||||
<span className="font-medium text-foreground">
|
||||
{" "}
|
||||
All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors.
|
||||
{t(
|
||||
"All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors.",
|
||||
)}
|
||||
</span>
|
||||
</p>
|
||||
</section>
|
||||
@@ -267,11 +301,12 @@ export default function LoginPage() {
|
||||
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
|
||||
7
|
||||
</span>
|
||||
Article 7 · Disclaimer and Limitation of Liability
|
||||
{t("Article 7 · Disclaimer and Limitation of Liability")}
|
||||
</h4>
|
||||
<p className="pl-7">
|
||||
This software is provided on an "AS IS" and "AS
|
||||
AVAILABLE" basis, without any express or implied warranty, including but not limited to warranties of merchantability, fitness for a particular purpose, accuracy, and non-infringement. To the maximum extent permitted by applicable law, this software's authors and contributors are not liable for any direct, indirect, incidental, special, or consequential loss arising from using or being unable to use this software (regardless of whether it is used properly), including but not limited to data loss, system damage, business interruption, loss of profit, or legal disputes.
|
||||
{t(
|
||||
'This software is provided on an "AS IS" and "AS AVAILABLE" basis, without any express or implied warranty, including but not limited to warranties of merchantability, fitness for a particular purpose, accuracy, and non-infringement. To the maximum extent permitted by applicable law, this software\'s authors and contributors are not liable for any direct, indirect, incidental, special, or consequential loss arising from using or being unable to use this software (regardless of whether it is used properly), including but not limited to data loss, system damage, business interruption, loss of profit, or legal disputes.',
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -280,17 +315,19 @@ export default function LoginPage() {
|
||||
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
|
||||
8
|
||||
</span>
|
||||
Article 8 · Changes to the Terms and Final Interpretation
|
||||
{t("Article 8 · Changes to the Terms and Final Interpretation")}
|
||||
</h4>
|
||||
<p className="pl-7">
|
||||
The authors may update this Statement from time to time as laws, regulations, or project development require; the updated version ships with the project and takes effect on its publication date, and your continued use of this software means you accept the revised terms. To the extent permitted by law, the authors hold the final right of interpretation of this Statement. If any provision of this Statement is held invalid, the remaining provisions stay in effect.
|
||||
{t(
|
||||
"The authors may update this Statement from time to time as laws, regulations, or project development require; the updated version ships with the project and takes effect on its publication date, and your continued use of this software means you accept the revised terms. To the extent permitted by law, the authors hold the final right of interpretation of this Statement. If any provision of this Statement is held invalid, the remaining provisions stay in effect.",
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mx-0 mb-0 flex-col items-stretch gap-2 rounded-b-xl px-6 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{readToEnd ? "You have read all the terms" : "Scroll the terms to the bottom to confirm"}
|
||||
{readToEnd ? t("You have read all the terms") : t("Scroll the terms to the bottom to confirm")}
|
||||
</p>
|
||||
<DialogClose asChild>
|
||||
<Button
|
||||
@@ -301,7 +338,7 @@ export default function LoginPage() {
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
I have read and agree to all the terms
|
||||
{t("I have read and agree to all the terms")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
@@ -29,7 +30,7 @@ export default function SetupPage() {
|
||||
if (initialized) router.replace("/login");
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err instanceof Error ? err.message : "Unable to connect to the backend service");
|
||||
setError(err instanceof Error ? err.message : t("Unable to connect to the backend service"));
|
||||
setUnavailable(true);
|
||||
})
|
||||
.finally(() => setChecking(false));
|
||||
@@ -38,11 +39,11 @@ export default function SetupPage() {
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (password !== confirm) {
|
||||
setError("The two passwords do not match");
|
||||
setError(t("The two passwords do not match"));
|
||||
return;
|
||||
}
|
||||
if (password.length < 12) {
|
||||
setError("Password must be at least 12 characters");
|
||||
setError(t("Password must be at least 12 characters"));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@@ -52,7 +53,7 @@ export default function SetupPage() {
|
||||
auth.setToken(token);
|
||||
router.replace("/function/tasks");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Initialization failed");
|
||||
setError(err instanceof Error ? err.message : t("Initialization failed"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -77,52 +78,56 @@ export default function SetupPage() {
|
||||
<div className="flex w-full items-center justify-center bg-background p-8 lg:w-2/3">
|
||||
<div className="w-full max-w-md space-y-10 py-24 lg:py-32">
|
||||
<div className="space-y-4 text-center">
|
||||
<h2 className="text-2xl font-medium tracking-tight">{unavailable ? "Cannot confirm initialization state" : "Set initial password"}</h2>
|
||||
<h2 className="text-2xl font-medium tracking-tight">{unavailable ? t("Cannot confirm initialization state") : t("Set initial password")}</h2>
|
||||
<p className="mx-auto max-w-xl text-muted-foreground">
|
||||
{unavailable
|
||||
? "The backend or database is temporarily unavailable. To avoid overwriting a password already set on this instance, setup is temporarily closed — restore the service and try again."
|
||||
: "First time using ARTEX? Enter the setup token from the server log, then set a login password for the account (at least 12 characters)"}
|
||||
? t(
|
||||
"The backend or database is temporarily unavailable. To avoid overwriting a password already set on this instance, setup is temporarily closed — restore the service and try again.",
|
||||
)
|
||||
: t(
|
||||
"First time using ARTEX? Enter the setup token from the server log, then set a login password for the account (at least 12 characters)",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{unavailable ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
{error && <p className="text-center text-sm text-destructive">{error}</p>}
|
||||
<Button type="button" className="w-full" onClick={() => window.location.reload()}>
|
||||
Retry
|
||||
{t("Retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="setup-token">Setup token</Label>
|
||||
<Label htmlFor="setup-token">{t("Setup token")}</Label>
|
||||
<Input
|
||||
id="setup-token"
|
||||
value={setupToken}
|
||||
onChange={(e) => setSetupToken(e.target.value)}
|
||||
placeholder="Printed in the server log at startup"
|
||||
placeholder={t("Printed in the server log at startup")}
|
||||
autoFocus
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password">New password</Label>
|
||||
<Label htmlFor="password">{t("New password")}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="At least 12 characters"
|
||||
placeholder={t("At least 12 characters")}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="confirm">Confirm password</Label>
|
||||
<Label htmlFor="confirm">{t("Confirm password")}</Label>
|
||||
<Input
|
||||
id="confirm"
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
placeholder="Enter the password again"
|
||||
placeholder={t("Enter the password again")}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
@@ -132,7 +137,7 @@ export default function SetupPage() {
|
||||
className="w-full"
|
||||
disabled={loading || !setupToken.trim() || !password || !confirm}
|
||||
>
|
||||
{loading ? "Saving..." : "Set password and sign in"}
|
||||
{loading ? t("Saving...") : t("Set password and sign in")}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { t } from "@/i18n";
|
||||
|
||||
export default function Home() {
|
||||
redirect("/function/tasks");
|
||||
return <>Coming Soon</>;
|
||||
return <>{t("Coming Soon")}</>;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { X } from "lucide-react";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||
import { useCurrentUser } from "@/hooks/use-current-user";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.client";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -57,11 +58,11 @@ export function MainContent({ children }: { children: ReactNode }) {
|
||||
const updateBanner = latest ? (
|
||||
<div className="flex shrink-0 items-center justify-center gap-2 border-b bg-muted/50 px-4 py-1 text-xs">
|
||||
<a href={RELEASES_URL} target="_blank" rel="noreferrer" className="underline-offset-2 hover:underline">
|
||||
ARTEX {latest} is available. See the release notes.
|
||||
{t("ARTEX {version} is available. See the release notes.", { version: latest })}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Dismiss update notice"
|
||||
aria-label={t("Dismiss update notice")}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() => {
|
||||
setLocalStorageValue(UPDATE_DISMISSED_KEY, latest);
|
||||
@@ -102,7 +103,7 @@ export function MainContent({ children }: { children: ReactNode }) {
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{version && (
|
||||
<span className="font-medium text-muted-foreground text-xs tabular-nums">Version · {version}</span>
|
||||
<span className="font-medium text-muted-foreground text-xs tabular-nums">{t("Version · {version}", { version })}</span>
|
||||
)}
|
||||
<LayoutControls />
|
||||
<ThemeSwitcher />
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { t } from "@/i18n";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { cn, getInitials } from "@/lib/utils";
|
||||
|
||||
@@ -64,7 +65,7 @@ export function AccountSwitcher({
|
||||
</Avatar>
|
||||
<div className="grid min-w-0 flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">{user.name}</span>
|
||||
<span className="truncate text-xs capitalize">{user.role}</span>
|
||||
<span className="truncate text-xs capitalize">{t(user.role)}</span>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
@@ -80,11 +81,11 @@ export function AccountSwitcher({
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setPwOpen(true)}>
|
||||
<KeyRound />
|
||||
Change password
|
||||
{t("Change password")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
|
||||
<LogOut />
|
||||
Sign out
|
||||
{t("Sign out")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export function ChangePasswordDialog({
|
||||
@@ -41,37 +42,44 @@ export function ChangePasswordDialog({
|
||||
function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!oldPassword || !newPassword) {
|
||||
toast.error("Fill in the current password and the new password");
|
||||
toast.error(t("Fill in the current password and the new password"));
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
toast.error("The two new passwords do not match");
|
||||
toast.error(t("The two new passwords do not match"));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
api
|
||||
.changePassword(oldPassword, newPassword)
|
||||
.then(() => {
|
||||
toast.success("Password changed");
|
||||
toast.success(t("Password changed"));
|
||||
onOpenChange(false);
|
||||
})
|
||||
.catch((err) => toast.error(`Change failed: ${(err as Error).message}`))
|
||||
.catch((err) => toast.error(t("Change failed: {error}", { error: (err as Error).message })))
|
||||
.finally(() => setSaving(false));
|
||||
}
|
||||
|
||||
// The username stays bold; it is placed through a placeholder so the sentence is translated whole.
|
||||
const [descBefore, descAfter = ""] = t(
|
||||
"The username is fixed as {username}. Enter the current password to verify; login tokens issued before the change stay valid until they expire.",
|
||||
).split("{username}");
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<form onSubmit={submit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Change password</DialogTitle>
|
||||
<DialogTitle>{t("Change password")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
The username is fixed as <b>ARTEX</b>. Enter the current password to verify; login tokens issued before the change stay valid until they expire.
|
||||
{descBefore}
|
||||
<b>ARTEX</b>
|
||||
{descAfter}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-3 py-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="cp-old">Current password</Label>
|
||||
<Label htmlFor="cp-old">{t("Current password")}</Label>
|
||||
<Input
|
||||
id="cp-old"
|
||||
type="password"
|
||||
@@ -82,7 +90,7 @@ export function ChangePasswordDialog({
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="cp-new">New password</Label>
|
||||
<Label htmlFor="cp-new">{t("New password")}</Label>
|
||||
<Input
|
||||
id="cp-new"
|
||||
type="password"
|
||||
@@ -93,7 +101,7 @@ export function ChangePasswordDialog({
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="cp-confirm">Confirm new password</Label>
|
||||
<Label htmlFor="cp-confirm">{t("Confirm new password")}</Label>
|
||||
<Input
|
||||
id="cp-confirm"
|
||||
type="password"
|
||||
@@ -106,10 +114,10 @@ export function ChangePasswordDialog({
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
|
||||
Cancel
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{saving ? "Changing…" : "Confirm change"}
|
||||
{saving ? t("Changing…") : t("Confirm change")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
@@ -21,6 +21,7 @@ import { persistPreference } from "@/lib/preferences/preferences-storage";
|
||||
import { THEME_PRESET_OPTIONS, type ThemeMode, type ThemePreset } from "@/lib/preferences/theme";
|
||||
import { applyThemePreset } from "@/lib/preferences/theme-utils";
|
||||
import { usePreferencesStore } from "@/stores/preferences/preferences-provider";
|
||||
import { type Locale, LOCALES, locale, setLocale, t } from "@/i18n";
|
||||
|
||||
export function LayoutControls() {
|
||||
const themeMode = usePreferencesStore((s) => s.themeMode);
|
||||
@@ -106,15 +107,33 @@ export function LayoutControls() {
|
||||
<PopoverContent align="end">
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="space-y-1.5">
|
||||
<h4 className="font-medium text-sm leading-none">Preferences</h4>
|
||||
<p className="text-muted-foreground text-xs">Customize your dashboard layout preferences.</p>
|
||||
<h4 className="font-medium text-sm leading-none">{t("Preferences")}</h4>
|
||||
<p className="text-muted-foreground text-xs">{t("Customize your dashboard layout preferences.")}</p>
|
||||
</div>
|
||||
<div className="space-y-3 **:data-[slot=toggle-group]:w-full **:data-[slot=toggle-group-item]:flex-1 **:data-[slot=toggle-group-item]:text-xs">
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">Theme Preset</Label>
|
||||
<Label className="font-medium text-xs">{t("Language")}</Label>
|
||||
<ToggleGroup
|
||||
size="sm"
|
||||
spacing={0}
|
||||
variant="outline"
|
||||
type="single"
|
||||
value={locale}
|
||||
onValueChange={(v: string) => v && setLocale(v as Locale)}
|
||||
>
|
||||
{LOCALES.map((l) => (
|
||||
<ToggleGroupItem key={l.code} value={l.code} aria-label={l.label}>
|
||||
{l.label}
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">{t("Theme Preset")}</Label>
|
||||
<Select value={themePreset} onValueChange={onThemePresetChange}>
|
||||
<SelectTrigger size="sm" className="w-full text-xs">
|
||||
<SelectValue placeholder="Preset" />
|
||||
<SelectValue placeholder={t("Preset")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
@@ -136,10 +155,10 @@ export function LayoutControls() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">Fonts</Label>
|
||||
<Label className="font-medium text-xs">{t("Fonts")}</Label>
|
||||
<Select value={font} onValueChange={onFontChange}>
|
||||
<SelectTrigger size="sm" className="w-full text-xs">
|
||||
<SelectValue placeholder="Select font" />
|
||||
<SelectValue placeholder={t("Select font")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
@@ -154,7 +173,7 @@ export function LayoutControls() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">Theme Mode</Label>
|
||||
<Label className="font-medium text-xs">{t("Theme Mode")}</Label>
|
||||
<ToggleGroup
|
||||
size="sm"
|
||||
spacing={0}
|
||||
@@ -163,20 +182,20 @@ export function LayoutControls() {
|
||||
value={themeMode}
|
||||
onValueChange={onThemeModeChange}
|
||||
>
|
||||
<ToggleGroupItem value="light" aria-label="Toggle light">
|
||||
Light
|
||||
<ToggleGroupItem value="light" aria-label={t("Light")}>
|
||||
{t("Light")}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="dark" aria-label="Toggle dark">
|
||||
Dark
|
||||
<ToggleGroupItem value="dark" aria-label={t("Dark")}>
|
||||
{t("Dark")}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="system" aria-label="Toggle system">
|
||||
System
|
||||
<ToggleGroupItem value="system" aria-label={t("System")}>
|
||||
{t("System")}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">Page Layout</Label>
|
||||
<Label className="font-medium text-xs">{t("Page Layout")}</Label>
|
||||
<ToggleGroup
|
||||
size="sm"
|
||||
spacing={0}
|
||||
@@ -185,17 +204,17 @@ export function LayoutControls() {
|
||||
value={contentLayout}
|
||||
onValueChange={onContentLayoutChange}
|
||||
>
|
||||
<ToggleGroupItem value="centered" aria-label="Toggle centered">
|
||||
Centered
|
||||
<ToggleGroupItem value="centered" aria-label={t("Centered")}>
|
||||
{t("Centered")}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="full-width" aria-label="Toggle full-width">
|
||||
Full Width
|
||||
<ToggleGroupItem value="full-width" aria-label={t("Full Width")}>
|
||||
{t("Full Width")}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">Navbar Behavior</Label>
|
||||
<Label className="font-medium text-xs">{t("Navbar Behavior")}</Label>
|
||||
<ToggleGroup
|
||||
size="sm"
|
||||
spacing={0}
|
||||
@@ -204,17 +223,17 @@ export function LayoutControls() {
|
||||
value={navbarStyle}
|
||||
onValueChange={onNavbarStyleChange}
|
||||
>
|
||||
<ToggleGroupItem value="sticky" aria-label="Toggle sticky">
|
||||
Sticky
|
||||
<ToggleGroupItem value="sticky" aria-label={t("Sticky")}>
|
||||
{t("Sticky")}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="scroll" aria-label="Toggle scroll">
|
||||
Scroll
|
||||
<ToggleGroupItem value="scroll" aria-label={t("Scroll")}>
|
||||
{t("Scroll")}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">Sidebar Style</Label>
|
||||
<Label className="font-medium text-xs">{t("Sidebar Style")}</Label>
|
||||
<ToggleGroup
|
||||
size="sm"
|
||||
spacing={0}
|
||||
@@ -223,20 +242,20 @@ export function LayoutControls() {
|
||||
value={variant}
|
||||
onValueChange={onSidebarStyleChange}
|
||||
>
|
||||
<ToggleGroupItem value="inset" aria-label="Toggle inset">
|
||||
Inset
|
||||
<ToggleGroupItem value="inset" aria-label={t("Inset")}>
|
||||
{t("Inset")}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="sidebar" aria-label="Toggle sidebar">
|
||||
Sidebar
|
||||
<ToggleGroupItem value="sidebar" aria-label={t("Sidebar")}>
|
||||
{t("Sidebar")}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="floating" aria-label="Toggle floating">
|
||||
Floating
|
||||
<ToggleGroupItem value="floating" aria-label={t("Floating")}>
|
||||
{t("Floating")}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="font-medium text-xs">Sidebar Collapse Mode</Label>
|
||||
<Label className="font-medium text-xs">{t("Sidebar Collapse Mode")}</Label>
|
||||
<ToggleGroup
|
||||
size="sm"
|
||||
spacing={0}
|
||||
@@ -245,17 +264,17 @@ export function LayoutControls() {
|
||||
value={collapsible}
|
||||
onValueChange={onSidebarCollapseModeChange}
|
||||
>
|
||||
<ToggleGroupItem value="icon" aria-label="Toggle icon">
|
||||
Icon
|
||||
<ToggleGroupItem value="icon" aria-label={t("Icon")}>
|
||||
{t("Icon")}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="offcanvas" aria-label="Toggle offcanvas">
|
||||
OffCanvas
|
||||
<ToggleGroupItem value="offcanvas" aria-label={t("OffCanvas")}>
|
||||
{t("OffCanvas")}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
<Button type="button" size="sm" variant="outline" className="w-full text-xs" onClick={handleRestore}>
|
||||
Restore Defaults
|
||||
{t("Restore Defaults")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
export function NavDocuments({
|
||||
items,
|
||||
@@ -32,7 +33,7 @@ export function NavDocuments({
|
||||
|
||||
return (
|
||||
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
|
||||
<SidebarGroupLabel>Documents</SidebarGroupLabel>
|
||||
<SidebarGroupLabel>{t("Documents")}</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{items.map((item) => (
|
||||
<SidebarMenuItem key={item.name}>
|
||||
@@ -46,7 +47,7 @@ export function NavDocuments({
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuAction showOnHover className="rounded-sm data-[state=open]:bg-accent">
|
||||
<Ellipsis />
|
||||
<span className="sr-only">More</span>
|
||||
<span className="sr-only">{t("More")}</span>
|
||||
</SidebarMenuAction>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
@@ -56,16 +57,16 @@ export function NavDocuments({
|
||||
>
|
||||
<DropdownMenuItem>
|
||||
<Folder />
|
||||
<span>Open</span>
|
||||
<span>{t("Open")}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Forward />
|
||||
<span>Share</span>
|
||||
<span>{t("Share")}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive">
|
||||
<Trash2 />
|
||||
<span>Delete</span>
|
||||
<span>{t("Delete")}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
@@ -74,7 +75,7 @@ export function NavDocuments({
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton className="text-sidebar-foreground/70">
|
||||
<Ellipsis className="text-sidebar-foreground/70" />
|
||||
<span>More</span>
|
||||
<span>{t("More")}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
SidebarMenuSubItem,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { t } from "@/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type {
|
||||
NavBadge,
|
||||
@@ -321,7 +322,7 @@ function NavItemBadge({ badge }: { badge?: NavBadge }) {
|
||||
badge === "soon" && "border-muted-foreground text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{badge}
|
||||
{t(badge)}
|
||||
</SidebarMenuBadge>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
|
||||
import { t } from "@/i18n";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { getInitials } from "@/lib/utils";
|
||||
|
||||
@@ -79,12 +80,12 @@ export function NavUser({
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setPwOpen(true)}>
|
||||
<KeyRound />
|
||||
Change password
|
||||
{t("Change password")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
|
||||
<LogOut />
|
||||
Sign out
|
||||
{t("Sign out")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "@/components/ui/command";
|
||||
import { t } from "@/i18n";
|
||||
import type { NavMainItem } from "@/navigation/sidebar/sidebar-items";
|
||||
import { sidebarItems } from "@/navigation/sidebar/sidebar-items";
|
||||
|
||||
@@ -33,7 +34,7 @@ type SearchItem = {
|
||||
const sidebarGroupLabels = new Set(sidebarItems.flatMap((group) => (group.label ? [group.label] : [])));
|
||||
|
||||
function getSubItemGroup(groupLabel: string | undefined, itemTitle: string) {
|
||||
return sidebarGroupLabels.has(itemTitle) ? (groupLabel ?? "Other") : itemTitle;
|
||||
return sidebarGroupLabels.has(itemTitle) ? (groupLabel ?? t("Other")) : itemTitle;
|
||||
}
|
||||
|
||||
const searchItems: SearchItem[] = sidebarItems.flatMap((group) =>
|
||||
@@ -52,7 +53,7 @@ const searchItems: SearchItem[] = sidebarItems.flatMap((group) =>
|
||||
return [
|
||||
{
|
||||
id: item.id,
|
||||
group: group.label ?? "Other",
|
||||
group: group.label ?? t("Other"),
|
||||
label: item.title,
|
||||
url: item.url,
|
||||
icon: item.icon,
|
||||
@@ -138,16 +139,16 @@ export function SearchDialog() {
|
||||
className="px-0! font-normal text-muted-foreground hover:no-underline"
|
||||
>
|
||||
<Search data-icon="inline-start" />
|
||||
Search
|
||||
{t("Search")}
|
||||
<kbd className="inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-medium text-[10px]">
|
||||
<span className="text-xs">⌘</span>J
|
||||
</kbd>
|
||||
</Button>
|
||||
<CommandDialog open={open} onOpenChange={handleOpenChange}>
|
||||
<Command>
|
||||
<CommandInput placeholder="Search dashboards, users, and more…" value={query} onValueChange={setQuery} />
|
||||
<CommandInput placeholder={t("Search dashboards, users, and more…")} value={query} onValueChange={setQuery} />
|
||||
<CommandList>
|
||||
<CommandEmpty>No results found.</CommandEmpty>
|
||||
<CommandEmpty>{t("No results found.")}</CommandEmpty>
|
||||
{query ? renderGroups(searchItems) : renderGroups(recommendations)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
|
||||
@@ -4,24 +4,27 @@ import { siX } from "simple-icons";
|
||||
|
||||
import { SimpleIcon } from "@/components/simple-icon";
|
||||
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
export function SidebarSupportCard() {
|
||||
// The X link sits inside the sentence through a placeholder so the word order can follow the locale.
|
||||
const [before, after = ""] = t("Open an issue or do reach out to me on {x}.").split("{x}");
|
||||
return (
|
||||
<Card size="sm" className="overflow-hidden shadow-none group-data-[collapsible=icon]:hidden">
|
||||
<CardHeader className="min-w-0 px-4">
|
||||
<CardTitle className="truncate text-sm">Looking for something more?</CardTitle>
|
||||
<CardTitle className="truncate text-sm">{t("Looking for something more?")}</CardTitle>
|
||||
<CardDescription className="line-clamp-2">
|
||||
Open an issue or do reach out to me on
|
||||
{before.trimEnd()}
|
||||
<Link
|
||||
href="https://x.com/arhamkhnz"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
aria-label="Reach out on X"
|
||||
aria-label={t("Reach out on X")}
|
||||
className="inline-flex items-center text-foreground"
|
||||
>
|
||||
<SimpleIcon icon={siX} aria-hidden className="size-3 fill-current" />
|
||||
</Link>
|
||||
.
|
||||
{after}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
@@ -3,11 +3,18 @@
|
||||
import { Monitor, Moon, Sun } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { t } from "@/i18n";
|
||||
import { persistPreference } from "@/lib/preferences/preferences-storage";
|
||||
import { usePreferencesStore } from "@/stores/preferences/preferences-provider";
|
||||
|
||||
const THEME_CYCLE = ["light", "dark", "system"] as const;
|
||||
|
||||
const THEME_LABELS: Record<(typeof THEME_CYCLE)[number], string> = {
|
||||
light: t("Light"),
|
||||
dark: t("Dark"),
|
||||
system: t("System"),
|
||||
};
|
||||
|
||||
export function ThemeSwitcher() {
|
||||
const themeMode = usePreferencesStore((s) => s.themeMode);
|
||||
const setThemeMode = usePreferencesStore((s) => s.setThemeMode);
|
||||
@@ -21,7 +28,7 @@ export function ThemeSwitcher() {
|
||||
};
|
||||
|
||||
return (
|
||||
<Button size="icon" onClick={cycleTheme} aria-label={`Current theme: ${themeMode}. Click to cycle themes`}>
|
||||
<Button size="icon" onClick={cycleTheme} aria-label={t("Current theme: {theme}. Click to cycle themes", { theme: THEME_LABELS[themeMode] ?? themeMode })}>
|
||||
{/* SYSTEM */}
|
||||
<Monitor className="hidden [html[data-theme-mode=system]_&]:block" />
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.
|
||||
import { isBtwCommand } from "@/lib/side-questions";
|
||||
import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
|
||||
// fmtBytes renders a human file size for attachment chips (mirrors transcript.tsx).
|
||||
function fmtBytes(n: number): string {
|
||||
@@ -137,7 +138,7 @@ function LiveBadge() {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded bg-blue-500/15 px-1.5 py-0.5 text-[10px] font-medium text-blue-600 dark:text-blue-400">
|
||||
<span className="size-1 animate-pulse rounded-full bg-blue-500" />
|
||||
Live
|
||||
{t("Live")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -203,7 +204,7 @@ function Composer({
|
||||
type="button"
|
||||
className="ml-0.5 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => onRemoveAttachment(a.path)}
|
||||
title="Remove"
|
||||
title={t("Remove")}
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</button>
|
||||
@@ -234,7 +235,7 @@ function Composer({
|
||||
variant="ghost"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={disabled || uploading}
|
||||
title="Upload files"
|
||||
title={t("Upload files")}
|
||||
>
|
||||
{uploading ? <Loader2Icon className="size-4 animate-spin" /> : <PaperclipIcon className="size-4" />}
|
||||
</Button>
|
||||
@@ -250,14 +251,14 @@ function Composer({
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
{running && allowBtw && isBtwCommand(value) && (
|
||||
<Button size="icon" onClick={onSend} aria-label="Send side question" title="Send side question">
|
||||
<Button size="icon" onClick={onSend} aria-label={t("Send side question")} title={t("Send side question")}>
|
||||
<ArrowUpIcon />
|
||||
</Button>
|
||||
)}
|
||||
{running ? (
|
||||
// while a run is in flight the send button becomes a stop button —
|
||||
// aborts just this session (the trigger queue keeps going).
|
||||
<Button size="icon" variant="destructive" onClick={onStop} disabled={stopDisabled} title="Stop this run">
|
||||
<Button size="icon" variant="destructive" onClick={onStop} disabled={stopDisabled} title={t("Stop this run")}>
|
||||
<Square className="size-3.5 fill-current" />
|
||||
</Button>
|
||||
) : (
|
||||
@@ -265,8 +266,8 @@ function Composer({
|
||||
size="icon"
|
||||
onClick={onSend}
|
||||
disabled={disabled || (!value.trim() && atts.length === 0)}
|
||||
title="Send message"
|
||||
aria-label="Send message"
|
||||
title={t("Send message")}
|
||||
aria-label={t("Send message")}
|
||||
>
|
||||
<ArrowUpIcon />
|
||||
</Button>
|
||||
@@ -294,7 +295,11 @@ function LLMProfileRow({
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const activeDefault = profiles.find((p) => p.is_default);
|
||||
const current = selected != null ? profiles.find((p) => Number(p.id) === selected) : null;
|
||||
const label = current ? current.name : `Default${activeDefault ? ` (${activeDefault.name})` : ""}`;
|
||||
const label = current
|
||||
? current.name
|
||||
: activeDefault
|
||||
? t("Default ({name})", { name: activeDefault.name })
|
||||
: t("Default");
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-1 px-1 pt-0.5 pb-1">
|
||||
@@ -309,12 +314,12 @@ function LLMProfileRow({
|
||||
disabled={disabled}
|
||||
className="flex shrink-0 items-center gap-0.5 text-primary text-xs hover:underline disabled:pointer-events-none disabled:opacity-40"
|
||||
>
|
||||
Change
|
||||
{t("Change")}
|
||||
<ChevronDownIcon className="size-3" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-64 p-1">
|
||||
<p className="text-muted-foreground px-2 py-1 text-[11px] font-medium">Select an LLM profile</p>
|
||||
<p className="text-muted-foreground px-2 py-1 text-[11px] font-medium">{t("Select an LLM profile")}</p>
|
||||
{/* default option */}
|
||||
<button
|
||||
type="button"
|
||||
@@ -327,7 +332,9 @@ function LLMProfileRow({
|
||||
selected == null && "bg-accent",
|
||||
)}
|
||||
>
|
||||
<span className="text-sm">Default{activeDefault ? ` (${activeDefault.name})` : ""}</span>
|
||||
<span className="text-sm">
|
||||
{activeDefault ? t("Default ({name})", { name: activeDefault.name }) : t("Default")}
|
||||
</span>
|
||||
{activeDefault && (
|
||||
<span className="text-muted-foreground text-[11px]">
|
||||
{activeDefault.format} · {activeDefault.model}
|
||||
@@ -395,7 +402,7 @@ function DraftChat({
|
||||
await api.sendConversationMessage(c.id, msg);
|
||||
onStarted(c);
|
||||
} catch (e) {
|
||||
toast.error("Send failed: " + (e as Error).message);
|
||||
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
@@ -413,7 +420,7 @@ function DraftChat({
|
||||
const r = await api.chatUpload("session", `conv-${c.id}`, files);
|
||||
onStarted(c, { input, attachments: r.attachments });
|
||||
} catch (e) {
|
||||
toast.error("Upload failed: " + (e as Error).message);
|
||||
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
@@ -421,7 +428,7 @@ function DraftChat({
|
||||
const agentPicker = (
|
||||
<Select value={agentKey} onValueChange={setAgentKey}>
|
||||
<SelectTrigger className="w-full sm:w-40">
|
||||
<SelectValue placeholder="Select an agent…" />
|
||||
<SelectValue placeholder={t("Select an agent…")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
@@ -432,7 +439,7 @@ function DraftChat({
|
||||
{a.name}
|
||||
{!a.builtin && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-[9px]">
|
||||
Custom
|
||||
{t("Custom")}
|
||||
</Badge>
|
||||
)}
|
||||
</span>
|
||||
@@ -450,7 +457,9 @@ function DraftChat({
|
||||
<div className="bg-primary/10 flex size-12 items-center justify-center rounded-full">
|
||||
<Bot className="text-primary size-6" />
|
||||
</div>
|
||||
<div className="text-sm font-medium">Start a conversation with "{agent?.name ?? "Agent"}"</div>
|
||||
<div className="text-sm font-medium">
|
||||
{t('Start a conversation with "{name}"', { name: agent?.name ?? t("Agent") })}
|
||||
</div>
|
||||
{agent?.description && <p className="text-muted-foreground max-w-md text-xs">{agent.description}</p>}
|
||||
</div>
|
||||
|
||||
@@ -459,7 +468,7 @@ function DraftChat({
|
||||
onChange={setInput}
|
||||
onSend={send}
|
||||
disabled={sending || uploading || !agentKey}
|
||||
placeholder="Type a message, @ to reference records, Enter to send"
|
||||
placeholder={t("Type a message, @ to reference records, Enter to send")}
|
||||
leftSlot={agentPicker}
|
||||
onPickFiles={pickFiles}
|
||||
uploading={uploading}
|
||||
@@ -518,7 +527,7 @@ function ChatView({
|
||||
await api.updateConversationProfile(conv.id, id);
|
||||
onConvUpdated();
|
||||
} catch (e) {
|
||||
toast.error("Failed to switch LLM: " + (e as Error).message);
|
||||
toast.error(t("Failed to switch LLM: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -716,7 +725,7 @@ function ChatView({
|
||||
const r = await api.chatUpload("session", `conv-${conv.id}`, files);
|
||||
setAttachments((prev) => [...prev, ...r.attachments]);
|
||||
} catch (e) {
|
||||
toast.error("Upload failed: " + (e as Error).message);
|
||||
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
@@ -736,7 +745,7 @@ function ChatView({
|
||||
// fetch avoids racing a separate post-send request against the poller.
|
||||
setRunning(true);
|
||||
} catch (e) {
|
||||
toast.error("Send failed: " + (e as Error).message);
|
||||
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
|
||||
setInput(msg); // restore so the user doesn't lose their text
|
||||
setAttachments(atts); // and their attachments
|
||||
} finally {
|
||||
@@ -753,7 +762,7 @@ function ChatView({
|
||||
try {
|
||||
await api.stopConversation(conv.id);
|
||||
} catch (e) {
|
||||
toast.error("Stop failed: " + (e as Error).message);
|
||||
toast.error(t("Stop failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setStopping(false);
|
||||
}
|
||||
@@ -768,7 +777,7 @@ function ChatView({
|
||||
<span className="text-muted-foreground hidden shrink-0 font-mono text-xs sm:inline">{conv.agent_key}</span>
|
||||
{agent && !agent.builtin && (
|
||||
<Badge variant="outline" className="shrink-0 px-1.5 py-0 text-[10px]">
|
||||
Custom
|
||||
{t("Custom")}
|
||||
</Badge>
|
||||
)}
|
||||
{agent?.description && (
|
||||
@@ -778,13 +787,17 @@ function ChatView({
|
||||
<SideQuestionButton side={side} />
|
||||
<div className="text-muted-foreground ml-auto flex min-w-0 max-w-full items-center justify-end gap-x-3 gap-y-1 text-xs max-sm:w-full max-sm:flex-wrap">
|
||||
{tokenTotal.turns > 0 && (
|
||||
<span title="Agent loop turns (model calls)" className="tabular-nums">
|
||||
{tokenTotal.turns} turns
|
||||
<span title={t("Agent loop turns (model calls)")} className="tabular-nums">
|
||||
{t("{count} turns", { count: tokenTotal.turns })}
|
||||
</span>
|
||||
)}
|
||||
{tokenTotal.any && (
|
||||
<span title="input / cache(read) / output tokens" className="min-w-0 truncate tabular-nums">
|
||||
input {fmtTokens(tokenTotal.i)} · cache {fmtTokens(tokenTotal.cr)} · output {fmtTokens(tokenTotal.o)}
|
||||
<span title={t("input / cache(read) / output tokens")} className="min-w-0 truncate tabular-nums">
|
||||
{t("input {input} · cache {cache} · output {output}", {
|
||||
input: fmtTokens(tokenTotal.i),
|
||||
cache: fmtTokens(tokenTotal.cr),
|
||||
output: fmtTokens(tokenTotal.o),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -797,12 +810,12 @@ function ChatView({
|
||||
<div className="min-w-0 max-w-full px-4 py-3" ref={contentRef}>
|
||||
{messages.length === 0 && !running ? (
|
||||
<div className="text-muted-foreground py-10 text-center text-sm">
|
||||
Start a conversation with "{agent?.name ?? conv.agent_key}"
|
||||
{t('Start a conversation with "{name}"', { name: agent?.name ?? conv.agent_key })}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{hasMore && (
|
||||
<div className="text-muted-foreground/70 pb-2 text-center text-[11px]">Scroll up to load earlier messages…</div>
|
||||
<div className="text-muted-foreground/70 pb-2 text-center text-[11px]">{t("Scroll up to load earlier messages…")}</div>
|
||||
)}
|
||||
<Transcript activity={messages} live={running} chat fetchDetail={fetchDetail} focusedSeq={focusHistory.ready ? approvalFocus.state?.source?.seq : undefined} />
|
||||
</>
|
||||
@@ -816,7 +829,11 @@ function ChatView({
|
||||
onSend={send}
|
||||
disabled={running || sending}
|
||||
allowBtw
|
||||
placeholder={running ? "Agent is replying; type /btw to ask a side question…" : "Type a message, @ to reference records, Enter to send"}
|
||||
placeholder={
|
||||
running
|
||||
? t("Agent is replying; type /btw to ask a side question…")
|
||||
: t("Type a message, @ to reference records, Enter to send")
|
||||
}
|
||||
running={running}
|
||||
onStop={stop}
|
||||
stopDisabled={stopping}
|
||||
@@ -897,7 +914,7 @@ const ConversationItem = React.memo(function ConversationItem({
|
||||
<Checkbox
|
||||
checked={selectedForDelete}
|
||||
onCheckedChange={(checked) => onSelectedForDeleteChange(conv.id, checked === true)}
|
||||
aria-label={`Select conversation "${conv.title || "New conversation"}"`}
|
||||
aria-label={t('Select conversation "{title}"', { title: conv.title || t("New conversation") })}
|
||||
className="ml-1 shrink-0"
|
||||
/>
|
||||
)}
|
||||
@@ -924,16 +941,16 @@ const ConversationItem = React.memo(function ConversationItem({
|
||||
type="button"
|
||||
onClick={() => onSelect(conv.id)}
|
||||
onDoubleClick={() => onStartRename(conv)}
|
||||
title="Double-click to rename"
|
||||
title={t("Double-click to rename")}
|
||||
className="min-w-0 flex-1 rounded-md px-2 py-1.5 text-left"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
{pinned && <PinIcon className="text-primary size-3 shrink-0" aria-label="Pinned" />}
|
||||
<div className="truncate text-sm">{conv.title || "New conversation"}</div>
|
||||
{pinned && <PinIcon className="text-primary size-3 shrink-0" aria-label={t("Pinned")} />}
|
||||
<div className="truncate text-sm">{conv.title || t("New conversation")}</div>
|
||||
{conv.running ? (
|
||||
<Badge variant="secondary" className="shrink-0 gap-1" title="Agent is running">
|
||||
<Badge variant="secondary" className="shrink-0 gap-1" title={t("Agent is running")}>
|
||||
<Spinner className="size-3" aria-hidden="true" />
|
||||
Running
|
||||
{t("Running")}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -946,7 +963,7 @@ const ConversationItem = React.memo(function ConversationItem({
|
||||
</>
|
||||
)}
|
||||
<span className="shrink-0">
|
||||
{new Date(conv.created_at).toLocaleDateString("zh-CN", {
|
||||
{new Date(conv.created_at).toLocaleDateString(intlLocale, {
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
@@ -963,7 +980,7 @@ const ConversationItem = React.memo(function ConversationItem({
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="text-muted-foreground shrink-0"
|
||||
aria-label={`Manage conversation "${conv.title || "New conversation"}"`}
|
||||
aria-label={t('Manage conversation "{title}"', { title: conv.title || t("New conversation") })}
|
||||
>
|
||||
<MoreHorizontalIcon />
|
||||
</Button>
|
||||
@@ -972,18 +989,18 @@ const ConversationItem = React.memo(function ConversationItem({
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onSelect={() => onStartRename(conv)}>
|
||||
<PencilIcon />
|
||||
Rename
|
||||
{t("Rename")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => onTogglePinned(conv)}>
|
||||
{pinned ? <PinOffIcon /> : <PinIcon />}
|
||||
{pinned ? "Unpin" : "Pin"}
|
||||
{pinned ? t("Unpin") : t("Pin")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem variant="destructive" onSelect={() => setDeleteOpen(true)}>
|
||||
<Trash2Icon />
|
||||
Delete
|
||||
{t("Delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
@@ -991,12 +1008,14 @@ const ConversationItem = React.memo(function ConversationItem({
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete conversation "{conv.title || "New conversation"}"?</AlertDialogTitle>
|
||||
<AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
|
||||
<AlertDialogTitle>
|
||||
{t('Delete conversation "{title}"?', { title: conv.title || t("New conversation") })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t("This action cannot be undone.")}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => onDelete(conv.id)}>Delete</AlertDialogAction>
|
||||
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => onDelete(conv.id)}>{t("Delete")}</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
@@ -1022,7 +1041,7 @@ function AgentGroupHeader({
|
||||
type="button"
|
||||
onClick={() => onToggle(group.key)}
|
||||
aria-expanded={!collapsed}
|
||||
title={collapsed ? `Expand "${group.name}"` : `Collapse "${group.name}"`}
|
||||
title={collapsed ? t('Expand "{name}"', { name: group.name }) : t('Collapse "{name}"', { name: group.name })}
|
||||
className={cn(
|
||||
"sticky top-0 z-10 flex min-w-0 items-center gap-1.5 rounded-md bg-card px-1.5 py-1 text-left font-medium text-[11px] transition-colors hover:bg-accent/50",
|
||||
collapsed && hasActive ? "text-foreground" : "text-muted-foreground",
|
||||
@@ -1032,10 +1051,10 @@ function AgentGroupHeader({
|
||||
<Bot className="size-3 shrink-0" />
|
||||
<span className="min-w-0 flex-1 truncate">{group.name}</span>
|
||||
{collapsed && hasActive && (
|
||||
<span className="size-1.5 shrink-0 rounded-full bg-primary" title="The current conversation is in this group" />
|
||||
<span className="size-1.5 shrink-0 rounded-full bg-primary" title={t("The current conversation is in this group")} />
|
||||
)}
|
||||
{group.runningCount > 0 && (
|
||||
<Spinner className="size-3 shrink-0" aria-label={`${group.runningCount} conversations running`} />
|
||||
<Spinner className="size-3 shrink-0" aria-label={t("{count} conversations running", { count: group.runningCount })} />
|
||||
)}
|
||||
<span className="shrink-0 tabular-nums opacity-60">{group.conversations.length}</span>
|
||||
</button>
|
||||
@@ -1211,10 +1230,10 @@ export default function ChatPage() {
|
||||
if (agentFilter !== null) keys.add(agentFilter);
|
||||
return [...keys]
|
||||
.map((key) => ({ key, name: agentByKey.get(key)?.name || key, count: counts.get(key) ?? 0 }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, "zh-CN"));
|
||||
.sort((a, b) => a.name.localeCompare(b.name, intlLocale));
|
||||
}, [convs, chatAgents, agentByKey, agentFilter]);
|
||||
const conversationCountLabel =
|
||||
agentFilter === null ? `${convs.length} total` : `${filteredConversations.length} / ${convs.length}`;
|
||||
agentFilter === null ? t("{count} total", { count: convs.length }) : `${filteredConversations.length} / ${convs.length}`;
|
||||
|
||||
function changeAgentFilter(key: string | null) {
|
||||
setAgentFilter(key);
|
||||
@@ -1265,7 +1284,7 @@ export default function ChatPage() {
|
||||
});
|
||||
void reloadConvs();
|
||||
} catch (e) {
|
||||
toast.error("Delete failed: " + (e as Error).message);
|
||||
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[reloadConvs],
|
||||
@@ -1282,7 +1301,7 @@ export default function ChatPage() {
|
||||
const result = await api.deleteConversations(ids.slice(offset, offset + 100));
|
||||
for (const item of result.items) {
|
||||
if (item.ok) deleted.add(item.id);
|
||||
else failed.push({ id: item.id, error: item.error ?? "conversation not found" });
|
||||
else failed.push({ id: item.id, error: item.error ?? t("conversation not found") });
|
||||
}
|
||||
}
|
||||
if (deleted.has(selectedId ?? -1)) selectConversation(null);
|
||||
@@ -1291,13 +1310,18 @@ export default function ChatPage() {
|
||||
for (const id of deleted) next.delete(id);
|
||||
return next;
|
||||
});
|
||||
if (deleted.size > 0) toast.success(`Deleted ${deleted.size} conversations`);
|
||||
if (deleted.size > 0) toast.success(t("Deleted {count} conversations", { count: deleted.size }));
|
||||
if (failed.length > 0) {
|
||||
const details = failed
|
||||
.slice(0, 3)
|
||||
.map((item) => `#${item.id} (${item.error})`)
|
||||
.join("; ");
|
||||
toast.error(`Failed to delete ${failed.length} conversations: ${details}${failed.length > 3 ? " etc." : ""}`);
|
||||
toast.error(
|
||||
t("Failed to delete {count} conversations: {details}", {
|
||||
count: failed.length,
|
||||
details: failed.length > 3 ? t("{items} etc.", { items: details }) : details,
|
||||
}),
|
||||
);
|
||||
}
|
||||
setBulkDeleteOpen(false);
|
||||
// Fully successful → return to the clean list; keep selection mode on if
|
||||
@@ -1305,7 +1329,7 @@ export default function ChatPage() {
|
||||
if (failed.length === 0) setSelectionMode(false);
|
||||
void reloadConvs();
|
||||
} catch (error) {
|
||||
toast.error(`Bulk delete failed: ${(error as Error).message}`);
|
||||
toast.error(t("Bulk delete failed: {error}", { error: (error as Error).message }));
|
||||
void reloadConvs();
|
||||
} finally {
|
||||
setBulkDeleting(false);
|
||||
@@ -1319,7 +1343,8 @@ export default function ChatPage() {
|
||||
await api.pinConversation(conversation.id, !pinned);
|
||||
void reloadConvs();
|
||||
} catch (e) {
|
||||
toast.error(`Failed to ${pinned ? "unpin" : "pin"}: ${(e as Error).message}`);
|
||||
const error = (e as Error).message;
|
||||
toast.error(pinned ? t("Failed to unpin: {error}", { error }) : t("Failed to pin: {error}", { error }));
|
||||
}
|
||||
},
|
||||
[reloadConvs],
|
||||
@@ -1338,7 +1363,7 @@ export default function ChatPage() {
|
||||
await api.renameConversation(id, title);
|
||||
void reloadConvs();
|
||||
} catch (e) {
|
||||
toast.error("Rename failed: " + (e as Error).message);
|
||||
toast.error(t("Rename failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[reloadConvs],
|
||||
@@ -1355,20 +1380,20 @@ export default function ChatPage() {
|
||||
<div className="bg-card flex flex-col overflow-hidden rounded-lg border">
|
||||
<div className="flex flex-col gap-2 border-b p-2">
|
||||
<Button size="sm" className="w-full" onClick={() => selectConversation(null)}>
|
||||
<PlusIcon /> New conversation
|
||||
<PlusIcon /> {t("New conversation")}
|
||||
</Button>
|
||||
<Select
|
||||
value={agentFilter === null ? "all" : `agent:${agentFilter}`}
|
||||
onValueChange={(value) => changeAgentFilter(value === "all" ? null : value.slice(6))}
|
||||
disabled={bulkDeleting}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-full min-w-0" aria-label="Filter conversations by agent">
|
||||
<SelectTrigger size="sm" className="w-full min-w-0" aria-label={t("Filter conversations by agent")}>
|
||||
<Bot />
|
||||
<SelectValue placeholder="All agents" />
|
||||
<SelectValue placeholder={t("All agents")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value="all">All agents</SelectItem>
|
||||
<SelectItem value="all">{t("All agents")}</SelectItem>
|
||||
{agentFilterOptions.map((agent) => (
|
||||
<SelectItem key={agent.key} value={`agent:${agent.key}`}>
|
||||
{agent.name} ({agent.count})
|
||||
@@ -1383,11 +1408,13 @@ export default function ChatPage() {
|
||||
<Checkbox
|
||||
checked={conversationHeaderChecked}
|
||||
onCheckedChange={(checked) => toggleAllConversations(checked === true)}
|
||||
aria-label="Select all conversations matching the current filter"
|
||||
aria-label={t("Select all conversations matching the current filter")}
|
||||
disabled={filteredConversations.length === 0 || bulkDeleting}
|
||||
/>
|
||||
<span className="text-muted-foreground min-w-0 flex-1 text-xs tabular-nums">
|
||||
{selectedConversationCount > 0 ? `${selectedConversationCount} selected` : conversationCountLabel}
|
||||
{selectedConversationCount > 0
|
||||
? t("{count} selected", { count: selectedConversationCount })
|
||||
: conversationCountLabel}
|
||||
</span>
|
||||
{selectedConversationCount > 0 && (
|
||||
<Button
|
||||
@@ -1397,11 +1424,11 @@ export default function ChatPage() {
|
||||
onClick={() => setBulkDeleteOpen(true)}
|
||||
>
|
||||
<Trash2Icon data-icon="inline-start" />
|
||||
Delete
|
||||
{t("Delete")}
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="ghost" onClick={exitSelectionMode}>
|
||||
Done
|
||||
{t("Done")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
@@ -1417,7 +1444,7 @@ export default function ChatPage() {
|
||||
disabled={filteredConversations.length === 0}
|
||||
>
|
||||
<ListChecksIcon data-icon="inline-start" />
|
||||
Select
|
||||
{t("Select")}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
@@ -1430,7 +1457,7 @@ export default function ChatPage() {
|
||||
<div className="flex min-w-0 flex-col gap-0.5 p-2">
|
||||
{filteredConversations.length === 0 && (
|
||||
<p className="text-muted-foreground px-2 py-6 text-center text-xs">
|
||||
{agentFilter === null ? "No conversations yet" : "No conversations for this agent"}
|
||||
{agentFilter === null ? t("No conversations yet") : t("No conversations for this agent")}
|
||||
</p>
|
||||
)}
|
||||
{pinnedConversations.map((c) => (
|
||||
@@ -1496,7 +1523,7 @@ export default function ChatPage() {
|
||||
className="mt-1 w-full"
|
||||
onClick={() => setVisibleConversationCount((count) => count + CONVERSATION_LIST_PAGE)}
|
||||
>
|
||||
Load more
|
||||
{t("Load more")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -1517,7 +1544,7 @@ export default function ChatPage() {
|
||||
/>
|
||||
) : sourceRequested ? (
|
||||
<div role="status" className="p-6 text-sm text-muted-foreground">
|
||||
{convsLoaded ? "The conversation has been deleted" : "Loading the conversation…"}
|
||||
{convsLoaded ? t("The conversation has been deleted") : t("Loading the conversation…")}
|
||||
</div>
|
||||
) : (
|
||||
<DraftChat
|
||||
@@ -1545,11 +1572,15 @@ export default function ChatPage() {
|
||||
<AlertDialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {selectedConversationCount} selected conversations?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Conversation messages and execution records will be deleted with them. This action cannot be undone.</AlertDialogDescription>
|
||||
<AlertDialogTitle>
|
||||
{t("Delete {count} selected conversations?", { count: selectedConversationCount })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("Conversation messages and execution records will be deleted with them. This action cannot be undone.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={bulkDeleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={bulkDeleting}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
disabled={bulkDeleting || selectedConversationCount === 0}
|
||||
@@ -1559,7 +1590,7 @@ export default function ChatPage() {
|
||||
}}
|
||||
>
|
||||
{bulkDeleting && <Loader2Icon data-icon="inline-start" className="animate-spin" />}
|
||||
{bulkDeleting ? "Deleting" : "Confirm delete"}
|
||||
{bulkDeleting ? t("Deleting") : t("Confirm delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -40,14 +40,15 @@ import type {
|
||||
UsageStats,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { t } from "@/i18n";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
|
||||
// ── chart constants ───────────────────────────────────────────────────────────
|
||||
|
||||
const dailyTrendConfig = {
|
||||
input: { label: "Input", color: "hsl(217 91% 60%)" },
|
||||
output: { label: "Output", color: "hsl(263 70% 60%)" },
|
||||
cacheRead: { label: "Cache read", color: "hsl(160 60% 45%)" },
|
||||
input: { label: t("Input"), color: "hsl(217 91% 60%)" },
|
||||
output: { label: t("Output"), color: "hsl(263 70% 60%)" },
|
||||
cacheRead: { label: t("Cache read"), color: "hsl(160 60% 45%)" },
|
||||
} satisfies ChartConfig;
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────────
|
||||
@@ -56,12 +57,12 @@ function fmtRel(ts?: string | number): string {
|
||||
if (!ts) return "—";
|
||||
const ms = Date.now() - (typeof ts === "number" ? ts * 1000 : Date.parse(ts as string));
|
||||
const s = Math.floor(ms / 1000);
|
||||
if (s < 60) return `${s}s ago`;
|
||||
if (s < 60) return t("{n}s ago", { n: s });
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `${m}m ago`;
|
||||
if (m < 60) return t("{n}m ago", { n: m });
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `${h}h ago`;
|
||||
return `${Math.floor(h / 24)}d ago`;
|
||||
if (h < 24) return t("{n}h ago", { n: h });
|
||||
return t("{n}d ago", { n: Math.floor(h / 24) });
|
||||
}
|
||||
|
||||
function fmtTokens(n: number): string {
|
||||
@@ -71,12 +72,12 @@ function fmtTokens(n: number): string {
|
||||
}
|
||||
|
||||
const ASSET_TYPE_LABELS: Record<string, string> = {
|
||||
root_domain: "Root domain",
|
||||
root_domain: t("Root domain"),
|
||||
ip: "IP",
|
||||
subdomain: "Subdomain",
|
||||
app: "App",
|
||||
service: "Service",
|
||||
endpoint: "Endpoint",
|
||||
subdomain: t("Subdomain"),
|
||||
app: t("App"),
|
||||
service: t("Service"),
|
||||
endpoint: t("Endpoint"),
|
||||
};
|
||||
|
||||
const ASSET_COLORS: Record<string, string> = {
|
||||
@@ -473,9 +474,9 @@ export default function DashboardPage() {
|
||||
|
||||
// activity kind label
|
||||
function kindLabel(a: Activity): string {
|
||||
if (a.kind === "tool_use") return a.tool ?? "tool_use";
|
||||
if (a.kind === "tool_result") return "tool_result";
|
||||
return a.kind;
|
||||
if (a.kind === "tool_use") return a.tool ?? t("tool_use");
|
||||
if (a.kind === "tool_result") return t("tool_result");
|
||||
return t(a.kind);
|
||||
}
|
||||
|
||||
function workerColor(w: string): string {
|
||||
@@ -497,8 +498,8 @@ export default function DashboardPage() {
|
||||
{/* ── Header ── */}
|
||||
<div>
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold tracking-tight">Overview</h1>
|
||||
<p className="text-xs text-muted-foreground">System-wide status · live refresh</p>
|
||||
<h1 className="text-lg font-semibold tracking-tight">{t("Overview")}</h1>
|
||||
<p className="text-xs text-muted-foreground">{t("System-wide status · live refresh")}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -508,7 +509,7 @@ export default function DashboardPage() {
|
||||
<Card className="gap-1">
|
||||
<CardHeader className="pb-0">
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
<TargetIcon className="size-3" /> Active tasks
|
||||
<TargetIcon className="size-3" /> {t("Active tasks")}
|
||||
</div>
|
||||
<div className="flex items-baseline gap-1.5">
|
||||
<span className="text-2xl font-semibold tabular-nums">{tasksByStatus.running ?? 0}</span>
|
||||
@@ -516,10 +517,16 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-wrap gap-x-2.5 gap-y-0.5 text-[10px]">
|
||||
{(tasksByStatus.running ?? 0) > 0 && <span className="text-blue-400">Exploring {tasksByStatus.running}</span>}
|
||||
{(tasksByStatus.paused ?? 0) > 0 && <span className="text-amber-400">Paused {tasksByStatus.paused}</span>}
|
||||
{(tasksByStatus.done ?? 0) > 0 && <span className="text-emerald-400">Completed {tasksByStatus.done}</span>}
|
||||
{tasks.length === 0 && <span className="text-muted-foreground">No tasks</span>}
|
||||
{(tasksByStatus.running ?? 0) > 0 && (
|
||||
<span className="text-blue-400">{t("Exploring {count}", { count: tasksByStatus.running })}</span>
|
||||
)}
|
||||
{(tasksByStatus.paused ?? 0) > 0 && (
|
||||
<span className="text-amber-400">{t("Paused {count}", { count: tasksByStatus.paused })}</span>
|
||||
)}
|
||||
{(tasksByStatus.done ?? 0) > 0 && (
|
||||
<span className="text-emerald-400">{t("Completed {count}", { count: tasksByStatus.done })}</span>
|
||||
)}
|
||||
{tasks.length === 0 && <span className="text-muted-foreground">{t("No tasks")}</span>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -527,15 +534,15 @@ export default function DashboardPage() {
|
||||
<Card className="gap-1">
|
||||
<CardHeader className="pb-0">
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
<BugIcon className="size-3" /> Confirmed findings
|
||||
<BugIcon className="size-3" /> {t("Confirmed findings")}
|
||||
</div>
|
||||
<div className="text-2xl font-semibold tabular-nums">{findings.length}</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-wrap gap-2.5 text-[10px]">
|
||||
<span className="text-rose-500">Critical {findingsBySev.critical}</span>
|
||||
<span className="text-red-400">High {findingsBySev.high}</span>
|
||||
<span className="text-amber-400">Medium {findingsBySev.medium}</span>
|
||||
<span className="text-slate-400">Low {findingsBySev.low}</span>
|
||||
<span className="text-rose-500">{t("Critical {count}", { count: findingsBySev.critical })}</span>
|
||||
<span className="text-red-400">{t("High {count}", { count: findingsBySev.high })}</span>
|
||||
<span className="text-amber-400">{t("Medium {count}", { count: findingsBySev.medium })}</span>
|
||||
<span className="text-slate-400">{t("Low {count}", { count: findingsBySev.low })}</span>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -543,18 +550,18 @@ export default function DashboardPage() {
|
||||
<Card className="gap-1">
|
||||
<CardHeader className="pb-0">
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
<NetworkIcon className="size-3" /> Asset nodes
|
||||
<NetworkIcon className="size-3" /> {t("Asset nodes")}
|
||||
</div>
|
||||
<div className="text-2xl font-semibold tabular-nums">{totalAssets}</div>
|
||||
</CardHeader>
|
||||
<CardContent className="text-[10px] text-muted-foreground">Shared across tasks</CardContent>
|
||||
<CardContent className="text-[10px] text-muted-foreground">{t("Shared across tasks")}</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Traffic exchanges */}
|
||||
<Card className="gap-1">
|
||||
<CardHeader className="pb-0">
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
<ActivityIcon className="size-3" /> Traffic exchanges
|
||||
<ActivityIcon className="size-3" /> {t("Traffic exchanges")}
|
||||
</div>
|
||||
<div className="text-2xl font-semibold tabular-nums">{traffic.length}</div>
|
||||
</CardHeader>
|
||||
@@ -562,10 +569,10 @@ export default function DashboardPage() {
|
||||
{settings?.traffic_capture ? (
|
||||
<>
|
||||
<LiveDot />
|
||||
<span>Recording</span>
|
||||
<span>{t("Recording")}</span>
|
||||
</>
|
||||
) : (
|
||||
<span>Capture is off</span>
|
||||
<span>{t("Capture is off")}</span>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -574,15 +581,18 @@ export default function DashboardPage() {
|
||||
<Card className="gap-1">
|
||||
<CardHeader className="pb-0">
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
<ZapIcon className="size-3" /> Token usage
|
||||
<ZapIcon className="size-3" /> {t("Token usage")}
|
||||
</div>
|
||||
<div className="text-2xl font-semibold tabular-nums">
|
||||
{fmtTokens(displayedTokens.input + displayedTokens.output) || "—"}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="text-[10px] text-muted-foreground">
|
||||
In {fmtTokens(displayedTokens.input)} (incl. cache {fmtTokens(displayedTokens.cacheRead)}) · Out{" "}
|
||||
{fmtTokens(displayedTokens.output)}
|
||||
{t("In {input} (incl. cache {cache}) · Out {output}", {
|
||||
input: fmtTokens(displayedTokens.input),
|
||||
cache: fmtTokens(displayedTokens.cacheRead),
|
||||
output: fmtTokens(displayedTokens.output),
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -593,13 +603,13 @@ export default function DashboardPage() {
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 text-xs font-semibold">
|
||||
<ZapIcon className="size-3.5 text-muted-foreground" />
|
||||
LLM token usage
|
||||
{t("LLM token usage")}
|
||||
{/* Data source toggle: old = activity stats (includes historical tasks), new = the llm_usage metering ledger (more accurate, only covers data since it was enabled) */}
|
||||
<div className="ml-1 flex gap-0.5 rounded-md border bg-muted/30 p-0.5">
|
||||
{(
|
||||
[
|
||||
{ v: "old", label: "Old" },
|
||||
{ v: "new", label: "New" },
|
||||
{ v: "old", label: t("Old") },
|
||||
{ v: "new", label: t("New") },
|
||||
] as const
|
||||
).map(({ v, label }) => (
|
||||
<button
|
||||
@@ -608,8 +618,12 @@ export default function DashboardPage() {
|
||||
onClick={() => setTokenVersion(v)}
|
||||
title={
|
||||
v === "new"
|
||||
? "New: from the llm_usage metering ledger, exact per call and including aborted runs; only covers data since it was enabled"
|
||||
: "Old: from activity stats (includes historical tasks); aborted runs are not counted and it cannot break down by model"
|
||||
? t(
|
||||
"New: from the llm_usage metering ledger, exact per call and including aborted runs; only covers data since it was enabled",
|
||||
)
|
||||
: t(
|
||||
"Old: from activity stats (includes historical tasks); aborted runs are not counted and it cannot break down by model",
|
||||
)
|
||||
}
|
||||
className={cn(
|
||||
"rounded px-2 py-0.5 text-[9px] font-medium transition-colors",
|
||||
@@ -638,7 +652,7 @@ export default function DashboardPage() {
|
||||
: "bg-muted/30 text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
All
|
||||
{t("All")}
|
||||
</button>
|
||||
{llmProfiles.map((p) => {
|
||||
const key = Number(p.id);
|
||||
@@ -667,7 +681,7 @@ export default function DashboardPage() {
|
||||
: "bg-emerald-500/20 text-emerald-400",
|
||||
)}
|
||||
>
|
||||
Default
|
||||
{t("Default")}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
@@ -682,11 +696,13 @@ export default function DashboardPage() {
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Total */}
|
||||
<div>
|
||||
<div className="text-[10px] text-muted-foreground">Total (input+output)</div>
|
||||
<div className="text-[10px] text-muted-foreground">{t("Total (input+output)")}</div>
|
||||
<div className="mt-0.5 text-3xl font-bold tabular-nums tracking-tight">
|
||||
{fmtTokens(displayedTokens.input + displayedTokens.output) || "—"}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[10px] text-muted-foreground">{displayedTokens.taskCount} tasks</div>
|
||||
<div className="mt-0.5 text-[10px] text-muted-foreground">
|
||||
{t("{count} tasks", { count: displayedTokens.taskCount })}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Per-type bars */}
|
||||
@@ -696,19 +712,19 @@ export default function DashboardPage() {
|
||||
const total = displayedTokens.input + displayedTokens.output;
|
||||
return [
|
||||
{
|
||||
label: "Input (uncached)",
|
||||
label: t("Input (uncached)"),
|
||||
value: displayedTokens.input - displayedTokens.cacheRead,
|
||||
barColor: dailyTrendConfig.input.color!,
|
||||
text: "text-blue-400",
|
||||
},
|
||||
{
|
||||
label: "Cache hits",
|
||||
label: t("Cache hits"),
|
||||
value: displayedTokens.cacheRead,
|
||||
barColor: dailyTrendConfig.cacheRead.color!,
|
||||
text: "text-emerald-400",
|
||||
},
|
||||
{
|
||||
label: "Output",
|
||||
label: t("Output"),
|
||||
value: displayedTokens.output,
|
||||
barColor: dailyTrendConfig.output.color!,
|
||||
text: "text-violet-400",
|
||||
@@ -740,7 +756,7 @@ export default function DashboardPage() {
|
||||
const hitPct = denominator > 0 ? Math.round((displayedTokens.cacheRead / denominator) * 100) : 0;
|
||||
return (
|
||||
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2 text-[10px]">
|
||||
<span className="text-muted-foreground">Cache hit rate</span>
|
||||
<span className="text-muted-foreground">{t("Cache hit rate")}</span>
|
||||
<span
|
||||
className={cn("font-semibold tabular-nums", hitPct > 50 ? "text-emerald-400" : "text-amber-400")}
|
||||
>
|
||||
@@ -768,11 +784,11 @@ export default function DashboardPage() {
|
||||
<div className="flex gap-0.5 rounded-md border bg-muted/30 p-0.5">
|
||||
{(
|
||||
[
|
||||
{ days: 7, label: "7d" },
|
||||
{ days: 30, label: "30d" },
|
||||
{ days: 90, label: "3mo" },
|
||||
{ days: 180, label: "6mo" },
|
||||
{ days: 365, label: "1y" },
|
||||
{ days: 7, label: t("7d") },
|
||||
{ days: 30, label: t("30d") },
|
||||
{ days: 90, label: t("3mo") },
|
||||
{ days: 180, label: t("6mo") },
|
||||
{ days: 365, label: t("1y") },
|
||||
] as const
|
||||
).map(({ days, label }) => (
|
||||
<button
|
||||
@@ -797,7 +813,7 @@ export default function DashboardPage() {
|
||||
className="flex flex-1 items-center justify-center rounded-lg border bg-muted/10 text-xs text-muted-foreground"
|
||||
style={{ minHeight: 180 }}
|
||||
>
|
||||
No data
|
||||
{t("No data")}
|
||||
</div>
|
||||
) : (
|
||||
<ChartContainer config={dailyTrendConfig} className="h-[200px] w-full">
|
||||
@@ -852,17 +868,17 @@ export default function DashboardPage() {
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-1.5 text-xs font-semibold">
|
||||
<ActivityIcon className="size-3.5 text-muted-foreground" />
|
||||
Activity feed
|
||||
{t("Activity feed")}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{activity.filter((a) => a.kind !== "usage").length} events
|
||||
{t("{count} events", { count: activity.filter((a) => a.kind !== "usage").length })}
|
||||
</span>
|
||||
<Link
|
||||
href="/function/tasks"
|
||||
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
View tasks <ArrowUpRightIcon className="size-3" />
|
||||
{t("View tasks")} <ArrowUpRightIcon className="size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
@@ -873,7 +889,7 @@ export default function DashboardPage() {
|
||||
if (count === 0) return null;
|
||||
return (
|
||||
<span key={kind} className="rounded border bg-muted/20 px-1.5 py-0.5 text-[9px] text-muted-foreground">
|
||||
{kind} <strong className="text-foreground/70">{count}</strong>
|
||||
{t(kind)} <strong className="text-foreground/70">{count}</strong>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
@@ -881,7 +897,7 @@ export default function DashboardPage() {
|
||||
|
||||
<div className="divide-y">
|
||||
{recentActivity.length === 0 ? (
|
||||
<div className="py-4 text-center text-xs text-muted-foreground">No activity records</div>
|
||||
<div className="py-4 text-center text-xs text-muted-foreground">{t("No activity records")}</div>
|
||||
) : (
|
||||
recentActivity.map((a) => (
|
||||
<div key={a.seq} className="flex gap-2.5 py-2">
|
||||
@@ -899,7 +915,7 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
<div className="shrink-0 text-right">
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[9px] text-muted-foreground">
|
||||
{a.kind}
|
||||
{t(a.kind)}
|
||||
</Badge>
|
||||
<div className="mt-0.5 text-[9px] tabular-nums text-muted-foreground">{fmtRel(a.ts)}</div>
|
||||
</div>
|
||||
@@ -914,19 +930,19 @@ export default function DashboardPage() {
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-1.5 text-xs font-semibold">
|
||||
<BugIcon className="size-3.5 text-muted-foreground" />
|
||||
Findings
|
||||
{t("Findings")}
|
||||
</div>
|
||||
<Link
|
||||
href="/function/findings"
|
||||
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
All <ArrowUpRightIcon className="size-3" />
|
||||
{t("All")} <ArrowUpRightIcon className="size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="divide-y">
|
||||
{recentFindings.length === 0 ? (
|
||||
<div className="py-4 text-center text-xs text-muted-foreground">No findings</div>
|
||||
<div className="py-4 text-center text-xs text-muted-foreground">{t("No findings")}</div>
|
||||
) : (
|
||||
recentFindings.map((f) => (
|
||||
<div key={f.id} className="flex items-start gap-2 py-2">
|
||||
@@ -959,15 +975,15 @@ export default function DashboardPage() {
|
||||
<div className="flex items-center justify-between border-b px-4 py-3">
|
||||
<div className="flex items-center gap-1.5 text-xs font-semibold">
|
||||
<ClockIcon className="size-3.5 text-muted-foreground" />
|
||||
Tasks
|
||||
{t("Tasks")}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] text-muted-foreground">{tasks.length} tasks</span>
|
||||
<span className="text-[10px] text-muted-foreground">{t("{count} tasks", { count: tasks.length })}</span>
|
||||
<Link
|
||||
href="/function/tasks"
|
||||
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
All <ArrowUpRightIcon className="size-3" />
|
||||
{t("All")} <ArrowUpRightIcon className="size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
@@ -979,7 +995,7 @@ export default function DashboardPage() {
|
||||
key={h}
|
||||
className="px-4 py-2 text-left text-[9px] font-semibold uppercase tracking-widest text-muted-foreground first:pl-4"
|
||||
>
|
||||
{h}
|
||||
{t(h)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
@@ -988,7 +1004,7 @@ export default function DashboardPage() {
|
||||
{sortedTasks.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-6 text-center text-xs text-muted-foreground">
|
||||
No tasks
|
||||
{t("No tasks")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
@@ -1046,12 +1062,12 @@ export default function DashboardPage() {
|
||||
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
|
||||
{/* Asset distribution */}
|
||||
<Card className="p-4">
|
||||
<SectionTitle icon={NetworkIcon} sub="By type">
|
||||
Asset distribution
|
||||
<SectionTitle icon={NetworkIcon} sub={t("By type")}>
|
||||
{t("Asset distribution")}
|
||||
</SectionTitle>
|
||||
|
||||
{assetByType.length === 0 ? (
|
||||
<div className="py-6 text-center text-xs text-muted-foreground">No asset data</div>
|
||||
<div className="py-6 text-center text-xs text-muted-foreground">{t("No asset data")}</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{assetByType.map(([type, count]) => (
|
||||
@@ -1071,18 +1087,20 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-3 border-t pt-3 text-[10px] text-muted-foreground">{totalAssets} nodes in total</div>
|
||||
<div className="mt-3 border-t pt-3 text-[10px] text-muted-foreground">
|
||||
{t("{count} nodes in total", { count: totalAssets })}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Traffic status codes */}
|
||||
<Card className="p-4">
|
||||
<SectionTitle icon={ActivityIcon} sub={`${traffic.length} requests`}>
|
||||
Traffic status codes
|
||||
<SectionTitle icon={ActivityIcon} sub={t("{count} requests", { count: traffic.length })}>
|
||||
{t("Traffic status codes")}
|
||||
</SectionTitle>
|
||||
|
||||
{/* bar chart */}
|
||||
{trafficByCodes.length === 0 ? (
|
||||
<div className="py-6 text-center text-xs text-muted-foreground">No traffic data</div>
|
||||
<div className="py-6 text-center text-xs text-muted-foreground">{t("No traffic data")}</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-3 flex items-end gap-2" style={{ height: 52 }}>
|
||||
@@ -1099,7 +1117,7 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-2.5">
|
||||
<div className="mb-1.5 text-[10px] text-muted-foreground">Recent requests</div>
|
||||
<div className="mb-1.5 text-[10px] text-muted-foreground">{t("Recent requests")}</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{recentTraffic.map((e) => (
|
||||
<div key={e.id} className="flex items-center gap-1.5 text-[10px]">
|
||||
@@ -1128,11 +1146,11 @@ export default function DashboardPage() {
|
||||
|
||||
{/* System status & pending approvals */}
|
||||
<Card className="p-4">
|
||||
<SectionTitle icon={ShieldCheckIcon}>System status</SectionTitle>
|
||||
<SectionTitle icon={ShieldCheckIcon}>{t("System status")}</SectionTitle>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
|
||||
<div className="text-[10px] text-muted-foreground">LLM config</div>
|
||||
<div className="text-[10px] text-muted-foreground">{t("LLM config")}</div>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn(
|
||||
@@ -1142,12 +1160,12 @@ export default function DashboardPage() {
|
||||
: "border-red-500/30 bg-red-500/10 text-red-400",
|
||||
)}
|
||||
>
|
||||
{stats?.llm_configured ? "Configured" : "Not configured"}
|
||||
{stats?.llm_configured ? t("Configured") : t("Not configured")}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
|
||||
<div className="text-[10px] text-muted-foreground">Traffic capture</div>
|
||||
<div className="text-[10px] text-muted-foreground">{t("Traffic capture")}</div>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn(
|
||||
@@ -1157,13 +1175,13 @@ export default function DashboardPage() {
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{settings?.traffic_capture ? "On" : "Off"}
|
||||
{settings?.traffic_capture ? t("On") : t("Off")}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{activeProfile && (
|
||||
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
|
||||
<div className="text-[10px] text-muted-foreground">Active model</div>
|
||||
<div className="text-[10px] text-muted-foreground">{t("Active model")}</div>
|
||||
<span className="font-mono text-[10px]">{activeProfile.model}</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -1172,7 +1190,9 @@ export default function DashboardPage() {
|
||||
{/* pending approvals */}
|
||||
{pendingCount > 0 && (
|
||||
<div className="mt-3">
|
||||
<div className="mb-1.5 text-[10px] font-medium text-amber-400">Pending approvals ({pendingCount})</div>
|
||||
<div className="mb-1.5 text-[10px] font-medium text-amber-400">
|
||||
{t("Pending approvals ({count})", { count: pendingCount })}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{pending.slice(0, 3).map((p) => (
|
||||
<Link
|
||||
@@ -1192,7 +1212,7 @@ export default function DashboardPage() {
|
||||
href="/system/intercept/approvals"
|
||||
className="text-center text-[10px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{pendingCount - 3} more…
|
||||
{t("{count} more…", { count: pendingCount - 3 })}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
@@ -1202,7 +1222,7 @@ export default function DashboardPage() {
|
||||
{pendingCount === 0 && (
|
||||
<div className="mt-3 rounded-lg border bg-muted/10 px-3 py-3 text-center text-[10px] text-muted-foreground">
|
||||
<ShieldCheckIcon className="mx-auto mb-1 size-4 text-emerald-500/50" />
|
||||
No pending interception approvals
|
||||
{t("No pending interception approvals")}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
@@ -63,6 +63,7 @@ import { parseCompanyScopeText } from "@/lib/company-scope";
|
||||
import { httpHref } from "@/lib/http-href";
|
||||
import type { Asset, Company, CompanyScopeRule } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
const METHOD_COLOR: Record<string, string> = {
|
||||
GET: "bg-emerald-100 text-emerald-700",
|
||||
@@ -99,13 +100,13 @@ function statusTone(code: number) {
|
||||
const PAGE_SIZES = [25, 50, 100, 200];
|
||||
|
||||
const TABS: { key: string; label: string; icon: LucideIcon }[] = [
|
||||
{ key: "company", label: "Companies", icon: BuildingIcon },
|
||||
{ key: "root_domain", label: "Root domains", icon: GlobeIcon },
|
||||
{ key: "company", label: t("Companies"), icon: BuildingIcon },
|
||||
{ key: "root_domain", label: t("Root domains"), icon: GlobeIcon },
|
||||
{ key: "ip", label: "IP", icon: NetworkIcon },
|
||||
{ key: "subdomain", label: "Subdomains", icon: GlobeIcon },
|
||||
{ key: "app", label: "Apps", icon: SmartphoneIcon },
|
||||
{ key: "service", label: "Services", icon: LayoutTemplateIcon },
|
||||
{ key: "endpoint", label: "Endpoints", icon: LinkIcon },
|
||||
{ key: "subdomain", label: t("Subdomains"), icon: GlobeIcon },
|
||||
{ key: "app", label: t("Apps"), icon: SmartphoneIcon },
|
||||
{ key: "service", label: t("Services"), icon: LayoutTemplateIcon },
|
||||
{ key: "endpoint", label: t("Endpoints"), icon: LinkIcon },
|
||||
];
|
||||
|
||||
export default function AssetsPage() {
|
||||
@@ -193,11 +194,11 @@ export default function AssetsPage() {
|
||||
setDeleting(true);
|
||||
try {
|
||||
const res = await api.deleteAssets(deleteIds);
|
||||
toast.success(`Deleted ${res.deleted} assets`);
|
||||
toast.success(t("Deleted {count} assets", { count: res.deleted }));
|
||||
setSelected(new Set());
|
||||
refresh();
|
||||
} catch (e) {
|
||||
toast.error("Delete failed: " + String((e as Error)?.message ?? e));
|
||||
toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) }));
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setDeleteOpen(false);
|
||||
@@ -211,12 +212,12 @@ export default function AssetsPage() {
|
||||
const res = await api.deleteCompany(companyDeleteTarget.id, companyDeleteAssets);
|
||||
const msg =
|
||||
companyDeleteAssets && res.assets_deleted > 0
|
||||
? `Company deleted, along with ${res.assets_deleted} assets`
|
||||
: "Company deleted";
|
||||
? t("Company deleted, along with {count} assets", { count: res.assets_deleted })
|
||||
: t("Company deleted");
|
||||
toast.success(msg);
|
||||
refresh();
|
||||
} catch (e) {
|
||||
toast.error("Delete failed: " + String((e as Error)?.message ?? e));
|
||||
toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) }));
|
||||
} finally {
|
||||
setCompanyDeleting(false);
|
||||
setCompanyDeleteTarget(null);
|
||||
@@ -317,19 +318,19 @@ export default function AssetsPage() {
|
||||
<div className="flex h-[calc(100vh-6rem)] min-h-0 flex-col gap-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Assets</h1>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{t("Assets")}</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
<span className="tabular-nums">{totalAssets}</span> assets in total
|
||||
<span className="text-sm text-muted-foreground tabular-nums">
|
||||
{t("{count} assets in total", { count: totalAssets })}
|
||||
</span>
|
||||
{selected.size > 0 && (
|
||||
<Button variant="destructive" size="sm" onClick={() => openDelete(Array.from(selected) as number[])}>
|
||||
<Trash2Icon className="size-3.5" /> Delete selected ({selected.size})
|
||||
<Trash2Icon className="size-3.5" /> {t("Delete selected ({count})", { count: selected.size })}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" size="sm" onClick={refresh} disabled={loading}>
|
||||
<RefreshCwIcon className={cn("size-4", loading && "animate-spin")} /> Refresh
|
||||
<RefreshCwIcon className={cn("size-4", loading && "animate-spin")} /> {t("Refresh")}
|
||||
</Button>
|
||||
<CompanyDialog onSaved={refresh} />
|
||||
</div>
|
||||
@@ -355,10 +356,10 @@ export default function AssetsPage() {
|
||||
<Table>
|
||||
<TableHeader className="sticky top-0 z-10 bg-card">
|
||||
<TableRow>
|
||||
<TableHead>Company</TableHead>
|
||||
<TableHead className="w-24 text-right">Assets</TableHead>
|
||||
<TableHead>Asset scope</TableHead>
|
||||
<TableHead className="w-36 text-right">Actions</TableHead>
|
||||
<TableHead>{t("Company")}</TableHead>
|
||||
<TableHead className="w-24 text-right">{t("Assets")}</TableHead>
|
||||
<TableHead>{t("Asset scope")}</TableHead>
|
||||
<TableHead className="w-36 text-right">{t("Actions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -381,7 +382,7 @@ export default function AssetsPage() {
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">No scope set</span>
|
||||
<span className="text-xs text-muted-foreground">{t("No scope set")}</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
@@ -396,7 +397,7 @@ export default function AssetsPage() {
|
||||
setCompanyDeleteTarget(c);
|
||||
setCompanyDeleteAssets(false);
|
||||
}}
|
||||
aria-label={`Delete company ${c.name}`}
|
||||
aria-label={t("Delete company {name}", { name: c.name })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -407,7 +408,9 @@ export default function AssetsPage() {
|
||||
{companies.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="py-10 text-center text-sm text-muted-foreground">
|
||||
No companies yet. Click "Add company" in the top-right corner and fill in the asset scope; the system will automatically claim matching assets.
|
||||
{t(
|
||||
'No companies yet. Click "Add company" in the top-right corner and fill in the asset scope; the system will automatically claim matching assets.',
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@@ -440,7 +443,7 @@ export default function AssetsPage() {
|
||||
<TableCell className="font-mono text-xs font-medium">{a.domain}</TableCell>
|
||||
<TableCell className="text-xs">{a.icp || "—"}</TableCell>
|
||||
<TableCell className="text-xs">
|
||||
{companyName(a.company_id) || <span className="text-muted-foreground">Unassigned</span>}
|
||||
{companyName(a.company_id) || <span className="text-muted-foreground">{t("Unassigned")}</span>}
|
||||
</TableCell>
|
||||
<TableCell className="w-8 pl-0">
|
||||
<Button
|
||||
@@ -448,7 +451,7 @@ export default function AssetsPage() {
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => openDelete([a.id])}
|
||||
aria-label={`Delete asset ${a.domain || a.id}`}
|
||||
aria-label={t("Delete asset {name}", { name: a.domain || a.id })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -495,7 +498,7 @@ export default function AssetsPage() {
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => openDelete([a.id])}
|
||||
aria-label={`Delete asset ${a.ip || a.id}`}
|
||||
aria-label={t("Delete asset {name}", { name: a.ip || a.id })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -537,7 +540,7 @@ export default function AssetsPage() {
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => openDelete([a.id])}
|
||||
aria-label={`Delete asset ${a.domain || a.id}`}
|
||||
aria-label={t("Delete asset {name}", { name: a.domain || a.id })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -577,7 +580,7 @@ export default function AssetsPage() {
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => openDelete([a.id])}
|
||||
aria-label={`Delete asset ${a.app_name || a.id}`}
|
||||
aria-label={t("Delete asset {name}", { name: a.app_name || a.id })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -657,7 +660,7 @@ export default function AssetsPage() {
|
||||
) : (
|
||||
(a.auth ?? []).map((authItem, i) => {
|
||||
const item = authItem as Record<string, string>;
|
||||
const label = item.type || item.username || "Auth";
|
||||
const label = item.type || item.username || t("Auth");
|
||||
return (
|
||||
<span key={i} className="inline-flex items-center gap-1 text-[11px]">
|
||||
<KeyRoundIcon className="size-3 text-muted-foreground" />
|
||||
@@ -673,7 +676,7 @@ export default function AssetsPage() {
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => openDelete([a.id])}
|
||||
aria-label={`Delete asset ${a.url || a.id}`}
|
||||
aria-label={t("Delete asset {name}", { name: a.url || a.id })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -725,7 +728,7 @@ export default function AssetsPage() {
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => openDelete([a.id])}
|
||||
aria-label={`Delete asset ${a.url || a.id}`}
|
||||
aria-label={t("Delete asset {name}", { name: a.url || a.id })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -739,14 +742,15 @@ export default function AssetsPage() {
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirm delete</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("Confirm delete")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently delete <span className="font-semibold tabular-nums">{deleteIds.length}</span>{" "}
|
||||
asset records. This action cannot be undone.
|
||||
{t("This will permanently delete {count} asset records. This action cannot be undone.", {
|
||||
count: deleteIds.length,
|
||||
})}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -755,7 +759,7 @@ export default function AssetsPage() {
|
||||
disabled={deleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleting ? "Deleting…" : "Confirm delete"}
|
||||
{deleting ? t("Deleting…") : t("Confirm delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
@@ -772,10 +776,14 @@ export default function AssetsPage() {
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete company · {companyDeleteTarget?.name}</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("Delete company · {name}", { name: companyDeleteTarget?.name ?? "" })}</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-3">
|
||||
<p>This will permanently delete the company and its asset scope configuration. This action cannot be undone.</p>
|
||||
<p>
|
||||
{t(
|
||||
"This will permanently delete the company and its asset scope configuration. This action cannot be undone.",
|
||||
)}
|
||||
</p>
|
||||
<label
|
||||
htmlFor="delete-assets-opt"
|
||||
className="flex cursor-pointer items-center gap-2.5 rounded-md border p-3 hover:bg-muted/50"
|
||||
@@ -786,15 +794,17 @@ export default function AssetsPage() {
|
||||
onCheckedChange={(v) => setCompanyDeleteAssets(!!v)}
|
||||
/>
|
||||
<span className="text-sm leading-snug">
|
||||
Also delete all assets under this company
|
||||
<span className="block text-xs text-muted-foreground">Leave unchecked to keep the assets and only remove the ownership</span>
|
||||
{t("Also delete all assets under this company")}
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{t("Leave unchecked to keep the assets and only remove the ownership")}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={companyDeleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={companyDeleting}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -803,7 +813,7 @@ export default function AssetsPage() {
|
||||
disabled={companyDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{companyDeleting ? "Deleting…" : "Confirm delete"}
|
||||
{companyDeleting ? t("Deleting…") : t("Confirm delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
@@ -861,7 +871,7 @@ function AssetCard({
|
||||
/>
|
||||
</TableHead>
|
||||
) : (
|
||||
<TableHead key={c + i}>{c}</TableHead>
|
||||
<TableHead key={c + i}>{c && t(c)}</TableHead>
|
||||
),
|
||||
)}
|
||||
</TableRow>
|
||||
@@ -872,7 +882,7 @@ function AssetCard({
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={cols.length} className="py-12 text-center text-sm text-muted-foreground">
|
||||
{loaded ? "No data." : "Loading…"}
|
||||
{loaded ? t("No data.") : t("Loading…")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@@ -889,7 +899,7 @@ function AssetCard({
|
||||
<SelectGroup>
|
||||
{PAGE_SIZES.map((n) => (
|
||||
<SelectItem key={n} value={String(n)}>
|
||||
{n} / page
|
||||
{t("{count} / page", { count: n })}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
@@ -989,11 +999,11 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
|
||||
|
||||
const submit = async () => {
|
||||
if (!name.trim()) {
|
||||
toast.error("Please enter a company name");
|
||||
toast.error(t("Please enter a company name"));
|
||||
return;
|
||||
}
|
||||
if (parsedScope.errors.length > 0) {
|
||||
toast.error("Please fix the invalid asset scope");
|
||||
toast.error(t("Please fix the invalid asset scope"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
@@ -1001,14 +1011,15 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
|
||||
const res = await api.createCompany(name.trim(), parsedScope.rules);
|
||||
const added = res.scope_added ?? 0;
|
||||
const invalid = res.scope_invalid ?? 0;
|
||||
if (invalid > 0) toast.warning(`Company created, ${added} scopes added; ${invalid} invalid lines`);
|
||||
else toast.success(`Company created, ${added} scopes added`);
|
||||
if (invalid > 0)
|
||||
toast.warning(t("Company created, {added} scopes added; {invalid} invalid lines", { added, invalid }));
|
||||
else toast.success(t("Company created, {added} scopes added", { added }));
|
||||
setOpen(false);
|
||||
onSaved();
|
||||
} catch (e) {
|
||||
const msg = String((e as Error)?.message ?? e);
|
||||
if (/:\s*409$/.test(msg)) toast.error("Company already exists; try a different name");
|
||||
else toast.error(`Save failed: ${msg}`);
|
||||
if (/:\s*409$/.test(msg)) toast.error(t("Company already exists; try a different name"));
|
||||
else toast.error(t("Save failed: {error}", { error: msg }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -1018,21 +1029,25 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button size="sm">
|
||||
<BuildingIcon data-icon="inline-start" /> Add company
|
||||
<BuildingIcon data-icon="inline-start" /> {t("Add company")}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className="w-full! max-w-none! gap-0 p-0 sm:w-[520px]! sm:max-w-[520px]!">
|
||||
<SheetHeader className="border-b p-6">
|
||||
<SheetTitle>Add company</SheetTitle>
|
||||
<SheetDescription>Configure the company and its asset scope. Keywords only serve as agent hints and do not automatically assign assets.</SheetDescription>
|
||||
<SheetTitle>{t("Add company")}</SheetTitle>
|
||||
<SheetDescription>
|
||||
{t(
|
||||
"Configure the company and its asset scope. Keywords only serve as agent hints and do not automatically assign assets.",
|
||||
)}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="cn-name">Company name</FieldLabel>
|
||||
<FieldLabel htmlFor="cn-name">{t("Company name")}</FieldLabel>
|
||||
<Input
|
||||
id="cn-name"
|
||||
placeholder="e.g. Acme Corp (name must be unique)"
|
||||
placeholder={t("e.g. Acme Corp (name must be unique)")}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
@@ -1042,10 +1057,10 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
|
||||
</div>
|
||||
<SheetFooter className="flex-row justify-end gap-2 border-t p-4">
|
||||
<Button variant="outline" onClick={() => setOpen(false)} disabled={busy}>
|
||||
Cancel
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={busy || !name.trim() || parsedScope.errors.length > 0}>
|
||||
{busy ? "Saving…" : "Save"}
|
||||
{busy ? t("Saving…") : t("Save")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
@@ -1073,20 +1088,20 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
|
||||
|
||||
const submit = async () => {
|
||||
if (parsedScope.errors.length > 0) {
|
||||
toast.error("Please fix the invalid asset scope");
|
||||
toast.error(t("Please fix the invalid asset scope"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.updateCompanyScope(company.id, parsedScope.rules, reason);
|
||||
const errCount = res.invalid ?? 0;
|
||||
if (errCount > 0) toast.warning(`Saved; ${errCount} invalid lines`);
|
||||
else toast.success(`Scope updated, ${res.added} entries in total`);
|
||||
if (errCount > 0) toast.warning(t("Saved; {count} invalid lines", { count: errCount }));
|
||||
else toast.success(t("Scope updated, {count} entries in total", { count: res.added }));
|
||||
showScopeWarnings(res.warnings);
|
||||
setOpen(false);
|
||||
onSaved();
|
||||
} catch (e) {
|
||||
toast.error(`Save failed: ${String((e as Error)?.message ?? e)}`);
|
||||
toast.error(t("Save failed: {error}", { error: String((e as Error)?.message ?? e) }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -1096,14 +1111,16 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-7">
|
||||
Edit
|
||||
{t("Edit")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit asset scope · {company.name}</DialogTitle>
|
||||
<DialogTitle>{t("Edit asset scope · {name}", { name: company.name })}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Saving replaces all existing scopes. ICP matches assets exactly; company keywords only serve as agent hints.
|
||||
{t(
|
||||
"Saving replaces all existing scopes. ICP matches assets exactly; company keywords only serve as agent hints.",
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<FieldGroup className="py-2">
|
||||
@@ -1114,10 +1131,10 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
|
||||
parsed={parsedScope}
|
||||
/>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="es-reason">Attribution basis (optional)</FieldLabel>
|
||||
<FieldLabel htmlFor="es-reason">{t("Attribution basis (optional)")}</FieldLabel>
|
||||
<Input
|
||||
id="es-reason"
|
||||
placeholder="e.g. certificate / whois / ASN evidence"
|
||||
placeholder={t("e.g. certificate / whois / ASN evidence")}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
@@ -1125,10 +1142,10 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
|
||||
</FieldGroup>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setOpen(false)} disabled={busy}>
|
||||
Cancel
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={busy || parsedScope.errors.length > 0}>
|
||||
{busy ? "Saving…" : "Overwrite save"}
|
||||
{busy ? t("Saving…") : t("Overwrite save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
@@ -1152,24 +1169,24 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
|
||||
|
||||
const submit = async () => {
|
||||
if (parsedScope.rules.length === 0) {
|
||||
toast.error("Please enter the scopes to append");
|
||||
toast.error(t("Please enter the scopes to append"));
|
||||
return;
|
||||
}
|
||||
if (parsedScope.errors.length > 0) {
|
||||
toast.error("Please fix the invalid asset scope");
|
||||
toast.error(t("Please fix the invalid asset scope"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.addCompanyScope(company.id, parsedScope.rules, reason);
|
||||
const errCount = res.invalid ?? 0;
|
||||
if (errCount > 0) toast.warning(`Saved; ${errCount} invalid lines`);
|
||||
else toast.success(`Appended ${res.added} scopes`);
|
||||
if (errCount > 0) toast.warning(t("Saved; {count} invalid lines", { count: errCount }));
|
||||
else toast.success(t("Appended {count} scopes", { count: res.added }));
|
||||
showScopeWarnings(res.warnings);
|
||||
setOpen(false);
|
||||
onSaved();
|
||||
} catch (e) {
|
||||
toast.error(`Save failed: ${String((e as Error)?.message ?? e)}`);
|
||||
toast.error(t("Save failed: {error}", { error: String((e as Error)?.message ?? e) }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -1179,13 +1196,17 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-7">
|
||||
Append
|
||||
{t("Append")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Append asset scope · {company.name}</DialogTitle>
|
||||
<DialogDescription>New scopes are appended to the existing ones. ICP matches assets exactly; company keywords only serve as agent hints.</DialogDescription>
|
||||
<DialogTitle>{t("Append asset scope · {name}", { name: company.name })}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(
|
||||
"New scopes are appended to the existing ones. ICP matches assets exactly; company keywords only serve as agent hints.",
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<FieldGroup className="py-2">
|
||||
<ScopeTextEditor
|
||||
@@ -1195,10 +1216,10 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
|
||||
parsed={parsedScope}
|
||||
/>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="as-reason">Attribution basis (optional)</FieldLabel>
|
||||
<FieldLabel htmlFor="as-reason">{t("Attribution basis (optional)")}</FieldLabel>
|
||||
<Input
|
||||
id="as-reason"
|
||||
placeholder="e.g. certificate / whois / ASN evidence"
|
||||
placeholder={t("e.g. certificate / whois / ASN evidence")}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
@@ -1206,10 +1227,10 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
|
||||
</FieldGroup>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setOpen(false)} disabled={busy}>
|
||||
Cancel
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={busy || parsedScope.rules.length === 0 || parsedScope.errors.length > 0}>
|
||||
{busy ? "Saving…" : "Append"}
|
||||
{busy ? t("Saving…") : t("Append")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -15,9 +15,10 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
|
||||
import { api } from "@/lib/api";
|
||||
import type { CommandRecord, ToolStat } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
|
||||
function fmtTime(ts: string) {
|
||||
return new Date(ts).toLocaleString("zh-CN", {
|
||||
return new Date(ts).toLocaleString(intlLocale, {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
@@ -130,7 +131,7 @@ export default function CommandsPage() {
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<TerminalIcon className="h-5 w-5 text-muted-foreground" />
|
||||
<h1 className="text-xl font-semibold tracking-tight">Tool executions</h1>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{t("Tool executions")}</h1>
|
||||
<Badge variant="secondary">{total}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
@@ -140,14 +141,14 @@ export default function CommandsPage() {
|
||||
<div className="relative max-w-sm flex-1">
|
||||
<SearchIcon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search tools / arguments..."
|
||||
placeholder={t("Search tools / arguments...")}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
className="h-8 pl-8"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
placeholder="Task ID"
|
||||
placeholder={t("Task ID")}
|
||||
className="h-8 w-28"
|
||||
value={taskFilter}
|
||||
onChange={(e) => setTaskFilter(e.target.value.replace(/\D/g, ""))}
|
||||
@@ -159,7 +160,7 @@ export default function CommandsPage() {
|
||||
<SelectContent>
|
||||
{PAGE_SIZES.map((n) => (
|
||||
<SelectItem key={n} value={String(n)}>
|
||||
{n} / page
|
||||
{t("{count} / page", { count: n })}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
@@ -167,7 +168,7 @@ export default function CommandsPage() {
|
||||
|
||||
<Button variant="outline" size="sm" className="h-8" onClick={() => setStatsOpen(true)}>
|
||||
<BarChart3Icon className="size-4" />
|
||||
Stats
|
||||
{t("Stats")}
|
||||
</Button>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2 text-xs text-muted-foreground">
|
||||
@@ -205,12 +206,12 @@ export default function CommandsPage() {
|
||||
<Table>
|
||||
<TableHeader className="sticky top-0 z-10 bg-card">
|
||||
<TableRow>
|
||||
<TableHead className="w-[130px]">Time</TableHead>
|
||||
<TableHead className="w-[60px]">Task</TableHead>
|
||||
<TableHead className="w-[90px]">Worker</TableHead>
|
||||
<TableHead className="w-[110px]">Tool</TableHead>
|
||||
<TableHead>Input</TableHead>
|
||||
<TableHead className="w-[60px]">Status</TableHead>
|
||||
<TableHead className="w-[130px]">{t("Time")}</TableHead>
|
||||
<TableHead className="w-[60px]">{t("Task")}</TableHead>
|
||||
<TableHead className="w-[90px]">{t("Worker")}</TableHead>
|
||||
<TableHead className="w-[110px]">{t("Tool")}</TableHead>
|
||||
<TableHead>{t("Input")}</TableHead>
|
||||
<TableHead className="w-[60px]">{t("Status")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -223,7 +224,7 @@ export default function CommandsPage() {
|
||||
) : commands.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="py-12 text-center text-sm text-muted-foreground">
|
||||
No tool execution records yet
|
||||
{t("No tool execution records yet")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
@@ -255,11 +256,11 @@ export default function CommandsPage() {
|
||||
<TableCell>
|
||||
{cmd.is_error ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
Failed
|
||||
{t("Failed")}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs text-emerald-600">
|
||||
Success
|
||||
{t("Success")}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
@@ -276,21 +277,20 @@ export default function CommandsPage() {
|
||||
<Dialog open={statsOpen} onOpenChange={setStatsOpen}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Tool call stats</DialogTitle>
|
||||
<DialogTitle>{t("Tool call stats")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{taskFilter || queryQ ? "All records under the current filters" : "All tool execution records"}
|
||||
{taskFilter || queryQ ? t("All records under the current filters") : t("All tool execution records")}
|
||||
{stats.length > 0 && (
|
||||
<>
|
||||
<span className="tabular-nums">
|
||||
{" · "}
|
||||
<span className="tabular-nums">{stats.length}</span> tools ·{" "}
|
||||
<span className="tabular-nums">{statsTotal}</span> calls
|
||||
{t("{tools} tools · {calls} calls", { tools: stats.length, calls: statsTotal })}
|
||||
{statsErrors > 0 && (
|
||||
<>
|
||||
{" · Failed "}
|
||||
<span className="tabular-nums text-red-600 dark:text-red-400">{statsErrors}</span>
|
||||
{" · "}
|
||||
<span className="text-red-600 dark:text-red-400">{t("Failed {count}", { count: statsErrors })}</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
</span>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
@@ -300,7 +300,7 @@ export default function CommandsPage() {
|
||||
<Loader2Icon className="mx-auto h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : stats.length === 0 ? (
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">No stats data</div>
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">{t("No stats data")}</div>
|
||||
) : (
|
||||
<div className="-mr-2 max-h-[55vh] space-y-1 overflow-auto pr-2">
|
||||
{stats.map((s) => (
|
||||
@@ -309,7 +309,9 @@ export default function CommandsPage() {
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate font-mono text-xs font-medium">{s.tool}</span>
|
||||
{s.errors > 0 && (
|
||||
<span className="text-[11px] tabular-nums text-red-600 dark:text-red-400">Failed {s.errors}</span>
|
||||
<span className="text-[11px] tabular-nums text-red-600 dark:text-red-400">
|
||||
{t("Failed {count}", { count: s.errors })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted">
|
||||
@@ -337,7 +339,7 @@ export default function CommandsPage() {
|
||||
{selected && (
|
||||
<>
|
||||
<SheetHeader className="border-b px-5 py-4">
|
||||
<SheetTitle className="pr-8">Tool execution details</SheetTitle>
|
||||
<SheetTitle className="pr-8">{t("Tool execution details")}</SheetTitle>
|
||||
<SheetDescription>{fmtTime(selected.created_at)}</SheetDescription>
|
||||
<div className="flex flex-wrap items-center gap-2 pt-2">
|
||||
<Badge variant="outline" className="text-xs font-mono">
|
||||
@@ -351,18 +353,18 @@ export default function CommandsPage() {
|
||||
</Badge>
|
||||
{selected.is_error ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
Failed
|
||||
{t("Failed")}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs text-emerald-600">
|
||||
Success
|
||||
{t("Success")}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</SheetHeader>
|
||||
<div className="grid min-h-0 flex-1 grid-rows-2 divide-y">
|
||||
<div className="flex min-h-0 min-w-0 flex-col">
|
||||
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">Input</div>
|
||||
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">{t("Input")}</div>
|
||||
<div className="min-h-0 flex-1 overflow-auto">
|
||||
<pre className="p-5 font-mono text-xs break-all whitespace-pre-wrap">
|
||||
{toolInput(selected.command)}
|
||||
@@ -370,7 +372,7 @@ export default function CommandsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-h-0 min-w-0 flex-col">
|
||||
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">Output</div>
|
||||
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">{t("Output")}</div>
|
||||
<div className="min-h-0 flex-1 overflow-auto">
|
||||
<pre
|
||||
className={cn(
|
||||
@@ -378,7 +380,7 @@ export default function CommandsPage() {
|
||||
selected.is_error && "text-red-600 dark:text-red-400",
|
||||
)}
|
||||
>
|
||||
{selected.output || "(empty)"}
|
||||
{selected.output || t("(empty)")}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -20,6 +20,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
|
||||
import type { FindingAssetKind, FindingAssetNode } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
// Icons reuse the assets page's type mapping, so the same asset kind looks the same in both places.
|
||||
const KIND_ICON: Record<FindingAssetKind, LucideIcon> = {
|
||||
@@ -34,14 +35,14 @@ const KIND_ICON: Record<FindingAssetKind, LucideIcon> = {
|
||||
};
|
||||
|
||||
const KIND_LABEL: Record<FindingAssetKind, string> = {
|
||||
company: "Company",
|
||||
root_domain: "Root domain",
|
||||
subdomain: "Subdomain",
|
||||
company: t("Company"),
|
||||
root_domain: t("Root domain"),
|
||||
subdomain: t("Subdomain"),
|
||||
ip: "IP",
|
||||
app: "App",
|
||||
service: "Service",
|
||||
endpoint: "Endpoint",
|
||||
none: "Unlinked",
|
||||
app: t("App"),
|
||||
service: t("Service"),
|
||||
endpoint: t("Endpoint"),
|
||||
none: t("Unlinked"),
|
||||
};
|
||||
|
||||
// TreeNode is the tree assembled from the node array. The backend already sorts by "most findings under the same parent first",
|
||||
@@ -233,9 +234,9 @@ export function AssetTree({
|
||||
[isExpanded],
|
||||
);
|
||||
|
||||
let emptyHint = "No findings are linked to assets under the current filters.";
|
||||
if (loading) emptyHint = "Loading…";
|
||||
else if (searching) emptyHint = "No matching assets.";
|
||||
let emptyHint = t("No findings are linked to assets under the current filters.");
|
||||
if (loading) emptyHint = t("Loading…");
|
||||
else if (searching) emptyHint = t("No matching assets.");
|
||||
|
||||
const rows: React.ReactNode[] = [];
|
||||
const pushRows = (list: TreeNode[]) => {
|
||||
@@ -264,8 +265,8 @@ export function AssetTree({
|
||||
type="search"
|
||||
value={keyword}
|
||||
onChange={(event) => setKeyword(event.target.value)}
|
||||
placeholder="Filter assets"
|
||||
aria-label="Filter assets"
|
||||
placeholder={t("Filter assets")}
|
||||
aria-label={t("Filter assets")}
|
||||
/>
|
||||
<InputGroupAddon>
|
||||
<SearchIcon aria-hidden="true" />
|
||||
@@ -278,8 +279,8 @@ export function AssetTree({
|
||||
className="size-8 shrink-0 text-muted-foreground"
|
||||
onClick={onRefresh}
|
||||
disabled={loading}
|
||||
aria-label="Refresh asset tree"
|
||||
title="Refresh asset tree"
|
||||
aria-label={t("Refresh asset tree")}
|
||||
title={t("Refresh asset tree")}
|
||||
>
|
||||
<RefreshCwIcon className={cn("size-4", loading && "animate-spin")} />
|
||||
</Button>
|
||||
@@ -294,7 +295,7 @@ export function AssetTree({
|
||||
selected === null ? "bg-accent font-medium" : "hover:bg-accent/50",
|
||||
)}
|
||||
>
|
||||
<span>All assets</span>
|
||||
<span>{t("All assets")}</span>
|
||||
<span className="text-xs tabular-nums text-muted-foreground">{findingTotal}</span>
|
||||
</button>
|
||||
|
||||
@@ -307,8 +308,10 @@ export function AssetTree({
|
||||
|
||||
{truncated && (
|
||||
<p className="px-1 text-xs text-muted-foreground">
|
||||
Too many assets; the {(droppedKinds ?? []).map((k) => KIND_LABEL[k as FindingAssetKind] ?? k).join(" / ")}
|
||||
levels are hidden (their counts still roll up into the parents). Narrow with the filters or the filter box to see the full hierarchy.
|
||||
{t(
|
||||
"Too many assets; the {kinds} levels are hidden (their counts still roll up into the parents). Narrow with the filters or the filter box to see the full hierarchy.",
|
||||
{ kinds: (droppedKinds ?? []).map((k) => KIND_LABEL[k as FindingAssetKind] ?? k).join(" / ") },
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -343,7 +346,7 @@ function AssetTreeRow({
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
className="flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground"
|
||||
aria-label={open ? "Collapse" : "Expand"}
|
||||
aria-label={open ? t("Collapse") : t("Expand")}
|
||||
aria-expanded={open}
|
||||
>
|
||||
<ChevronRightIcon className={cn("size-3.5 transition-transform", open && "rotate-90")} />
|
||||
@@ -362,16 +365,16 @@ function AssetTreeRow({
|
||||
</button>
|
||||
<span className="flex shrink-0 items-center gap-1 text-xs tabular-nums">
|
||||
{node.critical > 0 && (
|
||||
<span className="text-rose-600" title={`Critical ${node.critical}`}>
|
||||
<span className="text-rose-600" title={t("Critical {count}", { count: node.critical })}>
|
||||
{node.critical}
|
||||
</span>
|
||||
)}
|
||||
{node.high > 0 && (
|
||||
<span className="text-red-500" title={`High ${node.high}`}>
|
||||
<span className="text-red-500" title={t("High {count}", { count: node.high })}>
|
||||
{node.high}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-muted-foreground" title={`${node.total} findings total`}>
|
||||
<span className="text-muted-foreground" title={t("{count} findings total", { count: node.total })}>
|
||||
{node.total}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
@@ -46,6 +46,7 @@ import type {
|
||||
VerificationStatus,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
|
||||
export const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"];
|
||||
|
||||
@@ -78,11 +79,11 @@ export const FINDING_REPORT_STATES: FindingReportState[] = [
|
||||
];
|
||||
|
||||
export const REPORT_STATE_META: Record<FindingReportState, { label: string; tone: Tone }> = {
|
||||
none: { label: "Not submitted", tone: "slate" },
|
||||
submitted: { label: "Submitted", tone: "amber" },
|
||||
accepted: { label: "Accepted", tone: "green" },
|
||||
rejected: { label: "Rejected", tone: "red" },
|
||||
duplicate: { label: "Duplicate report", tone: "neutral" },
|
||||
none: { label: t("Not submitted"), tone: "slate" },
|
||||
submitted: { label: t("Submitted"), tone: "amber" },
|
||||
accepted: { label: t("Accepted"), tone: "green" },
|
||||
rejected: { label: t("Rejected"), tone: "red" },
|
||||
duplicate: { label: t("Duplicate report"), tone: "neutral" },
|
||||
};
|
||||
|
||||
export function ReportStateBadge({ state }: { state?: FindingReportState }) {
|
||||
@@ -102,11 +103,11 @@ export function ReportStateBadge({ state }: { state?: FindingReportState }) {
|
||||
|
||||
// Verification outcome → label/tone, on the same tone tokens StatusBadge uses.
|
||||
export const VERIFICATION_META: Record<VerificationStatus, { label: string; tone: Tone }> = {
|
||||
verified: { label: "Verified", tone: "green" },
|
||||
unverified: { label: "Unverified", tone: "slate" },
|
||||
blocked: { label: "Blocked", tone: "amber" },
|
||||
not_assessed: { label: "Not assessed", tone: "red" },
|
||||
false_positive: { label: "False positive", tone: "neutral" },
|
||||
verified: { label: t("Verified"), tone: "green" },
|
||||
unverified: { label: t("Unverified"), tone: "slate" },
|
||||
blocked: { label: t("Blocked"), tone: "amber" },
|
||||
not_assessed: { label: t("Not assessed"), tone: "red" },
|
||||
false_positive: { label: t("False positive"), tone: "neutral" },
|
||||
};
|
||||
|
||||
// VerificationBadge shows the automated verification outcome ("Verified L3" when a
|
||||
@@ -155,7 +156,7 @@ export function isSameFinding(left: Finding, right: Finding): boolean {
|
||||
}
|
||||
|
||||
export function fmtTime(ts: string) {
|
||||
return new Date(ts).toLocaleString("zh-CN", {
|
||||
return new Date(ts).toLocaleString(intlLocale, {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
@@ -208,7 +209,7 @@ export function FindingsTable({
|
||||
activeRetests,
|
||||
onDeepen,
|
||||
onDelete,
|
||||
selectAllLabel = "Select all on this page",
|
||||
selectAllLabel = t("Select all on this page"),
|
||||
}: FindingsTableProps) {
|
||||
const selectableIds = items.map((finding) => finding.finding_id).filter((id): id is string => Boolean(id));
|
||||
const selectedCount = selectableIds.filter((id) => selectedIds.has(id)).length;
|
||||
@@ -232,14 +233,14 @@ export function FindingsTable({
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="w-8" />
|
||||
<TableHead className="w-20">Severity</TableHead>
|
||||
<TableHead>Vulnerability</TableHead>
|
||||
<TableHead className="w-44">Asset</TableHead>
|
||||
<TableHead className="w-28">Status</TableHead>
|
||||
<TableHead className="w-36">Report</TableHead>
|
||||
<TableHead className="w-32">Task</TableHead>
|
||||
<TableHead className="w-24">Time</TableHead>
|
||||
<TableHead className="w-48">Actions</TableHead>
|
||||
<TableHead className="w-20">{t("Severity")}</TableHead>
|
||||
<TableHead>{t("Vulnerability")}</TableHead>
|
||||
<TableHead className="w-44">{t("Asset")}</TableHead>
|
||||
<TableHead className="w-28">{t("Status")}</TableHead>
|
||||
<TableHead className="w-36">{t("Report")}</TableHead>
|
||||
<TableHead className="w-32">{t("Task")}</TableHead>
|
||||
<TableHead className="w-24">{t("Time")}</TableHead>
|
||||
<TableHead className="w-48">{t("Actions")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -266,7 +267,7 @@ export function FindingsTable({
|
||||
<Checkbox
|
||||
checked={selectedIds.has(f.finding_id)}
|
||||
onCheckedChange={(c) => onToggleSelected(f.finding_id as string, c === true)}
|
||||
aria-label="Select this vulnerability"
|
||||
aria-label={t("Select this vulnerability")}
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
@@ -285,16 +286,16 @@ export function FindingsTable({
|
||||
href={`/function/findings/detail?id=${f.finding_id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="truncate font-medium hover:text-primary hover:underline"
|
||||
title="View finding details"
|
||||
title={t("View finding details")}
|
||||
>
|
||||
{f.name || f.vulnclass || "Uncategorized"}
|
||||
{f.name || f.vulnclass || t("Uncategorized")}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="truncate font-medium">{f.name || f.vulnclass || "Uncategorized"}</span>
|
||||
<span className="truncate font-medium">{f.name || f.vulnclass || t("Uncategorized")}</span>
|
||||
)}
|
||||
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<Badge variant="outline">Traffic evidence: {f.traffic_count ?? 0}</Badge>
|
||||
<Badge variant="outline">{t("Traffic evidence: {count}", { count: f.traffic_count ?? 0 })}</Badge>
|
||||
<VerificationBadge finding={f} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -378,22 +379,27 @@ export function FindingsTable({
|
||||
<div className="flex items-center gap-1">
|
||||
{retest ? (
|
||||
<Button asChild size="sm" variant="ghost">
|
||||
<Link href={`/chat?c=${retest.conversation_id}`} title="View the retest in progress">
|
||||
<Link href={`/chat?c=${retest.conversation_id}`} title={t("View the retest in progress")}>
|
||||
<Spinner data-icon="inline-start" />
|
||||
Retesting
|
||||
{t("Retesting")}
|
||||
</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
{!retest && f.finding_id && !f.inherited ? (
|
||||
<Button size="sm" variant="ghost" onClick={() => onRetest(f)} title="Retest this vulnerability in a separate conversation">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => onRetest(f)}
|
||||
title={t("Retest this vulnerability in a separate conversation")}
|
||||
>
|
||||
<RotateCcwIcon data-icon="inline-start" />
|
||||
Retest
|
||||
{t("Retest")}
|
||||
</Button>
|
||||
) : null}
|
||||
{f.finding_id && f.task_id && (
|
||||
<Button size="sm" variant="ghost" onClick={() => onDeepen(f)}>
|
||||
<FlaskConicalIcon data-icon="inline-start" />
|
||||
Deepen
|
||||
{t("Deepen")}
|
||||
</Button>
|
||||
)}
|
||||
{f.finding_id && (
|
||||
@@ -403,25 +409,24 @@ export function FindingsTable({
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
aria-label="Delete vulnerability"
|
||||
aria-label={t("Delete vulnerability")}
|
||||
>
|
||||
<Trash2Icon className="size-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete this vulnerability?</AlertDialogTitle>
|
||||
<AlertDialogDescription className="break-words">
|
||||
"
|
||||
<span className="break-all">
|
||||
{f.name || f.vulnclass || f.summary || `#${f.finding_id}`}
|
||||
</span>
|
||||
" will be permanently deleted and removed from the findings list, the task findings tab, and the exploration graph. This action cannot be undone.
|
||||
<AlertDialogTitle>{t("Delete this vulnerability?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription className="[overflow-wrap:anywhere]">
|
||||
{t(
|
||||
'"{name}" will be permanently deleted and removed from the findings list, the task findings tab, and the exploration graph. This action cannot be undone.',
|
||||
{ name: f.name || f.vulnclass || f.summary || `#${f.finding_id}` },
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => onDelete(f)}>Delete</AlertDialogAction>
|
||||
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => onDelete(f)}>{t("Delete")}</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
@@ -439,23 +444,23 @@ export function FindingsTable({
|
||||
{f.finding_id && edit && (
|
||||
<div className="flex flex-wrap items-end gap-3 rounded-md border bg-background px-3 py-2.5">
|
||||
<div className="flex min-w-[12rem] flex-1 flex-col gap-1">
|
||||
<Label className="text-xs text-muted-foreground">Vulnerability</Label>
|
||||
<Label className="text-xs text-muted-foreground">{t("Vulnerability")}</Label>
|
||||
<Input
|
||||
value={edit.name}
|
||||
onChange={(e) => onEditChange((s) => (s ? { ...s, name: e.target.value } : s))}
|
||||
placeholder="Readable title; falls back to category when empty"
|
||||
placeholder={t("Readable title; falls back to category when empty")}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex min-w-[10rem] flex-col gap-1">
|
||||
<Label className="text-xs text-muted-foreground">Category</Label>
|
||||
<Label className="text-xs text-muted-foreground">{t("Category")}</Label>
|
||||
<Input
|
||||
value={edit.vulnclass}
|
||||
onChange={(e) => onEditChange((s) => (s ? { ...s, vulnclass: e.target.value } : s))}
|
||||
placeholder="e.g. SQL Injection"
|
||||
placeholder={t("e.g. SQL Injection")}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label className="text-xs text-muted-foreground">Severity</Label>
|
||||
<Label className="text-xs text-muted-foreground">{t("Severity")}</Label>
|
||||
<Select
|
||||
value={edit.severity}
|
||||
onValueChange={(v) => onEditChange((s) => (s ? { ...s, severity: v as Severity } : s))}
|
||||
@@ -473,23 +478,23 @@ export function FindingsTable({
|
||||
</Select>
|
||||
</div>
|
||||
<Button size="sm" disabled={saving} onClick={() => onSave(f)}>
|
||||
{saving ? "Saving…" : "Save"}
|
||||
{saving ? t("Saving…") : t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<ShieldAlertIcon className="size-3.5" />
|
||||
Evidence
|
||||
{t("Evidence")}
|
||||
{f.vulnclass && (
|
||||
<span>
|
||||
· Type:
|
||||
· {t("Type:")}
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 font-mono">{f.vulnclass}</code>
|
||||
</span>
|
||||
)}
|
||||
{f.param_id && <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{f.param_id}</code>}
|
||||
{f.assets && f.assets.length > 0 && (
|
||||
<span className="flex flex-wrap items-center gap-1">
|
||||
· Assets:
|
||||
· {t("Assets:")}
|
||||
{f.assets.map((a) => (
|
||||
<code key={a.id} className="rounded bg-muted px-1.5 py-0.5 font-mono" title={a.type}>
|
||||
{a.label}
|
||||
@@ -508,12 +513,12 @@ export function FindingsTable({
|
||||
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-2">
|
||||
<FileTextIcon className="size-3.5" />
|
||||
Detailed report
|
||||
{t("Detailed report")}
|
||||
</span>
|
||||
{reports[rowKey]?.status === "done" && reports[rowKey]?.text.trim() && (
|
||||
<CopyButton
|
||||
text={reports[rowKey]?.text}
|
||||
successMessage="Detailed report copied"
|
||||
successMessage={t("Detailed report copied")}
|
||||
variant="ghost"
|
||||
className="h-6 px-2 text-xs"
|
||||
/>
|
||||
@@ -522,11 +527,11 @@ export function FindingsTable({
|
||||
{(() => {
|
||||
const rep = reports[rowKey];
|
||||
if (!rep || rep.status === "loading")
|
||||
return <p className="text-xs text-muted-foreground">Loading…</p>;
|
||||
return <p className="text-xs text-muted-foreground">{t("Loading…")}</p>;
|
||||
if (rep.status === "error")
|
||||
return <p className="text-xs text-muted-foreground">Failed to load the report.</p>;
|
||||
return <p className="text-xs text-muted-foreground">{t("Failed to load the report.")}</p>;
|
||||
if (!rep.text.trim())
|
||||
return <p className="text-xs text-muted-foreground">No detailed report yet.</p>;
|
||||
return <p className="text-xs text-muted-foreground">{t("No detailed report yet.")}</p>;
|
||||
return (
|
||||
// break-words inherits into paragraphs/lists; pre additionally gets
|
||||
// whitespace-pre-wrap so code blocks wrap too — otherwise long code lines/URLs
|
||||
@@ -548,7 +553,7 @@ export function FindingsTable({
|
||||
{items.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={COLUMN_COUNT} className="py-12 text-center text-sm text-muted-foreground">
|
||||
No matching findings.
|
||||
{t("No matching findings.")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as React from "react";
|
||||
import { ExplorationGraph } from "@/components/exploration-graph";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Edge, TaskNode } from "@/lib/types";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
// FindingLineageView renders the exploration sub-graph from the task's initial
|
||||
// node down to this finding's node — the same exploration graph canvas as the task graph,
|
||||
@@ -35,7 +36,7 @@ export function FindingLineageView({ findingId }: { findingId: string }) {
|
||||
if (loaded && nodes.length === 0) {
|
||||
return (
|
||||
<p className="text-muted-foreground p-6 text-sm">
|
||||
No lineage to display (this vulnerability is not linked to an exploration node, or its task has been deleted).
|
||||
{t("No lineage to display (this vulnerability is not linked to an exploration node, or its task has been deleted).")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -45,7 +46,7 @@ export function FindingLineageView({ findingId }: { findingId: string }) {
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
className="h-[68vh]"
|
||||
emptyHint={loaded ? "No lineage" : "Loading…"}
|
||||
emptyHint={loaded ? t("No lineage") : t("Loading…")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { api } from "@/lib/api";
|
||||
import { statusMeta } from "@/lib/status";
|
||||
import type { Finding, FindingReportState, FindingStatus, Severity } from "@/lib/types";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
|
||||
import {
|
||||
FINDING_REPORT_STATES,
|
||||
@@ -47,7 +48,7 @@ const FINDING_STATUSES: FindingStatus[] = [
|
||||
];
|
||||
|
||||
function fmtTime(ts: string) {
|
||||
return new Date(ts).toLocaleString("zh-CN");
|
||||
return new Date(ts).toLocaleString(intlLocale);
|
||||
}
|
||||
|
||||
// FieldRow is one label/value line in the right-hand status panel.
|
||||
@@ -91,10 +92,10 @@ function FindingDetailInner() {
|
||||
try {
|
||||
const updated = await api.setFindingSeverity(id, next);
|
||||
setFinding(updated);
|
||||
toast.success(`Severity changed to "${statusMeta("severity", next).label}"`);
|
||||
toast.success(t('Severity changed to "{label}"', { label: statusMeta("severity", next).label }));
|
||||
} catch (e) {
|
||||
setFinding((cur) => (cur ? { ...cur, severity: prev } : cur));
|
||||
toast.error("Update failed: " + (e as Error).message);
|
||||
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[finding, id],
|
||||
@@ -108,10 +109,10 @@ function FindingDetailInner() {
|
||||
try {
|
||||
const updated = await api.setFindingStatus(id, next);
|
||||
setFinding(updated);
|
||||
toast.success(`Status changed to "${statusMeta("finding", next).label}"`);
|
||||
toast.success(t('Status changed to "{label}"', { label: statusMeta("finding", next).label }));
|
||||
} catch (e) {
|
||||
setFinding((cur) => (cur ? { ...cur, status: prev } : cur));
|
||||
toast.error("Update failed: " + (e as Error).message);
|
||||
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[finding, id],
|
||||
@@ -125,10 +126,10 @@ function FindingDetailInner() {
|
||||
try {
|
||||
const updated = await api.setFindingReportState(id, next);
|
||||
setFinding(updated);
|
||||
toast.success(`Report stage changed to "${REPORT_STATE_META[next].label}"`);
|
||||
toast.success(t('Report stage changed to "{label}"', { label: REPORT_STATE_META[next].label }));
|
||||
} catch (e) {
|
||||
setFinding((cur) => (cur ? { ...cur, report_state: prev } : cur));
|
||||
toast.error("Update failed: " + (e as Error).message);
|
||||
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[finding, id],
|
||||
@@ -137,11 +138,11 @@ function FindingDetailInner() {
|
||||
if (!finding) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-10 text-center">
|
||||
<p className="text-muted-foreground">{loaded ? `Finding ${id} not found` : "Loading…"}</p>
|
||||
<p className="text-muted-foreground">{loaded ? t("Finding {id} not found", { id }) : t("Loading…")}</p>
|
||||
{loaded && (
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/function/findings">
|
||||
<ArrowLeftIcon /> Back to findings
|
||||
<ArrowLeftIcon /> {t("Back to findings")}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
@@ -149,7 +150,7 @@ function FindingDetailInner() {
|
||||
);
|
||||
}
|
||||
|
||||
const title = finding.name || finding.vulnclass || "Uncategorized";
|
||||
const title = finding.name || finding.vulnclass || t("Uncategorized");
|
||||
|
||||
return (
|
||||
<Tabs value={tab} onValueChange={setTab} className="flex flex-1 flex-col gap-0">
|
||||
@@ -173,12 +174,12 @@ function FindingDetailInner() {
|
||||
<ReportStateBadge state={finding.report_state} />
|
||||
<VerificationBadge finding={finding} />
|
||||
{finding.inherited && finding.source_task_id && (
|
||||
<Badge variant="outline">Source task #{finding.source_task_id} · read-only</Badge>
|
||||
<Badge variant="outline">{t("Source task #{id} · read-only", { id: finding.source_task_id })}</Badge>
|
||||
)}
|
||||
</div>
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview">Overview</TabsTrigger>
|
||||
<TabsTrigger value="lineage">Exploration graph</TabsTrigger>
|
||||
<TabsTrigger value="overview">{t("Overview")}</TabsTrigger>
|
||||
<TabsTrigger value="lineage">{t("Exploration graph")}</TabsTrigger>
|
||||
</TabsList>
|
||||
</header>
|
||||
|
||||
@@ -191,16 +192,16 @@ function FindingDetailInner() {
|
||||
<div className="flex flex-col gap-4 lg:col-span-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">Digest</CardTitle>
|
||||
<CardTitle className="text-sm">{t("Digest")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.summary || "(no digest)"}</p>
|
||||
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.summary || t("(no digest)")}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<FindingRetestPanel key={id} findingId={id} readOnly={finding.inherited} onCompleted={load} />
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">Evidence / PoC</CardTitle>
|
||||
<CardTitle className="text-sm">{t("Evidence / PoC")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{finding.evidence ? (
|
||||
@@ -208,14 +209,14 @@ function FindingDetailInner() {
|
||||
{finding.evidence}
|
||||
</pre>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">(no evidence)</p>
|
||||
<p className="text-sm text-muted-foreground">{t("(no evidence)")}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
{finding.counterevidence?.trim() && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">Counterevidence</CardTitle>
|
||||
<CardTitle className="text-sm">{t("Counterevidence")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.counterevidence}</p>
|
||||
@@ -225,7 +226,7 @@ function FindingDetailInner() {
|
||||
{finding.confidence_rationale?.trim() && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">Confidence rationale</CardTitle>
|
||||
<CardTitle className="text-sm">{t("Confidence rationale")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.confidence_rationale}</p>
|
||||
@@ -242,19 +243,21 @@ function FindingDetailInner() {
|
||||
{/* Below evidence: detailed report (rendered Markdown) */}
|
||||
<Card>
|
||||
<CardHeader className="flex-row items-center justify-between">
|
||||
<CardTitle className="text-sm">Detailed report</CardTitle>
|
||||
{finding.report && <CopyButton text={finding.report} successMessage="Detailed report copied" />}
|
||||
<CardTitle className="text-sm">{t("Detailed report")}</CardTitle>
|
||||
{finding.report && <CopyButton text={finding.report} successMessage={t("Detailed report copied")} />}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{finding.report_stale ? (
|
||||
<Alert>
|
||||
<AlertDescription>Traffic evidence has changed; the detailed report is pending an update.</AlertDescription>
|
||||
<AlertDescription>
|
||||
{t("Traffic evidence has changed; the detailed report is pending an update.")}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
{finding.report ? (
|
||||
<Markdown text={finding.report} />
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">No detailed report yet.</p>
|
||||
<p className="text-sm text-muted-foreground">{t("No detailed report yet.")}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -263,18 +266,18 @@ function FindingDetailInner() {
|
||||
{/* Right column: status panel */}
|
||||
<Card className="h-fit lg:sticky lg:top-24">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">Status</CardTitle>
|
||||
<CardTitle className="text-sm">{t("Status")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="divide-y">
|
||||
{/* Vulnerability ID */}
|
||||
<FieldRow label="Vulnerability ID">
|
||||
<FieldRow label={t("Vulnerability ID")}>
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs text-muted-foreground">
|
||||
#{finding.id}
|
||||
</code>
|
||||
</FieldRow>
|
||||
|
||||
{/* Severity */}
|
||||
<FieldRow label="Severity">
|
||||
<FieldRow label={t("Severity")}>
|
||||
{finding.inherited ? (
|
||||
<StatusBadge domain="severity" value={finding.severity} dot />
|
||||
) : (
|
||||
@@ -296,7 +299,7 @@ function FindingDetailInner() {
|
||||
</FieldRow>
|
||||
|
||||
{/* Triage status */}
|
||||
<FieldRow label="Triage status">
|
||||
<FieldRow label={t("Triage status")}>
|
||||
{finding.inherited ? (
|
||||
<StatusBadge domain="finding" value={finding.status} dot />
|
||||
) : (
|
||||
@@ -317,7 +320,7 @@ function FindingDetailInner() {
|
||||
)}
|
||||
</FieldRow>
|
||||
|
||||
<FieldRow label="Report stage">
|
||||
<FieldRow label={t("Report stage")}>
|
||||
{finding.inherited ? (
|
||||
<ReportStateBadge state={finding.report_state} />
|
||||
) : (
|
||||
@@ -343,7 +346,7 @@ function FindingDetailInner() {
|
||||
|
||||
{/* Verification: automated outcome; the note explains any state other than verified */}
|
||||
{finding.verification_status && (
|
||||
<FieldRow label="Verification">
|
||||
<FieldRow label={t("Verification")}>
|
||||
<VerificationBadge finding={finding} />
|
||||
{finding.verification_status !== "verified" && finding.verification_note?.trim() && (
|
||||
<p className="whitespace-pre-wrap break-words text-muted-foreground text-xs">
|
||||
@@ -354,7 +357,7 @@ function FindingDetailInner() {
|
||||
)}
|
||||
|
||||
{/* Vulnerability type */}
|
||||
<FieldRow label="Vulnerability type">
|
||||
<FieldRow label={t("Vulnerability type")}>
|
||||
{finding.vulnclass ? (
|
||||
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{finding.vulnclass}</code>
|
||||
) : (
|
||||
@@ -363,7 +366,7 @@ function FindingDetailInner() {
|
||||
</FieldRow>
|
||||
|
||||
{/* Assets */}
|
||||
<FieldRow label="Assets">
|
||||
<FieldRow label={t("Assets")}>
|
||||
{finding.assets && finding.assets.length > 0 ? (
|
||||
<div className="flex flex-wrap justify-end gap-1">
|
||||
{finding.assets.map((a) => (
|
||||
@@ -382,7 +385,7 @@ function FindingDetailInner() {
|
||||
</FieldRow>
|
||||
|
||||
{/* Task */}
|
||||
<FieldRow label="Task">
|
||||
<FieldRow label={t("Task")}>
|
||||
{finding.task_id ? (
|
||||
<Link
|
||||
href={`/function/tasks/detail?id=${finding.task_id}`}
|
||||
@@ -393,12 +396,12 @@ function FindingDetailInner() {
|
||||
<ArrowUpRightIcon className="size-3 shrink-0" />
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-muted-foreground">— (task deleted)</span>
|
||||
<span className="text-muted-foreground">{t("— (task deleted)")}</span>
|
||||
)}
|
||||
</FieldRow>
|
||||
|
||||
{/* Found at */}
|
||||
<FieldRow label="Found at">
|
||||
<FieldRow label={t("Found at")}>
|
||||
<span className="tabular-nums">{fmtTime(finding.ts)}</span>
|
||||
</FieldRow>
|
||||
</CardContent>
|
||||
|
||||
@@ -73,6 +73,7 @@ import {
|
||||
VERIFICATION_STATUSES,
|
||||
} from "./_components/findings-table";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
const FINDING_LIST_PREFERENCE_KEY = "artex_finding_list_preferences";
|
||||
|
||||
@@ -201,7 +202,7 @@ export default function FindingsPage() {
|
||||
setActiveRetests(Object.fromEntries(rows.map((item) => [item.finding_id, item])));
|
||||
failed = false;
|
||||
} catch (error) {
|
||||
if (!disposed && !failed) toast.error(`Failed to load retest status: ${(error as Error).message}`);
|
||||
if (!disposed && !failed) toast.error(t("Failed to load retest status: {error}", { error: (error as Error).message }));
|
||||
failed = true;
|
||||
} finally {
|
||||
if (!disposed) timer = setTimeout(() => void refreshRetests(), 3000);
|
||||
@@ -324,9 +325,9 @@ export default function FindingsPage() {
|
||||
ids: [...selectedIds],
|
||||
});
|
||||
setExportOpen(false);
|
||||
toast.success("Export download started");
|
||||
toast.success(t("Export download started"));
|
||||
} catch (e) {
|
||||
toast.error(`Export failed: ${(e as Error).message}`);
|
||||
toast.error(t("Export failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
@@ -420,7 +421,7 @@ export default function FindingsPage() {
|
||||
} catch (e) {
|
||||
if (request !== assetTreeRequest.current || activeFilterFingerprint.current !== requestFilter) return;
|
||||
setAssetTree((current) => ({ ...current, loading: false }));
|
||||
toast.error(`Failed to load the asset tree: ${(e as Error).message}`);
|
||||
toast.error(t("Failed to load the asset tree: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
}, [filterFingerprint, reportState, severity, status, verificationStatus, vulnclass, task, query, sort]);
|
||||
|
||||
@@ -669,7 +670,7 @@ export default function FindingsPage() {
|
||||
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, status: next } : x)));
|
||||
try {
|
||||
await api.setFindingStatus(f.finding_id, next);
|
||||
toast.success(`Marked as "${statusMeta("finding", next).label}"`);
|
||||
toast.success(t('Marked as "{label}"', { label: statusMeta("finding", next).label }));
|
||||
// refresh stat cards (pending count) and drop the row if it no longer matches the status filter
|
||||
api
|
||||
.findingStats()
|
||||
@@ -685,7 +686,7 @@ export default function FindingsPage() {
|
||||
refreshAfterMutation(f);
|
||||
} catch (e) {
|
||||
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, status: prev } : x)));
|
||||
toast.error(`Update failed: ${(e as Error).message}`);
|
||||
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[refreshAfterMutation, setFindings, status],
|
||||
@@ -698,7 +699,7 @@ export default function FindingsPage() {
|
||||
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, report_state: next } : x)));
|
||||
try {
|
||||
await api.setFindingReportState(f.finding_id, next);
|
||||
toast.success(`Report stage set to "${REPORT_STATE_META[next].label}"`);
|
||||
toast.success(t('Report stage set to "{label}"', { label: REPORT_STATE_META[next].label }));
|
||||
api
|
||||
.findingStats()
|
||||
.then(setStats)
|
||||
@@ -713,7 +714,7 @@ export default function FindingsPage() {
|
||||
refreshAfterMutation(f);
|
||||
} catch (e) {
|
||||
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, report_state: prev } : x)));
|
||||
toast.error(`Update failed: ${(e as Error).message}`);
|
||||
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[refreshAfterMutation, reportState, setFindings],
|
||||
@@ -729,9 +730,7 @@ export default function FindingsPage() {
|
||||
const r = await api.bulkSetFindingStatus([...selectedIds], next);
|
||||
setSelectedIds(new Set());
|
||||
const label = statusMeta("finding", next).label;
|
||||
toast.success(
|
||||
r.updated === 1 ? `Marked 1 finding as "${label}"` : `Marked ${r.updated} findings as "${label}"`,
|
||||
);
|
||||
toast.success(t('Marked {count} findings as "{label}"', { count: r.updated, label }));
|
||||
void loadFlat();
|
||||
if (view === "asset") void loadAssetTree();
|
||||
api
|
||||
@@ -741,7 +740,7 @@ export default function FindingsPage() {
|
||||
// The list reload remains valid even if the aggregate refresh fails.
|
||||
});
|
||||
} catch (e) {
|
||||
toast.error(`Bulk update failed: ${(e as Error).message}`);
|
||||
toast.error(t("Bulk update failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setBulkBusy(false);
|
||||
}
|
||||
@@ -757,11 +756,7 @@ export default function FindingsPage() {
|
||||
const r = await api.bulkSetFindingReportState([...selectedIds], next);
|
||||
setSelectedIds(new Set());
|
||||
const label = REPORT_STATE_META[next].label;
|
||||
toast.success(
|
||||
r.updated === 1
|
||||
? `Set report stage of 1 finding to "${label}"`
|
||||
: `Set report stage of ${r.updated} findings to "${label}"`,
|
||||
);
|
||||
toast.success(t('Set report stage of {count} findings to "{label}"', { count: r.updated, label }));
|
||||
void loadFlat();
|
||||
if (view === "asset") void loadAssetTree();
|
||||
api
|
||||
@@ -771,7 +766,7 @@ export default function FindingsPage() {
|
||||
// The list reload remains valid even if the aggregate refresh fails.
|
||||
});
|
||||
} catch (e) {
|
||||
toast.error(`Bulk update failed: ${(e as Error).message}`);
|
||||
toast.error(t("Bulk update failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setBulkBusy(false);
|
||||
}
|
||||
@@ -828,7 +823,7 @@ export default function FindingsPage() {
|
||||
: x,
|
||||
),
|
||||
);
|
||||
toast.success("Saved");
|
||||
toast.success(t("Saved"));
|
||||
api
|
||||
.findingStats()
|
||||
.then(setStats)
|
||||
@@ -837,7 +832,7 @@ export default function FindingsPage() {
|
||||
});
|
||||
refreshAfterMutation(f);
|
||||
} catch (e) {
|
||||
toast.error(`Save failed: ${(e as Error).message}`);
|
||||
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -861,7 +856,7 @@ export default function FindingsPage() {
|
||||
setFlat((cur) => ({ ...cur, total: Math.max(0, cur.total - 1) }));
|
||||
const rowKey = findingRowKey(f);
|
||||
setExpanded((cur) => (cur === rowKey ? null : cur));
|
||||
toast.success("Vulnerability deleted");
|
||||
toast.success(t("Vulnerability deleted"));
|
||||
api
|
||||
.findingStats()
|
||||
.then(setStats)
|
||||
@@ -870,7 +865,7 @@ export default function FindingsPage() {
|
||||
});
|
||||
refreshAfterMutation(f, true);
|
||||
} catch (e) {
|
||||
toast.error(`Delete failed: ${(e as Error).message}`);
|
||||
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
},
|
||||
[refreshAfterMutation, setFindings],
|
||||
@@ -888,28 +883,28 @@ export default function FindingsPage() {
|
||||
const result = await api.deepenFinding(deepenFinding.finding_id, deepenDescription.trim());
|
||||
toast.success(
|
||||
result.queued
|
||||
? `Deepen intent #${result.intent_id} has entered the task queue`
|
||||
: `Created high-priority worker intent #${result.intent_id}`,
|
||||
? t("Deepen intent #{id} has entered the task queue", { id: result.intent_id })
|
||||
: t("Created high-priority worker intent #{id}", { id: result.intent_id }),
|
||||
);
|
||||
refreshAfterMutation(deepenFinding);
|
||||
setDeepenFinding(null);
|
||||
setDeepenDescription("");
|
||||
} catch (error) {
|
||||
toast.error(`Submit failed: ${(error as Error).message}`);
|
||||
toast.error(t("Submit failed: {error}", { error: (error as Error).message }));
|
||||
} finally {
|
||||
setDeepening(false);
|
||||
}
|
||||
}
|
||||
|
||||
const statCards = [
|
||||
{ label: "Total findings", value: stats.total, icon: BugIcon },
|
||||
{ label: "Pending", value: stats.pending, tone: "text-amber-500", icon: ClockIcon },
|
||||
{ label: "Submitted", value: stats.submitted, tone: "text-amber-500", icon: FileUpIcon },
|
||||
{ label: "Accepted", value: stats.accepted, tone: "text-emerald-500", icon: CircleCheckIcon },
|
||||
{ label: "Critical", value: stats.critical, tone: "text-rose-600", icon: ShieldAlertIcon },
|
||||
{ label: "High", value: stats.high, tone: "text-red-500", icon: TriangleAlertIcon },
|
||||
{ label: "Medium", value: stats.medium, tone: "text-amber-500", icon: TriangleAlertIcon },
|
||||
{ label: "Low", value: stats.low, tone: "text-slate-500", icon: InfoIcon },
|
||||
{ label: t("Total findings"), value: stats.total, icon: BugIcon },
|
||||
{ label: t("Pending"), value: stats.pending, tone: "text-amber-500", icon: ClockIcon },
|
||||
{ label: t("Submitted"), value: stats.submitted, tone: "text-amber-500", icon: FileUpIcon },
|
||||
{ label: t("Accepted"), value: stats.accepted, tone: "text-emerald-500", icon: CircleCheckIcon },
|
||||
{ label: t("Critical"), value: stats.critical, tone: "text-rose-600", icon: ShieldAlertIcon },
|
||||
{ label: t("High"), value: stats.high, tone: "text-red-500", icon: TriangleAlertIcon },
|
||||
{ label: t("Medium"), value: stats.medium, tone: "text-amber-500", icon: TriangleAlertIcon },
|
||||
{ label: t("Low"), value: stats.low, tone: "text-slate-500", icon: InfoIcon },
|
||||
];
|
||||
|
||||
// The "current filter" count in the export dialog: both views share the same filters, only the counting source differs.
|
||||
@@ -949,7 +944,7 @@ export default function FindingsPage() {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FindingsTable items={flat.items} selectAllLabel="Select all on this page" {...rowProps} />
|
||||
<FindingsTable items={flat.items} selectAllLabel={t("Select all on this page")} {...rowProps} />
|
||||
<TablePagination
|
||||
page={flatPage}
|
||||
pageSize={flatPageSize}
|
||||
@@ -971,14 +966,14 @@ export default function FindingsPage() {
|
||||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Findings</h1>
|
||||
<p className="text-muted-foreground text-sm">Cross-task vulnerability overview</p>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{t("Findings")}</h1>
|
||||
<p className="text-muted-foreground text-sm">{t("Cross-task vulnerability overview")}</p>
|
||||
</div>
|
||||
<Tabs value={view} onValueChange={(v) => setView(v as FindingView)}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="flat">All findings</TabsTrigger>
|
||||
<TabsTrigger value="grouped">By task</TabsTrigger>
|
||||
<TabsTrigger value="asset">By asset</TabsTrigger>
|
||||
<TabsTrigger value="flat">{t("All findings")}</TabsTrigger>
|
||||
<TabsTrigger value="grouped">{t("By task")}</TabsTrigger>
|
||||
<TabsTrigger value="asset">{t("By asset")}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
@@ -1006,8 +1001,8 @@ export default function FindingsPage() {
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Search findings"
|
||||
aria-label="Search findings"
|
||||
placeholder={t("Search findings")}
|
||||
aria-label={t("Search findings")}
|
||||
/>
|
||||
<InputGroupAddon>
|
||||
<SearchIcon aria-hidden="true" />
|
||||
@@ -1024,14 +1019,14 @@ export default function FindingsPage() {
|
||||
>
|
||||
{(
|
||||
[
|
||||
["all", "All"],
|
||||
["critical", "Critical"],
|
||||
["high", "High"],
|
||||
["medium", "Medium"],
|
||||
["low", "Low"],
|
||||
["all", t("All")],
|
||||
["critical", t("Critical")],
|
||||
["high", t("High")],
|
||||
["medium", t("Medium")],
|
||||
["low", t("Low")],
|
||||
] as const
|
||||
).map(([val, label]) => (
|
||||
<ToggleGroupItem key={val} value={val} aria-label={`Filter by ${label} severity`}>
|
||||
<ToggleGroupItem key={val} value={val} aria-label={t("Filter by {label} severity", { label })}>
|
||||
{label}
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
@@ -1039,10 +1034,10 @@ export default function FindingsPage() {
|
||||
|
||||
<Select value={status} onValueChange={(v) => setStatus(v as "all" | FindingStatus)}>
|
||||
<SelectTrigger size="sm" className="w-32">
|
||||
<SelectValue placeholder="Status" />
|
||||
<SelectValue placeholder={t("Status")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
<SelectItem value="all">{t("All statuses")}</SelectItem>
|
||||
{FINDING_STATUSES.map((st) => (
|
||||
<SelectItem key={st} value={st}>
|
||||
{statusMeta("finding", st).label}
|
||||
@@ -1053,10 +1048,10 @@ export default function FindingsPage() {
|
||||
|
||||
<Select value={reportState} onValueChange={(v) => setReportState(v as "all" | FindingReportState)}>
|
||||
<SelectTrigger size="sm" className="w-40">
|
||||
<SelectValue placeholder="Report stage" />
|
||||
<SelectValue placeholder={t("Report stage")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All report stages</SelectItem>
|
||||
<SelectItem value="all">{t("All report stages")}</SelectItem>
|
||||
{FINDING_REPORT_STATES.map((st) => (
|
||||
<SelectItem key={st} value={st}>
|
||||
{REPORT_STATE_META[st].label}
|
||||
@@ -1070,10 +1065,10 @@ export default function FindingsPage() {
|
||||
onValueChange={(v) => setVerificationStatus(v as "all" | VerificationStatus)}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-48">
|
||||
<SelectValue placeholder="Verification" />
|
||||
<SelectValue placeholder={t("Verification")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All verification states</SelectItem>
|
||||
<SelectItem value="all">{t("All verification states")}</SelectItem>
|
||||
{VERIFICATION_STATUSES.map((st) => (
|
||||
<SelectItem key={st} value={st}>
|
||||
{VERIFICATION_META[st].label}
|
||||
@@ -1084,10 +1079,10 @@ export default function FindingsPage() {
|
||||
|
||||
<Select value={vulnclass} onValueChange={setVulnclass}>
|
||||
<SelectTrigger size="sm" className="w-40">
|
||||
<SelectValue placeholder="Vulnerability type" />
|
||||
<SelectValue placeholder={t("Vulnerability type")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All types</SelectItem>
|
||||
<SelectItem value="all">{t("All types")}</SelectItem>
|
||||
{stats.vulnclasses.map((vc) => (
|
||||
<SelectItem key={vc} value={vc}>
|
||||
{vc}
|
||||
@@ -1098,14 +1093,14 @@ export default function FindingsPage() {
|
||||
|
||||
<Select value={task} onValueChange={setTask}>
|
||||
<SelectTrigger size="sm" className="w-48">
|
||||
<SelectValue placeholder="Task" />
|
||||
<SelectValue placeholder={t("Task")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All tasks</SelectItem>
|
||||
<SelectItem value={UNASSIGNED_TASK}>Unlinked / task deleted</SelectItem>
|
||||
{(stats.tasks ?? []).map((t) => {
|
||||
const id = String(t.id);
|
||||
const label = t.name || t.description || `Task #${id} (deleted)`;
|
||||
<SelectItem value="all">{t("All tasks")}</SelectItem>
|
||||
<SelectItem value={UNASSIGNED_TASK}>{t("Unlinked / task deleted")}</SelectItem>
|
||||
{(stats.tasks ?? []).map((option) => {
|
||||
const id = String(option.id);
|
||||
const label = option.name || option.description || t("Task #{id} (deleted)", { id });
|
||||
return (
|
||||
<SelectItem key={id} value={id}>
|
||||
<span className="flex w-full items-center gap-2">
|
||||
@@ -1114,7 +1109,7 @@ export default function FindingsPage() {
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground tabular-nums">
|
||||
<BugIcon className="size-3.5" aria-hidden="true" />
|
||||
{t.count}
|
||||
{option.count}
|
||||
</span>
|
||||
</span>
|
||||
</SelectItem>
|
||||
@@ -1128,15 +1123,17 @@ export default function FindingsPage() {
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="severity">By severity</SelectItem>
|
||||
<SelectItem value="time">By time</SelectItem>
|
||||
<SelectItem value="severity">{t("By severity")}</SelectItem>
|
||||
<SelectItem value="time">{t("By time")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<div className="ml-auto flex items-center gap-3">
|
||||
{selectedIds.size > 0 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground tabular-nums">{selectedIds.size} selected</span>
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
{t("{count} selected", { count: selectedIds.size })}
|
||||
</span>
|
||||
<Select
|
||||
value=""
|
||||
onValueChange={(v) => {
|
||||
@@ -1144,8 +1141,8 @@ export default function FindingsPage() {
|
||||
}}
|
||||
disabled={bulkBusy}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-40" aria-label="Set the status of the selected findings">
|
||||
<SelectValue placeholder={bulkBusy ? "Updating…" : "Set status"} />
|
||||
<SelectTrigger size="sm" className="w-40" aria-label={t("Set the status of the selected findings")}>
|
||||
<SelectValue placeholder={bulkBusy ? t("Updating…") : t("Set status")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{FINDING_STATUSES.map((st) => (
|
||||
@@ -1162,8 +1159,8 @@ export default function FindingsPage() {
|
||||
}}
|
||||
disabled={bulkBusy}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-44" aria-label="Set the report stage of the selected findings">
|
||||
<SelectValue placeholder={bulkBusy ? "Updating…" : "Set report stage"} />
|
||||
<SelectTrigger size="sm" className="w-44" aria-label={t("Set the report stage of the selected findings")}>
|
||||
<SelectValue placeholder={bulkBusy ? t("Updating…") : t("Set report stage")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{FINDING_REPORT_STATES.map((st) => (
|
||||
@@ -1176,7 +1173,7 @@ export default function FindingsPage() {
|
||||
</div>
|
||||
)}
|
||||
<Button size="sm" variant="outline" onClick={openExport}>
|
||||
<DownloadIcon /> Export
|
||||
<DownloadIcon /> {t("Export")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1212,7 +1209,7 @@ export default function FindingsPage() {
|
||||
className={cn("hover:text-foreground", assetScope === null && "font-medium text-foreground")}
|
||||
onClick={() => setAssetScope(null)}
|
||||
>
|
||||
All assets
|
||||
{t("All assets")}
|
||||
</button>
|
||||
{assetPath.map((node) => (
|
||||
<React.Fragment key={node.key}>
|
||||
@@ -1230,7 +1227,7 @@ export default function FindingsPage() {
|
||||
</button>
|
||||
</React.Fragment>
|
||||
))}
|
||||
<span className="ml-auto shrink-0 text-xs tabular-nums">{flat.total} in total</span>
|
||||
<span className="ml-auto shrink-0 text-xs tabular-nums">{t("{count} in total", { count: flat.total })}</span>
|
||||
</div>
|
||||
{flatListCard}
|
||||
</div>
|
||||
@@ -1269,13 +1266,13 @@ export default function FindingsPage() {
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<CardTitle className="truncate text-sm">
|
||||
{group.task_id === null
|
||||
? "Unlinked / task deleted"
|
||||
? t("Unlinked / task deleted")
|
||||
: group.task_name
|
||||
? `${group.task_name} (task #${group.task_id})`
|
||||
: `Task #${group.task_id}`}
|
||||
? t("{name} (task #{id})", { name: group.task_name, id: group.task_id })
|
||||
: t("Task #{id}", { id: group.task_id })}
|
||||
</CardTitle>
|
||||
<CardDescription className="truncate" title={group.task_description}>
|
||||
{group.task_description || "Source task unavailable"}
|
||||
{group.task_description || t("Source task unavailable")}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</button>
|
||||
@@ -1298,7 +1295,7 @@ export default function FindingsPage() {
|
||||
<Button size="icon-sm" variant="ghost" asChild>
|
||||
<Link
|
||||
href={`/function/tasks/detail?id=${group.task_id}`}
|
||||
aria-label={`View task #${group.task_id}`}
|
||||
aria-label={t("View task #{id}", { id: group.task_id })}
|
||||
>
|
||||
<ArrowUpRightIcon />
|
||||
</Link>
|
||||
@@ -1315,7 +1312,11 @@ export default function FindingsPage() {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FindingsTable items={state.items} selectAllLabel="Select all on this page in this group" {...rowProps} />
|
||||
<FindingsTable
|
||||
items={state.items}
|
||||
selectAllLabel={t("Select all on this page in this group")}
|
||||
{...rowProps}
|
||||
/>
|
||||
<TablePagination
|
||||
page={state.page}
|
||||
pageSize={state.pageSize}
|
||||
@@ -1332,7 +1333,7 @@ export default function FindingsPage() {
|
||||
})}
|
||||
{groups.length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center text-sm text-muted-foreground">No matching findings.</CardContent>
|
||||
<CardContent className="py-12 text-center text-sm text-muted-foreground">{t("No matching findings.")}</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<TablePagination
|
||||
@@ -1381,25 +1382,30 @@ export default function FindingsPage() {
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Deepen exploitation</DialogTitle>
|
||||
<DialogTitle>{t("Deepen exploitation")}</DialogTitle>
|
||||
<DialogDescription className="break-words">
|
||||
A priority-10 worker intent will be created in the original task #{deepenFinding?.task_id} to run secondary verification based on this vulnerability:
|
||||
{t(
|
||||
"A priority-10 worker intent will be created in the original task #{id} to run secondary verification based on this vulnerability:",
|
||||
{ id: deepenFinding?.task_id ?? "" },
|
||||
)}{" "}
|
||||
{deepenFinding?.name || deepenFinding?.vulnclass || deepenFinding?.summary}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="finding-deepen-description">Exploitation description</FieldLabel>
|
||||
<FieldLabel htmlFor="finding-deepen-description">{t("Exploitation description")}</FieldLabel>
|
||||
<Textarea
|
||||
id="finding-deepen-description"
|
||||
value={deepenDescription}
|
||||
onChange={(event) => setDeepenDescription(event.target.value)}
|
||||
maxLength={4000}
|
||||
placeholder="Describe the exploitation path to verify, boundary conditions, targets, or expected evidence"
|
||||
placeholder={t(
|
||||
"Describe the exploitation path to verify, boundary conditions, targets, or expected evidence",
|
||||
)}
|
||||
disabled={deepening}
|
||||
/>
|
||||
<FieldDescription className="flex justify-between gap-3">
|
||||
<span>The new intent inherits this vulnerability's asset anchors.</span>
|
||||
<span>{t("The new intent inherits this vulnerability's asset anchors.")}</span>
|
||||
<span className="shrink-0 tabular-nums">{deepenDescription.length} / 4000</span>
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
@@ -1413,11 +1419,11 @@ export default function FindingsPage() {
|
||||
}}
|
||||
disabled={deepening}
|
||||
>
|
||||
Cancel
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={submitDeepen} disabled={deepening || !deepenDescription.trim()}>
|
||||
{deepening && <Spinner data-icon="inline-start" />}
|
||||
Create deepen intent
|
||||
{t("Create deepen intent")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
@@ -1426,42 +1432,46 @@ export default function FindingsPage() {
|
||||
<Dialog open={exportOpen} onOpenChange={setExportOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Export findings</DialogTitle>
|
||||
<DialogDescription>Choose the export scope and format; the browser downloads the file automatically once generated.</DialogDescription>
|
||||
<DialogTitle>{t("Export findings")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("Choose the export scope and format; the browser downloads the file automatically once generated.")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-5 py-1">
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs text-muted-foreground">Export scope</span>
|
||||
<span className="text-xs text-muted-foreground">{t("Export scope")}</span>
|
||||
<RadioGroup value={exportScope} onValueChange={(v) => setExportScope(v as typeof exportScope)}>
|
||||
<label htmlFor="export-scope-filtered" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-scope-filtered" value="filtered" /> Export the current filter results ({filteredTotal}{" "}
|
||||
items)
|
||||
<RadioGroupItem id="export-scope-filtered" value="filtered" />{" "}
|
||||
{t("Export the current filter results ({count} items)", { count: filteredTotal })}
|
||||
</label>
|
||||
<label htmlFor="export-scope-all" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-scope-all" value="all" /> Export all
|
||||
<RadioGroupItem id="export-scope-all" value="all" /> {t("Export all")}
|
||||
</label>
|
||||
<label
|
||||
htmlFor="export-scope-selected"
|
||||
className={cn("flex items-center gap-2 text-sm", selectedIds.size === 0 && "text-muted-foreground")}
|
||||
>
|
||||
<RadioGroupItem id="export-scope-selected" value="selected" disabled={selectedIds.size === 0} />
|
||||
Export the {selectedIds.size} selected items
|
||||
{t("Export the {count} selected items", { count: selectedIds.size })}
|
||||
</label>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs text-muted-foreground">Export format</span>
|
||||
<span className="text-xs text-muted-foreground">{t("Export format")}</span>
|
||||
<RadioGroup value={exportFormat} onValueChange={(v) => setExportFormat(v as typeof exportFormat)}>
|
||||
<label htmlFor="export-format-md-single" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-format-md-single" value="md-single" /> Markdown summary report (a single .md file)
|
||||
<RadioGroupItem id="export-format-md-single" value="md-single" />{" "}
|
||||
{t("Markdown summary report (a single .md file)")}
|
||||
</label>
|
||||
<label htmlFor="export-format-md-zip" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-format-md-zip" value="md-zip" /> Markdown per finding (one .md per vulnerability, packaged as .zip)
|
||||
<RadioGroupItem id="export-format-md-zip" value="md-zip" />{" "}
|
||||
{t("Markdown per finding (one .md per vulnerability, packaged as .zip)")}
|
||||
</label>
|
||||
<label htmlFor="export-format-csv" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-format-csv" value="csv" /> CSV table (.csv)
|
||||
<RadioGroupItem id="export-format-csv" value="csv" /> {t("CSV table (.csv)")}
|
||||
</label>
|
||||
<label htmlFor="export-format-json" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-format-json" value="json" /> JSON (.json)
|
||||
@@ -1472,10 +1482,10 @@ export default function FindingsPage() {
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setExportOpen(false)} disabled={exporting}>
|
||||
Cancel
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={doExport} disabled={exporting || (exportScope === "selected" && selectedIds.size === 0)}>
|
||||
<DownloadIcon /> {exporting ? "Exporting…" : "Export"}
|
||||
<DownloadIcon /> {exporting ? t("Exporting…") : t("Export")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -45,11 +45,12 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { LLMRecordItem, LLMRecordDetail, LLMTask } from "@/lib/types";
|
||||
|
||||
function fmtTime(ts: string) {
|
||||
return new Date(ts).toLocaleString("zh-CN", {
|
||||
return new Date(ts).toLocaleString(intlLocale, {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
@@ -109,7 +110,7 @@ function CopyButton({ text }: { text: string }) {
|
||||
size="icon"
|
||||
className="size-5 shrink-0"
|
||||
disabled={disabled}
|
||||
title={copied ? "Copied" : "Copy content"}
|
||||
title={copied ? t("Copied") : t("Copy content")}
|
||||
onClick={copy}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3 text-emerald-600" /> : <CopyIcon className="size-3" />}
|
||||
@@ -267,7 +268,7 @@ export default function LLMRecordsPage() {
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioIcon className="h-5 w-5 text-muted-foreground" />
|
||||
<h1 className="text-xl font-semibold tracking-tight">LLM recording</h1>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{t("LLM recording")}</h1>
|
||||
<Badge variant="secondary">{total}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
@@ -277,26 +278,26 @@ export default function LLMRecordsPage() {
|
||||
<div className="relative max-w-sm flex-1">
|
||||
<SearchIcon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search Session ID..."
|
||||
placeholder={t("Search Session ID...")}
|
||||
value={session}
|
||||
onChange={(e) => setSession(e.target.value)}
|
||||
className="h-8 pl-8"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
placeholder="Model"
|
||||
placeholder={t("Model")}
|
||||
className="h-8 w-48"
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
/>
|
||||
<Select value={pickedTask} onValueChange={setPickedTask}>
|
||||
<SelectTrigger size="sm" className="w-56">
|
||||
<SelectValue placeholder="Select a task…" />
|
||||
<SelectValue placeholder={t("Select a task…")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{tasks.length === 0 ? (
|
||||
<SelectItem value="__none__" disabled>
|
||||
No task records yet
|
||||
{t("No task records yet")}
|
||||
</SelectItem>
|
||||
) : (
|
||||
tasks.map((t) => (
|
||||
@@ -313,11 +314,11 @@ export default function LLMRecordsPage() {
|
||||
size="sm"
|
||||
className="h-8"
|
||||
disabled={!pickedTask || deleting}
|
||||
title={pickedTask ? undefined : "Select a task above first"}
|
||||
title={pickedTask ? undefined : t("Select a task above first")}
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
Delete task conversations
|
||||
{t("Delete task conversations")}
|
||||
</Button>
|
||||
<Select value={String(size)} onValueChange={(v) => setSize(Number(v))}>
|
||||
<SelectTrigger size="sm" className="w-28">
|
||||
@@ -326,7 +327,7 @@ export default function LLMRecordsPage() {
|
||||
<SelectContent>
|
||||
{PAGE_SIZES.map((n) => (
|
||||
<SelectItem key={n} value={String(n)}>
|
||||
{n} / page
|
||||
{t("{count} / page", { count: n })}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
@@ -348,7 +349,7 @@ export default function LLMRecordsPage() {
|
||||
recEnabled ? "text-foreground" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{recEnabled ? "Recording" : "Off"}
|
||||
{recEnabled ? t("Recording") : t("Off")}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -387,14 +388,14 @@ export default function LLMRecordsPage() {
|
||||
<Table>
|
||||
<TableHeader className="sticky top-0 z-10 bg-card">
|
||||
<TableRow>
|
||||
<TableHead className="w-[130px]">Time</TableHead>
|
||||
<TableHead className="w-[60px]">Task</TableHead>
|
||||
<TableHead className="w-[90px]">Worker</TableHead>
|
||||
<TableHead className="w-[100px]">Profile</TableHead>
|
||||
<TableHead className="w-[140px]">Model</TableHead>
|
||||
<TableHead className="w-[70px]">Latency</TableHead>
|
||||
<TableHead className="w-[90px]">Tokens</TableHead>
|
||||
<TableHead className="w-[60px]">Status</TableHead>
|
||||
<TableHead className="w-[130px]">{t("Time")}</TableHead>
|
||||
<TableHead className="w-[60px]">{t("Task")}</TableHead>
|
||||
<TableHead className="w-[90px]">{t("Worker")}</TableHead>
|
||||
<TableHead className="w-[100px]">{t("Profile")}</TableHead>
|
||||
<TableHead className="w-[140px]">{t("Model")}</TableHead>
|
||||
<TableHead className="w-[70px]">{t("Latency")}</TableHead>
|
||||
<TableHead className="w-[90px]">{t("Tokens")}</TableHead>
|
||||
<TableHead className="w-[60px]">{t("Status")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -408,8 +409,8 @@ export default function LLMRecordsPage() {
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} className="py-12 text-center text-sm text-muted-foreground">
|
||||
{!recKnown || recEnabled
|
||||
? "No LLM call records yet"
|
||||
: "LLM call recording is off. Turn on the Recording toggle above to start capturing calls."}
|
||||
? t("No LLM call records yet")
|
||||
: t("LLM call recording is off. Turn on the Recording toggle above to start capturing calls.")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
@@ -451,9 +452,9 @@ export default function LLMRecordsPage() {
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{rec.status === "ok" ? (
|
||||
<Badge variant="secondary" className="text-xs text-emerald-600">OK</Badge>
|
||||
<Badge variant="secondary" className="text-xs text-emerald-600">{t("OK")}</Badge>
|
||||
) : (
|
||||
<Badge variant="destructive" className="text-xs">Error</Badge>
|
||||
<Badge variant="destructive" className="text-xs">{t("Error")}</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -480,7 +481,7 @@ export default function LLMRecordsPage() {
|
||||
</Badge>
|
||||
{selected.task_id && (
|
||||
<Badge variant="outline" className="text-xs font-mono">
|
||||
Task #{selected.task_id}
|
||||
{t("Task #{id}", { id: selected.task_id })}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
@@ -490,9 +491,9 @@ export default function LLMRecordsPage() {
|
||||
{fmtLatency(selected.latency_ms)}
|
||||
</span>
|
||||
{selected.status === "ok" ? (
|
||||
<Badge variant="secondary" className="text-xs text-emerald-600">OK</Badge>
|
||||
<Badge variant="secondary" className="text-xs text-emerald-600">{t("OK")}</Badge>
|
||||
) : (
|
||||
<Badge variant="destructive" className="text-xs">Error</Badge>
|
||||
<Badge variant="destructive" className="text-xs">{t("Error")}</Badge>
|
||||
)}
|
||||
{/* Raw view toggle. Old records have no raw data; disable it rather than silently
|
||||
falling back, to avoid looking like "raw matches parsed". */}
|
||||
@@ -501,10 +502,14 @@ export default function LLMRecordsPage() {
|
||||
size="sm"
|
||||
className="ml-auto h-7 shrink-0 text-xs"
|
||||
disabled={!hasRaw}
|
||||
title={hasRaw ? "View the raw HTTP actually exchanged with the provider" : "This record was captured before the feature launched; no raw data"}
|
||||
title={
|
||||
hasRaw
|
||||
? t("View the raw HTTP actually exchanged with the provider")
|
||||
: t("This record was captured before the feature launched; no raw data")
|
||||
}
|
||||
onClick={() => setRawView((v) => !v)}
|
||||
>
|
||||
Raw
|
||||
{t("Raw")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -519,39 +524,39 @@ export default function LLMRecordsPage() {
|
||||
<div className="grid min-h-0 flex-1 grid-cols-2 divide-x">
|
||||
<div className="flex min-h-0 min-w-0 flex-col">
|
||||
<div className="flex items-center gap-2 border-b py-0.5 pr-1.5 pl-3 text-[11px] font-medium text-muted-foreground">
|
||||
<span>Request{showRaw && " · raw"}</span>
|
||||
<span>{showRaw ? t("Request · raw") : t("Request")}</span>
|
||||
<CopyButton text={reqText || ""} />
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-auto">
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center gap-2 p-3 text-xs text-muted-foreground">
|
||||
<Loader2Icon className="size-3.5 animate-spin" />
|
||||
Loading…
|
||||
{t("Loading…")}
|
||||
</div>
|
||||
) : (
|
||||
<pre className="p-3 font-mono text-xs break-all whitespace-pre-wrap">
|
||||
{reqText || "(empty)"}
|
||||
{reqText || t("(empty)")}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-h-0 min-w-0 flex-col">
|
||||
<div className="flex items-center gap-2 border-b py-0.5 pr-1.5 pl-3 text-[11px] font-medium text-muted-foreground">
|
||||
<span>Response{showRaw && " · raw (SSE)"}</span>
|
||||
<span>{showRaw ? t("Response · raw (SSE)") : t("Response")}</span>
|
||||
<CopyButton text={respText || ""} />
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-auto">
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center gap-2 p-3 text-xs text-muted-foreground">
|
||||
<Loader2Icon className="size-3.5 animate-spin" />
|
||||
Loading…
|
||||
{t("Loading…")}
|
||||
</div>
|
||||
) : (
|
||||
<pre className={cn(
|
||||
"p-3 font-mono text-xs break-all whitespace-pre-wrap",
|
||||
selected.status !== "ok" && "text-red-600 dark:text-red-400",
|
||||
)}>
|
||||
{respText || "(empty)"}
|
||||
{respText || t("(empty)")}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
@@ -564,13 +569,15 @@ export default function LLMRecordsPage() {
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete all LLM conversations for task "{pickedTask}"?</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t('Delete all LLM conversations for task "{task}"?', { task: pickedTask })}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently delete all LLM call records for this task (including raw requests/responses). This action cannot be undone.
|
||||
{t(
|
||||
"This will permanently delete all LLM call records for this task (including raw requests/responses). This action cannot be undone.",
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -579,7 +586,7 @@ export default function LLMRecordsPage() {
|
||||
disabled={deleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleting ? "Deleting…" : "Confirm delete"}
|
||||
{deleting ? t("Deleting…") : t("Confirm delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -15,6 +15,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { api } from "@/lib/api";
|
||||
import type { SSProject, SSTask } from "@/lib/types";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
type SSStatus = {
|
||||
exists: boolean;
|
||||
@@ -28,17 +29,17 @@ type SSStatus = {
|
||||
type Dimension = "project" | "task";
|
||||
|
||||
const ASSET_TYPES: { key: string; label: string }[] = [
|
||||
{ key: "subdomain", label: "Subdomain" },
|
||||
{ key: "service", label: "Service" },
|
||||
{ key: "app", label: "App" },
|
||||
{ key: "subdomain", label: t("Subdomain") },
|
||||
{ key: "service", label: t("Service") },
|
||||
{ key: "app", label: t("App") },
|
||||
];
|
||||
|
||||
export default function AssetSyncPage() {
|
||||
return (
|
||||
<div className="p-4 md:p-6">
|
||||
<div className="mb-4">
|
||||
<h1 className="font-semibold text-xl">Asset sync</h1>
|
||||
<p className="text-muted-foreground text-sm">Sync assets into the store from external data sources</p>
|
||||
<h1 className="font-semibold text-xl">{t("Asset sync")}</h1>
|
||||
<p className="text-muted-foreground text-sm">{t("Sync assets into the store from external data sources")}</p>
|
||||
</div>
|
||||
<Tabs defaultValue="scopesentry">
|
||||
<TabsList>
|
||||
@@ -61,7 +62,7 @@ function ScopeSentryPanel() {
|
||||
api
|
||||
.ssStatus()
|
||||
.then(setStatus)
|
||||
.catch((e) => toast.error(`Failed to read data source status: ${e.message}`))
|
||||
.catch((e) => toast.error(t("Failed to read data source status: {error}", { error: e.message })))
|
||||
.finally(() => setLoadingStatus(false));
|
||||
}, []);
|
||||
|
||||
@@ -79,7 +80,7 @@ function ScopeSentryPanel() {
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="py-8 text-center text-muted-foreground text-sm">
|
||||
Once the data source is ready, you can pick projects / tasks to sync.
|
||||
{t("Once the data source is ready, you can pick projects / tasks to sync.")}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
@@ -110,25 +111,25 @@ function DataSourceCard({
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.ssDatasource({});
|
||||
toast.success("ScopeSentry data source created; fill in the URL and key");
|
||||
toast.success(t("ScopeSentry data source created; fill in the URL and key"));
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
toast.error(`Create failed: ${(e as Error).message}`);
|
||||
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (!url.trim()) return toast.error("Please enter the MCP URL");
|
||||
if (!url.trim()) return toast.error(t("Please enter the MCP URL"));
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.ssDatasource({ url: url.trim(), api_key: apiKey.trim() });
|
||||
toast.success(r.enabled ? "Data source saved and enabled" : "Saved (enable conditions not yet met)");
|
||||
toast.success(r.enabled ? t("Data source saved and enabled") : t("Saved (enable conditions not yet met)"));
|
||||
setApiKey("");
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
toast.error(`Save failed: ${(e as Error).message}`);
|
||||
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -138,32 +139,34 @@ function DataSourceCard({
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<PlugZapIcon className="size-4" /> Data source status
|
||||
<PlugZapIcon className="size-4" /> {t("Data source status")}
|
||||
<StatusBadge status={status} loading={loading} />
|
||||
</CardTitle>
|
||||
<Button variant="ghost" size="sm" onClick={onChanged} disabled={loading}>
|
||||
<RefreshCwIcon className={loading ? "size-4 animate-spin" : "size-4"} /> Refresh
|
||||
<RefreshCwIcon className={loading ? "size-4 animate-spin" : "size-4"} /> {t("Refresh")}
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{!status?.exists ? (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No ScopeSentry data source yet. Creating one adds a placeholder MCP (empty URL/key, disabled).
|
||||
{t("No ScopeSentry data source yet. Creating one adds a placeholder MCP (empty URL/key, disabled).")}
|
||||
</p>
|
||||
<Button onClick={create} disabled={busy}>
|
||||
Create data source
|
||||
{t("Create data source")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{!status.configured && (
|
||||
<p className="text-amber-600 text-sm dark:text-amber-500">
|
||||
The data source is created but not configured; fill in the MCP URL and API key, then enable it.
|
||||
{t("The data source is created but not configured; fill in the MCP URL and API key, then enable it.")}
|
||||
</p>
|
||||
)}
|
||||
{status.configured && !status.enabled && (
|
||||
<p className="text-amber-600 text-sm dark:text-amber-500">The data source is configured but not enabled; it will be enabled automatically on save.</p>
|
||||
<p className="text-amber-600 text-sm dark:text-amber-500">
|
||||
{t("The data source is configured but not enabled; it will be enabled automatically on save.")}
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
@@ -171,7 +174,7 @@ function DataSourceCard({
|
||||
<Input placeholder="http://<host>:8082/mcp" value={url} onChange={(e) => setUrl(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>API Key (X-API-Key; leave empty to keep the current value)</Label>
|
||||
<Label>{t("API Key (X-API-Key; leave empty to keep the current value)")}</Label>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="ssk_..."
|
||||
@@ -182,10 +185,12 @@ function DataSourceCard({
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button onClick={save} disabled={busy}>
|
||||
Save & enable
|
||||
{t("Save & enable")}
|
||||
</Button>
|
||||
{status.enabled && status.tools.length > 0 && (
|
||||
<span className="text-muted-foreground text-xs">{status.tools.length} tools discovered</span>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{t("{count} tools discovered", { count: status.tools.length })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
@@ -196,19 +201,19 @@ function DataSourceCard({
|
||||
}
|
||||
|
||||
function StatusBadge({ status, loading }: { status: SSStatus | null; loading: boolean }) {
|
||||
if (loading || !status) return <Badge variant="secondary">Checking…</Badge>;
|
||||
if (!status.exists) return <Badge variant="destructive">Not created</Badge>;
|
||||
if (!status.configured) return <Badge variant="outline">Not configured</Badge>;
|
||||
if (!status.enabled) return <Badge variant="outline">Not enabled</Badge>;
|
||||
if (loading || !status) return <Badge variant="secondary">{t("Checking…")}</Badge>;
|
||||
if (!status.exists) return <Badge variant="destructive">{t("Not created")}</Badge>;
|
||||
if (!status.configured) return <Badge variant="outline">{t("Not configured")}</Badge>;
|
||||
if (!status.enabled) return <Badge variant="outline">{t("Not enabled")}</Badge>;
|
||||
if (status.reachable)
|
||||
return (
|
||||
<Badge className="bg-emerald-600 hover:bg-emerald-600">
|
||||
<CheckCircle2Icon className="mr-1 size-3" /> Connected
|
||||
<CheckCircle2Icon className="mr-1 size-3" /> {t("Connected")}
|
||||
</Badge>
|
||||
);
|
||||
return (
|
||||
<Badge variant="destructive">
|
||||
<AlertCircleIcon className="mr-1 size-3" /> Unreachable
|
||||
<AlertCircleIcon className="mr-1 size-3" /> {t("Unreachable")}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -241,7 +246,9 @@ function SyncWorkbench() {
|
||||
dimension === "project"
|
||||
? api.ssProjects(page, 50, search).then((r) => setProjects(r.projects))
|
||||
: api.ssTasks(page, 50, search).then(setTasks);
|
||||
fn.catch((e) => toast.error(`Failed to load the list: ${e.message}`)).finally(() => setLoading(false));
|
||||
fn.catch((e) => toast.error(t("Failed to load the list: {error}", { error: e.message }))).finally(() =>
|
||||
setLoading(false),
|
||||
);
|
||||
}, [dimension, page, search]);
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -266,8 +273,9 @@ function SyncWorkbench() {
|
||||
const chosenTypes = ASSET_TYPES.filter((t) => assetTypes[t.key]).map((t) => t.key);
|
||||
|
||||
const runSync = async () => {
|
||||
if (selected.size === 0) return toast.error(`Select at least one ${dimension === "project" ? "project" : "task"}`);
|
||||
if (chosenTypes.length === 0) return toast.error("Select at least one asset type");
|
||||
if (selected.size === 0)
|
||||
return toast.error(dimension === "project" ? t("Select at least one project") : t("Select at least one task"));
|
||||
if (chosenTypes.length === 0) return toast.error(t("Select at least one asset type"));
|
||||
setSyncing(true);
|
||||
setResult(null);
|
||||
try {
|
||||
@@ -279,9 +287,9 @@ function SyncWorkbench() {
|
||||
});
|
||||
setResult(r);
|
||||
const total = Object.values(r.synced ?? {}).reduce((a, b) => a + b, 0);
|
||||
toast.success(`Sync finished; ${total} assets ingested in total`);
|
||||
toast.success(t("Sync finished; {count} assets ingested in total", { count: total }));
|
||||
} catch (e) {
|
||||
toast.error(`Sync failed: ${(e as Error).message}`);
|
||||
toast.error(t("Sync failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
}
|
||||
@@ -292,7 +300,7 @@ function SyncWorkbench() {
|
||||
return (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="py-8 text-center text-muted-foreground text-sm">
|
||||
Loading…
|
||||
{t("Loading…")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
@@ -301,7 +309,7 @@ function SyncWorkbench() {
|
||||
return (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="py-8 text-center text-muted-foreground text-sm">
|
||||
No data
|
||||
{t("No data")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
@@ -337,7 +345,7 @@ function SyncWorkbench() {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Pick data to sync</CardTitle>
|
||||
<CardTitle className="text-base">{t("Pick data to sync")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Dimension switch */}
|
||||
@@ -349,14 +357,14 @@ function SyncWorkbench() {
|
||||
}}
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="project">By project</TabsTrigger>
|
||||
<TabsTrigger value="task">By task</TabsTrigger>
|
||||
<TabsTrigger value="project">{t("By project")}</TabsTrigger>
|
||||
<TabsTrigger value="task">{t("By task")}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
{/* Asset types + options */}
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<span className="font-medium text-sm">Assets to sync:</span>
|
||||
<span className="font-medium text-sm">{t("Assets to sync:")}</span>
|
||||
{ASSET_TYPES.map((t) => (
|
||||
<label key={t.key} htmlFor={`at-${t.key}`} className="flex items-center gap-1.5 text-sm">
|
||||
<Checkbox
|
||||
@@ -370,7 +378,7 @@ function SyncWorkbench() {
|
||||
{dimension === "project" && (
|
||||
<label htmlFor="create-company" className="flex items-center gap-1.5 text-sm">
|
||||
<Checkbox id="create-company" checked={createCompany} onCheckedChange={(c) => setCreateCompany(!!c)} />
|
||||
Create a company per project and write its asset scope
|
||||
{t("Create a company per project and write its asset scope")}
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
@@ -381,7 +389,7 @@ function SyncWorkbench() {
|
||||
<SearchIcon className="absolute top-1/2 left-2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
className="pl-8"
|
||||
placeholder={dimension === "project" ? "Search project names" : "Search task names"}
|
||||
placeholder={dimension === "project" ? t("Search project names") : t("Search task names")}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
@@ -396,9 +404,9 @@ function SyncWorkbench() {
|
||||
<RefreshCwIcon className={loading ? "size-4 animate-spin" : "size-4"} />
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
<span className="text-muted-foreground text-xs">{selected.size} selected</span>
|
||||
<span className="text-muted-foreground text-xs">{t("{count} selected", { count: selected.size })}</span>
|
||||
<Button onClick={runSync} disabled={syncing || selected.size === 0}>
|
||||
<DownloadIcon className={syncing ? "size-4 animate-pulse" : "size-4"} /> Sync selected
|
||||
<DownloadIcon className={syncing ? "size-4 animate-pulse" : "size-4"} /> {t("Sync selected")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -410,16 +418,16 @@ function SyncWorkbench() {
|
||||
<TableHead className="w-10">
|
||||
<Checkbox checked={rows.length > 0 && selected.size === rows.length} onCheckedChange={toggleAll} />
|
||||
</TableHead>
|
||||
<TableHead>{dimension === "project" ? "Project name" : "Task name"}</TableHead>
|
||||
<TableHead>{dimension === "project" ? t("Project name") : t("Task name")}</TableHead>
|
||||
{dimension === "project" ? (
|
||||
<>
|
||||
<TableHead>Tag</TableHead>
|
||||
<TableHead className="text-right">Assets</TableHead>
|
||||
<TableHead>{t("Tag")}</TableHead>
|
||||
<TableHead className="text-right">{t("Assets")}</TableHead>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Time</TableHead>
|
||||
<TableHead>{t("Status")}</TableHead>
|
||||
<TableHead>{t("Time")}</TableHead>
|
||||
</>
|
||||
)}
|
||||
</TableRow>
|
||||
@@ -431,16 +439,16 @@ function SyncWorkbench() {
|
||||
{/* Pagination */}
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button variant="outline" size="sm" disabled={page <= 1 || loading} onClick={() => setPage((p) => p - 1)}>
|
||||
Previous
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
<span className="text-muted-foreground text-xs">Page {page}</span>
|
||||
<span className="text-muted-foreground text-xs">{t("Page {page}", { page })}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={rows.length < 50 || loading}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
Next
|
||||
{t("Next")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -453,7 +461,7 @@ function SyncWorkbench() {
|
||||
|
||||
function SyncResult({ result }: { result: Awaited<ReturnType<typeof api.ssSync>> }) {
|
||||
const synced = result.synced ?? {};
|
||||
const labels: Record<string, string> = { subdomain: "Subdomain", service: "Service", app: "App", ip: "IP" };
|
||||
const labels: Record<string, string> = { subdomain: t("Subdomain"), service: t("Service"), app: t("App"), ip: "IP" };
|
||||
return (
|
||||
<div className="space-y-2 rounded-md border bg-muted/40 p-3 text-sm">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
@@ -464,7 +472,9 @@ function SyncResult({ result }: { result: Awaited<ReturnType<typeof api.ssSync>>
|
||||
))}
|
||||
</div>
|
||||
{result.companies && result.companies.length > 0 && (
|
||||
<p className="text-muted-foreground">Companies created/updated: {result.companies.join(", ")}</p>
|
||||
<p className="text-muted-foreground">
|
||||
{t("Companies created/updated: {names}", { names: result.companies.join(", ") })}
|
||||
</p>
|
||||
)}
|
||||
{result.warnings && result.warnings.length > 0 && (
|
||||
<ul className="list-inside list-disc text-amber-600 dark:text-amber-500">
|
||||
@@ -478,7 +488,7 @@ function SyncResult({ result }: { result: Awaited<ReturnType<typeof api.ssSync>>
|
||||
{result.errors.slice(0, 20).map((em) => (
|
||||
<li key={em}>{em}</li>
|
||||
))}
|
||||
{result.errors.length > 20 && <li>… {result.errors.length} errors in total</li>}
|
||||
{result.errors.length > 20 && <li>{t("… {count} errors in total", { count: result.errors.length })}</li>}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -44,6 +44,7 @@ import { taskAssetSourceLabel } from "@/lib/task-assets";
|
||||
import type { Asset, NewAssetType } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
const PAGE_SIZES = [25, 50, 100, 200];
|
||||
|
||||
@@ -58,12 +59,12 @@ const METHOD_COLOR: Record<string, string> = {
|
||||
};
|
||||
|
||||
const TABS: { key: NewAssetType; label: string; icon: LucideIcon }[] = [
|
||||
{ key: "root_domain", label: "Root domain", icon: GlobeIcon },
|
||||
{ key: "root_domain", label: t("Root domain"), icon: GlobeIcon },
|
||||
{ key: "ip", label: "IP", icon: NetworkIcon },
|
||||
{ key: "subdomain", label: "Subdomain", icon: GlobeIcon },
|
||||
{ key: "app", label: "App", icon: SmartphoneIcon },
|
||||
{ key: "service", label: "Service", icon: LayoutTemplateIcon },
|
||||
{ key: "endpoint", label: "Endpoint", icon: LinkIcon },
|
||||
{ key: "subdomain", label: t("Subdomain"), icon: GlobeIcon },
|
||||
{ key: "app", label: t("App"), icon: SmartphoneIcon },
|
||||
{ key: "service", label: t("Service"), icon: LayoutTemplateIcon },
|
||||
{ key: "endpoint", label: t("Endpoint"), icon: LinkIcon },
|
||||
];
|
||||
|
||||
function firstText(values: Array<string | undefined>, fallback: string): string {
|
||||
@@ -134,7 +135,10 @@ function Chips({ items, mono }: { items: string[]; mono?: boolean }) {
|
||||
|
||||
function SourceCell({ asset }: { asset: Asset }) {
|
||||
const source = firstText([asset.task_source], "legacy");
|
||||
const summary = firstText([asset.task_source_summary], "Migrated from a historical task's asset association; no more detailed source information");
|
||||
const summary = firstText(
|
||||
[asset.task_source_summary],
|
||||
t("Migrated from a historical task's asset association; no more detailed source information"),
|
||||
);
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
@@ -147,7 +151,7 @@ function SourceCell({ asset }: { asset: Asset }) {
|
||||
<span className="font-medium">{taskAssetSourceLabel(source)}</span>
|
||||
<span className="[overflow-wrap:anywhere]">{summary}</span>
|
||||
{asset.task_source_node_id ? (
|
||||
<span className="font-mono opacity-80">Source node #{asset.task_source_node_id}</span>
|
||||
<span className="font-mono opacity-80">{t("Source node #{id}", { id: asset.task_source_node_id })}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
@@ -193,7 +197,7 @@ function AssetCard({
|
||||
tableRows = (
|
||||
<TableRow>
|
||||
<TableCell colSpan={cols.length} className="py-10 text-center text-muted-foreground text-sm">
|
||||
No test assets in this category yet
|
||||
{t("No test assets in this category yet")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
@@ -228,7 +232,7 @@ function AssetCard({
|
||||
<SelectGroup>
|
||||
{PAGE_SIZES.map((value) => (
|
||||
<SelectItem key={value} value={String(value)}>
|
||||
{value} / page
|
||||
{t("{count} / page", { count: value })}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
@@ -244,7 +248,7 @@ function AssetCard({
|
||||
size="icon-sm"
|
||||
disabled={page <= 0}
|
||||
onClick={() => onPage(Math.max(0, page - 1))}
|
||||
aria-label="Previous page"
|
||||
aria-label={t("Previous page")}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
@@ -256,7 +260,7 @@ function AssetCard({
|
||||
size="icon-sm"
|
||||
disabled={page + 1 >= pageCount}
|
||||
onClick={() => onPage(Math.min(pageCount - 1, page + 1))}
|
||||
aria-label="Next page"
|
||||
aria-label={t("Next page")}
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
@@ -294,11 +298,16 @@ function AddTaskAssetsSheet({
|
||||
try {
|
||||
const result = await api.registerTaskAssetScopes(taskId, parsedScope.rules);
|
||||
const assetSummary = result.assets_linked + result.assets_existing;
|
||||
toast.success(`Registered ${result.requested} scopes, linked ${assetSummary} domain/IP assets`);
|
||||
toast.success(
|
||||
t("Registered {scopes} scopes, linked {assets} domain/IP assets", {
|
||||
scopes: result.requested,
|
||||
assets: assetSummary,
|
||||
}),
|
||||
);
|
||||
onAttached();
|
||||
onOpenChange(false);
|
||||
} catch (reason) {
|
||||
toast.error(`Failed to add: ${String((reason as Error)?.message ?? reason)}`);
|
||||
toast.error(t("Failed to add: {error}", { error: String((reason as Error)?.message ?? reason) }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -308,9 +317,11 @@ function AddTaskAssetsSheet({
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent className="w-full sm:max-w-xl">
|
||||
<SheetHeader>
|
||||
<SheetTitle>Add test assets</SheetTitle>
|
||||
<SheetTitle>{t("Add test assets")}</SheetTitle>
|
||||
<SheetDescription>
|
||||
Enter the test scope directly. Domains and IPs create or reuse global assets; CIDRs, ICP records, and keywords act as agent scope context.
|
||||
{t(
|
||||
"Enter the test scope directly. Domains and IPs create or reuse global assets; CIDRs, ICP records, and keywords act as agent scope context.",
|
||||
)}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-4">
|
||||
@@ -319,20 +330,24 @@ function AddTaskAssetsSheet({
|
||||
value={scopeText}
|
||||
onValueChange={setScopeText}
|
||||
parsed={parsedScope}
|
||||
label="Test assets and scope"
|
||||
description="One entry per line; domains, IPs, CIDRs, ICP records, and keywords are recognized automatically."
|
||||
label={t("Test assets and scope")}
|
||||
description={t(
|
||||
"One entry per line; domains, IPs, CIDRs, ICP records, and keywords are recognized automatically.",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
|
||||
Cancel
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => void attach()}
|
||||
disabled={saving || parsedScope.rules.length === 0 || parsedScope.errors.length > 0}
|
||||
>
|
||||
{saving ? <Spinner data-icon="inline-start" /> : <PlusIcon data-icon="inline-start" />}
|
||||
Register {parsedScope.rules.length > 0 ? parsedScope.rules.length : ""} entries
|
||||
{parsedScope.rules.length > 0
|
||||
? t("Register {count} entries", { count: parsedScope.rules.length })
|
||||
: t("Register entries")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
@@ -405,7 +420,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
setRows([]);
|
||||
setTotal(0);
|
||||
} else {
|
||||
toast.error(`Failed to load task assets: ${message}`);
|
||||
toast.error(t("Failed to load task assets: {error}", { error: message }));
|
||||
}
|
||||
} finally {
|
||||
if (active && assetsRequestRef.current === request) {
|
||||
@@ -439,11 +454,11 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
setRemoving(true);
|
||||
try {
|
||||
await api.detachTaskAsset(taskId, removeTarget.id);
|
||||
toast.success(`Removed ${assetLabel(removeTarget)} from the current task`);
|
||||
toast.success(t("Removed {label} from the current task", { label: assetLabel(removeTarget) }));
|
||||
setRemoveTarget(null);
|
||||
refresh();
|
||||
} catch (reason) {
|
||||
toast.error(`Failed to remove: ${String((reason as Error)?.message ?? reason)}`);
|
||||
toast.error(t("Failed to remove: {error}", { error: String((reason as Error)?.message ?? reason) }));
|
||||
} finally {
|
||||
setRemoving(false);
|
||||
}
|
||||
@@ -454,8 +469,8 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setRemoveTarget(asset)}
|
||||
aria-label={`Remove asset ${assetLabel(asset)} from the task`}
|
||||
title="Remove from task"
|
||||
aria-label={t("Remove asset {label} from the task", { label: assetLabel(asset) })}
|
||||
title={t("Remove from task")}
|
||||
>
|
||||
<Trash2Icon />
|
||||
</Button>
|
||||
@@ -478,12 +493,14 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h2 className="font-medium text-sm">Test assets</h2>
|
||||
<p className="text-muted-foreground text-xs">This task is linked to {totalAll} assets in total</p>
|
||||
<h2 className="font-medium text-sm">{t("Test assets")}</h2>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("This task is linked to {count} assets in total", { count: totalAll })}
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => setAddOpen(true)}>
|
||||
<PlusIcon data-icon="inline-start" />
|
||||
Add test assets
|
||||
{t("Add test assets")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -507,7 +524,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
{searchBox}
|
||||
|
||||
<TabsContent value="root_domain" className="mt-0 flex min-h-0 flex-1 flex-col">
|
||||
<AssetCard cols={["Domain", "ICP record", "Source", "Actions"]} {...commonCardProps}>
|
||||
<AssetCard cols={[t("Domain"), t("ICP record"), t("Source"), t("Actions")]} {...commonCardProps}>
|
||||
{rows.map((asset) => (
|
||||
<TableRow key={asset.id}>
|
||||
<TableCell className="font-medium font-mono text-xs">{asset.domain}</TableCell>
|
||||
@@ -522,7 +539,10 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="ip" className="mt-0 flex min-h-0 flex-1 flex-col">
|
||||
<AssetCard cols={["IP", "C segment", "Bound domains", "Open ports", "Source", "Actions"]} {...commonCardProps}>
|
||||
<AssetCard
|
||||
cols={["IP", t("C segment"), t("Bound domains"), t("Open ports"), t("Source"), t("Actions")]}
|
||||
{...commonCardProps}
|
||||
>
|
||||
{rows.map((asset) => (
|
||||
<TableRow key={asset.id}>
|
||||
<TableCell className="font-medium font-mono text-xs">{asset.ip}</TableCell>
|
||||
@@ -548,7 +568,10 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="subdomain" className="mt-0 flex min-h-0 flex-1 flex-col">
|
||||
<AssetCard cols={["Domain", "Root domain", "Record type", "Record value", "Source", "Actions"]} {...commonCardProps}>
|
||||
<AssetCard
|
||||
cols={[t("Domain"), t("Root domain"), t("Record type"), t("Record value"), t("Source"), t("Actions")]}
|
||||
{...commonCardProps}
|
||||
>
|
||||
{rows.map((asset) => (
|
||||
<TableRow key={asset.id}>
|
||||
<TableCell className="font-medium font-mono text-xs">{asset.domain}</TableCell>
|
||||
@@ -567,7 +590,10 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="app" className="mt-0 flex min-h-0 flex-1 flex-col">
|
||||
<AssetCard cols={["App", "Address", "Category", "Title", "Fingerprints", "Source", "Actions"]} {...commonCardProps}>
|
||||
<AssetCard
|
||||
cols={[t("App"), t("Address"), t("Category"), t("Title"), t("Fingerprints"), t("Source"), t("Actions")]}
|
||||
{...commonCardProps}
|
||||
>
|
||||
{rows.map((asset) => (
|
||||
<TableRow key={asset.id}>
|
||||
<TableCell className="max-w-48 truncate font-medium text-xs">{asset.app_name || "—"}</TableCell>
|
||||
@@ -590,7 +616,16 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
|
||||
<TabsContent value="service" className="mt-0 flex min-h-0 flex-1 flex-col">
|
||||
<AssetCard
|
||||
cols={["Address / service", "Status code", "Title", "Response size", "Fingerprints", "Auth", "Source", "Actions"]}
|
||||
cols={[
|
||||
t("Address / service"),
|
||||
t("Status code"),
|
||||
t("Title"),
|
||||
t("Response size"),
|
||||
t("Fingerprints"),
|
||||
t("Auth"),
|
||||
t("Source"),
|
||||
t("Actions"),
|
||||
]}
|
||||
{...commonCardProps}
|
||||
>
|
||||
{rows.map((asset) => {
|
||||
@@ -631,7 +666,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
className="inline-flex items-center gap-1 text-[11px]"
|
||||
>
|
||||
<KeyRoundIcon className="size-3 text-muted-foreground" />
|
||||
<span className="font-mono">{item.type || item.username || "Auth"}</span>
|
||||
<span className="font-mono">{item.type || item.username || t("Auth")}</span>
|
||||
</span>
|
||||
);
|
||||
})
|
||||
@@ -648,7 +683,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="endpoint" className="mt-0 flex min-h-0 flex-1 flex-col">
|
||||
<AssetCard cols={["Method", "Full URL", "Params", "Source", "Actions"]} {...commonCardProps}>
|
||||
<AssetCard cols={[t("Method"), t("Full URL"), t("Params"), t("Source"), t("Actions")]} {...commonCardProps}>
|
||||
{rows.map((asset) => (
|
||||
<TableRow key={asset.id}>
|
||||
<TableCell className="w-16">
|
||||
@@ -681,14 +716,16 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
<AlertDialog open={Boolean(removeTarget)} onOpenChange={(open) => !open && !removing && setRemoveTarget(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove from this task?</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("Remove from this task?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription className="[overflow-wrap:anywhere]">
|
||||
{removeTarget ? `Remove "${assetLabel(removeTarget)}" from this task's test assets.` : ""}
|
||||
Global assets, linked traffic, and historical blackboard anchors are kept.
|
||||
{removeTarget
|
||||
? `${t('Remove "{label}" from this task\'s test assets.', { label: assetLabel(removeTarget) })} `
|
||||
: ""}
|
||||
{t("Global assets, linked traffic, and historical blackboard anchors are kept.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={removing}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={removing}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
disabled={removing}
|
||||
@@ -698,7 +735,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
|
||||
}}
|
||||
>
|
||||
{removing ? <Spinner data-icon="inline-start" /> : <Trash2Icon data-icon="inline-start" />}
|
||||
{removing ? "Removing" : "Remove"}
|
||||
{removing ? t("Removing") : t("Remove")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -34,6 +34,7 @@ import { taskAssetTypeLabel } from "@/lib/task-assets";
|
||||
import type { Edge, ExploreKind, FindingAsset, NewAssetType, TaskNode } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
|
||||
const PAGE_SIZES = [20, 50, 100];
|
||||
const POLL_MS = 8000;
|
||||
@@ -44,49 +45,49 @@ type KindMeta = { label: string; icon: LucideIcon; dot: string; chip: string };
|
||||
// the broadcast a stream view (timeline rows); the two differ in information density and color needs, so they evolve separately.
|
||||
const KIND_META: Record<string, KindMeta> = {
|
||||
begin: {
|
||||
label: "Start",
|
||||
label: t("Start"),
|
||||
icon: FlagIcon,
|
||||
dot: "bg-slate-500",
|
||||
chip: "bg-slate-500/15 text-slate-600 dark:text-slate-300",
|
||||
},
|
||||
task: {
|
||||
label: "Root task",
|
||||
label: t("Root task"),
|
||||
icon: FlagIcon,
|
||||
dot: "bg-slate-500",
|
||||
chip: "bg-slate-500/15 text-slate-600 dark:text-slate-300",
|
||||
},
|
||||
goal: {
|
||||
label: "Goal",
|
||||
label: t("Goal"),
|
||||
icon: TargetIcon,
|
||||
dot: "bg-emerald-500",
|
||||
chip: "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",
|
||||
},
|
||||
intent: {
|
||||
label: "Intent",
|
||||
label: t("Intent"),
|
||||
icon: CompassIcon,
|
||||
dot: "bg-blue-500",
|
||||
chip: "bg-blue-500/15 text-blue-600 dark:text-blue-400",
|
||||
},
|
||||
fact: {
|
||||
label: "Fact",
|
||||
label: t("Fact"),
|
||||
icon: FlaskConicalIcon,
|
||||
dot: "bg-amber-500",
|
||||
chip: "bg-amber-500/15 text-amber-600 dark:text-amber-400",
|
||||
},
|
||||
finding: {
|
||||
label: "Vulnerability",
|
||||
label: t("Vulnerability"),
|
||||
icon: BugIcon,
|
||||
dot: "bg-rose-500",
|
||||
chip: "bg-rose-500/15 text-rose-600 dark:text-rose-400",
|
||||
},
|
||||
hint: {
|
||||
label: "Hint",
|
||||
label: t("Hint"),
|
||||
icon: LightbulbIcon,
|
||||
dot: "bg-violet-500",
|
||||
chip: "bg-violet-500/15 text-violet-600 dark:text-violet-400",
|
||||
},
|
||||
digest: {
|
||||
label: "Digest",
|
||||
label: t("Digest"),
|
||||
icon: LayersIcon,
|
||||
dot: "bg-teal-500",
|
||||
chip: "bg-teal-500/15 text-teal-600 dark:text-teal-400",
|
||||
@@ -97,32 +98,32 @@ const KIND_META: Record<string, KindMeta> = {
|
||||
const FILTER_KINDS: ExploreKind[] = ["goal", "intent", "fact", "finding", "hint", "digest"];
|
||||
|
||||
const REL_LABEL: Record<string, string> = {
|
||||
spawns: "Spawns",
|
||||
derived_from: "Intent chain",
|
||||
yields: "Yields",
|
||||
proves: "Proves",
|
||||
covers: "Compresses",
|
||||
spawns: t("Spawns"),
|
||||
derived_from: t("Intent chain"),
|
||||
yields: t("Yields"),
|
||||
proves: t("Proves"),
|
||||
covers: t("Compresses"),
|
||||
};
|
||||
|
||||
// State semantics for goal / intent come from the global status table (StatusBadge); the other kinds' states only
|
||||
// appear in the graph and broadcast, so they are defined here.
|
||||
const STATE_META: Record<string, Record<string, { label: string; tone: Tone }>> = {
|
||||
fact: {
|
||||
origin: { label: "Start", tone: "slate" },
|
||||
confirmed: { label: "Confirmed", tone: "green" },
|
||||
dismissed: { label: "Dismissed", tone: "slate" },
|
||||
origin: { label: t("Start"), tone: "slate" },
|
||||
confirmed: { label: t("Confirmed"), tone: "green" },
|
||||
dismissed: { label: t("Dismissed"), tone: "slate" },
|
||||
},
|
||||
finding: {
|
||||
confirmed: { label: "Confirmed", tone: "red" },
|
||||
dismissed: { label: "Excluded", tone: "slate" },
|
||||
confirmed: { label: t("Confirmed"), tone: "red" },
|
||||
dismissed: { label: t("Excluded"), tone: "slate" },
|
||||
},
|
||||
hint: {
|
||||
active: { label: "Pending adoption", tone: "violet" },
|
||||
consumed: { label: "Adopted", tone: "slate" },
|
||||
active: { label: t("Pending adoption"), tone: "violet" },
|
||||
consumed: { label: t("Adopted"), tone: "slate" },
|
||||
},
|
||||
digest: {
|
||||
active: { label: "Active", tone: "green" },
|
||||
superseded: { label: "Superseded", tone: "slate" },
|
||||
active: { label: t("Active"), tone: "green" },
|
||||
superseded: { label: t("Superseded"), tone: "slate" },
|
||||
},
|
||||
};
|
||||
|
||||
@@ -160,7 +161,7 @@ function summaryOf(n: TaskNode): string {
|
||||
}
|
||||
|
||||
function prettyPayload(raw?: string): string {
|
||||
if (!raw?.trim()) return "(no payload)";
|
||||
if (!raw?.trim()) return t("(no payload)");
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(raw), null, 2);
|
||||
} catch {
|
||||
@@ -171,14 +172,14 @@ function prettyPayload(raw?: string): string {
|
||||
function relTime(ts: number, now: number): string {
|
||||
if (!now || !ts) return "";
|
||||
const sec = Math.max(0, (now - ts) / 1000);
|
||||
if (sec < 60) return "just now";
|
||||
if (sec < 3600) return `${Math.floor(sec / 60)} minutes ago`;
|
||||
if (sec < 86400) return `${Math.floor(sec / 3600)} hours ago`;
|
||||
return `${Math.floor(sec / 86400)} days ago`;
|
||||
if (sec < 60) return t("just now");
|
||||
if (sec < 3600) return t("{count} minutes ago", { count: Math.floor(sec / 60) });
|
||||
if (sec < 86400) return t("{count} hours ago", { count: Math.floor(sec / 3600) });
|
||||
return t("{count} days ago", { count: Math.floor(sec / 86400) });
|
||||
}
|
||||
|
||||
const dayFmt = new Intl.DateTimeFormat("zh-CN", { month: "long", day: "numeric", weekday: "short" });
|
||||
const clockFmt = new Intl.DateTimeFormat("zh-CN", {
|
||||
const dayFmt = new Intl.DateTimeFormat(intlLocale, { month: "long", day: "numeric", weekday: "short" });
|
||||
const clockFmt = new Intl.DateTimeFormat(intlLocale, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
@@ -216,7 +217,9 @@ function AssetList({ assets, dense = false }: { assets: FindingAsset[]; dense?:
|
||||
if (assets.length === 0) return null;
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-1.5 text-xs font-medium text-muted-foreground">Assets involved · {assets.length}</div>
|
||||
<div className="mb-1.5 text-xs font-medium text-muted-foreground">
|
||||
{t("Assets involved · {count}", { count: assets.length })}
|
||||
</div>
|
||||
<ul className="flex flex-wrap gap-1.5">
|
||||
{assets.map((a) => {
|
||||
// At runtime a.type may be a kind not covered by the label table; fall back to the raw string. The type cast keeps the fallback from being flagged as redundant.
|
||||
@@ -259,11 +262,11 @@ function RelatedNodeCard({ node, assets }: { node: TaskNode; assets: FindingAsse
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
|
||||
<span>Type {meta.label}</span>
|
||||
<span>Source {node.origin || "system"}</span>
|
||||
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString("zh-CN")}</span>
|
||||
<span>{t("Type {type}", { type: meta.label })}</span>
|
||||
<span>{t("Source {source}", { source: node.origin || "system" })}</span>
|
||||
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString(intlLocale)}</span>
|
||||
</div>
|
||||
<p className="line-clamp-4 text-xs break-words">{summary || "(no summary)"}</p>
|
||||
<p className="line-clamp-4 text-xs break-words">{summary || t("(no summary)")}</p>
|
||||
<AssetList assets={assets} dense />
|
||||
<pre className="max-h-40 overflow-auto rounded border bg-muted/40 p-2 font-mono text-[11px] whitespace-pre-wrap">
|
||||
{prettyPayload(node.payload)}
|
||||
@@ -304,7 +307,7 @@ function RelatedList({
|
||||
className="flex min-w-0 cursor-help items-center gap-2 text-left hover:underline"
|
||||
>
|
||||
<KindChip kind={viewKind(node)} />
|
||||
<span className="truncate">{summaryOf(node) || `Node #${node.id}`}</span>
|
||||
<span className="truncate">{summaryOf(node) || t("Node #{id}", { id: node.id })}</span>
|
||||
</button>
|
||||
</HoverCardTrigger>
|
||||
<HoverCardContent align="start" className="w-96">
|
||||
@@ -312,7 +315,7 @@ function RelatedList({
|
||||
</HoverCardContent>
|
||||
</HoverCard>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Node #{row.id}</span>
|
||||
<span className="text-muted-foreground">{t("Node #{id}", { id: row.id })}</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
@@ -387,12 +390,12 @@ function BroadcastRow({
|
||||
)}
|
||||
{fresh && (
|
||||
<span className="rounded bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground">
|
||||
New
|
||||
{t("New")}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto shrink-0 text-xs text-muted-foreground">{node.origin || "system"}</span>
|
||||
</div>
|
||||
<p className={cn("mt-1 text-sm", !open && "line-clamp-2")}>{summary || `Node #${node.id}`}</p>
|
||||
<p className={cn("mt-1 text-sm", !open && "line-clamp-2")}>{summary || t("Node #{id}", { id: node.id })}</p>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
@@ -400,23 +403,23 @@ function BroadcastRow({
|
||||
<div className="mt-2 ml-5 flex flex-col gap-3 rounded-md border bg-muted/30 p-3">
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
<span>
|
||||
Node <code className="font-mono">#{node.id}</code>
|
||||
{t("Node")} <code className="font-mono">#{node.id}</code>
|
||||
</span>
|
||||
<span>Type {meta.label}</span>
|
||||
<span>Source {node.origin || "system"}</span>
|
||||
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString("zh-CN")}</span>
|
||||
<span>{t("Type {type}", { type: meta.label })}</span>
|
||||
<span>{t("Source {source}", { source: node.origin || "system" })}</span>
|
||||
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString(intlLocale)}</span>
|
||||
</div>
|
||||
{node.state === "deleted" && node.delete_reason && (
|
||||
<div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs">
|
||||
<span className="font-medium text-destructive">Deletion reason</span>
|
||||
<span className="font-medium text-destructive">{t("Deletion reason")}</span>
|
||||
<span className="ml-2 break-words text-muted-foreground">{node.delete_reason}</span>
|
||||
</div>
|
||||
)}
|
||||
<AssetList assets={assets[node.id] ?? []} />
|
||||
{(upstream.length > 0 || downstream.length > 0) && (
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<RelatedList title="Upstream · comes from these" rows={upstream} refs={refs} assets={assets} />
|
||||
<RelatedList title="Downstream · produced by this" rows={downstream} refs={refs} assets={assets} />
|
||||
<RelatedList title={t("Upstream · comes from these")} rows={upstream} refs={refs} assets={assets} />
|
||||
<RelatedList title={t("Downstream · produced by this")} rows={downstream} refs={refs} assets={assets} />
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
@@ -559,7 +562,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
const groups: Array<{ day: string; rows: TaskNode[] }> = [];
|
||||
for (const node of items) {
|
||||
const ts = Date.parse(node.ts);
|
||||
const day = Number.isNaN(ts) ? "Unknown date" : dayFmt.format(ts);
|
||||
const day = Number.isNaN(ts) ? t("Unknown date") : dayFmt.format(ts);
|
||||
const last = groups[groups.length - 1];
|
||||
if (last && last.day === day) last.rows.push(node);
|
||||
else groups.push({ day, rows: [node] });
|
||||
@@ -574,9 +577,9 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
<Input
|
||||
value={queryInput}
|
||||
onChange={(e) => setQueryInput(e.target.value)}
|
||||
placeholder="Search content / source / node id"
|
||||
placeholder={t("Search content / source / node id")}
|
||||
className="h-8 pl-8"
|
||||
aria-label="Search broadcasts"
|
||||
aria-label={t("Search broadcasts")}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
@@ -608,7 +611,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
{t("Clear")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -621,20 +624,24 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
setOrder((o) => (o === "desc" ? "asc" : "desc"));
|
||||
setPage(1);
|
||||
}}
|
||||
aria-label={order === "desc" ? "Currently newest first; click to switch to oldest first" : "Currently oldest first; click to switch to newest first"}
|
||||
aria-label={
|
||||
order === "desc"
|
||||
? t("Currently newest first; click to switch to oldest first")
|
||||
: t("Currently oldest first; click to switch to newest first")
|
||||
}
|
||||
>
|
||||
{order === "desc" ? <ArrowDownIcon /> : <ArrowUpIcon />}
|
||||
{order === "desc" ? "Newest first" : "Oldest first"}
|
||||
{order === "desc" ? t("Newest first") : t("Oldest first")}
|
||||
</Button>
|
||||
<Button
|
||||
variant={live ? "outline" : "secondary"}
|
||||
size="sm"
|
||||
className="h-8"
|
||||
onClick={() => setLive((v) => !v)}
|
||||
aria-label={live ? "Pause auto-refresh" : "Resume auto-refresh"}
|
||||
aria-label={live ? t("Pause auto-refresh") : t("Resume auto-refresh")}
|
||||
>
|
||||
{live ? <PauseIcon /> : <PlayIcon />}
|
||||
{live ? "Auto-refresh" : "Paused"}
|
||||
{live ? t("Auto-refresh") : t("Paused")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -647,7 +654,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
className="flex w-full items-center justify-center gap-1.5 border-b bg-primary/10 py-1.5 text-xs font-medium text-primary hover:bg-primary/15"
|
||||
>
|
||||
<ArrowUpToLineIcon className="size-3.5" />
|
||||
{pending > 99 ? "99+" : pending} new broadcasts · Back to latest
|
||||
{t("{count} new broadcasts · Back to latest", { count: pending > 99 ? "99+" : pending })}
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -660,7 +667,9 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<p className="py-10 text-center text-sm text-muted-foreground">
|
||||
{query || kinds.length > 0 ? "No broadcasts match the filters." : "This task has not produced any exploration nodes yet."}
|
||||
{query || kinds.length > 0
|
||||
? t("No broadcasts match the filters.")
|
||||
: t("This task has not produced any exploration nodes yet.")}
|
||||
</p>
|
||||
) : (
|
||||
groups.map((group) => (
|
||||
@@ -697,7 +706,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
<SelectGroup>
|
||||
{PAGE_SIZES.map((n) => (
|
||||
<SelectItem key={n} value={String(n)}>
|
||||
{n} / page
|
||||
{t("{count} / page", { count: n })}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
@@ -712,7 +721,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
size="icon-sm"
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||
aria-label="Previous page"
|
||||
aria-label={t("Previous page")}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
@@ -724,7 +733,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
|
||||
size="icon-sm"
|
||||
disabled={page >= pageCount}
|
||||
onClick={() => setPage((p) => Math.min(pageCount, p + 1))}
|
||||
aria-label="Next page"
|
||||
aria-label={t("Next page")}
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
|
||||
@@ -24,7 +24,9 @@ import {
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { statusMeta } from "@/lib/status";
|
||||
import type { CoverageAssetRef, CoverageAssetRefs, CoverageGraphEdge, CoverageGraphNode } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -37,13 +39,13 @@ type Kind = CoverageGraphNode["kind"];
|
||||
type KindMeta = { label: string; icon: LucideIcon; iconBg: string; hex: string; size: number };
|
||||
|
||||
const kindMeta: Record<Kind, KindMeta> = {
|
||||
company: { label: "Company", icon: Building2, iconBg: "bg-slate-500", hex: "#64748b", size: 46 },
|
||||
root_domain: { label: "Root domain", icon: Globe, iconBg: "bg-indigo-500", hex: "#6366f1", size: 38 },
|
||||
subdomain: { label: "Subdomain", icon: Waypoints, iconBg: "bg-blue-500", hex: "#3b82f6", size: 30 },
|
||||
company: { label: t("Company"), icon: Building2, iconBg: "bg-slate-500", hex: "#64748b", size: 46 },
|
||||
root_domain: { label: t("Root domain"), icon: Globe, iconBg: "bg-indigo-500", hex: "#6366f1", size: 38 },
|
||||
subdomain: { label: t("Subdomain"), icon: Waypoints, iconBg: "bg-blue-500", hex: "#3b82f6", size: 30 },
|
||||
ip: { label: "IP", icon: Server, iconBg: "bg-cyan-600", hex: "#0891b2", size: 28 },
|
||||
service: { label: "Service", icon: Radio, iconBg: "bg-amber-500", hex: "#f59e0b", size: 26 },
|
||||
app: { label: "App", icon: AppWindow, iconBg: "bg-fuchsia-500", hex: "#d946ef", size: 26 },
|
||||
endpoint: { label: "Endpoint", icon: Link2, iconBg: "bg-rose-500", hex: "#f43f5e", size: 20 },
|
||||
service: { label: t("Service"), icon: Radio, iconBg: "bg-amber-500", hex: "#f59e0b", size: 26 },
|
||||
app: { label: t("App"), icon: AppWindow, iconBg: "bg-fuchsia-500", hex: "#d946ef", size: 26 },
|
||||
endpoint: { label: t("Endpoint"), icon: Link2, iconBg: "bg-rose-500", hex: "#f43f5e", size: 20 },
|
||||
};
|
||||
|
||||
// G6 node icons use the platform's lucide icons: render lucide SVG paths (v1.22) as white-stroked
|
||||
@@ -220,7 +222,7 @@ function toG6Nodes(renderNodes: RenderNode[]): G6NodeDatum[] {
|
||||
fold: true,
|
||||
tested: false,
|
||||
inScope: false,
|
||||
lbl: `${rn.hidden.length} more ${kindMeta[rn.kind].label}`,
|
||||
lbl: t("{count} more {kind}", { count: rn.hidden.length, kind: kindMeta[rn.kind].label }),
|
||||
size: 24,
|
||||
};
|
||||
}
|
||||
@@ -280,11 +282,15 @@ function RefList({ title, items }: { title: string; items: CoverageAssetRef[] })
|
||||
className="flex flex-wrap items-start gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-xs"
|
||||
>
|
||||
<span className="shrink-0 font-mono text-muted-foreground">#{r.id}</span>
|
||||
{r.state && <span className="shrink-0 text-muted-foreground">{r.state}</span>}
|
||||
{r.state && (
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
{statusMeta(r.kind === "intent" ? "intent" : "node", r.state).label}
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-32 flex-1 break-words text-foreground">{r.summary || "—"}</span>
|
||||
{r.inherited && r.source_task_id && (
|
||||
<Badge variant="outline" className="shrink-0">
|
||||
Source #{r.source_task_id} · read-only
|
||||
{t("Source #{id} · read-only", { id: r.source_task_id })}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
@@ -345,42 +351,42 @@ function AssetSheet({
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="flex w-full min-w-0 flex-col gap-4 p-4">
|
||||
<section>
|
||||
<h4 className="text-muted-foreground mb-1 text-xs font-medium">Properties</h4>
|
||||
<DetailRow label="Type">{meta.label}</DetailRow>
|
||||
<DetailRow label="Test status">
|
||||
<h4 className="text-muted-foreground mb-1 text-xs font-medium">{t("Properties")}</h4>
|
||||
<DetailRow label={t("Type")}>{meta.label}</DetailRow>
|
||||
<DetailRow label={t("Test status")}>
|
||||
{node.in_scope ? (
|
||||
node.tested ? (
|
||||
<span className="text-emerald-600 dark:text-emerald-400">Tested</span>
|
||||
<span className="text-emerald-600 dark:text-emerald-400">{t("Tested")}</span>
|
||||
) : (
|
||||
<span className="text-neutral-500">Untested</span>
|
||||
<span className="text-neutral-500">{t("Untested")}</span>
|
||||
)
|
||||
) : (
|
||||
<span className="text-neutral-400">Out of scope (connecting node)</span>
|
||||
<span className="text-neutral-400">{t("Out of scope (connecting node)")}</span>
|
||||
)}
|
||||
</DetailRow>
|
||||
<DetailRow label="Domain">{node.domain}</DetailRow>
|
||||
<DetailRow label="Root domain">{node.root_domain}</DetailRow>
|
||||
<DetailRow label={t("Domain")}>{node.domain}</DetailRow>
|
||||
<DetailRow label={t("Root domain")}>{node.root_domain}</DetailRow>
|
||||
<DetailRow label="IP">{node.ip}</DetailRow>
|
||||
<DetailRow label="Port">{node.port ? node.port : undefined}</DetailRow>
|
||||
<DetailRow label={t("Port")}>{node.port ? node.port : undefined}</DetailRow>
|
||||
<DetailRow label="URL">
|
||||
{node.url ? <span className="font-mono text-xs break-all">{node.url}</span> : undefined}
|
||||
</DetailRow>
|
||||
<DetailRow label="Title">{node.page_title}</DetailRow>
|
||||
<DetailRow label="Status code">{node.status_code ? node.status_code : undefined}</DetailRow>
|
||||
<DetailRow label="App">{node.app_name}</DetailRow>
|
||||
<DetailRow label="Asset ID">
|
||||
<DetailRow label={t("Title")}>{node.page_title}</DetailRow>
|
||||
<DetailRow label={t("Status code")}>{node.status_code ? node.status_code : undefined}</DetailRow>
|
||||
<DetailRow label={t("App")}>{node.app_name}</DetailRow>
|
||||
<DetailRow label={t("Asset ID")}>
|
||||
{node.asset_id ? <span className="font-mono text-xs">{node.asset_id}</span> : undefined}
|
||||
</DetailRow>
|
||||
</section>
|
||||
{refs && (refs.intents.length > 0 || refs.facts.length > 0 || refs.findings.length > 0) && (
|
||||
<section className="flex flex-col gap-3 border-t pt-3">
|
||||
<RefList title="Related intents" items={refs.intents} />
|
||||
<RefList title="Related facts" items={refs.facts} />
|
||||
<RefList title="Related findings" items={refs.findings} />
|
||||
<RefList title={t("Related intents")} items={refs.intents} />
|
||||
<RefList title={t("Related facts")} items={refs.facts} />
|
||||
<RefList title={t("Related findings")} items={refs.findings} />
|
||||
</section>
|
||||
)}
|
||||
<section className="border-t pt-3">
|
||||
<h4 className="text-muted-foreground mb-1.5 text-xs font-medium">Raw data</h4>
|
||||
<h4 className="text-muted-foreground mb-1.5 text-xs font-medium">{t("Raw data")}</h4>
|
||||
<pre className="bg-muted/50 text-foreground max-w-full overflow-hidden rounded-md border p-3 font-mono text-xs leading-relaxed break-all whitespace-pre-wrap">
|
||||
{raw}
|
||||
</pre>
|
||||
@@ -414,9 +420,11 @@ function FoldSheet({
|
||||
<>
|
||||
<SheetHeader className="border-b p-4">
|
||||
<SheetTitle className="text-base">
|
||||
Hidden {meta.label} ({fold.hidden.length})
|
||||
{t("Hidden {kind} ({count})", { kind: meta.label, count: fold.hidden.length })}
|
||||
</SheetTitle>
|
||||
<p className="text-muted-foreground text-xs">Tested items are shown first. Click "Show more" to pull the next batch into the graph.</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t('Tested items are shown first. Click "Show more" to pull the next batch into the graph.')}
|
||||
</p>
|
||||
</SheetHeader>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="flex flex-col gap-1 p-3">
|
||||
@@ -445,7 +453,7 @@ function FoldSheet({
|
||||
</ScrollArea>
|
||||
<div className="border-t p-3">
|
||||
<Button className="w-full" variant="outline" onClick={() => onShowMore(fold.groupId)}>
|
||||
Show more (+{FOLD_STEP})
|
||||
{t("Show more (+{count})", { count: FOLD_STEP })}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
@@ -644,19 +652,21 @@ function GraphInner({ taskId, coverageEnabled = true }: { taskId: string; covera
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
{total > 0 ? (
|
||||
<span className="text-muted-foreground">
|
||||
In scope <span className="text-foreground font-semibold tabular-nums">{inScope}</span>
|
||||
{t("In scope")} <span className="text-foreground font-semibold tabular-nums">{inScope}</span>
|
||||
{coverageEnabled && (
|
||||
<>
|
||||
{" "}
|
||||
· Tested{" "}
|
||||
· {t("Tested")}{" "}
|
||||
<span className="font-semibold tabular-nums text-emerald-600 dark:text-emerald-400">{tested}</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">{loading ? "Loading…" : "No in-scope assets yet (anchor the task scope first)"}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{loading ? t("Loading…") : t("No in-scope assets yet (anchor the task scope first)")}
|
||||
</span>
|
||||
)}
|
||||
<Button variant="ghost" size="icon" className="size-6" onClick={fetchGraph} title="Refresh">
|
||||
<Button variant="ghost" size="icon" className="size-6" onClick={fetchGraph} title={t("Refresh")}>
|
||||
<RefreshCw className={cn("size-3.5", loading && "animate-spin")} />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -678,19 +688,20 @@ function GraphInner({ taskId, coverageEnabled = true }: { taskId: string; covera
|
||||
{coverageEnabled && (
|
||||
<>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span className="size-3 rounded-full bg-emerald-500" /> Tested (highlighted)
|
||||
<span className="size-3 rounded-full bg-emerald-500" /> {t("Tested (highlighted)")}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span className="size-3 rounded-full bg-neutral-400" /> Untested
|
||||
<span className="size-3 rounded-full bg-neutral-400" /> {t("Untested")}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span className="size-3 rounded-full border border-dashed border-neutral-400 bg-neutral-200" /> Out of scope
|
||||
<span className="size-3 rounded-full border border-dashed border-neutral-400 bg-neutral-200" />{" "}
|
||||
{t("Out of scope")}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground/80 border-border/60 border-t pt-2 leading-relaxed">
|
||||
Force-directed layout; drag nodes and scroll to zoom. The gray "⋯" is a fold node — click it to expand more.
|
||||
{t('Force-directed layout; drag nodes and scroll to zoom. The gray "⋯" is a fold node — click it to expand more.')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { TaskCredential } from "@/lib/types";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
@@ -77,9 +78,9 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Test accounts</CardTitle>
|
||||
<CardTitle>{t("Test accounts")}</CardTitle>
|
||||
<CardDescription>
|
||||
Test accounts for this task. Entries with an empty password mean the agent registers that account and records it. Agent-recorded accounts appear here automatically.
|
||||
{t("Test accounts for this task. Entries with an empty password mean the agent registers that account and records it. Agent-recorded accounts appear here automatically.")}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
@@ -89,9 +90,9 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
|
||||
) : items.length === 0 ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>No test accounts</EmptyTitle>
|
||||
<EmptyTitle>{t("No test accounts")}</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
Add one below, or declare them when creating the task — the agent reuses them for authenticated testing.
|
||||
{t("Add one below, or declare them when creating the task — the agent reuses them for authenticated testing.")}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
@@ -102,13 +103,13 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
|
||||
<code className="text-sm font-medium">{c.domain}</code>
|
||||
<span className="text-muted-foreground text-sm">{c.username}</span>
|
||||
<Badge variant={c.source === "agent" ? "secondary" : "outline"}>
|
||||
{c.source === "agent" ? "agent-recorded" : "declared"}
|
||||
{c.source === "agent" ? t("agent-recorded") : t("declared")}
|
||||
</Badge>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<code className="max-w-40 truncate rounded bg-muted px-2 py-0.5 text-sm">
|
||||
{c.password === "" ? "— agent generates —" : "stored, hidden"}
|
||||
{c.password === "" ? t("— agent generates —") : t("stored, hidden")}
|
||||
</code>
|
||||
<Button size="icon" variant="ghost" className="size-7" aria-label="Delete credential" onClick={() => remove(c.id)}>
|
||||
<Button size="icon" variant="ghost" className="size-7" aria-label={t("Delete credential")} onClick={() => remove(c.id)}>
|
||||
<TrashIcon />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -118,18 +119,18 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-2 sm:grid-cols-[1fr_1fr_1fr_auto]">
|
||||
<Input placeholder="domain (e.g. target.example.com)" value={domain} onChange={(e) => setDomain(e.target.value)} />
|
||||
<Input placeholder="email or username" value={username} onChange={(e) => setUsername(e.target.value)} />
|
||||
<Input placeholder={t("domain (e.g. target.example.com)")} value={domain} onChange={(e) => setDomain(e.target.value)} />
|
||||
<Input placeholder={t("email or username")} value={username} onChange={(e) => setUsername(e.target.value)} />
|
||||
<Input
|
||||
placeholder="password (empty = agent generates)"
|
||||
placeholder={t("password (empty = agent generates)")}
|
||||
type="text"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
<Button variant="outline" disabled={adding || !domain.trim() || !username.trim()} onClick={add}>
|
||||
<PlusIcon /> Add
|
||||
<PlusIcon /> {t("Add")}
|
||||
</Button>
|
||||
<Input className="sm:col-span-4" placeholder="note (optional, e.g. program alias account)" value={note} onChange={(e) => setNote(e.target.value)} />
|
||||
<Input className="sm:col-span-4" placeholder={t("note (optional, e.g. program alias account)")} value={note} onChange={(e) => setNote(e.target.value)} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -11,6 +11,7 @@ import { StatusBadge } from "@/components/status-badge";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger } from "@/components/ui/select";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { useStoredSortPreference } from "@/lib/sort-preference";
|
||||
import { statusMeta } from "@/lib/status";
|
||||
@@ -26,7 +27,7 @@ const FINDING_SORT_PREFERENCE_KEY = "artex_task_findings_sort";
|
||||
function findingLabel(finding: Finding): string {
|
||||
if (finding.name?.trim()) return finding.name;
|
||||
if (finding.vulnclass?.trim()) return finding.vulnclass;
|
||||
return "Uncategorized";
|
||||
return t("Uncategorized");
|
||||
}
|
||||
|
||||
const FINDING_STATUSES: FindingStatus[] = [
|
||||
@@ -68,14 +69,14 @@ function Row({
|
||||
<span className="truncate font-medium">{findingLabel(f)}</span>
|
||||
{f.inherited && f.source_task_id && (
|
||||
<Badge variant="outline" className="shrink-0">
|
||||
Source #{f.source_task_id} · read-only
|
||||
{t("Source #{id} · read-only", { id: f.source_task_id })}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
|
||||
</div>
|
||||
</button>
|
||||
<Badge variant="outline">Traffic evidence {f.traffic_count ?? 0}</Badge>
|
||||
<Badge variant="outline">{t("Traffic evidence {count}", { count: f.traffic_count ?? 0 })}</Badge>
|
||||
{f.assets && f.assets.length > 0 && (
|
||||
<div className="hidden shrink-0 flex-wrap justify-end gap-1 sm:flex">
|
||||
{f.assets.slice(0, 2).map((a) => (
|
||||
@@ -109,7 +110,7 @@ function Row({
|
||||
<StatusBadge domain="finding" value={f.status} dot />
|
||||
)}
|
||||
<span className="hidden shrink-0 text-xs text-muted-foreground md:block">
|
||||
{new Date(f.ts).toLocaleString("zh-CN")}
|
||||
{new Date(f.ts).toLocaleString(intlLocale)}
|
||||
</span>
|
||||
{f.finding_id && (
|
||||
<Link
|
||||
@@ -119,16 +120,16 @@ function Row({
|
||||
: `/function/findings/detail?id=${f.finding_id}`
|
||||
}
|
||||
className="text-muted-foreground hover:text-primary inline-flex shrink-0 items-center gap-0.5 text-xs"
|
||||
title="View vulnerability details"
|
||||
title={t("View vulnerability details")}
|
||||
>
|
||||
Details
|
||||
{t("Details")}
|
||||
<ArrowUpRightIcon className="size-3" />
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
{open && (
|
||||
<div className="bg-muted/30 px-4 pb-4 pl-11">
|
||||
<div className="mb-1 text-xs font-medium text-muted-foreground">Evidence / PoC</div>
|
||||
<div className="mb-1 text-xs font-medium text-muted-foreground">{t("Evidence / PoC")}</div>
|
||||
<pre className="overflow-auto rounded-md border bg-background p-3 font-mono text-xs whitespace-pre-wrap">
|
||||
{f.evidence}
|
||||
</pre>
|
||||
@@ -173,10 +174,10 @@ export function FindingsTab({ taskId }: { taskId: string }) {
|
||||
setFindings((cur) => cur.map((x) => (x.id === f.id ? { ...x, status: next } : x)));
|
||||
try {
|
||||
await api.setFindingStatus(f.finding_id, next);
|
||||
toast.success(`Marked as "${statusMeta("finding", next).label}"`);
|
||||
toast.success(t("Marked as \"{status}\"", { status: statusMeta("finding", next).label }));
|
||||
} catch (e) {
|
||||
setFindings((cur) => cur.map((x) => (x.id === f.id ? { ...x, status: prev } : x)));
|
||||
toast.error("Update failed: " + (e as Error).message);
|
||||
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -192,11 +193,15 @@ export function FindingsTab({ taskId }: { taskId: string }) {
|
||||
<Card className="overflow-hidden py-0">
|
||||
<CardContent className="px-0">
|
||||
<div className="flex items-center border-b px-4 py-2 text-xs text-muted-foreground">
|
||||
<span className="min-w-0 flex-1">Vulnerabilities</span>
|
||||
<span className="min-w-0 flex-1">{t("Vulnerabilities")}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1 outline-none focus-visible:underline"
|
||||
aria-label={`Discovery time currently ${sortPreference.direction === "asc" ? "ascending" : "descending"}, click to toggle sort direction`}
|
||||
aria-label={
|
||||
sortPreference.direction === "asc"
|
||||
? t("Discovery time currently ascending, click to toggle sort direction")
|
||||
: t("Discovery time currently descending, click to toggle sort direction")
|
||||
}
|
||||
onClick={() =>
|
||||
setSortPreference((current) => ({
|
||||
field: "time",
|
||||
@@ -204,7 +209,7 @@ export function FindingsTab({ taskId }: { taskId: string }) {
|
||||
}))
|
||||
}
|
||||
>
|
||||
<span>Discovery time</span>
|
||||
<span>{t("Discovery time")}</span>
|
||||
{sortPreference.direction === "asc" ? (
|
||||
<ArrowUpIcon className="size-3.5" />
|
||||
) : (
|
||||
@@ -216,7 +221,7 @@ export function FindingsTab({ taskId }: { taskId: string }) {
|
||||
<Row key={f.id} f={f} contextTaskId={taskId} onStatus={onStatus} />
|
||||
))}
|
||||
{items.length === 0 && (
|
||||
<p className="px-4 py-8 text-center text-sm text-muted-foreground">No confirmed findings yet for this task or its directly linked tasks.</p>
|
||||
<p className="px-4 py-8 text-center text-sm text-muted-foreground">{t("No confirmed findings yet for this task or its directly linked tasks.")}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -28,11 +28,13 @@ import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select"
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { api } from "@/lib/api";
|
||||
import { taskAssetTypeLabel } from "@/lib/task-assets";
|
||||
import type {
|
||||
AssetInterceptKind,
|
||||
AssetInterceptRule,
|
||||
Finding,
|
||||
ModelTokenStat,
|
||||
NewAssetType,
|
||||
Stats,
|
||||
Task,
|
||||
TaskConstraint,
|
||||
@@ -41,6 +43,7 @@ import type {
|
||||
TaskScopeRow,
|
||||
} from "@/lib/types";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
|
||||
// Compact token count formatting (12345 → 12.3k, 2000000 → 2M).
|
||||
function fmtTokens(n: number): string {
|
||||
@@ -60,24 +63,24 @@ function scopeValue(row: TaskScopeRow): string {
|
||||
if (row.value) return row.value;
|
||||
if (row.domain) return row.domain;
|
||||
if (row.net) return row.net;
|
||||
if (row.company_id) return row.company_name?.trim() ? row.company_name : `Company #${row.company_id}`;
|
||||
if (row.company_id) return row.company_name?.trim() ? row.company_name : t("Company #{id}", { id: row.company_id });
|
||||
return "—";
|
||||
}
|
||||
|
||||
const SCOPE_KIND_LABELS: Record<TaskScopeRow["kind"], string> = {
|
||||
company: "Company",
|
||||
root_domain: "Root domain",
|
||||
subdomain: "Subdomain",
|
||||
company: t("Company"),
|
||||
root_domain: t("Root domain"),
|
||||
subdomain: t("Subdomain"),
|
||||
ip: "IP",
|
||||
cidr: "CIDR",
|
||||
icp: "ICP",
|
||||
keyword: "Keyword",
|
||||
keyword: t("Keyword"),
|
||||
};
|
||||
|
||||
const SCOPE_SOURCE_LABELS: Record<TaskScopeRow["source"], string> = {
|
||||
auto: "Auto",
|
||||
agent: "Agent",
|
||||
manual: "Manual",
|
||||
auto: t("Auto"),
|
||||
agent: t("Agent"),
|
||||
manual: t("Manual"),
|
||||
};
|
||||
|
||||
function StatCard({
|
||||
@@ -186,7 +189,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
setGoalVuln("");
|
||||
await loadGoals();
|
||||
} catch (e) {
|
||||
setGoalErr(e instanceof Error ? e.message : "Failed to add");
|
||||
setGoalErr(e instanceof Error ? e.message : t("Failed to add"));
|
||||
} finally {
|
||||
setGoalBusy(false);
|
||||
}
|
||||
@@ -214,7 +217,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
cancelEditGoal();
|
||||
await loadGoals();
|
||||
} catch (e) {
|
||||
setGoalErr(e instanceof Error ? e.message : "Failed to save");
|
||||
setGoalErr(e instanceof Error ? e.message : t("Failed to save"));
|
||||
} finally {
|
||||
setGoalBusy(false);
|
||||
}
|
||||
@@ -248,7 +251,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
setConText("");
|
||||
await loadConstraints();
|
||||
} catch (e) {
|
||||
setConErr(e instanceof Error ? e.message : "Failed to add");
|
||||
setConErr(e instanceof Error ? e.message : t("Failed to add"));
|
||||
} finally {
|
||||
setConBusy(false);
|
||||
}
|
||||
@@ -276,7 +279,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
cancelEditConstraint();
|
||||
await loadConstraints();
|
||||
} catch (e) {
|
||||
setConErr(e instanceof Error ? e.message : "Failed to save");
|
||||
setConErr(e instanceof Error ? e.message : t("Failed to save"));
|
||||
} finally {
|
||||
setConBusy(false);
|
||||
}
|
||||
@@ -301,7 +304,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
setScopeValueInput("");
|
||||
await loadScope();
|
||||
} catch (e) {
|
||||
setScopeErr(e instanceof Error ? e.message : "Failed to add");
|
||||
setScopeErr(e instanceof Error ? e.message : t("Failed to add"));
|
||||
} finally {
|
||||
setScopeBusy(false);
|
||||
}
|
||||
@@ -439,16 +442,16 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<TargetIcon className="size-4 text-primary" /> Task description & goal
|
||||
<TargetIcon className="size-4 text-primary" /> {t("Task description & goal")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="text-xs font-medium text-muted-foreground">Description</div>
|
||||
<div className="text-xs font-medium text-muted-foreground">{t("Description")}</div>
|
||||
<p className="text-sm whitespace-pre-wrap break-words">{task?.description?.trim() || "—"}</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="text-xs font-medium text-muted-foreground">Goal</div>
|
||||
<div className="text-xs font-medium text-muted-foreground">{t("Goal")}</div>
|
||||
<p className="text-sm whitespace-pre-wrap break-words">{task?.goal?.trim() || "—"}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -458,9 +461,11 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<ListChecksIcon className="size-4 text-primary" /> Goal management
|
||||
<ListChecksIcon className="size-4 text-primary" /> {t("Goal management")}
|
||||
<span className="text-muted-foreground text-xs font-normal">
|
||||
(final verifiable goals, {goals.length} in total; adds/edits notify the planner and revive the task)
|
||||
{t("(final verifiable goals, {count} in total; adds/edits notify the planner and revive the task)", {
|
||||
count: goals.length,
|
||||
})}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -469,7 +474,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
className="h-7 min-w-56 flex-1 text-sm"
|
||||
placeholder="Add a goal, e.g. 'gain unauthorized access with an admin account'"
|
||||
placeholder={t("Add a goal, e.g. 'gain unauthorized access with an admin account'")}
|
||||
value={goalText}
|
||||
onChange={(e) => setGoalText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
@@ -479,7 +484,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
/>
|
||||
<Input
|
||||
className="h-7 w-32 text-sm"
|
||||
placeholder="Vulnerability class (optional)"
|
||||
placeholder={t("Vulnerability class (optional)")}
|
||||
value={goalVuln}
|
||||
onChange={(e) => setGoalVuln(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
@@ -488,7 +493,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
disabled={goalBusy}
|
||||
/>
|
||||
<Button size="sm" variant="outline" disabled={goalBusy || !goalText.trim()} onClick={() => void addGoal()}>
|
||||
<PlusIcon className="size-3.5" /> Add
|
||||
<PlusIcon className="size-3.5" /> {t("Add")}
|
||||
</Button>
|
||||
{goalErr && <span className="text-xs text-red-500">{goalErr}</span>}
|
||||
</div>
|
||||
@@ -511,7 +516,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
/>
|
||||
<Input
|
||||
className="h-7 w-32 text-sm"
|
||||
placeholder="Vulnerability class (optional)"
|
||||
placeholder={t("Vulnerability class (optional)")}
|
||||
value={editVuln}
|
||||
onChange={(e) => setEditVuln(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
@@ -571,7 +576,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No goals yet. Once added, the planner dispatches exploration intents from them and judges completion.</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("No goals yet. Once added, the planner dispatches exploration intents from them and judges completion.")}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -581,9 +588,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<ShieldAlertIcon className="size-4 text-amber-500" /> Operation constraints
|
||||
<ShieldAlertIcon className="size-4 text-amber-500" /> {t("Operation constraints")}
|
||||
<span className="text-muted-foreground text-xs font-normal">
|
||||
(bounds planner/worker exploration, {constraints.length} in total; changes take effect at the next planning round)
|
||||
{t(
|
||||
"(bounds planner/worker exploration, {count} in total; changes take effect at the next planning round)",
|
||||
{ count: constraints.length },
|
||||
)}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -595,12 +605,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
value={conKind}
|
||||
onChange={(e) => setConKind(e.target.value as TaskConstraint["kind"])}
|
||||
>
|
||||
<NativeSelectOption value="deny">Deny</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">Allow</NativeSelectOption>
|
||||
<NativeSelectOption value="deny">{t("Deny")}</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
<Input
|
||||
className="h-7 min-w-56 flex-1 text-sm"
|
||||
placeholder="One operation constraint, e.g. 'test only the current port, do not scan other ports'"
|
||||
placeholder={t("One operation constraint, e.g. 'test only the current port, do not scan other ports'")}
|
||||
value={conText}
|
||||
onChange={(e) => setConText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
@@ -614,7 +624,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
disabled={conBusy || !conText.trim()}
|
||||
onClick={() => void addConstraint()}
|
||||
>
|
||||
<PlusIcon className="size-3.5" /> Add
|
||||
<PlusIcon className="size-3.5" /> {t("Add")}
|
||||
</Button>
|
||||
{conErr && <span className="text-xs text-red-500">{conErr}</span>}
|
||||
</div>
|
||||
@@ -629,8 +639,8 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
value={editConKind}
|
||||
onChange={(e) => setEditConKind(e.target.value as TaskConstraint["kind"])}
|
||||
>
|
||||
<NativeSelectOption value="deny">Deny</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">Allow</NativeSelectOption>
|
||||
<NativeSelectOption value="deny">{t("Deny")}</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
<Input
|
||||
className="h-7 min-w-56 flex-1 text-sm"
|
||||
@@ -671,7 +681,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
: "bg-red-500/15 text-red-600 dark:text-red-400"
|
||||
}`}
|
||||
>
|
||||
{c.kind === "allow" ? "Allow" : "Deny"}
|
||||
{c.kind === "allow" ? t("Allow") : t("Deny")}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 break-words">{c.text}</span>
|
||||
<Button
|
||||
@@ -698,7 +708,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No operation constraints yet. They are extracted automatically from the description/goal at task creation; you can also add, edit, or delete them here to bound which operations are allowed/denied.
|
||||
{t(
|
||||
"No operation constraints yet. They are extracted automatically from the description/goal at task creation; you can also add, edit, or delete them here to bound which operations are allowed/denied.",
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -708,8 +720,8 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<TargetIcon className="size-4 text-emerald-500" /> Asset test coverage
|
||||
<span className="text-muted-foreground text-xs font-normal">(rough estimate, for reference only)</span>
|
||||
<TargetIcon className="size-4 text-emerald-500" /> {t("Asset test coverage")}
|
||||
<span className="text-muted-foreground text-xs font-normal">{t("(rough estimate, for reference only)")}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
@@ -718,7 +730,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
{coverage.pct != null ? Math.round(coverage.pct * 100) + "%" : "—"}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-sm">
|
||||
Tested {coverage.tested} / in scope {coverage.denominator}
|
||||
{t("Tested {tested} / in scope {total}", { tested: coverage.tested, total: coverage.denominator })}
|
||||
</span>
|
||||
</div>
|
||||
{coverage.pct != null && <Progress value={Math.round(coverage.pct * 100)} />}
|
||||
@@ -726,7 +738,10 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<div className="flex flex-wrap gap-1.5 text-xs">
|
||||
{coverage.by_type.map((b) => (
|
||||
<span key={b.type} className="bg-muted rounded px-1.5 py-0.5">
|
||||
<span className="text-muted-foreground">{b.type}</span>{" "}
|
||||
<span className="text-muted-foreground">
|
||||
{(taskAssetTypeLabel as (x: NewAssetType) => string | undefined)(b.type as NewAssetType) ||
|
||||
b.type}
|
||||
</span>{" "}
|
||||
<span className="tabular-nums font-medium">
|
||||
{b.tested}/{b.total}
|
||||
</span>
|
||||
@@ -739,11 +754,11 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
)}
|
||||
{coverage.gaps && (
|
||||
<div className="text-xs">
|
||||
<span className="font-medium">Coverage gaps: {coverage.gaps.length}</span>
|
||||
<span className="font-medium">{t("Coverage gaps: {count}", { count: coverage.gaps.length })}</span>
|
||||
<ul className="text-muted-foreground mt-1 list-disc pl-4">
|
||||
{coverage.gaps.map((g, i) => (
|
||||
<li key={i}>
|
||||
{g.kind} {g.surface ? g.surface + " " : ""}
|
||||
{t(g.kind)} {g.surface ? g.surface + " " : ""}
|
||||
{g.risk_area}
|
||||
</li>
|
||||
))}
|
||||
@@ -757,9 +772,11 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<CoinsIcon className="size-4 text-amber-500" /> LLM token usage
|
||||
<CoinsIcon className="size-4 text-amber-500" /> {t("LLM token usage")}
|
||||
<span className="text-muted-foreground text-xs font-normal">
|
||||
(per model{tokenTotals.calls > 0 ? `, ${tokenTotals.calls} calls in total` : ""})
|
||||
{tokenTotals.calls > 0
|
||||
? t("(per model, {count} calls in total)", { count: tokenTotals.calls })
|
||||
: t("(per model)")}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -769,19 +786,19 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
{/* Totals overview */}
|
||||
<div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 text-sm">
|
||||
<span className="tabular-nums">
|
||||
<span className="text-muted-foreground">Input </span>
|
||||
<span className="text-muted-foreground">{t("Input")} </span>
|
||||
<span className="font-semibold">{fmtTokens(tokenTotals.input)}</span>
|
||||
</span>
|
||||
<span className="tabular-nums">
|
||||
<span className="text-muted-foreground">Output </span>
|
||||
<span className="text-muted-foreground">{t("Output")} </span>
|
||||
<span className="font-semibold">{fmtTokens(tokenTotals.output)}</span>
|
||||
</span>
|
||||
<span className="tabular-nums">
|
||||
<span className="text-muted-foreground">Cache read </span>
|
||||
<span className="text-muted-foreground">{t("Cache read")} </span>
|
||||
<span className="font-semibold">{fmtTokens(tokenTotals.cacheRead)}</span>
|
||||
</span>
|
||||
<span className="tabular-nums">
|
||||
<span className="text-muted-foreground">Cache hit rate </span>
|
||||
<span className="text-muted-foreground">{t("Cache hit rate")} </span>
|
||||
<span className="font-semibold text-emerald-500">
|
||||
{cacheHitRate(tokenTotals.cacheRead, tokenTotals.input)}
|
||||
</span>
|
||||
@@ -792,12 +809,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b text-left text-xs">
|
||||
<th className="py-1.5 pr-3 font-medium">Model</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">Calls</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">Input</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">Output</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">Cache read</th>
|
||||
<th className="py-1.5 text-right font-medium">Hit rate</th>
|
||||
<th className="py-1.5 pr-3 font-medium">{t("Model")}</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">{t("Calls")}</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">{t("Input")}</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">{t("Output")}</th>
|
||||
<th className="py-1.5 pr-3 text-right font-medium">{t("Cache read")}</th>
|
||||
<th className="py-1.5 text-right font-medium">{t("Hit rate")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -820,7 +837,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No LLM usage yet (the task has made no calls, or records are still being written).</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("No LLM usage yet (the task has made no calls, or records are still being written).")}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -828,9 +847,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<ShieldCheckIcon className="size-4 text-emerald-500" /> Test scope
|
||||
<ShieldCheckIcon className="size-4 text-emerald-500" /> {t("Test scope")}
|
||||
<span className="text-muted-foreground text-xs font-normal">
|
||||
(coverage scope, not enforced, {scope.length} in total)
|
||||
{t("(coverage scope, not enforced, {count} in total)", { count: scope.length })}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -842,26 +861,26 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
value={scopeKind}
|
||||
onChange={(e) => setScopeKind(e.target.value as TaskScopeRow["kind"])}
|
||||
>
|
||||
<NativeSelectOption value="root_domain">Root domain</NativeSelectOption>
|
||||
<NativeSelectOption value="subdomain">Subdomain</NativeSelectOption>
|
||||
<NativeSelectOption value="root_domain">{t("Root domain")}</NativeSelectOption>
|
||||
<NativeSelectOption value="subdomain">{t("Subdomain")}</NativeSelectOption>
|
||||
<NativeSelectOption value="ip">IP</NativeSelectOption>
|
||||
<NativeSelectOption value="cidr">CIDR</NativeSelectOption>
|
||||
<NativeSelectOption value="icp">ICP</NativeSelectOption>
|
||||
<NativeSelectOption value="keyword">Keyword</NativeSelectOption>
|
||||
<NativeSelectOption value="company">Company</NativeSelectOption>
|
||||
<NativeSelectOption value="keyword">{t("Keyword")}</NativeSelectOption>
|
||||
<NativeSelectOption value="company">{t("Company")}</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
<Input
|
||||
className="h-7 w-56 text-sm"
|
||||
placeholder={
|
||||
scopeKind === "company"
|
||||
? "Company name or id"
|
||||
? t("Company name or id")
|
||||
: scopeKind === "ip" || scopeKind === "cidr"
|
||||
? "e.g. 10.0.0.1 or 10.0.0.0/24"
|
||||
? t("e.g. 10.0.0.1 or 10.0.0.0/24")
|
||||
: scopeKind === "icp"
|
||||
? "e.g. Beijing ICP No.12345678-1"
|
||||
? t("e.g. Beijing ICP No.12345678-1")
|
||||
: scopeKind === "keyword"
|
||||
? "e.g. a company-name keyword"
|
||||
: "e.g. example.com"
|
||||
? t("e.g. a company-name keyword")
|
||||
: t("e.g. example.com")
|
||||
}
|
||||
value={scopeValueInput}
|
||||
onChange={(e) => setScopeValueInput(e.target.value)}
|
||||
@@ -876,7 +895,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
disabled={scopeBusy || !scopeValueInput.trim()}
|
||||
onClick={() => void addScope()}
|
||||
>
|
||||
<PlusIcon className="size-3.5" /> Add
|
||||
<PlusIcon className="size-3.5" /> {t("Add")}
|
||||
</Button>
|
||||
{scopeErr && <span className="text-xs text-red-500">{scopeErr}</span>}
|
||||
</div>
|
||||
@@ -900,13 +919,15 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Trash2Icon className="size-3.5 text-red-500" />
|
||||
</Button>
|
||||
) : (
|
||||
<span className="text-muted-foreground shrink-0 text-xs">Inherited</span>
|
||||
<span className="text-muted-foreground shrink-0 text-xs">{t("Inherited")}</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No test scope yet; once added it serves as the asset coverage denominator.</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("No test scope yet; once added it serves as the asset coverage denominator.")}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -914,12 +935,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<ActivityIcon className="size-4 text-blue-500" /> Heartbeat
|
||||
<ActivityIcon className="size-4 text-blue-500" /> {t("Heartbeat")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">Engine state</div>
|
||||
<div className="text-xs text-muted-foreground">{t("Engine state")}</div>
|
||||
<StatusBadge
|
||||
domain="engine"
|
||||
value={stats?.engine_mode ?? task?.engine_mode ?? "idle"}
|
||||
@@ -928,28 +949,28 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">Running workers</div>
|
||||
<div className="text-xs text-muted-foreground">{t("Running workers")}</div>
|
||||
<div className="mt-1 text-lg font-semibold tabular-nums">{running.length}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">Last activity</div>
|
||||
<div className="text-xs text-muted-foreground">{t("Last activity")}</div>
|
||||
<div className="mt-1 inline-flex items-center gap-1 text-sm">
|
||||
<ClockIcon className="size-3.5" />
|
||||
{task?.last_activity ? new Date(task.last_activity).toLocaleTimeString("zh-CN") : "—"}
|
||||
{task?.last_activity ? new Date(task.last_activity).toLocaleTimeString(intlLocale) : "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Goals {task?.goals_met ?? 0}/{task?.goals_total ?? 0}
|
||||
{t("Goals {met}/{total}", { met: task?.goals_met ?? 0, total: task?.goals_total ?? 0 })}
|
||||
</div>
|
||||
<Progress value={goalsPct} className="mt-2" />
|
||||
</div>
|
||||
{task?.completed_unix && task.completed_unix > 0 ? (
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">Completed at</div>
|
||||
<div className="text-xs text-muted-foreground">{t("Completed at")}</div>
|
||||
<div className="mt-1 inline-flex items-center gap-1 text-sm">
|
||||
<ClockIcon className="size-3.5" />
|
||||
{new Date(task.completed_unix * 1000).toLocaleString("zh-CN")}
|
||||
{new Date(task.completed_unix * 1000).toLocaleString(intlLocale)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -961,7 +982,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm">
|
||||
<TargetIcon className="size-4" /> Running intents
|
||||
<TargetIcon className="size-4" /> {t("Running intents")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
@@ -971,32 +992,32 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<span className="min-w-0 flex-1 truncate">{i.payload}</span>
|
||||
</div>
|
||||
))}
|
||||
{running.length === 0 && <p className="text-sm text-muted-foreground">No running intents</p>}
|
||||
{running.length === 0 && <p className="text-sm text-muted-foreground">{t("No running intents")}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm">
|
||||
<AlertTriangleIcon className="size-4 text-amber-500" /> Needs attention
|
||||
<AlertTriangleIcon className="size-4 text-amber-500" /> {t("Needs attention")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div>
|
||||
<div className="text-2xl font-semibold tabular-nums text-red-600">{taskFindings.length}</div>
|
||||
<div className="text-xs text-muted-foreground">Confirmed vulnerabilities</div>
|
||||
<div className="text-xs text-muted-foreground">{t("Confirmed vulnerabilities")}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-semibold tabular-nums text-blue-600">{running.length}</div>
|
||||
<div className="text-xs text-muted-foreground">Running</div>
|
||||
<div className="text-xs text-muted-foreground">{t("Running")}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-semibold tabular-nums">{open.length}</div>
|
||||
<div className="text-xs text-muted-foreground">frontier open</div>
|
||||
<div className="text-xs text-muted-foreground">{t("frontier open")}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-semibold tabular-nums text-red-600">{blocked.length}</div>
|
||||
<div className="text-xs text-muted-foreground">Blocked intents</div>
|
||||
<div className="text-xs text-muted-foreground">{t("Blocked intents")}</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -1004,7 +1025,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm">
|
||||
<BugIcon className="size-4 text-red-500" /> Recent findings
|
||||
<BugIcon className="size-4 text-red-500" /> {t("Recent findings")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
@@ -1014,7 +1035,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<span className="min-w-0 flex-1 truncate">{f.summary}</span>
|
||||
</div>
|
||||
))}
|
||||
{taskFindings.length === 0 && <p className="text-sm text-muted-foreground">No findings yet</p>}
|
||||
{taskFindings.length === 0 && <p className="text-sm text-muted-foreground">{t("No findings yet")}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -1025,12 +1046,14 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
<Card className="border-red-500/30">
|
||||
<CardHeader className="flex-row items-center justify-between gap-2 space-y-0">
|
||||
<CardTitle className="flex items-center gap-2 text-sm">
|
||||
<AlertTriangleIcon className="size-4 text-red-500" /> Blocked/errored intents
|
||||
<span className="text-xs font-normal text-muted-foreground">({blocked.length} in total, re-runnable)</span>
|
||||
<AlertTriangleIcon className="size-4 text-red-500" /> {t("Blocked/errored intents")}
|
||||
<span className="text-xs font-normal text-muted-foreground">
|
||||
{t("({count} in total, re-runnable)", { count: blocked.length })}
|
||||
</span>
|
||||
</CardTitle>
|
||||
<Button size="sm" variant="outline" disabled={rerunning.has("__all__")} onClick={() => void rerunAll()}>
|
||||
<RefreshCwIcon className={`size-3.5 ${rerunning.has("__all__") ? "animate-spin" : ""}`} />
|
||||
Re-run all
|
||||
{t("Re-run all")}
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
@@ -1046,13 +1069,15 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
onClick={() => void rerunOne(i.id)}
|
||||
>
|
||||
<RefreshCwIcon className={`size-3 ${rerunning.has(i.id) ? "animate-spin" : ""}`} />
|
||||
Re-run
|
||||
{t("Re-run")}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{blocked.length > 20 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Only the first 20 are shown; click "Re-run all" to handle the remaining {blocked.length - 20}.
|
||||
{t('Only the first 20 are shown; click "Re-run all" to handle the remaining {count}.', {
|
||||
count: blocked.length - 20,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -1061,21 +1086,26 @@ export function OverviewTab({ taskId }: { taskId: string }) {
|
||||
|
||||
{/* Stat cards */}
|
||||
<div className="grid grid-cols-2 gap-4 lg:grid-cols-3">
|
||||
<StatCard label="Open intents" value={open.length} icon={ShieldCheckIcon} sub="frontier open" />
|
||||
<StatCard label="Confirmed findings" value={taskFindings.length} icon={BugIcon} sub="this task" />
|
||||
<StatCard label="Total intents" value={intents.length} icon={AlertTriangleIcon} sub="all intents of this task" />
|
||||
<StatCard label={t("Open intents")} value={open.length} icon={ShieldCheckIcon} sub={t("frontier open")} />
|
||||
<StatCard label={t("Confirmed findings")} value={taskFindings.length} icon={BugIcon} sub={t("this task")} />
|
||||
<StatCard
|
||||
label={t("Total intents")}
|
||||
value={intents.length}
|
||||
icon={AlertTriangleIcon}
|
||||
sub={t("all intents of this task")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const TASK_RULE_KIND_OPTIONS: { value: AssetInterceptKind; label: string; placeholder: string }[] = [
|
||||
{ value: "exact_domain", label: "Domain (exact)", placeholder: "example.gov.cn" },
|
||||
{ value: "exact_ip", label: "IP (exact)", placeholder: "203.0.113.10" },
|
||||
{ value: "exact_url", label: "URL (exact)", placeholder: "https://example.com/login" },
|
||||
{ value: "fuzzy_domain", label: "Domain (fuzzy)", placeholder: ".gov.cn" },
|
||||
{ value: "fuzzy_ip", label: "IP (fuzzy)", placeholder: "203.0.113." },
|
||||
{ value: "fuzzy_url", label: "URL (fuzzy)", placeholder: "/admin" },
|
||||
{ value: "exact_domain", label: t("Domain (exact)"), placeholder: "example.gov.cn" },
|
||||
{ value: "exact_ip", label: t("IP (exact)"), placeholder: "203.0.113.10" },
|
||||
{ value: "exact_url", label: t("URL (exact)"), placeholder: "https://example.com/login" },
|
||||
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), placeholder: ".gov.cn" },
|
||||
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), placeholder: "203.0.113." },
|
||||
{ value: "fuzzy_url", label: t("URL (fuzzy)"), placeholder: "/admin" },
|
||||
{ value: "cidr", label: "CIDR", placeholder: "192.168.0.0/16" },
|
||||
];
|
||||
|
||||
@@ -1187,9 +1217,11 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<ShieldCheckIcon className="size-4 text-sky-500" /> Task-level asset intercept / allow
|
||||
<ShieldCheckIcon className="size-4 text-sky-500" /> {t("Task-level asset intercept / allow")}
|
||||
<span className="text-muted-foreground text-xs font-normal">
|
||||
(this task only, never global; block rules evaluate before allow rules, {rules.length} in total)
|
||||
{t("(this task only, never global; block rules evaluate before allow rules, {count} in total)", {
|
||||
count: rules.length,
|
||||
})}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -1197,8 +1229,8 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
|
||||
{/* Add form */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<NativeSelect size="sm" value={newAction} onChange={(e) => setNewAction(e.target.value as "block" | "allow")}>
|
||||
<NativeSelectOption value="block">Block</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">Allow</NativeSelectOption>
|
||||
<NativeSelectOption value="block">{t("Block")}</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
<NativeSelect size="sm" value={newKind} onChange={(e) => setNewKind(e.target.value as AssetInterceptKind)}>
|
||||
{TASK_RULE_KIND_OPTIONS.map((o) => (
|
||||
@@ -1219,13 +1251,13 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
|
||||
/>
|
||||
<Input
|
||||
className="h-7 w-36 text-sm"
|
||||
placeholder="Note (optional)"
|
||||
placeholder={t("Note (optional)")}
|
||||
value={newNote}
|
||||
onChange={(e) => setNewNote(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
<Button size="sm" variant="outline" disabled={busy || !newPattern.trim()} onClick={() => void add()}>
|
||||
<PlusIcon className="size-3.5" /> Add
|
||||
<PlusIcon className="size-3.5" /> {t("Add")}
|
||||
</Button>
|
||||
{err && <span className="text-xs text-red-500">{err}</span>}
|
||||
</div>
|
||||
@@ -1240,8 +1272,8 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
|
||||
value={editAction}
|
||||
onChange={(e) => setEditAction(e.target.value as "block" | "allow")}
|
||||
>
|
||||
<NativeSelectOption value="block">Block</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">Allow</NativeSelectOption>
|
||||
<NativeSelectOption value="block">{t("Block")}</NativeSelectOption>
|
||||
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
<NativeSelect
|
||||
size="sm"
|
||||
@@ -1267,7 +1299,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
|
||||
/>
|
||||
<Input
|
||||
className="h-7 w-36 text-sm"
|
||||
placeholder="Note (optional)"
|
||||
placeholder={t("Note (optional)")}
|
||||
value={editNote}
|
||||
onChange={(e) => setEditNote(e.target.value)}
|
||||
disabled={busy}
|
||||
@@ -1300,7 +1332,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
|
||||
: "bg-red-500/15 text-red-600 dark:text-red-400"
|
||||
}`}
|
||||
>
|
||||
{r.action === "allow" ? "Allow" : "Block"}
|
||||
{r.action === "allow" ? t("Allow") : t("Block")}
|
||||
</span>
|
||||
<span className="text-muted-foreground shrink-0 text-xs">{TASK_RULE_KIND_LABEL[r.kind]}</span>
|
||||
<code className="bg-muted min-w-0 flex-1 truncate rounded px-1.5 py-0.5 text-xs">{r.pattern}</code>
|
||||
@@ -1332,7 +1364,9 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No task-level rules. A "Block" hit forbids testing; "Allow" is a whitelist — once configured, this task only permits assets that match an allow rule (no whitelist when unconfigured).
|
||||
{t(
|
||||
'No task-level rules. A "Block" hit forbids testing; "Allow" is a whitelist — once configured, this task only permits assets that match an allow rule (no whitelist when unconfigured).',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user