-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcnvd-plugin.ts
More file actions
975 lines (895 loc) · 30.4 KB
/
Copy pathcnvd-plugin.ts
File metadata and controls
975 lines (895 loc) · 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
import { createHash } from "node:crypto"
import {
appendFileSync,
existsSync,
mkdirSync,
readFileSync,
writeFileSync,
} from "node:fs"
import { join } from "node:path"
import { tool, type Plugin } from "@opencode-ai/plugin"
type ScopeEntry = {
target: string
owner?: string
authorization?: string
expiresAt?: string
notes?: string
}
type MemoryRecord = {
id: string
ts: string
kind: string
agent?: string
target?: string
title?: string
content: string
tags: string[]
severity?: string
status?: string
}
type RiskRecord = {
id: string
ts: string
toolName: string
args: Record<string, unknown>
reason: string
status: "pending" | "approved" | "rejected"
decisionReason?: string
}
type StageName =
| "scope"
| "asset"
| "analysis"
| "cve"
| "scan"
| "validate"
| "audit"
| "report"
| "risk_review"
type StageStatus = "pending" | "in_progress" | "blocked" | "done"
type MemoryState = {
scope: ScopeEntry[]
records: MemoryRecord[]
risks: RiskRecord[]
stages: Record<StageName, StageStatus>
}
const defaultStages: Record<StageName, StageStatus> = {
scope: "pending",
asset: "pending",
analysis: "pending",
cve: "pending",
scan: "pending",
validate: "pending",
audit: "pending",
report: "pending",
risk_review: "pending",
}
const writeTools = new Set(["write", "edit", "patch", "todowrite"])
const riskToolPatterns = [
/post[_-]?exploit/i,
/persistence/i,
/lateral/i,
/credential/i,
/webshell/i,
/stager/i,
/evasion/i,
/bypass/i,
]
const destructiveShellPatterns = [
/\brm\s+-/i,
/\bmv\s+/i,
/\bchmod\s+/i,
/\bchown\s+/i,
/\bkill(?:all)?\s+/i,
/\bpkill\s+/i,
/\bdd\s+/i,
/\bmkfs\b/i,
/\btruncate\s+/i,
/\bsed\s+-i\b/i,
/\bperl\s+-pi\b/i,
/\bpython\d*\s+-c\b.*\b(open|unlink|remove|rmdir|shutil\.rmtree)\b/i,
/\bcurl\b.*\s-X\s*(POST|PUT|PATCH|DELETE)\b/i,
]
function now() {
return new Date().toISOString()
}
function makeId(prefix: string, value: unknown) {
return `${prefix}_${createHash("sha256")
.update(`${now()}:${JSON.stringify(value)}`)
.digest("hex")
.slice(0, 12)}`
}
function normalizeTarget(value: string) {
return value.trim().replace(/\/+$/, "")
}
function safeCampaignId(value: string) {
const normalized = value.trim().replace(/[^\p{L}\p{N}._-]+/gu, "-")
return normalized.replace(/^-+|-+$/g, "") || `campaign-${Date.now()}`
}
function tokenize(value: string) {
return value
.toLowerCase()
.split(/[^a-z0-9\u4e00-\u9fa5._:/-]+/u)
.filter((item) => item.length >= 2)
}
function unique(values: string[]) {
return [...new Set(values)]
}
function loadJson<T>(filePath: string, fallback: T): T {
if (!existsSync(filePath)) return fallback
try {
return JSON.parse(readFileSync(filePath, "utf8")) as T
} catch {
return fallback
}
}
async function loadBunSqlite(): Promise<any | undefined> {
try {
const dynamicImport = new Function("specifier", "return import(specifier)")
return await dynamicImport("bun:sqlite")
} catch {
return undefined
}
}
function createDefaultState(): MemoryState {
return {
scope: [],
records: [],
risks: [],
stages: { ...defaultStages },
}
}
async function createMemoryStore(root: string) {
const campaignsDir = root
const activeCampaignPath = join(root, "cnvd-active-campaign.txt")
const sqlite = await loadBunSqlite()
const Database = sqlite?.Database
let campaignId = existsSync(activeCampaignPath)
? safeCampaignId(readFileSync(activeCampaignPath, "utf8"))
: "default"
let campaignDir = ""
let db: any | undefined
let state = createDefaultState()
const scope = new Map<string, ScopeEntry>()
function currentPaths() {
return {
campaignDir,
dbPath: join(campaignDir, "campaign.db"),
statePath: join(campaignDir, "state.json"),
eventLogPath: join(campaignDir, "events.jsonl"),
riskLogPath: join(campaignDir, "risk-queue.jsonl"),
scratchboardPath: join(campaignDir, "scratchboard.md"),
evidenceDir: join(campaignDir, "evidence"),
reportsDir: join(campaignDir, "reports"),
tmpDir: join(campaignDir, "tmp"),
}
}
function exec(sql: string) {
db?.exec(sql)
}
function queryAll(sql: string, params: unknown[] = []) {
if (!db) return []
return db.query(sql).all(...params)
}
function queryGet(sql: string, params: unknown[] = []) {
if (!db) return undefined
return db.query(sql).get(...params)
}
function run(sql: string, params: unknown[] = []) {
db?.query(sql).run(...params)
}
function initDatabase() {
if (!db) return
exec(`
CREATE TABLE IF NOT EXISTS campaigns (
id TEXT PRIMARY KEY,
title TEXT,
status TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS scopes (
target TEXT PRIMARY KEY,
owner TEXT,
authorization TEXT,
expires_at TEXT,
notes TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS stages (
name TEXT PRIMARY KEY,
status TEXT NOT NULL,
notes TEXT,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS memory_records (
id TEXT PRIMARY KEY,
ts TEXT NOT NULL,
kind TEXT NOT NULL,
agent TEXT,
target TEXT,
title TEXT,
content TEXT NOT NULL,
tags TEXT NOT NULL,
severity TEXT,
status TEXT
);
CREATE TABLE IF NOT EXISTS risk_queue (
id TEXT PRIMARY KEY,
ts TEXT NOT NULL,
tool_name TEXT NOT NULL,
args_json TEXT NOT NULL,
reason TEXT NOT NULL,
status TEXT NOT NULL,
decision_reason TEXT
);
CREATE TABLE IF NOT EXISTS audit_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL,
kind TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_memory_kind ON memory_records(kind);
CREATE INDEX IF NOT EXISTS idx_memory_target ON memory_records(target);
CREATE INDEX IF NOT EXISTS idx_risk_status ON risk_queue(status);
`)
run(
"INSERT OR IGNORE INTO campaigns (id, title, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
[campaignId, campaignId, "active", now(), now()],
)
for (const [name, status] of Object.entries(defaultStages)) {
run(
"INSERT OR IGNORE INTO stages (name, status, notes, updated_at) VALUES (?, ?, ?, ?)",
[name, status, "", now()],
)
}
}
function loadStateFromSqlite() {
if (!db) return
const scopes = queryAll("SELECT * FROM scopes ORDER BY created_at ASC") as any[]
const records = queryAll("SELECT * FROM memory_records ORDER BY ts ASC") as any[]
const risks = queryAll("SELECT * FROM risk_queue ORDER BY ts ASC") as any[]
const stages = queryAll("SELECT * FROM stages ORDER BY name ASC") as any[]
state = {
scope: scopes.map((item) => ({
target: item.target,
owner: item.owner ?? undefined,
authorization: item.authorization ?? undefined,
expiresAt: item.expires_at ?? undefined,
notes: item.notes ?? undefined,
})),
records: records.map((item) => ({
id: item.id,
ts: item.ts,
kind: item.kind,
agent: item.agent ?? undefined,
target: item.target ?? undefined,
title: item.title ?? undefined,
content: item.content,
tags: JSON.parse(item.tags || "[]"),
severity: item.severity ?? undefined,
status: item.status ?? undefined,
})),
risks: risks.map((item) => ({
id: item.id,
ts: item.ts,
toolName: item.tool_name,
args: JSON.parse(item.args_json || "{}"),
reason: item.reason,
status: item.status,
decisionReason: item.decision_reason ?? undefined,
})),
stages: {
...defaultStages,
...Object.fromEntries(stages.map((item) => [item.name, item.status])),
},
}
scope.clear()
for (const item of state.scope) scope.set(item.target, item)
}
function ensureScratchboard() {
const { scratchboardPath } = currentPaths()
if (existsSync(scratchboardPath)) return
writeFileSync(
scratchboardPath,
[
`# CNVD Campaign Scratchboard: ${campaignId}`,
"",
"## Current Goal",
"- ",
"",
"## Authorized Scope",
"- ",
"",
"## Key Assets",
"- ",
"",
"## Active Hypotheses",
"- ",
"",
"## Confirmed Findings",
"- ",
"",
"## Missing Evidence",
"- ",
"",
"## Pending Risks",
"- ",
].join("\n"),
)
}
function refreshCampaignDir() {
campaignDir = join(campaignsDir, campaignId)
const paths = currentPaths()
mkdirSync(paths.campaignDir, { recursive: true })
mkdirSync(paths.evidenceDir, { recursive: true })
mkdirSync(paths.reportsDir, { recursive: true })
mkdirSync(paths.tmpDir, { recursive: true })
writeFileSync(activeCampaignPath, `${campaignId}\n`)
if (Database) db = new Database(paths.dbPath)
initDatabase()
state = db ? createDefaultState() : loadJson<MemoryState>(paths.statePath, createDefaultState())
loadStateFromSqlite()
if (!db) {
scope.clear()
for (const item of state.scope) scope.set(item.target, item)
}
ensureScratchboard()
saveState()
}
function switchCampaign(nextCampaignId: string, title?: string) {
campaignId = safeCampaignId(nextCampaignId)
if (db?.close) db.close()
db = undefined
refreshCampaignDir()
if (title && db) {
run("UPDATE campaigns SET title = ?, updated_at = ? WHERE id = ?", [title, now(), campaignId])
}
appendEvent("campaign_started", { campaignId, title })
return summarize()
}
function saveState() {
state.scope = [...scope.values()]
if (!db) {
writeFileSync(currentPaths().statePath, `${JSON.stringify(state, null, 2)}\n`)
}
}
function appendEvent(kind: string, payload: unknown) {
const event = { ts: now(), kind, payload }
appendFileSync(currentPaths().eventLogPath, `${JSON.stringify(event)}\n`)
if (db) {
run("INSERT INTO audit_events (ts, kind, payload_json) VALUES (?, ?, ?)", [
event.ts,
kind,
JSON.stringify(payload),
])
}
}
function addScope(entry: ScopeEntry) {
scope.set(entry.target, entry)
if (db) {
run(
`INSERT OR REPLACE INTO scopes
(target, owner, authorization, expires_at, notes, created_at)
VALUES (?, ?, ?, ?, ?, ?)`,
[
entry.target,
entry.owner ?? null,
entry.authorization ?? null,
entry.expiresAt ?? null,
entry.notes ?? null,
now(),
],
)
}
appendEvent("scope_registered", entry)
saveState()
}
function addMemory(input: Omit<MemoryRecord, "id" | "ts" | "tags"> & { tags?: string[] }) {
const record: MemoryRecord = {
id: makeId("mem", input),
ts: now(),
kind: input.kind,
agent: input.agent,
target: input.target,
title: input.title,
content: input.content,
tags: unique([...(input.tags ?? []), ...tokenize(`${input.title ?? ""} ${input.content}`)]).slice(0, 80),
severity: input.severity,
status: input.status,
}
state.records.push(record)
if (db) {
run(
`INSERT INTO memory_records
(id, ts, kind, agent, target, title, content, tags, severity, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
record.id,
record.ts,
record.kind,
record.agent ?? null,
record.target ?? null,
record.title ?? null,
record.content,
JSON.stringify(record.tags),
record.severity ?? null,
record.status ?? null,
],
)
}
appendEvent("memory_recorded", record)
saveState()
return record
}
function addRisk(toolName: string, args: Record<string, unknown>, reason: string) {
const risk: RiskRecord = {
id: makeId("risk", { toolName, args, reason }),
ts: now(),
toolName,
args,
reason,
status: "pending",
}
state.risks.push(risk)
appendFileSync(currentPaths().riskLogPath, `${JSON.stringify(risk)}\n`)
if (db) {
run(
`INSERT INTO risk_queue
(id, ts, tool_name, args_json, reason, status, decision_reason)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[risk.id, risk.ts, toolName, JSON.stringify(args), reason, risk.status, null],
)
}
appendEvent("risk_deferred", risk)
saveState()
return risk
}
function isRegisteredTarget(value: string) {
const normalized = normalizeTarget(value)
if (scope.has(normalized)) return true
for (const target of scope.keys()) {
if (normalized === target || normalized.startsWith(`${target}/`)) return true
}
return false
}
function targetMatches(value: string | undefined, target: string) {
if (!value) return false
const normalizedValue = normalizeTarget(value)
const normalizedTarget = normalizeTarget(target)
return (
normalizedValue === normalizedTarget ||
normalizedValue.startsWith(`${normalizedTarget}/`) ||
normalizedTarget.startsWith(`${normalizedValue}/`)
)
}
function recordMatchesTarget(record: MemoryRecord, target?: string) {
if (!target) return true
return targetMatches(record.target, target)
}
function riskMatchesTarget(risk: RiskRecord, target?: string) {
if (!target) return true
const normalizedTarget = normalizeTarget(target)
return JSON.stringify(risk.args).includes(normalizedTarget)
}
function searchMemory(query: string, limit: number, target?: string) {
const terms = tokenize(query)
return state.records
.filter((record) => recordMatchesTarget(record, target))
.map((record) => {
const haystack = tokenize(
`${record.kind} ${record.agent ?? ""} ${record.target ?? ""} ${record.title ?? ""} ${record.content} ${record.tags.join(" ")}`,
)
const score = terms.filter((term) => haystack.includes(term)).length
return { record, score }
})
.filter((item) => item.score > 0)
.sort((a, b) => b.score - a.score || b.record.ts.localeCompare(a.record.ts))
.slice(0, limit)
.map((item) => item.record)
}
function updateStage(stage: StageName, status: StageStatus, notes?: string) {
state.stages[stage] = status
if (db) {
run(
"INSERT OR REPLACE INTO stages (name, status, notes, updated_at) VALUES (?, ?, ?, ?)",
[stage, status, notes ?? "", now()],
)
}
appendEvent("stage_updated", { stage, status, notes })
saveState()
return state.stages
}
function readScratchboard() {
return readFileSync(currentPaths().scratchboardPath, "utf8")
}
function updateScratchboard(content: string, append: boolean) {
if (append) {
appendFileSync(currentPaths().scratchboardPath, `\n\n${content}\n`)
} else {
writeFileSync(currentPaths().scratchboardPath, `${content.trim()}\n`)
}
appendEvent("scratchboard_updated", { append })
return readScratchboard()
}
function campaignGaps(target?: string) {
const targetRecords = state.records.filter((record) => recordMatchesTarget(record, target))
const pendingStages = Object.entries(state.stages)
.filter(([, status]) => status !== "done")
.map(([stage, status]) => ({ stage, status }))
const findings = targetRecords.filter((record) => record.kind === "finding")
const evidence = targetRecords.filter((record) => record.kind === "evidence")
const hypotheses = targetRecords.filter((record) => record.kind === "hypothesis")
const pendingRisks = state.risks.filter(
(risk) => risk.status === "pending" && riskMatchesTarget(risk, target),
)
const missingEvidence = hypotheses
.filter((hypothesis) => {
if (!hypothesis.target) return false
return !evidence.some((item) => item.target === hypothesis.target)
})
.slice(0, 20)
return {
pendingStages,
missingEvidence,
unvalidatedFindings: findings.filter((item) => item.status !== "confirmed").slice(0, 20),
pendingRisks: pendingRisks.slice(0, 20),
}
}
function summarize(target?: string) {
const targetRecords = state.records.filter((record) => recordMatchesTarget(record, target))
const targetRisks = state.risks.filter((risk) => riskMatchesTarget(risk, target))
const targetScopes = target
? [...scope.values()].filter((entry) => targetMatches(entry.target, target))
: [...scope.values()]
const byKind = targetRecords.reduce<Record<string, number>>((acc, record) => {
acc[record.kind] = (acc[record.kind] ?? 0) + 1
return acc
}, {})
const paths = currentPaths()
return {
campaignId,
target: target ? normalizeTarget(target) : undefined,
storage: db ? "sqlite" : "json-fallback",
campaignDir: paths.campaignDir,
databasePath: paths.dbPath,
scratchboardPath: paths.scratchboardPath,
scopeCount: targetScopes.length,
recordCount: targetRecords.length,
pendingRiskCount: targetRisks.filter((risk) => risk.status === "pending").length,
stages: state.stages,
byKind,
recentRecords: targetRecords.slice(-10),
gaps: campaignGaps(target),
}
}
function listRisks(status?: string) {
return state.risks.filter((risk) => (status ? risk.status === status : true))
}
function decideRisk(id: string, status: "approved" | "rejected", reason?: string) {
const risk = state.risks.find((item) => item.id === id)
if (!risk) throw new Error(`risk not found: ${id}`)
risk.status = status
risk.decisionReason = reason
if (db) {
run("UPDATE risk_queue SET status = ?, decision_reason = ? WHERE id = ?", [
status,
reason ?? null,
id,
])
}
appendEvent("risk_decision_recorded", { id, status, reason })
saveState()
return risk
}
refreshCampaignDir()
return {
get campaignId() {
return campaignId
},
scope,
addScope,
addMemory,
addRisk,
appendEvent,
isRegisteredTarget,
searchMemory,
summarize,
switchCampaign,
updateStage,
readScratchboard,
updateScratchboard,
listRisks,
decideRisk,
}
}
function maybeUrlFromArgs(args: Record<string, unknown>) {
for (const key of ["url", "target", "baseUrl", "host"]) {
const value = args[key]
if (typeof value === "string" && value.trim()) return value
}
return undefined
}
function urlsFromCommand(command: string) {
return command.match(/https?:\/\/[^\s"'<>]+/g) ?? []
}
function inspectTool(
memory: Awaited<ReturnType<typeof createMemoryStore>>,
toolName: string,
args: Record<string, unknown>,
) {
const lowered = toolName.toLowerCase()
if (writeTools.has(lowered)) {
return { allowed: false, reason: "file modification tools are disabled for this workflow" }
}
if (riskToolPatterns.some((pattern) => pattern.test(toolName))) {
return {
allowed: false,
reason:
"post-exploitation, persistence, lateral movement, credential access, and evasion tools are deferred for unified approval",
}
}
if (lowered === "bash") {
const command = String(args.command ?? "")
if (destructiveShellPatterns.some((pattern) => pattern.test(command))) {
return {
allowed: false,
reason: "destructive or state-changing shell command is deferred for unified approval",
}
}
for (const url of urlsFromCommand(command)) {
if (!memory.isRegisteredTarget(url)) {
return { allowed: false, reason: `target is not registered in the authorized scope: ${url}` }
}
}
}
// CNVD internal tools (scope_register, risk decisions, etc.) bypass scope check
if (lowered.startsWith('cnvd_')) {
return { allowed: true, reason: "allowed" }
}
const target = maybeUrlFromArgs(args)
if (target && !memory.isRegisteredTarget(target)) {
return { allowed: false, reason: `target is not registered in the authorized scope: ${target}` }
}
return { allowed: true, reason: "allowed" }
}
export const CnvdPlugin: Plugin = async ({ directory }) => {
const memory = await createMemoryStore(directory)
return {
"tool.execute.before": async (input, output) => {
const args = output.args ?? {}
const decision = inspectTool(memory, input.tool, args)
if (decision.allowed) return
const risk = memory.addRisk(input.tool, args, decision.reason)
throw new Error(
`CNVD boundary: deferred high-risk or out-of-scope action ${risk.id}. Continue with a safe alternative and review the queue later.`,
)
},
tool: {
cnvd_campaign_start: tool({
description:
"Start or switch to a campaign_id. Creates <campaign_id>/ in the current workspace with SQLite, scratchboard, events, evidence, reports, and tmp directories.",
args: {
campaignId: tool.schema.string().describe("Stable campaign ID."),
title: tool.schema.string().optional().describe("Human readable campaign title."),
},
async execute(args) {
return JSON.stringify(memory.switchCampaign(args.campaignId, args.title), null, 2)
},
}),
cnvd_campaign_status: tool({
description:
"Return current system campaign status: stage progress, unfinished work, missing evidence, pending risks, and storage paths. Optionally pass target only to narrow within the same system.",
args: {
target: tool.schema.string().optional().describe("Optional URL/IP target to narrow records within the current system campaign."),
},
async execute(args) {
return JSON.stringify(memory.summarize(args.target), null, 2)
},
}),
cnvd_stage_update: tool({
description: "Update campaign stage status.",
args: {
stage: tool.schema
.string()
.describe("scope, asset, analysis, cve, scan, validate, audit, report, or risk_review."),
status: tool.schema
.string()
.describe("pending, in_progress, blocked, or done."),
notes: tool.schema.string().optional().describe("Short stage notes."),
},
async execute(args) {
if (!(args.stage in defaultStages)) throw new Error(`unknown stage: ${args.stage}`)
if (!["pending", "in_progress", "blocked", "done"].includes(args.status)) {
throw new Error(`unknown status: ${args.status}`)
}
return JSON.stringify(
memory.updateStage(args.stage as StageName, args.status as StageStatus, args.notes),
null,
2,
)
},
}),
cnvd_scratchboard_read: tool({
description: "Read the campaign scratchboard for fast context recovery.",
args: {},
async execute() {
return memory.readScratchboard()
},
}),
cnvd_scratchboard_update: tool({
description:
"Update campaign scratchboard. Keep it compact: current goal, scope, key assets, active hypotheses, findings, gaps, pending risks.",
args: {
content: tool.schema.string().describe("Markdown scratchboard content."),
append: tool.schema.boolean().optional().describe("Append instead of replacing."),
},
async execute(args) {
return memory.updateScratchboard(args.content, args.append ?? false)
},
}),
cnvd_scope_register: tool({
description:
"Register an explicitly authorized CNVD testing target before any scan or validation.",
args: {
target: tool.schema.string().describe("Authorized URL, host, IP, or CIDR."),
owner: tool.schema.string().optional().describe("Asset owner or customer name."),
authorization: tool.schema
.string()
.optional()
.describe("Authorization ticket, contract, email reference, or task ID."),
expiresAt: tool.schema
.string()
.optional()
.describe("Authorization expiry date in YYYY-MM-DD format."),
notes: tool.schema.string().optional().describe("Scope notes and restrictions."),
},
async execute(args) {
const entry = { ...args, target: normalizeTarget(args.target) }
memory.addScope(entry)
return `Registered authorized scope in ${memory.campaignId}: ${entry.target}`
},
}),
cnvd_scope_list: tool({
description: "List currently registered authorized CNVD testing targets.",
args: {},
async execute() {
const scopes = [...memory.scope.values()]
return scopes.length === 0
? "No authorized targets have been registered."
: JSON.stringify(scopes, null, 2)
},
}),
cnvd_scope_check: tool({
description:
"Check whether a target is inside the registered authorized scope.",
args: {
target: tool.schema.string().describe("URL, host, IP, or path to check."),
},
async execute(args) {
const allowed = memory.isRegisteredTarget(args.target)
return JSON.stringify(
{
campaignId: memory.campaignId,
target: normalizeTarget(args.target),
allowed,
decision: allowed ? "in_scope" : "out_of_scope",
},
null,
2,
)
},
}),
cnvd_memory_record: tool({
description:
"Persist durable memory for long-running CNVD work: assets, hypotheses, evidence, decisions, findings, and report notes.",
args: {
kind: tool.schema
.string()
.describe("Record kind: asset, hypothesis, evidence, decision, finding, report_note, audit."),
content: tool.schema.string().describe("Structured memory content."),
agent: tool.schema.string().optional().describe("Agent that created the record."),
target: tool.schema.string().optional().describe("Related target."),
title: tool.schema.string().optional().describe("Short title."),
severity: tool.schema.string().optional().describe("Severity if applicable."),
status: tool.schema.string().optional().describe("Status if applicable."),
tags: tool.schema.array(tool.schema.string()).optional().describe("Search tags."),
},
async execute(args) {
if (args.target && !memory.isRegisteredTarget(args.target)) {
throw new Error(`CNVD boundary: target is not registered: ${args.target}`)
}
return JSON.stringify(memory.addMemory(args), null, 2)
},
}),
cnvd_memory_search: tool({
description:
"Search durable CNVD memory in the current system campaign before continuing work. Optionally pass target only to narrow within the same system.",
args: {
query: tool.schema.string().describe("Search query."),
limit: tool.schema.number().optional().describe("Maximum records to return."),
target: tool.schema.string().optional().describe("Optional URL/IP target to narrow records within the current system campaign."),
},
async execute(args) {
return JSON.stringify(memory.searchMemory(args.query, args.limit ?? 10, args.target), null, 2)
},
}),
cnvd_memory_snapshot: tool({
description:
"Return a compact durable-memory snapshot for the current system campaign. Optionally pass target only to narrow within the same system.",
args: {
target: tool.schema.string().optional().describe("Optional URL/IP target to narrow snapshot records within the current system campaign."),
},
async execute(args) {
return JSON.stringify(memory.summarize(args.target), null, 2)
},
}),
cnvd_risk_queue_list: tool({
description:
"List deferred high-risk, destructive, or out-of-scope actions for later unified user approval.",
args: {
status: tool.schema.string().optional().describe("pending, approved, or rejected."),
},
async execute(args) {
return JSON.stringify(memory.listRisks(args.status), null, 2)
},
}),
cnvd_risk_decision_record: tool({
description:
"Record the user's later unified decision for a deferred high-risk action.",
args: {
id: tool.schema.string().describe("Risk ID."),
status: tool.schema.string().describe("approved or rejected."),
reason: tool.schema.string().optional().describe("Decision reason."),
},
async execute(args) {
if (!["approved", "rejected"].includes(args.status)) {
throw new Error("status must be approved or rejected")
}
return JSON.stringify(
memory.decideRisk(args.id, args.status as "approved" | "rejected", args.reason),
null,
2,
)
},
}),
cnvd_evidence_template: tool({
description:
"Create a structured evidence template for CNVD vulnerability reporting without modifying files.",
args: {
title: tool.schema.string().describe("Vulnerability title."),
target: tool.schema.string().describe("Affected authorized target."),
category: tool.schema.string().describe("Vulnerability category."),
severity: tool.schema.string().describe("Severity estimate."),
},
async execute(args) {
if (!memory.isRegisteredTarget(args.target)) {
throw new Error(`CNVD boundary: target is not registered: ${args.target}`)
}
return [
`# ${args.title}`,
"",
`- Campaign: ${memory.campaignId}`,
`- Target: ${args.target}`,
`- Category: ${args.category}`,
`- Severity: ${args.severity}`,
"- Authorization: ",
"- Affected component: ",
"- Preconditions: ",
"- Reproduction steps:",
" 1. ",
"- Evidence:",
" - Request summary: ",
" - Response summary: ",
" - Screenshot or log reference: ",
"- Impact:",
"- Non-destructive validation result:",
"- Remediation recommendation:",
"- Retest notes:",
].join("\n")
},
}),
},
}
}
export default CnvdPlugin