mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-25 02:01:51 +08:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
566c533052
46 files changed
+4099
-182
No files matched your search
@@ -12,6 +12,7 @@ import {
|
||||
InfoIcon,
|
||||
SearchIcon,
|
||||
ShieldAlertIcon,
|
||||
Trash2Icon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -285,6 +286,10 @@ export default function FindingsPage() {
|
||||
const [includeOriginals, setIncludeOriginals] = React.useState(false);
|
||||
const [reviewing, setReviewing] = React.useState(false);
|
||||
const [exporting, setExporting] = React.useState(false);
|
||||
const [cleanupOpen, setCleanupOpen] = React.useState(false);
|
||||
const [cleanupScope, setCleanupScope] = React.useState<"filtered" | "all" | "selected">("all");
|
||||
const [cleaning, setCleaning] = React.useState(false);
|
||||
const [caseRefreshKey, setCaseRefreshKey] = React.useState(0);
|
||||
|
||||
const toggleSelected = React.useCallback((id: string, checked: boolean) => {
|
||||
setSelectedIds((prev) => {
|
||||
@@ -312,6 +317,23 @@ export default function FindingsPage() {
|
||||
setExportOpen(true);
|
||||
}
|
||||
|
||||
const hasActiveFilters =
|
||||
severity !== "all" ||
|
||||
status !== "all" ||
|
||||
vulnclass !== "all" ||
|
||||
task !== "all" ||
|
||||
query !== "" ||
|
||||
Boolean(dateRange.from) ||
|
||||
Boolean(dateRange.to) ||
|
||||
(view === "asset" && assetScope !== null);
|
||||
|
||||
function openCleanup() {
|
||||
if (selectedIds.size > 0) setCleanupScope("selected");
|
||||
else if (hasActiveFilters && stats.total > 0) setCleanupScope("filtered");
|
||||
else setCleanupScope("all");
|
||||
setCleanupOpen(true);
|
||||
}
|
||||
|
||||
async function doExport() {
|
||||
setExporting(true);
|
||||
try {
|
||||
@@ -791,6 +813,58 @@ export default function FindingsPage() {
|
||||
[refreshAfterMutation, refreshStats, setFindings, liveUI],
|
||||
);
|
||||
|
||||
async function doCleanup() {
|
||||
if (cleaning) return;
|
||||
setCleaning(true);
|
||||
try {
|
||||
const res = await api.cleanupFindings({
|
||||
scope: cleanupScope,
|
||||
filters: {
|
||||
severity,
|
||||
status,
|
||||
vulnclass,
|
||||
task,
|
||||
query,
|
||||
sort,
|
||||
...dateRange,
|
||||
assetScope: view === "asset" ? (assetScope ?? undefined) : undefined,
|
||||
},
|
||||
ids: [...selectedIds],
|
||||
});
|
||||
setCleanupOpen(false);
|
||||
setSelectedIds(new Set());
|
||||
setExpanded(null);
|
||||
setEdit(null);
|
||||
setReports({});
|
||||
setPage(1);
|
||||
setFlatPage(1);
|
||||
setExpandedGroups(new Set());
|
||||
setGroupFindings({});
|
||||
if (view === "asset" && cleanupScope === "all") {
|
||||
setAssetScope(null);
|
||||
}
|
||||
setCaseRefreshKey((v) => v + 1);
|
||||
void refreshStats();
|
||||
if (view === "asset") {
|
||||
void loadFlat();
|
||||
void loadAssetTree();
|
||||
} else if (view === "flat") {
|
||||
void loadFlat();
|
||||
} else if (view === "grouped") {
|
||||
void refreshGroups();
|
||||
}
|
||||
if (res.deleted > 0) {
|
||||
toast.success(t("findingsCleanup.success", { count: res.deleted }));
|
||||
} else {
|
||||
toast.info(t("findingsCleanup.empty"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(t("findingsCleanup.failed", { message: (e as Error).message }));
|
||||
} finally {
|
||||
setCleaning(false);
|
||||
}
|
||||
}
|
||||
|
||||
const openDeepen = React.useCallback((f: Finding) => {
|
||||
setDeepenFinding(f);
|
||||
setDeepenDescription("");
|
||||
@@ -1053,6 +1127,15 @@ export default function FindingsPage() {
|
||||
<Button size="sm" variant="outline" onClick={openExport}>
|
||||
<DownloadIcon /> {ui("screen.76420433f22d1c")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
disabled={cleaning || (statsLoaded && !hasActiveFilters && stats.total === 0 && selectedIds.size === 0)}
|
||||
onClick={openCleanup}
|
||||
>
|
||||
<Trash2Icon /> {t("findingsCleanup.button")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1121,6 +1204,7 @@ export default function FindingsPage() {
|
||||
query={{ severity, status, vulnclass, task, query, sort, ...dateRange }}
|
||||
selectedIds={selectedIds}
|
||||
onSelect={toggleSelected}
|
||||
refreshKey={caseRefreshKey}
|
||||
/>
|
||||
)}
|
||||
{view === "grouped" && (
|
||||
@@ -1394,6 +1478,62 @@ export default function FindingsPage() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={cleanupOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!cleaning) setCleanupOpen(open);
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("findingsCleanup.title")}</DialogTitle>
|
||||
<DialogDescription>{t("findingsCleanup.description")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-2 py-1">
|
||||
<span className="text-muted-foreground text-xs">{t("findingsCleanup.scopeLabel")}</span>
|
||||
<RadioGroup value={cleanupScope} onValueChange={(v) => setCleanupScope(v as typeof cleanupScope)}>
|
||||
<label
|
||||
htmlFor="cleanup-scope-filtered"
|
||||
className={cn("flex items-center gap-2 text-sm", stats.total === 0 && "text-muted-foreground")}
|
||||
>
|
||||
<RadioGroupItem id="cleanup-scope-filtered" value="filtered" disabled={stats.total === 0} />
|
||||
{t("findingsCleanup.scopeFiltered", { count: stats.total })}
|
||||
</label>
|
||||
<label
|
||||
htmlFor="cleanup-scope-selected"
|
||||
className={cn("flex items-center gap-2 text-sm", selectedIds.size === 0 && "text-muted-foreground")}
|
||||
>
|
||||
<RadioGroupItem id="cleanup-scope-selected" value="selected" disabled={selectedIds.size === 0} />
|
||||
{t("findingsCleanup.scopeSelected", { count: selectedIds.size })}
|
||||
</label>
|
||||
<label htmlFor="cleanup-scope-all" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="cleanup-scope-all" value="all" />
|
||||
{t("findingsCleanup.scopeAll")}
|
||||
</label>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCleanupOpen(false)} disabled={cleaning}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={doCleanup}
|
||||
disabled={
|
||||
cleaning ||
|
||||
(cleanupScope === "selected" && selectedIds.size === 0) ||
|
||||
(cleanupScope === "filtered" && stats.total === 0)
|
||||
}
|
||||
>
|
||||
{cleaning ? <Spinner data-icon="inline-start" /> : <Trash2Icon />}
|
||||
{cleaning ? t("findingsCleanup.cleaning") : t("findingsCleanup.confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
@@ -40,6 +42,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
|
||||
import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { LLMProfile, Task } from "@/lib/types";
|
||||
import { MAX_TASK_WORKER_COUNT, parseWorkerCountInput } from "@/lib/types";
|
||||
|
||||
import { AssetsTab } from "./_tabs/assets-tab";
|
||||
import { BroadcastTab } from "./_tabs/broadcast-tab";
|
||||
@@ -212,6 +215,87 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L
|
||||
);
|
||||
}
|
||||
|
||||
function TaskWorkerControl({ task, onUpdated }: { task: Task; onUpdated: (task: Task) => void }) {
|
||||
const { ui } = useUITranslation();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [draft, setDraft] = React.useState(String(task.worker_count ?? 0));
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const actual = task.worker_actual_count;
|
||||
const target = task.worker_target_count;
|
||||
const draining = actual !== undefined && target !== undefined && actual > target;
|
||||
|
||||
const save = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const count = parseWorkerCountInput(draft);
|
||||
if (count === null) {
|
||||
toast.error(ui("taskUI.invalidWorkers", { max: MAX_TASK_WORKER_COUNT }));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await api.updateTask(task.id, { worker_count: count });
|
||||
onUpdated(updated);
|
||||
setOpen(false);
|
||||
toast.success(ui("taskWorkers.saved"));
|
||||
} catch (error) {
|
||||
toast.error(ui("taskWorkers.saveFailed", { message: (error as Error).message }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">{ui("taskWorkers.counts", { actual: actual ?? "—", target: target ?? "—" })}</span>
|
||||
<Popover
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next);
|
||||
if (next) setDraft(String(task.worker_count ?? 0));
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button size="sm" variant="outline" className="h-7 text-xs">
|
||||
{ui("taskWorkers.edit")}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-[min(25rem,calc(100vw-2rem))] gap-4 p-4">
|
||||
<PopoverHeader>
|
||||
<PopoverTitle>{ui("taskWorkers.edit")}</PopoverTitle>
|
||||
<PopoverDescription>{ui("taskWorkers.help")}</PopoverDescription>
|
||||
</PopoverHeader>
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="task-worker-count">{ui("taskWorkers.label")}</Label>
|
||||
<Input
|
||||
id="task-worker-count"
|
||||
type="number"
|
||||
min={0}
|
||||
max={MAX_TASK_WORKER_COUNT}
|
||||
step={1}
|
||||
value={draft}
|
||||
disabled={saving}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{ui("taskWorkers.transitionHelp")}</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setOpen(false)} disabled={saving}>
|
||||
{ui("screen.3fd47edce45b36")}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" disabled={saving}>
|
||||
{saving && <Spinner data-icon="inline-start" />}
|
||||
{ui(saving ? "screen.a1a1720d3eb58a" : "screen.a3030bf8f16dc6")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{draining && <span className="text-amber-600">{ui("taskWorkers.draining")}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TaskDetailInner() {
|
||||
const { ui, liveUI } = useUITranslation();
|
||||
|
||||
@@ -437,6 +521,14 @@ function TaskDetailInner() {
|
||||
</Button>
|
||||
</div>
|
||||
<p className="truncate text-xs text-muted-foreground">{task.goal}</p>
|
||||
<TaskWorkerControl
|
||||
key={task.id}
|
||||
task={task}
|
||||
onUpdated={(updated) => {
|
||||
setTask(updated);
|
||||
load();
|
||||
}}
|
||||
/>
|
||||
{task.paused && task.pause_reason && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-amber-600">
|
||||
<span>
|
||||
|
||||
@@ -49,11 +49,12 @@ const MAX_TOKENS_FIELDS = (ui: UITranslate): { value: string; label: string }[]
|
||||
{ value: NONE, label: ui("screen.af7202f4ddd9ce") },
|
||||
{ value: "max_completion_tokens", label: "max_completion_tokens" },
|
||||
];
|
||||
// 另外两种格式各自定死了字段名,选项对它们无意义,说明文案里直接讲清楚。
|
||||
// 另外几种格式各自定死了字段名,选项对它们无意义,说明文案里直接讲清楚。
|
||||
const MAX_TOKENS_FIELD_HINTS = (ui: UITranslate): Record<string, string> => ({
|
||||
openai: ui("screen.8565b2d7398535"),
|
||||
anthropic: ui("screen.55138cdb37fe16"),
|
||||
"openai-responses": ui("screen.82b05dbd905574"),
|
||||
gemini: ui("llm.maxTokensFieldHint.gemini"),
|
||||
});
|
||||
const EFFORT_LEVELS = (ui: UITranslate): { value: string; label: string }[] => [
|
||||
{ value: NONE, label: ui("screen.d703a9bcd8b626") },
|
||||
@@ -325,7 +326,9 @@ function ProfileSheet({
|
||||
|
||||
const isNew = !profile;
|
||||
const [name, setName] = React.useState("");
|
||||
const [format, setFormat] = React.useState<"anthropic" | "openai" | "openai-responses" | "jev">("anthropic");
|
||||
const [format, setFormat] = React.useState<"anthropic" | "openai" | "openai-responses" | "gemini" | "jev">(
|
||||
"anthropic",
|
||||
);
|
||||
const [model, setModel] = React.useState("");
|
||||
const [baseUrl, setBaseUrl] = React.useState("");
|
||||
const [proxy, setProxy] = React.useState("");
|
||||
@@ -355,7 +358,10 @@ function ProfileSheet({
|
||||
if (!open) return;
|
||||
setName(profile?.name ?? "");
|
||||
setFormat(
|
||||
profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "jev"
|
||||
profile?.format === "openai" ||
|
||||
profile?.format === "openai-responses" ||
|
||||
profile?.format === "gemini" ||
|
||||
profile?.format === "jev"
|
||||
? profile.format
|
||||
: "anthropic",
|
||||
);
|
||||
@@ -509,7 +515,7 @@ function ProfileSheet({
|
||||
<Select
|
||||
value={format}
|
||||
onValueChange={(v) => {
|
||||
const next = v as "anthropic" | "openai" | "openai-responses" | "jev";
|
||||
const next = v as "anthropic" | "openai" | "openai-responses" | "gemini" | "jev";
|
||||
setFormat(next);
|
||||
if (next === "jev" && !model.trim()) setModel("jev-latest");
|
||||
}}
|
||||
@@ -521,6 +527,7 @@ function ProfileSheet({
|
||||
<SelectItem value="anthropic">Anthropic</SelectItem>
|
||||
<SelectItem value="openai">OpenAI (Chat Completions)</SelectItem>
|
||||
<SelectItem value="openai-responses">OpenAI (Responses API)</SelectItem>
|
||||
<SelectItem value="gemini">Google Gemini</SelectItem>
|
||||
<SelectItem value="jev">{ui("screen.1959e996efa50a")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -533,7 +540,7 @@ function ProfileSheet({
|
||||
<Input
|
||||
id="p-model"
|
||||
className="font-mono"
|
||||
placeholder="claude-opus-4-8"
|
||||
placeholder={format === "gemini" ? "gemini-2.5-pro" : "claude-opus-4-8"}
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
/>
|
||||
@@ -585,7 +592,9 @@ function ProfileSheet({
|
||||
<Input
|
||||
id="p-base-url"
|
||||
className="font-mono"
|
||||
placeholder="https://api.openai.com/v1"
|
||||
placeholder={
|
||||
format === "gemini" ? "https://generativelanguage.googleapis.com/v1beta" : "https://api.openai.com/v1"
|
||||
}
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
/>
|
||||
|
||||
@@ -1733,8 +1733,8 @@ export default function SystemSettingsPage() {
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t("settings.workersHelpStart")}
|
||||
<b>{t("settings.futureTasksOnly")}</b>
|
||||
{t("settings.runningTasksUnchanged")}
|
||||
<b>{t("settings.workersLiveUpdate")}</b>
|
||||
{t("settings.workersDrainHelp")}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
|
||||
@@ -448,6 +448,7 @@ export function FindingCaseList({
|
||||
contextTask,
|
||||
readOnly = false,
|
||||
onTotal,
|
||||
refreshKey = 0,
|
||||
}: {
|
||||
query: Omit<FindingQuery, "page" | "pageSize">;
|
||||
selectedIds?: Set<string>;
|
||||
@@ -455,6 +456,7 @@ export function FindingCaseList({
|
||||
contextTask?: string;
|
||||
readOnly?: boolean;
|
||||
onTotal?: (total: number) => void;
|
||||
refreshKey?: number;
|
||||
}) {
|
||||
const { ui } = useUITranslation();
|
||||
|
||||
@@ -464,10 +466,10 @@ export function FindingCaseList({
|
||||
const [error, setError] = React.useState("");
|
||||
const [refresh, setRefresh] = React.useState(0);
|
||||
const key = JSON.stringify(query);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: reset pagination when the filter fingerprint changes.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: reset pagination when the filter fingerprint or external refresh changes.
|
||||
React.useEffect(() => {
|
||||
setPage(1);
|
||||
}, [key]);
|
||||
}, [key, refreshKey]);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: refresh is an explicit reload requested after grouping/retry.
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
@@ -490,7 +492,7 @@ export function FindingCaseList({
|
||||
active = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [key, page, pageSize, refresh]);
|
||||
}, [key, page, pageSize, refresh, refreshKey]);
|
||||
React.useEffect(() => {
|
||||
if (data) onTotal?.(data.total);
|
||||
}, [data, onTotal]);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { buildRawResponse } from "./repeater-http";
|
||||
import { buildRawResponse, rawRequestTarget } from "./repeater-http";
|
||||
import type { RepeaterTab } from "./repeater-state";
|
||||
|
||||
export type RepeaterFilters = { query: string; method: string; path: string; response: string; status: string };
|
||||
@@ -7,13 +7,7 @@ export const DEFAULT_FILTERS: RepeaterFilters = { query: "", method: "all", path
|
||||
export function matchesRepeaterFilters(tab: RepeaterTab, filters: RepeaterFilters): boolean {
|
||||
const includes = (text: string, query: string) => text.toLowerCase().includes(query.trim().toLowerCase());
|
||||
if (filters.method !== "all" && tab.method.toUpperCase() !== filters.method) return false;
|
||||
let path = tab.url;
|
||||
try {
|
||||
const url = new URL(tab.url);
|
||||
path = url.pathname + url.search;
|
||||
} catch {
|
||||
/* Incomplete drafts remain searchable. */
|
||||
}
|
||||
const path = rawRequestTarget(tab.url) || tab.url;
|
||||
if (!includes(path, filters.path)) return false;
|
||||
const rawResponse = tab.response ? `${buildRawResponse(tab.response)}\n${tab.response.error || ""}` : "";
|
||||
if (!includes(rawResponse, filters.response)) return false;
|
||||
|
||||
@@ -103,12 +103,7 @@ export function requestFromTraffic(
|
||||
if (/…\[truncated\] @blob sha256:[a-f0-9]{64}/.test(request.body)) {
|
||||
throw new Error("请求正文为截断预览,请下载完整正文后再导入");
|
||||
}
|
||||
let host = exchange.host;
|
||||
try {
|
||||
host = new URL(exchange.url).host || host;
|
||||
} catch {
|
||||
/* Legacy URL uses the indexed host. */
|
||||
}
|
||||
const host = extractHttpHost(exchange.url) || exchange.host;
|
||||
const headersText = getHostHeader(request.headersText)
|
||||
? request.headersText
|
||||
: setHostHeader(request.headersText, host);
|
||||
@@ -124,26 +119,63 @@ export function requestFromTraffic(
|
||||
};
|
||||
}
|
||||
|
||||
export function connectionOrigin(url: string): string {
|
||||
type SplitHttpUrl = {
|
||||
origin: string;
|
||||
host: string;
|
||||
base: string;
|
||||
rest: string;
|
||||
};
|
||||
|
||||
// Parse only the scheme+authority via WHATWG URL so the raw request-target
|
||||
// (path and query) is never percent-encoded, dot-collapsed, or backslash-rewritten.
|
||||
function splitRawHttpUrl(raw: string): SplitHttpUrl | null {
|
||||
const trimmed = raw.trim();
|
||||
if (!/^https?:\/\//i.test(trimmed)) return null;
|
||||
const schemeEnd = trimmed.indexOf("://") + 3;
|
||||
const restOffset = trimmed.slice(schemeEnd).search(/[/?#]/);
|
||||
const restIndex = restOffset < 0 ? trimmed.length : schemeEnd + restOffset;
|
||||
const authority = trimmed.slice(schemeEnd, restIndex);
|
||||
if (!authority || authority.includes("\\")) return null;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return /^https?:$/.test(parsed.protocol) ? parsed.origin : "";
|
||||
const parsed = new URL(trimmed.slice(0, restIndex));
|
||||
if (!/^https?:$/.test(parsed.protocol) || !parsed.host) return null;
|
||||
return {
|
||||
origin: parsed.origin,
|
||||
host: parsed.host,
|
||||
base: parsed.href.replace(/\/$/, ""),
|
||||
rest: trimmed.slice(restIndex),
|
||||
};
|
||||
} catch {
|
||||
return "";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRequestTarget(rest: string): string {
|
||||
if (!rest) return "/";
|
||||
return rest.startsWith("?") ? `/${rest}` : rest;
|
||||
}
|
||||
|
||||
export function extractHttpHost(url: string): string {
|
||||
const parsed = splitRawHttpUrl(url);
|
||||
return parsed ? parsed.host : "";
|
||||
}
|
||||
|
||||
export function rawRequestTarget(url: string): string {
|
||||
const parsed = splitRawHttpUrl(url);
|
||||
if (!parsed) return "";
|
||||
return normalizeRequestTarget(parsed.rest.split("#", 1)[0]);
|
||||
}
|
||||
|
||||
export function connectionOrigin(url: string): string {
|
||||
const parsed = splitRawHttpUrl(url);
|
||||
return parsed ? parsed.origin : "";
|
||||
}
|
||||
|
||||
export function buildRawRequest(request: RepeaterInitial): string {
|
||||
if (request.rawRequest !== undefined) return request.rawRequest;
|
||||
let target = "/";
|
||||
let host = "";
|
||||
try {
|
||||
const url = new URL(request.url ?? "");
|
||||
target = url.pathname + url.search;
|
||||
host = url.host;
|
||||
} catch {
|
||||
/* New empty draft. */
|
||||
}
|
||||
const parsed = splitRawHttpUrl(request.url ?? "");
|
||||
const target = parsed ? normalizeRequestTarget(parsed.rest.split("#", 1)[0]) : "/";
|
||||
const host = parsed ? parsed.host : "";
|
||||
const headersText = request.headersText?.trim() ? request.headersText : `Host: ${host}`;
|
||||
return `${request.method ?? "GET"} ${target} HTTP/1.1\n${joinRequestText(headersText, request.body ?? "")}`;
|
||||
}
|
||||
@@ -157,19 +189,24 @@ export function parseRawRequest(
|
||||
const match = /^([A-Za-z]+)\s+(\S+)\s+(HTTP\/(?:1\.[01]|2(?:\.0)?))$/.exec(line);
|
||||
if (!match) throw new Error("请求首行应为:POST /path HTTP/1.1");
|
||||
const parts = splitRequestText(newline < 0 ? "" : text.slice(newline + 1));
|
||||
let url: URL;
|
||||
if (/^https?:\/\//i.test(match[2])) url = new URL(match[2]);
|
||||
else {
|
||||
if (!match[2].startsWith("/")) throw new Error("请求路径必须以 / 开头,或填写完整 http/https URL");
|
||||
const requestTarget = match[2];
|
||||
let url: string;
|
||||
if (/^https?:\/\//i.test(requestTarget)) {
|
||||
const parsed = splitRawHttpUrl(requestTarget);
|
||||
if (!parsed) throw new TypeError(`Invalid URL: ${requestTarget}`);
|
||||
if (parsed.rest.includes("#")) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
|
||||
url = `${parsed.base}${normalizeRequestTarget(parsed.rest)}`;
|
||||
} else {
|
||||
if (!requestTarget.startsWith("/")) throw new Error("请求路径必须以 / 开头,或填写完整 http/https URL");
|
||||
const origin = connectionOrigin(targetOrigin) || connectionOrigin(`https://${getHostHeader(parts.headersText)}`);
|
||||
if (!origin) throw new Error("请填写 Host 请求头或设置发送目标");
|
||||
url = new URL(origin + match[2]);
|
||||
if (requestTarget.includes("#")) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
|
||||
url = `${origin}${requestTarget}`;
|
||||
}
|
||||
if (url.hash) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
|
||||
return {
|
||||
...parts,
|
||||
method: match[1].toUpperCase(),
|
||||
url: url.href,
|
||||
url,
|
||||
httpVersion: match[3] === "HTTP/2" ? "HTTP/2.0" : match[3],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { RepeaterSendResponse } from "@/lib/types";
|
||||
|
||||
import type { RepeaterInitial } from "./repeater-http";
|
||||
import { extractHttpHost, type RepeaterInitial } from "./repeater-http";
|
||||
|
||||
export const STORAGE_KEY = "artex_repeater_workspace_v1";
|
||||
export const MAX_HISTORY = 20;
|
||||
@@ -99,12 +99,7 @@ export function seedWorkspace(
|
||||
opts: TabOptions = {},
|
||||
): RepeaterWorkspace {
|
||||
const method = initial.method?.trim().toUpperCase() || "GET";
|
||||
let host = "";
|
||||
try {
|
||||
host = new URL(initial.url ?? "").host;
|
||||
} catch {
|
||||
/* An empty/unfinished URL is a valid draft. */
|
||||
}
|
||||
const host = extractHttpHost(initial.url ?? "");
|
||||
return addTab(
|
||||
workspace,
|
||||
{ ...initial, method, source: meta },
|
||||
|
||||
@@ -582,3 +582,66 @@ test("evidence import preserves captured request line and protocol rather than r
|
||||
assert.equal(imported.targetOrigin, "https://example.test");
|
||||
assert.equal(buildRawRequest(imported), imported.rawRequest);
|
||||
});
|
||||
|
||||
test("raw request-target characters in query and path are preserved without WHATWG URL normalization", () => {
|
||||
const sqli = parseRawRequest("GET /item?id=1' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(sqli.url, "https://example.test/item?id=1'");
|
||||
|
||||
const specialQuery = parseRawRequest(
|
||||
"GET /item?id=1'\"<>`{}\\| HTTP/1.1\nHost: example.test\n\n",
|
||||
"http://example.test:8080",
|
||||
);
|
||||
assert.equal(specialQuery.url, "http://example.test:8080/item?id=1'\"<>`{}\\|");
|
||||
|
||||
const traversal = parseRawRequest("GET /a/../b/./c?id=1' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(traversal.url, "https://example.test/a/../b/./c?id=1'");
|
||||
|
||||
const encodedDots = parseRawRequest("GET /a/%2e%2e/b?x=' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(encodedDots.url, "https://example.test/a/%2e%2e/b?x='");
|
||||
|
||||
const rawPathChars = parseRawRequest("GET /a\\b\"c?q=' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(rawPathChars.url, "https://example.test/a\\b\"c?q='");
|
||||
|
||||
const absolute = parseRawRequest("GET http://elsewhere.test:8080/a/../item?id=1'\"<> HTTP/1.1\nHost: vhost.test\n\n");
|
||||
assert.equal(absolute.url, "http://elsewhere.test:8080/a/../item?id=1'\"<>");
|
||||
|
||||
assert.equal(
|
||||
parseRawRequest("GET http://elsewhere.test HTTP/1.1\nHost: elsewhere.test\n\n").url,
|
||||
"http://elsewhere.test/",
|
||||
);
|
||||
assert.equal(
|
||||
parseRawRequest("GET http://elsewhere.test?id=1' HTTP/1.1\nHost: elsewhere.test\n\n").url,
|
||||
"http://elsewhere.test/?id=1'",
|
||||
);
|
||||
|
||||
assert.throws(() => parseRawRequest("GET /item?id=1'#frag HTTP/1.1\nHost: example.test\n\n"), /URL 片段/);
|
||||
assert.throws(() => parseRawRequest("GET /item# HTTP/1.1\nHost: example.test\n\n"), /URL 片段/);
|
||||
assert.throws(
|
||||
() => parseRawRequest("GET http://example.test/item?id=1'#frag HTTP/1.1\nHost: example.test\n\n"),
|
||||
/URL 片段/,
|
||||
);
|
||||
assert.throws(() => parseRawRequest("GET http://example.test\\evil/path HTTP/1.1\nHost: example.test\n\n"));
|
||||
|
||||
const built = buildRawRequest({
|
||||
method: "GET",
|
||||
url: "https://example.test:8443/a/../item?id=1'",
|
||||
});
|
||||
assert.equal(built, "GET /a/../item?id=1' HTTP/1.1\nHost: example.test:8443\n\n");
|
||||
|
||||
const fromTraffic = requestFromTraffic("GET /item?id=1' HTTP/1.1\r\nHost: example.test\r\n\r\n", {
|
||||
method: "GET",
|
||||
url: "https://example.test/item?id=1'",
|
||||
host: "example.test",
|
||||
});
|
||||
assert.equal(fromTraffic.url, "https://example.test/item?id=1'");
|
||||
assert.match(fromTraffic.rawRequest, /^GET \/item\?id=1' HTTP\/1\.1\n/);
|
||||
|
||||
const tab = {
|
||||
...defaultWorkspace().tabs[0],
|
||||
method: "GET",
|
||||
url: "https://example.test/a/../item?id=1'",
|
||||
rawRequest: "GET /a/../item?id=1' HTTP/1.1\nHost: example.test\n\n",
|
||||
};
|
||||
assert.equal(matchesRepeaterFilters(tab, { ...DEFAULT_FILTERS, path: "id=1'" }), true);
|
||||
assert.equal(matchesRepeaterFilters(tab, { ...DEFAULT_FILTERS, path: "/a/../item" }), true);
|
||||
});
|
||||
@@ -214,6 +214,25 @@ export const messages = {
|
||||
],
|
||||
"ui.ascending": ["正序", "ascending"],
|
||||
"ui.descending": ["倒序", "descending"],
|
||||
"llm.maxTokensFieldHint.gemini": [
|
||||
"仅 openai 格式可选。Gemini 的字段名固定为 maxOutputTokens。",
|
||||
"Only configurable for the openai format. Gemini uses maxOutputTokens.",
|
||||
],
|
||||
"findingsCleanup.button": ["一键清理", "One-click cleanup"],
|
||||
"findingsCleanup.title": ["一键清理历史漏洞", "Clean up historical findings"],
|
||||
"findingsCleanup.description": [
|
||||
"永久删除所选范围内的漏洞发现记录及其来源探索节点、复测记录和归并成员关系,删除后无法恢复。",
|
||||
"Permanently delete matching findings along with their originating exploration nodes, retest records, and case memberships. This action cannot be undone.",
|
||||
],
|
||||
"findingsCleanup.scopeLabel": ["清理范围", "Cleanup scope"],
|
||||
"findingsCleanup.scopeFiltered": ["当前筛选结果({{count}} 条)", "Current filter results ({{count}})"],
|
||||
"findingsCleanup.scopeSelected": ["已勾选漏洞({{count}} 条)", "Selected findings ({{count}})"],
|
||||
"findingsCleanup.scopeAll": ["全部历史漏洞", "All historical findings"],
|
||||
"findingsCleanup.confirm": ["确认清理", "Confirm cleanup"],
|
||||
"findingsCleanup.cleaning": ["清理中…", "Cleaning up…"],
|
||||
"findingsCleanup.success": ["已清理 {{count}} 条漏洞", "Deleted {{count}} finding(s)"],
|
||||
"findingsCleanup.empty": ["没有符合条件的漏洞可清理", "No matching findings to delete"],
|
||||
"findingsCleanup.failed": ["清理失败:{{message}}", "Cleanup failed: {{message}}"],
|
||||
} satisfies Record<string, readonly [string, string]>;
|
||||
|
||||
const statuses: Record<string, readonly (readonly [string, string, string])[]> = {
|
||||
|
||||
@@ -12,14 +12,14 @@ export const settingsMessages = {
|
||||
"settings.workerLimit": ["Worker 总数不能超过 50", "The total number of Workers cannot exceed 50"],
|
||||
"settings.duplicatePoolProfile": ["不能重复选择同一个 LLM 配置", "Each LLM profile can only be selected once"],
|
||||
"settings.workerPoolsSaved": [
|
||||
"已保存多模型 Worker 池(对之后启动的任务生效)",
|
||||
"Model pools saved; applies to tasks started afterward",
|
||||
"已保存多模型 Worker 池,跟随全局配置的任务已热更新",
|
||||
"Model pools saved; tasks following the global configuration have been updated live",
|
||||
],
|
||||
"settings.saveFailed": ["保存失败:{{message}}", "Could not save: {{message}}"],
|
||||
"settings.positiveConcurrency": ["并发数必须是大于 0 的整数", "Concurrency must be a positive whole number"],
|
||||
"settings.workersSaved": [
|
||||
"已保存并发工作 agent 数(对之后启动的任务生效)",
|
||||
"Worker count saved; applies to tasks started afterward",
|
||||
"已保存工作并发,跟随全局配置的任务已热更新",
|
||||
"Worker count saved; tasks following the global configuration have been updated live",
|
||||
],
|
||||
"settings.saveFailedPrefix": ["保存失败:", "Could not save: "],
|
||||
"settings.pythonSaved": ["已保存 Python 解释器配置", "Python interpreter settings saved"],
|
||||
@@ -473,8 +473,14 @@ export const settingsMessages = {
|
||||
"每个任务并发运行的工作 agent 数量(默认 3)。数值越大并发探测越多、消耗也越高。修改后",
|
||||
"The number of Workers running concurrently per task (default: 3). More Workers mean more parallel probes and higher usage. Changes ",
|
||||
],
|
||||
"settings.futureTasksOnly": ["对之后启动的任务生效", "apply to tasks started afterward"],
|
||||
"settings.runningTasksUnchanged": [",正在运行的任务不受影响。", "; running tasks are unaffected."],
|
||||
"settings.workersLiveUpdate": [
|
||||
"即时更新跟随全局配置(worker_count = 0)的任务",
|
||||
"apply immediately to tasks following the global configuration (worker_count = 0)",
|
||||
],
|
||||
"settings.workersDrainHelp": [
|
||||
";单任务覆盖值不受影响。增容启动新 Worker loops;缩容等待在跑意图完成后退出,不会强杀,实际数量可能暂时高于目标。",
|
||||
"; per-task overrides are unchanged. Scaling up starts new Worker loops; scaling down lets running intents finish before loops exit, without force-cancelling them. Actual counts may temporarily exceed target.",
|
||||
],
|
||||
"settings.workerPools": ["多模型 Worker 池", "Model pools"],
|
||||
"settings.addPool": ["添加模型池", "Add model pool"],
|
||||
"settings.unavailableProfile": ["配置 #{{id}} 已删除/不可用", "Profile #{{id}} deleted or unavailable"],
|
||||
|
||||
@@ -1,4 +1,21 @@
|
||||
export const taskMessages = {
|
||||
"taskWorkers.edit": ["调整 Worker 并发", "Adjust Worker concurrency"],
|
||||
"taskWorkers.label": ["Worker 数量(0–50)", "Worker count (0–50)"],
|
||||
"taskWorkers.counts": ["Worker 实际 / 目标:{{actual}} / {{target}}", "Workers actual / target: {{actual}} / {{target}}"],
|
||||
"taskWorkers.help": [
|
||||
"0 表示跟随全局 Worker 配置;1–50 为本任务覆盖值,保存后热更新,无需重启任务。",
|
||||
"Use 0 to follow the global Worker configuration, or 1–50 to override it for this task. Saving applies changes live without restarting the task.",
|
||||
],
|
||||
"taskWorkers.transitionHelp": [
|
||||
"实际数量是存活的 Worker loops(含缩容退出中的 loops),不是正在执行的意图数。增容会启动新 loops;缩容等待正在执行的意图完成后退出,不会强杀意图,因此实际数量可能暂时高于目标。",
|
||||
"Actual counts live Worker loops, including draining loops, not in-flight intents. Scaling up starts new loops. Scaling down lets running intents finish before loops exit, without force-cancelling them, so actual may temporarily exceed target.",
|
||||
],
|
||||
"taskWorkers.draining": [
|
||||
"缩容过渡中:等待在跑意图完成,不会强杀。",
|
||||
"Scaling down: waiting for running intents to finish; they will not be force-cancelled.",
|
||||
],
|
||||
"taskWorkers.saved": ["Worker 并发已更新", "Worker concurrency updated"],
|
||||
"taskWorkers.saveFailed": ["Worker 并发更新失败:{{message}}", "Could not update Worker concurrency: {{message}}"],
|
||||
"taskFiles.tab": ["文件", "Files"],
|
||||
"taskFiles.tree": ["目录树", "Directory tree"],
|
||||
"taskFiles.recent": ["最近文件", "Recent files"],
|
||||
|
||||
+25
-1
@@ -524,7 +524,7 @@ export const api = {
|
||||
taskCategories: () => get<{ categories: TaskCategory[] }>("/task-categories").then((r) => arr(r.categories)),
|
||||
updateTask: (
|
||||
id: string,
|
||||
input: { name?: string; pinned?: boolean; remark?: string; share_global_assets?: boolean },
|
||||
input: { name?: string; pinned?: boolean; remark?: string; share_global_assets?: boolean; worker_count?: number },
|
||||
) => patch<Task>(`/tasks/${id}`, input),
|
||||
renameTask: (id: string, name: string) => patch<Task>(`/tasks/${id}`, { name }),
|
||||
pinTask: (id: string, pinned: boolean) => patch<Task>(`/tasks/${id}`, { pinned }),
|
||||
@@ -1011,6 +1011,30 @@ export const api = {
|
||||
) => patch<Finding>(`/exploration/findings/${id}`, fields),
|
||||
// 删除漏洞:移除 findings 记录 + 来源探索节点(从发现列表/任务发现 Tab/探索图一并消失)。
|
||||
deleteFinding: (id: string) => del<{ deleted: boolean; id: number }>(`/exploration/findings/${id}`),
|
||||
// 批量一键清理漏洞:按范围(当前筛选/全部/已勾选)移除 findings 记录及来源探索节点。
|
||||
cleanupFindings: (opts: {
|
||||
scope: "filtered" | "all" | "selected";
|
||||
filters?: Omit<FindingQuery, "page" | "pageSize">;
|
||||
ids?: string[];
|
||||
}) => {
|
||||
const body: Record<string, unknown> = { scope: opts.scope };
|
||||
if (opts.scope === "selected") {
|
||||
body.ids = opts.ids ?? [];
|
||||
} else if (opts.scope === "filtered" && opts.filters) {
|
||||
const f = opts.filters;
|
||||
body.filters = {
|
||||
...(f.severity && f.severity !== "all" ? { severity: f.severity } : {}),
|
||||
...(f.status && f.status !== "all" ? { status: f.status } : {}),
|
||||
...(f.vulnclass && f.vulnclass !== "all" ? { vulnclass: f.vulnclass } : {}),
|
||||
...(f.task && f.task !== "all" ? { task_id: f.task } : {}),
|
||||
...(f.query?.trim() ? { q: f.query.trim() } : {}),
|
||||
...(f.from ? { from: f.from } : {}),
|
||||
...(f.to ? { to: f.to } : {}),
|
||||
...(f.assetScope ? { asset_scope: f.assetScope } : {}),
|
||||
};
|
||||
}
|
||||
return del<{ deleted: number }>("/exploration/findings", body);
|
||||
},
|
||||
findingRetests: (id: string) =>
|
||||
get<{ retests: FindingRetest[] }>(`/exploration/findings/${encodeURIComponent(id)}/retests`).then((r) =>
|
||||
arr(r.retests),
|
||||
|
||||
@@ -58,6 +58,9 @@ export const tasks: Task[] = [
|
||||
description: "Acme 官网与后台外部渗透(acme.com)",
|
||||
goal: "拿到 acme.com 后台管理权限,确认可读取用户敏感数据。",
|
||||
status: "running",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 3,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-24T09:12:00Z"),
|
||||
created_unix: 1785489120,
|
||||
active_run_seconds: 28800,
|
||||
@@ -87,6 +90,9 @@ export const tasks: Task[] = [
|
||||
description: "api.acme.com 越权与注入测试",
|
||||
goal: "评估 api.acme.com 订单/用户接口的越权(IDOR)与注入风险。",
|
||||
status: "running",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 3,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-25T14:05:00Z"),
|
||||
created_unix: 1785592500,
|
||||
active_run_seconds: 14400,
|
||||
@@ -116,6 +122,9 @@ export const tasks: Task[] = [
|
||||
description: "shop.acme.com 支付与订单链路",
|
||||
goal: "评估支付与订单接口的越权、金额篡改与竞态风险。",
|
||||
status: "paused",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 3,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-22T08:30:00Z"),
|
||||
created_unix: 1785313800,
|
||||
active_run_seconds: 21600,
|
||||
@@ -144,6 +153,9 @@ export const tasks: Task[] = [
|
||||
description: "对外暴露面侦察(VPN / 边界服务)",
|
||||
goal: "识别 acme.com 对外暴露的可利用边界服务。",
|
||||
status: "done",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 0,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-18T08:00:00Z"),
|
||||
created_unix: 1784966400,
|
||||
active_run_seconds: 86400,
|
||||
|
||||
@@ -48,6 +48,7 @@ const mockInterceptHistory = structuredClone(D.interceptHistory);
|
||||
const mockInterceptPending = structuredClone(D.interceptPending);
|
||||
const mockInterceptDetails = structuredClone(D.interceptDetails);
|
||||
const mockTasks = structuredClone(D.tasks);
|
||||
const mockWorkerDrainUntil = new Map<string, number>();
|
||||
const mockFindings = structuredClone(D.findings);
|
||||
const mockLLMRecords = structuredClone(D.llmRecords);
|
||||
const mockTaskTemplates = structuredClone(D.taskTemplates);
|
||||
@@ -256,7 +257,33 @@ function mockTaskArchiveBlocker(taskID: string): string | undefined {
|
||||
)?.id;
|
||||
}
|
||||
|
||||
function reconcileMockWorkers(task: Task): void {
|
||||
const target = task.worker_count || D.settings.workers || 3;
|
||||
const previousTarget = task.worker_target_count;
|
||||
task.worker_target_count = target;
|
||||
if (task.status !== "running" && task.status !== "paused") {
|
||||
task.worker_actual_count = 0;
|
||||
mockWorkerDrainUntil.delete(task.id);
|
||||
return;
|
||||
}
|
||||
const actual = task.worker_actual_count ?? target;
|
||||
if (actual <= target) {
|
||||
task.worker_actual_count = target;
|
||||
mockWorkerDrainUntil.delete(task.id);
|
||||
} else {
|
||||
// Demo loops drain independently of in_flight; retain them across polls briefly.
|
||||
if (!mockWorkerDrainUntil.has(task.id) || previousTarget !== target) {
|
||||
mockWorkerDrainUntil.set(task.id, Date.now() + 10_000);
|
||||
}
|
||||
if (Date.now() >= (mockWorkerDrainUntil.get(task.id) ?? 0)) {
|
||||
task.worker_actual_count = target;
|
||||
mockWorkerDrainUntil.delete(task.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function publicMockTask(task: Task): Task {
|
||||
reconcileMockWorkers(task);
|
||||
const item = structuredClone(task);
|
||||
item.numeric_id = mockTaskAssetIDs.get(task.id);
|
||||
item.share_global_assets = task.share_global_assets ?? false;
|
||||
@@ -483,6 +510,10 @@ function mockFilterFindings(q: URLSearchParams): (typeof mockFindings)[number][]
|
||||
if (vulnclass) list = list.filter((finding) => finding.vulnclass === vulnclass);
|
||||
if (taskID === "__unassigned__") list = list.filter((finding) => !finding.task_id);
|
||||
else if (taskID) list = list.filter((finding) => finding.task_id === taskID);
|
||||
const fromTs = q.get("from") ? Date.parse(q.get("from") as string) : Number.NaN;
|
||||
const toTs = q.get("to") ? Date.parse(q.get("to") as string) : Number.NaN;
|
||||
if (Number.isFinite(fromTs)) list = list.filter((finding) => Date.parse(finding.ts) >= fromTs);
|
||||
if (Number.isFinite(toTs)) list = list.filter((finding) => Date.parse(finding.ts) <= toTs);
|
||||
return list;
|
||||
}
|
||||
|
||||
@@ -1323,6 +1354,7 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
company_ids: companyIDs,
|
||||
share_global_assets: b.share_global_assets === true,
|
||||
};
|
||||
reconcileMockWorkers(created);
|
||||
// Validate the attached preview schedule before mutating task state.
|
||||
const numericTaskID = nextMockTaskAssetID;
|
||||
if (b.schedule && typeof b.schedule === "object") {
|
||||
@@ -1527,8 +1559,10 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
const namePresent = has("name") && b.name !== null;
|
||||
const remarkPresent = has("remark") && b.remark !== null;
|
||||
const pinnedPresent = has("pinned") && b.pinned !== null;
|
||||
if (!namePresent && !remarkPresent && !pinnedPresent && !sharingPresent)
|
||||
throw new Error("至少需要提供 name、pinned、remark 或 share_global_assets");
|
||||
const workerCountPresent = has("worker_count") && b.worker_count !== null;
|
||||
const nextWorkerCount = workerCountPresent ? mockWorkerCount(b.worker_count) : task.worker_count;
|
||||
if (!namePresent && !remarkPresent && !pinnedPresent && !sharingPresent && !workerCountPresent)
|
||||
throw new Error("至少需要提供 name、pinned、remark、share_global_assets 或 worker_count");
|
||||
let nextName = task.name;
|
||||
let nextRemark = task.remark;
|
||||
let nextPinned = task.pinned;
|
||||
@@ -1550,8 +1584,9 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
task.remark = nextRemark;
|
||||
task.pinned = nextPinned;
|
||||
task.pinned_at = nextPinnedAt;
|
||||
task.worker_count = nextWorkerCount;
|
||||
sortMockTasks();
|
||||
return structuredClone(task);
|
||||
return publicMockTask(task);
|
||||
}
|
||||
if (seg[0] === "tasks" && seg.length === 2 && m === "DELETE") {
|
||||
const id = seg[1];
|
||||
@@ -2317,6 +2352,11 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
if (seg[0] === "exploration" && seg[1] === "findings" && seg.length === 3 && seg[2] !== "stats") {
|
||||
const f = mockFindings.find((x) => x.id === seg[2]);
|
||||
if (!f) return {};
|
||||
if (m === "DELETE") {
|
||||
const idx = mockFindings.findIndex((x) => x.id === seg[2]);
|
||||
if (idx >= 0) mockFindings.splice(idx, 1);
|
||||
return { deleted: idx >= 0, id: Number(seg[2]) || 0 };
|
||||
}
|
||||
if (m === "PATCH") {
|
||||
if (typeof b.status === "string") f.status = b.status as typeof f.status;
|
||||
if (typeof b.severity === "string") f.severity = b.severity as typeof f.severity;
|
||||
@@ -2339,6 +2379,41 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
};
|
||||
}
|
||||
if (path === "/exploration/findings") {
|
||||
if (m === "DELETE") {
|
||||
const scope = (typeof b.scope === "string" ? b.scope : q.get("scope"))?.trim() ?? "";
|
||||
let targets: (typeof mockFindings)[number][] = [];
|
||||
if (scope === "all") {
|
||||
targets = [...mockFindings];
|
||||
} else if (scope === "selected") {
|
||||
const rawIds = Array.isArray(b.ids)
|
||||
? b.ids.map((v) => String(v))
|
||||
: (q.get("ids") ?? "")
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const idSet = new Set(rawIds);
|
||||
targets = mockFindings.filter((f) => idSet.has(f.id));
|
||||
} else if (scope === "filtered") {
|
||||
const params = new URLSearchParams(q);
|
||||
if (b.filters && typeof b.filters === "object") {
|
||||
for (const [k, v] of Object.entries(b.filters as Record<string, unknown>)) {
|
||||
if (typeof v === "string" && v) params.set(k, v);
|
||||
}
|
||||
}
|
||||
targets = mockApplyAssetScope(mockFilterFindings(params), params.get("asset_scope"));
|
||||
} else {
|
||||
throw new Error(`bad scope: ${scope}`);
|
||||
}
|
||||
const targetSet = new Set(targets.map((f) => f.id));
|
||||
let deleted = 0;
|
||||
for (let i = mockFindings.length - 1; i >= 0; i--) {
|
||||
if (targetSet.has(mockFindings[i].id)) {
|
||||
mockFindings.splice(i, 1);
|
||||
deleted++;
|
||||
}
|
||||
}
|
||||
return { deleted };
|
||||
}
|
||||
// finding_id=id:真后端用独立表行 id 作为状态/详情句柄,mock 里用自身 id 顶上。
|
||||
// report 仅详情接口返回,列表剥掉(与后端一致)。
|
||||
const withFid = (f: (typeof mockFindings)[number]) => ({
|
||||
@@ -2463,6 +2538,7 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
next.workers = next.worker_pools.reduce((sum, pool) => sum + Number(pool.workers), 0);
|
||||
}
|
||||
Object.assign(D.settings, next);
|
||||
for (const task of mockTasks) reconcileMockWorkers(task);
|
||||
return next;
|
||||
}
|
||||
if (path === "/settings/basic-auth" && m === "GET") return { enabled: false, username: "", password_set: false };
|
||||
|
||||
@@ -26,6 +26,8 @@ export interface Task {
|
||||
id: string;
|
||||
remark?: string;
|
||||
worker_count?: number; // 本任务 Worker 数;0/缺省=用全局默认
|
||||
worker_actual_count?: number; // 当前存活的 Worker pool loops,含缩容退出中的 loops
|
||||
worker_target_count?: number; // 当前期望的 Worker slots 数量
|
||||
name?: string; // 可选任务名称;空/缺省=未命名,展示时回退到描述
|
||||
category_id?: number;
|
||||
category_name?: string;
|
||||
@@ -1028,7 +1030,7 @@ export interface Settings {
|
||||
show_egress_ip?: boolean; // 在顶栏显示直连 / 全局代理出口 IP;默认关闭
|
||||
egress_probe_url?: string; // 自定义 IP 探测服务;空=默认公共回显服务
|
||||
python_interpreter?: string; // 自定义脚本工具的 python 解释器路径(空=运行时检测)
|
||||
workers?: number; // 并发工作 agent 数(默认3);对之后启动的任务生效
|
||||
workers?: number; // 并发工作 agent 数(默认3);热更新跟随全局配置的任务
|
||||
worker_pools: WorkerPool[];
|
||||
// 任务并发上限:同时「运行中」的任务数上限。关闭=不限;开启后新建任务超限则排队,有空位自动启动。
|
||||
task_concurrency_enabled?: boolean; // 默认 false
|
||||
@@ -1154,7 +1156,7 @@ export interface NotificationDelivery {
|
||||
export interface LLMProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
format: "openai" | "anthropic" | "openai-responses" | "jev";
|
||||
format: "openai" | "anthropic" | "openai-responses" | "gemini" | "jev";
|
||||
base_url?: string;
|
||||
proxy?: string;
|
||||
model: string;
|
||||
|
||||
Reference in new issue
Block a user