Repository navigation
Expand file tree
/
Copy pathaudit.ts
More file actions
1302 lines (1183 loc) · 36 KB
/
Copy pathaudit.ts
File metadata and controls
1302 lines (1183 loc) · 36 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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from "node:path";
import { performance } from "node:perf_hooks";
import { z } from "zod";
import packageJson from "../package.json";
import { compareCodeUnits } from "./deterministic-order";
import {
type Confidence,
discoverProject,
type FrameworkAdapter,
type ProjectDiscovery,
} from "./discovery";
const AUDIT_CATEGORIES = [
"foundation",
"interaction",
"states",
"accessibility",
"forms",
"production-polish",
] as const;
const AUDIT_REPORT_SCHEMA_VERSION = 8 as const;
const ENGINE_VERSION = packageJson.version;
const CUSTOM_RULESET_VERSION = "custom";
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[a-zA-Z]:[\\/]/;
const CATEGORY_DETAILS = {
accessibility: {
title: "Accessibility",
weight: 20,
},
forms: {
title: "Forms and Data Entry",
weight: 10,
},
foundation: {
title: "Foundation",
weight: 20,
},
interaction: {
title: "Interaction",
weight: 20,
},
"production-polish": {
title: "Production Polish",
weight: 10,
},
states: {
title: "States",
weight: 20,
},
} as const satisfies Record<AuditCategory, { title: string; weight: number }>;
const AuditCategorySchema = z.enum(AUDIT_CATEGORIES);
const ActionableDispositionSchema = z.enum(["decide", "fix", "verify"]);
const ActionablePrioritySchema = z.enum(["P0", "P1", "P2"]);
const ConfidenceSchema = z.enum(["high", "medium", "low"]);
const RuleStatusSchema = z.enum(["advisory", "fail", "not-applicable", "pass"]);
const ScanSourceKindSchema = z.enum(["git", "snapshot", "working-tree"]);
const SeveritySchema = z.enum(["error", "info", "warning"]);
type ActionablePriority = z.infer<typeof ActionablePrioritySchema>;
type ActionableDisposition = z.infer<typeof ActionableDispositionSchema>;
type AuditCategory = (typeof AUDIT_CATEGORIES)[number];
type AuditRuleAdapter = "core" | FrameworkAdapter;
type AuditRuleStatus = z.infer<typeof RuleStatusSchema>;
type AuditSeverity = z.infer<typeof SeveritySchema>;
type AuditGrade = "A" | "B" | "C" | "D" | "F";
type ScanSourceKind = z.infer<typeof ScanSourceKindSchema>;
interface ScanSource {
digest: string | null;
kind: ScanSourceKind;
revision: string | null;
}
interface ScanScope {
categories: AuditCategory[];
}
interface AuditEvidence {
filePath?: string;
line?: number;
message: string;
}
interface AuditContext {
filesystemRoot: string;
project: ProjectDiscovery;
}
interface AuditRuleResult {
confidence?: Confidence;
evidence?: AuditEvidence[];
remediation?: string;
roast?: string;
status: AuditRuleStatus;
}
interface AuditRule {
adapters: AuditRuleAdapter[];
category: AuditCategory;
confidence: Confidence;
description: string;
id: string;
maxScore: number;
run: (context: AuditContext) => Promise<AuditRuleResult> | AuditRuleResult;
severity: AuditSeverity;
title: string;
}
interface AuditFinding {
category: AuditCategory;
confidence: Confidence;
description: string;
evidence: AuditEvidence[];
id: string;
impactsScore: boolean;
maxScore: number;
remediation: string | null;
roast: string | null;
score: number;
severity: AuditSeverity;
status: AuditRuleStatus;
title: string;
}
interface AuditCategoryScore {
applicable: boolean;
id: AuditCategory;
maxScore: number;
percentage: number | null;
score: number;
title: string;
weight: number;
}
interface AgentActionable {
acceptanceCriteria: string[];
category: AuditCategory;
confidence: Confidence;
disposition: ActionableDisposition;
evidence: AuditEvidence[];
findingId: string;
priority: ActionablePriority;
scoreImpact: number;
severity: AuditSeverity;
status: Extract<AuditRuleStatus, "advisory" | "fail">;
suggestedFix: string | null;
summary: string;
title: string;
}
interface AgentWorkItem {
acceptanceCriteria: string[];
categories: AuditCategory[];
disposition: ActionableDisposition;
evidence: AuditEvidence[];
findingIds: string[];
id: string;
priority: ActionablePriority;
rawScoreImpact: number;
suggestedFixes: string[];
summary: string;
title: string;
}
interface AgentVerification {
projectGates: string[];
shadscanCommand: string;
}
interface AgentHandoff {
actionables: AgentActionable[];
context: string[];
goal: string;
suggestedSkills: string[];
verification: AgentVerification;
workItems: AgentWorkItem[];
}
interface AuditReport {
agentHandoff: AgentHandoff;
categories: AuditCategoryScore[];
coverage: {
source: ProjectDiscovery["sourceCoverage"];
};
durationMs: number;
engineVersion: string;
findings: AuditFinding[];
framework: ProjectDiscovery["framework"];
grade: AuditGrade | null;
maxScore: 100;
packageManager: ProjectDiscovery["packageManager"];
packageName: string | null;
rulesetVersion: string;
schemaVersion: typeof AUDIT_REPORT_SCHEMA_VERSION;
scope: ScanScope;
score: number | null;
shadcn: Pick<
ProjectDiscovery["shadcn"],
"confidence" | "configPath" | "style"
>;
source: ScanSource;
versions: ProjectDiscovery["versions"];
warnings: string[];
}
interface RunAuditOptions {
category?: AuditCategory;
filesystemRoot?: string;
rules: AuditRule[];
rulesetVersion?: string;
signal?: AbortSignal;
source?: ScanSource;
}
const isPortableProjectPath = (filePath: string): boolean => {
if (filePath === ".") {
return true;
}
if (
filePath.startsWith("/") ||
filePath.startsWith("\\") ||
filePath.includes("\\") ||
WINDOWS_ABSOLUTE_PATH_PATTERN.test(filePath)
) {
return false;
}
return filePath.split("/").every((segment) => segment !== "..");
};
const ProjectPathSchema = z
.string()
.min(1)
.refine(isPortableProjectPath, "Expected a project-relative POSIX path.");
const AuditEvidenceSchema = z.object({
filePath: ProjectPathSchema.optional(),
line: z.number().int().positive().optional(),
message: z.string(),
});
const AuditFindingSchema = z.object({
category: AuditCategorySchema,
confidence: ConfidenceSchema,
description: z.string(),
evidence: z.array(AuditEvidenceSchema),
id: z.string(),
impactsScore: z.boolean(),
maxScore: z.number(),
remediation: z.string().nullable(),
roast: z.string().nullable(),
score: z.number(),
severity: SeveritySchema,
status: RuleStatusSchema,
title: z.string(),
});
const AgentActionableSchema = z.object({
acceptanceCriteria: z.array(z.string()),
category: AuditCategorySchema,
confidence: ConfidenceSchema,
disposition: ActionableDispositionSchema,
evidence: z.array(AuditEvidenceSchema),
findingId: z.string(),
priority: ActionablePrioritySchema,
scoreImpact: z.number(),
severity: SeveritySchema,
status: z.enum(["advisory", "fail"]),
suggestedFix: z.string().nullable(),
summary: z.string(),
title: z.string(),
});
const AgentWorkItemSchema = z.object({
acceptanceCriteria: z.array(z.string()),
categories: z.array(AuditCategorySchema).min(1),
disposition: ActionableDispositionSchema,
evidence: z.array(AuditEvidenceSchema),
findingIds: z.array(z.string()).min(1),
id: z.string(),
priority: ActionablePrioritySchema,
rawScoreImpact: z.number(),
suggestedFixes: z.array(z.string()),
summary: z.string(),
title: z.string(),
});
const AgentVerificationSchema = z.object({
projectGates: z.array(z.string()),
shadscanCommand: z.string(),
});
const AgentHandoffSchema = z.object({
actionables: z.array(AgentActionableSchema),
context: z.array(z.string()),
goal: z.string(),
suggestedSkills: z.array(z.string()),
verification: AgentVerificationSchema,
workItems: z.array(AgentWorkItemSchema),
});
const AuditReportSchema = z.object({
agentHandoff: AgentHandoffSchema,
categories: z.array(
z.object({
applicable: z.boolean(),
id: AuditCategorySchema,
maxScore: z.number(),
percentage: z.number().nullable(),
score: z.number(),
title: z.string(),
weight: z.number(),
})
),
coverage: z.object({
source: z.enum(["complete", "partial"]),
}),
durationMs: z.number(),
engineVersion: z.string().min(1),
findings: z.array(AuditFindingSchema),
framework: z.object({
adapter: z.enum([
"astro-react",
"generic-react",
"laravel-inertia-react",
"next-app-router",
"next-hybrid-router",
"next-pages-router",
"react-router-framework",
"tanstack-start",
"vite-react",
]),
evidence: z.array(z.string()),
}),
grade: z.enum(["A", "B", "C", "D", "F"]).nullable(),
maxScore: z.literal(100),
packageManager: z.enum(["bun", "npm", "pnpm", "unknown", "yarn"]),
packageName: z.string().nullable(),
rulesetVersion: z.string().min(1),
schemaVersion: z.literal(AUDIT_REPORT_SCHEMA_VERSION),
score: z.number().min(0).max(100).nullable(),
scope: z.object({
categories: z.array(AuditCategorySchema).min(1),
}),
shadcn: z.object({
confidence: ConfidenceSchema,
configPath: ProjectPathSchema.nullable(),
style: z.string().nullable(),
}),
source: z.object({
digest: z.string().min(1).nullable(),
kind: ScanSourceKindSchema,
revision: z.string().min(1).nullable(),
}),
versions: z.object({
astro: z.string().nullable(),
inertia: z.string().nullable(),
laravel: z.string().nullable(),
next: z.string().nullable(),
react: z.string().nullable(),
reactRouter: z.string().nullable(),
tanstackStart: z.string().nullable(),
vite: z.string().nullable(),
}),
warnings: z.array(z.string()),
});
const getGrade = (score: number): AuditGrade => {
if (score >= 90) {
return "A";
}
if (score >= 80) {
return "B";
}
if (score >= 70) {
return "C";
}
if (score >= 60) {
return "D";
}
return "F";
};
const getProjectRelativePath = (
rootDir: string,
filePath: string
): string | undefined => {
const absoluteRoot = path.resolve(rootDir);
const absoluteFile = path.resolve(absoluteRoot, filePath);
const relativePath = path.relative(absoluteRoot, absoluteFile);
const isOutsideRoot =
relativePath === ".." ||
relativePath.startsWith(`..${path.sep}`) ||
path.isAbsolute(relativePath);
if (isOutsideRoot) {
return;
}
if (relativePath === "") {
return ".";
}
return relativePath.split(path.sep).join("/");
};
const normalizeEvidencePaths = (
evidence: AuditEvidence[],
rootDir: string
): AuditEvidence[] =>
evidence
.map((item) => {
if (!item.filePath) {
return item;
}
const filePath = getProjectRelativePath(rootDir, item.filePath);
if (!filePath) {
return {
line: item.line,
message: item.message,
};
}
return { ...item, filePath };
})
.sort(
(left, right) =>
compareCodeUnits(left.filePath ?? "", right.filePath ?? "") ||
(left.line ?? 0) - (right.line ?? 0) ||
compareCodeUnits(left.message, right.message)
);
const normalizeFindingPaths = (
findings: AuditFinding[],
rootDir: string
): AuditFinding[] =>
findings.map((finding) => ({
...finding,
evidence: normalizeEvidencePaths(finding.evidence, rootDir),
}));
const shouldRunRule = ({
category,
project,
rule,
}: {
category?: AuditCategory;
project: ProjectDiscovery;
rule: AuditRule;
}): boolean => {
if (category && rule.category !== category) {
return false;
}
if (project.framework.adapter === "next-hybrid-router") {
return (
rule.adapters.includes("core") ||
rule.adapters.includes("next-app-router") ||
rule.adapters.includes("next-hybrid-router") ||
rule.adapters.includes("next-pages-router")
);
}
return (
rule.adapters.includes("core") ||
rule.adapters.includes(project.framework.adapter)
);
};
const normalizeFinding = (
rule: AuditRule,
result: AuditRuleResult
): AuditFinding => {
const confidence = result.confidence ?? rule.confidence;
const advisoryFail = result.status === "fail" && confidence === "low";
const status: AuditRuleStatus = advisoryFail ? "advisory" : result.status;
const impactsScore =
rule.maxScore > 0 && status !== "advisory" && status !== "not-applicable";
const maxScore = status === "not-applicable" ? 0 : rule.maxScore;
const score = (() => {
if (status === "pass" || status === "advisory") {
return maxScore;
}
return 0;
})();
return {
category: rule.category,
confidence,
description: rule.description,
evidence: result.evidence ?? [],
id: rule.id,
impactsScore,
maxScore,
remediation: result.remediation ?? null,
roast: result.roast ?? null,
score,
severity: rule.severity,
status,
title: rule.title,
};
};
const getCategoryScores = (findings: AuditFinding[]): AuditCategoryScore[] =>
AUDIT_CATEGORIES.map((category) => {
const categoryFindings = findings.filter(
(finding) => finding.category === category
);
const scoredFindings = categoryFindings.filter(
(finding) => finding.impactsScore
);
const rawMaxScore = scoredFindings.reduce(
(total, finding) => total + finding.maxScore,
0
);
const rawScore = scoredFindings.reduce(
(total, finding) => total + finding.score,
0
);
const applicable = rawMaxScore > 0;
const ratio = applicable ? rawScore / rawMaxScore : null;
const weight = CATEGORY_DETAILS[category].weight;
return {
applicable,
id: category,
maxScore: applicable ? weight : 0,
percentage: ratio === null ? null : Math.round(ratio * 100),
score: ratio === null ? 0 : ratio * weight,
title: CATEGORY_DETAILS[category].title,
weight,
};
});
const getTotalScore = (categories: AuditCategoryScore[]): number | null => {
const applicableCategories = categories.filter(
(category) => category.applicable
);
const activeWeight = applicableCategories.reduce(
(total, category) => total + category.weight,
0
);
if (activeWeight === 0) {
return null;
}
const weightedScore = applicableCategories.reduce(
(total, category) => total + category.score,
0
);
return Math.round((weightedScore / activeWeight) * 100);
};
const PRIORITY_ORDER: Record<ActionablePriority, number> = {
P0: 0,
P1: 1,
P2: 2,
};
const DISPOSITION_ORDER: Record<ActionableDisposition, number> = {
fix: 0,
decide: 1,
verify: 2,
};
const PROJECT_GATE_SCRIPT_NAMES = [
"check",
"lint",
"typecheck",
"test",
"build",
] as const;
const MAX_NAMESPACED_TEST_GATES = 20;
const SAFE_SCRIPT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$/;
const isNamespacedTestGate = (scriptName: string): boolean =>
SAFE_SCRIPT_NAME_PATTERN.test(scriptName) &&
(scriptName.startsWith("test:") || scriptName.endsWith(":test"));
const PACKAGE_EXECUTORS = {
bun: (packageSpecifier: string) => `bunx ${packageSpecifier}`,
npm: (packageSpecifier: string) => `npx --yes ${packageSpecifier}`,
pnpm: (packageSpecifier: string) => `pnpm dlx ${packageSpecifier}`,
unknown: (packageSpecifier: string) => `npx --yes ${packageSpecifier}`,
yarn: (packageSpecifier: string) =>
`yarn dlx --package ${packageSpecifier} shadscan`,
} as const satisfies Record<
ProjectDiscovery["packageManager"],
(packageSpecifier: string) => string
>;
const SCRIPT_RUNNERS = {
bun: "bun run",
npm: "npm run",
pnpm: "pnpm",
unknown: "npm run",
yarn: "yarn",
} as const satisfies Record<ProjectDiscovery["packageManager"], string>;
const SAFE_SHELL_ARGUMENT_PATTERN = /^[A-Za-z0-9_./:@+-]+$/;
const quoteShellArgument = (value: string): string =>
SAFE_SHELL_ARGUMENT_PATTERN.test(value)
? value
: `'${value.replaceAll("'", `'"'"'`)}'`;
const getSelectedProjectArgument = (
project: ProjectDiscovery
): string | null =>
project.selectedProjectPath === "."
? null
: quoteShellArgument(`./${project.selectedProjectPath}`);
const getProjectScriptRunner = (project: ProjectDiscovery): string => {
const projectArgument = getSelectedProjectArgument(project);
if (!projectArgument) {
return SCRIPT_RUNNERS[project.packageManager];
}
switch (project.packageManager) {
case "bun":
return `bun --cwd ${projectArgument} run`;
case "pnpm":
return `pnpm --dir ${projectArgument}`;
case "yarn":
return `yarn --cwd ${projectArgument}`;
default:
return `npm --prefix ${projectArgument} run`;
}
};
const PRODUCT_DECISION_DETAILS: Record<
string,
{ summary: string; title: string }
> = {
"command-menu-hotkey-present": {
summary:
"Decide whether the app has enough navigation or actions to justify a command menu and shortcut.",
title: "Decide the command-menu interaction",
},
"command-menu-present": {
summary:
"Decide whether the app has enough navigation or actions to justify a command menu and shortcut.",
title: "Decide the command-menu interaction",
},
"mobile-nav-present": {
summary:
"Choose a mobile navigation pattern that fits the app, or document why visible page flow is sufficient.",
title: "Decide the mobile navigation pattern",
},
"public-app-seo-files-present": {
summary:
"Choose whether the app should be indexed, then add framework-native SEO files or document an explicit noindex policy.",
title: "Decide the app indexing policy",
},
"toast-provider-mounted": {
summary:
"Choose how transient success and failure feedback should work before adding notification infrastructure.",
title: "Decide the transient-feedback pattern",
},
"toast-provider-present": {
summary:
"Choose how transient success and failure feedback should work before adding notification infrastructure.",
title: "Decide the transient-feedback pattern",
},
};
const WORK_ITEM_GROUPS = [
{
findingIds: ["forms-have-labels", "invalid-fields-associated-with-errors"],
id: "form-field-accessibility",
summary:
"Make each affected field discoverable by name and connect invalid state to its rendered error message.",
title: "Associate form fields with labels and errors",
},
{
findingIds: ["command-menu-present", "command-menu-hotkey-present"],
id: "command-menu",
summary:
"Decide whether the product warrants a command menu; if it does, ship the menu and its keyboard entry point together.",
title: "Decide the command-menu experience",
},
{
findingIds: [
"error-boundary-present",
"error-state-retry-present",
"route-loading-boundary-present",
"suspense-fallback-useful",
],
id: "route-resilience",
summary:
"Keep route failures recoverable and suspended content visibly represented instead of blanking the application shell.",
title: "Provide route recovery and useful loading UI",
},
{
findingIds: [
"toast-provider-present",
"toast-provider-mounted",
"status-messages-announced",
],
id: "transient-feedback",
summary:
"Choose a feedback channel based on real user actions, and avoid mounting an unused provider solely for the audit score.",
title: "Decide how transient feedback should work",
},
{
findingIds: [
"color-contrast-passes",
"pointer-target-size-passes",
"mobile-overflow-absent",
],
id: "rendered-ui-verification",
summary:
"Verify computed accessibility and responsive behavior in a browser at representative themes, states, and viewport widths.",
title: "Verify rendered accessibility and responsive behavior",
},
] as const;
const getActionablePriority = (finding: AuditFinding): ActionablePriority => {
if (finding.severity === "error" && finding.status === "fail") {
return "P0";
}
if (finding.status === "fail" && finding.confidence === "high") {
return "P1";
}
return "P2";
};
const getActionableDisposition = (
finding: AuditFinding
): ActionableDisposition => {
if (PRODUCT_DECISION_DETAILS[finding.id]) {
return "decide";
}
return finding.status === "advisory" ? "verify" : "fix";
};
const getActionableSummary = (
finding: AuditFinding,
disposition: ActionableDisposition
): string => {
const decisionDetails = PRODUCT_DECISION_DETAILS[finding.id];
if (decisionDetails) {
return decisionDetails.summary;
}
if (disposition === "verify") {
return `Verify ${finding.title}; shadscan has low-confidence evidence and did not reduce the score.`;
}
return `Fix ${finding.title}; shadscan marked this as a ${finding.confidence}-confidence missing UI fundamental.`;
};
const getActionableTitle = (
finding: AuditFinding,
disposition: ActionableDisposition
): string => {
const decisionDetails = PRODUCT_DECISION_DETAILS[finding.id];
if (decisionDetails) {
return decisionDetails.title;
}
return `${disposition === "verify" ? "Verify" : "Fix"} ${finding.title}`;
};
const getProjectGateCriterion = (
projectGates: string[],
prefix: string
): string => {
if (projectGates.length === 0) {
return `${prefix} inspect repository-owned package scripts, then run every authorized check, lint, typecheck, test, and build gate relevant to the change; report any gate that was not safe or authorized to run.`;
}
const commands = projectGates.map((command) => `\`${command}\``).join(", ");
return `${prefix} inspect the repository-owned script definitions, then run every authorized discovered project gate: ${commands}; report any gate that was not safe or authorized to run.`;
};
const getActionableAcceptanceCriteria = ({
disposition,
finding,
projectGates,
}: {
disposition: ActionableDisposition;
finding: AuditFinding;
projectGates: string[];
}): string[] => {
if (disposition === "verify") {
return [
"Record the finding as confirmed, verified-no-change, or unable-to-verify, with rendered or composed evidence.",
"Do not edit solely to force a score-neutral static advisory to report pass; it may remain advisory after successful verification.",
getProjectGateCriterion(projectGates, "If code changes,"),
];
}
if (disposition === "decide") {
return [
"Record an explicit implement-or-waive product decision based on the app's current workflows.",
`If implemented, the shadscan finding \`${finding.id}\` reports pass; if waived, keep it visible and report the rationale.`,
"Do not add unused infrastructure solely to increase the audit score.",
getProjectGateCriterion(projectGates, "If code changes,"),
];
}
const criteria = [
`The shadscan finding \`${finding.id}\` reports pass when rerun with the same ruleset and category scope.`,
];
if (finding.remediation) {
criteria.push(
`The implementation matches this remediation: ${finding.remediation}`
);
}
criteria.push(getProjectGateCriterion(projectGates, "After the change,"));
return criteria;
};
const getProjectGateCommands = (project: ProjectDiscovery): string[] => {
const runner = getProjectScriptRunner(project);
const standardGates = PROJECT_GATE_SCRIPT_NAMES.filter(
(scriptName) => project.scripts[scriptName] !== undefined
);
const namespacedTestGates = Object.keys(project.scripts)
.filter(isNamespacedTestGate)
.sort(compareCodeUnits)
.slice(0, MAX_NAMESPACED_TEST_GATES);
return [...standardGates, ...namespacedTestGates].map(
(scriptName) => `${runner} ${scriptName}`
);
};
const getShadscanCommand = (
project: ProjectDiscovery,
category: AuditCategory | undefined
): string => {
const executor = PACKAGE_EXECUTORS[project.packageManager];
const categoryOption = category ? ` --category ${category}` : "";
const projectArgument = getSelectedProjectArgument(project);
const projectOption = projectArgument ? ` ${projectArgument}` : "";
const packageSpecifier = `@shadscan/cli@${ENGINE_VERSION}`;
return `${executor(packageSpecifier)}${projectOption} --json${categoryOption}`;
};
const uniqueEvidence = (actionables: AgentActionable[]): AuditEvidence[] => {
const evidenceByKey = new Map<string, AuditEvidence>();
for (const actionable of actionables) {
for (const evidence of actionable.evidence) {
const key = `${evidence.filePath ?? ""}:${evidence.line ?? ""}:${evidence.message}`;
evidenceByKey.set(key, evidence);
}
}
return [...evidenceByKey.values()];
};
const getWorkItemDisposition = (
actionables: AgentActionable[]
): ActionableDisposition =>
[...actionables].sort(
(left, right) =>
DISPOSITION_ORDER[left.disposition] - DISPOSITION_ORDER[right.disposition]
)[0]?.disposition ?? "verify";
const getWorkItemPriority = (
actionables: AgentActionable[]
): ActionablePriority =>
[...actionables].sort(
(left, right) =>
PRIORITY_ORDER[left.priority] - PRIORITY_ORDER[right.priority]
)[0]?.priority ?? "P2";
const getWorkItemAcceptanceCriteria = ({
actionables,
disposition,
projectGates,
}: {
actionables: AgentActionable[];
disposition: ActionableDisposition;
projectGates: string[];
}): string[] => {
const findingIds = actionables.map(({ findingId }) => `\`${findingId}\``);
if (disposition === "verify") {
return [
`Record each related finding (${findingIds.join(", ")}) as confirmed, verified-no-change, or unable-to-verify, with rendered or composed evidence.`,
"Do not edit solely to force score-neutral static advisories to report pass; verified advisories may remain advisory.",
getProjectGateCriterion(projectGates, "If code changes,"),
];
}
if (disposition === "decide") {
return [
`Record one explicit implement-or-waive product decision covering ${findingIds.join(", ")}.`,
"If implemented, the related findings should pass; if waived, keep them visible and report the product rationale.",
"Do not add unused infrastructure solely to increase the audit score.",
getProjectGateCriterion(projectGates, "If code changes,"),
];
}
return [
...findingIds.map(
(findingId) =>
`The shadscan finding ${findingId} reports pass when rerun with the same ruleset and category scope.`
),
"The implementation addresses the user-facing problem described by the related remediations, not only the detector syntax.",
getProjectGateCriterion(projectGates, "After the change,"),
];
};
const createWorkItem = ({
actionables,
id,
projectGates,
summary,
title,
}: {
actionables: AgentActionable[];
id: string;
projectGates: string[];
summary: string;
title: string;
}): AgentWorkItem => {
const disposition = getWorkItemDisposition(actionables);
const suggestedFixes = [
...new Set(
actionables.flatMap(({ suggestedFix }) =>
suggestedFix ? [suggestedFix] : []
)
),
];
return {
acceptanceCriteria: getWorkItemAcceptanceCriteria({
actionables,
disposition,
projectGates,
}),
categories: AUDIT_CATEGORIES.filter((category) =>
actionables.some((actionable) => actionable.category === category)
),
disposition,
evidence: uniqueEvidence(actionables),
findingIds: actionables.map(({ findingId }) => findingId),
id,
priority: getWorkItemPriority(actionables),
rawScoreImpact: actionables.reduce(
(total, actionable) => total + actionable.scoreImpact,
0
),
suggestedFixes,
summary,
title,
};
};
const createWorkItems = (
actionables: AgentActionable[],
projectGates: string[]
): AgentWorkItem[] => {
const groupedFindingIds = new Set<string>();
const workItems: AgentWorkItem[] = [];
for (const group of WORK_ITEM_GROUPS) {
const matchingActionables = group.findingIds.flatMap((findingId) => {
const actionable = actionables.find(
(candidate) => candidate.findingId === findingId
);
return actionable ? [actionable] : [];
});
if (matchingActionables.length < 2) {
continue;
}
const dispositions = new Set(
matchingActionables.map(({ disposition }) => disposition)
);
for (const disposition of dispositions) {
const groupedActionables = matchingActionables.filter(
(actionable) => actionable.disposition === disposition
);
if (groupedActionables.length < 2) {
continue;
}
for (const actionable of groupedActionables) {
groupedFindingIds.add(actionable.findingId);
}