xploitscan-shared-rules 1.21.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,62 @@
1
1
  import { ParseResult } from '@babel/parser';
2
2
  import { File, Node, CallExpression, ObjectExpression, BinaryExpression } from '@babel/types';
3
3
 
4
+ /**
5
+ * Cross-file facts a rule cannot learn from the file it is scanning.
6
+ *
7
+ * Rules are deliberately single-file: `check(content, filePath)` sees one file
8
+ * and nothing else. That keeps them fast, order-independent and honest about
9
+ * what they can prove, and it is the right default. But some questions are
10
+ * genuinely answered in a different file, and answering them by guessing from
11
+ * the current one is worse than not answering at all.
12
+ *
13
+ * ProjectContext is the narrow exception: a small set of facts computed ONCE
14
+ * over the whole file list before any rule runs, then handed to every rule.
15
+ * It is intentionally not "here is every file" — that would let rules re-parse
16
+ * the project 214 times and quietly become a cross-file analyser, which the
17
+ * roadmap explicitly rules out as an unwinnable race against CodeQL.
18
+ *
19
+ * Every field is optional and every consumer must behave correctly when the
20
+ * context is absent, because most callers (the MCP server, the VS Code
21
+ * extension, single-file scans) have no project to build one from.
22
+ */
23
+ /** Parsed facts about the project being scanned. */
24
+ interface ProjectContext {
25
+ /**
26
+ * Supabase Edge Functions and whether the PLATFORM verifies a JWT before
27
+ * the function runs, from `supabase/config.toml`. Keyed by function name —
28
+ * the directory under `supabase/functions/`.
29
+ *
30
+ * A missing entry means "not declared", which is not the same as false:
31
+ * Supabase's own default is `verify_jwt = true`, but a function absent from
32
+ * config.toml may simply be undeclared, so callers must treat absent as
33
+ * unknown rather than assuming either way.
34
+ */
35
+ supabaseEdgeVerifyJwt?: Map<string, boolean>;
36
+ }
37
+ /**
38
+ * Parse `supabase/config.toml` for per-function `verify_jwt` settings.
39
+ *
40
+ * Deliberately a line scanner rather than a TOML parser. Only two constructs
41
+ * matter, adding a TOML dependency to a package that ships in a browser bundle
42
+ * is a poor trade for that, and a malformed config should yield fewer facts
43
+ * rather than an exception during a scan.
44
+ */
45
+ declare function parseSupabaseConfig(toml: string): Map<string, boolean>;
46
+ /** The function name for a path under `supabase/functions/<name>/…`. */
47
+ declare function supabaseFunctionName(filePath: string): string | null;
48
+ /**
49
+ * Build the context from the files about to be scanned.
50
+ *
51
+ * Cheap by construction: it reads a fixed, tiny set of paths rather than
52
+ * walking content, so adding a fact here costs one more lookup, not another
53
+ * pass over the project.
54
+ */
55
+ declare function buildProjectContext(files: Array<{
56
+ path: string;
57
+ content: string;
58
+ }>): ProjectContext;
59
+
4
60
  type Severity = "critical" | "high" | "medium" | "low" | "info";
5
61
  type Confidence = "high" | "medium" | "low";
6
62
  interface Finding {
@@ -66,13 +122,21 @@ interface RuleMatch {
66
122
  snippet: string;
67
123
  fix?: string;
68
124
  }
125
+
69
126
  interface CustomRule {
70
127
  id: string;
71
128
  title: string;
72
129
  severity: Severity;
73
130
  category: string;
74
131
  description: string;
75
- check: (content: string, filePath: string) => RuleMatch[];
132
+ /**
133
+ * Optional third argument: cross-file facts computed once per scan. Optional
134
+ * on purpose — every existing rule ignores it and still satisfies this type,
135
+ * and every caller that has no project (single-file scans, the MCP server,
136
+ * the editor extension) can omit it. A rule that uses it must behave
137
+ * correctly when it is undefined.
138
+ */
139
+ check: (content: string, filePath: string, project?: ProjectContext) => RuleMatch[];
76
140
  }
77
141
 
78
142
  /**
@@ -81,6 +145,73 @@ interface CustomRule {
81
145
  */
82
146
  declare function getSnippet(content: string, line: number, contextLines?: number): string;
83
147
 
148
+ /**
149
+ * Claude model IDs — the single place they are written down.
150
+ *
151
+ * There used to be three copies of "which model do we call", in three
152
+ * packages, each with its own literal. One of them (`ai-analyzer.ts`) sat on
153
+ * `claude-sonnet-4-5-20250514` for long enough that the model went two
154
+ * generations stale without anyone noticing, because nothing in the repo
155
+ * pointed at it. That is the same duplication defect that produced three
156
+ * copies of `calculateGrade` and two of `NON_APP_PATH_PATTERNS`.
157
+ *
158
+ * The lesson recorded in docs/BACKLOG.md applies exactly:
159
+ * "Import, don't restate — a shared function makes drift unexpressible,
160
+ * whereas a guard only catches it afterwards."
161
+ *
162
+ * So: import from here. `scripts/check-model-ids.js` fails CI on any Claude
163
+ * model literal written anywhere else, and on a stale review date below.
164
+ */
165
+ /**
166
+ * Deep analysis — open-ended discovery over up to 50KB of source at a time.
167
+ *
168
+ * Why Sonnet and not Haiku: this call *invents* findings rather than judging
169
+ * ones it was handed, and whatever it returns is pushed onto the finding list
170
+ * that `calculateGrade()` scores. A wrong finding here becomes a wrong letter
171
+ * grade shown to someone who, by construction, cannot tell a bogus finding
172
+ * from a real one — the audience is non-expert developers. It also runs on the
173
+ * *user's* own ANTHROPIC_API_KEY in the CLI (see `analyzeWithAI`), so the
174
+ * cost of the stronger model is not ours to optimise away.
175
+ */
176
+ declare const MODEL_ANALYSIS = "claude-sonnet-5";
177
+ /**
178
+ * High-volume narrow judgment — "is this specific finding a false positive?"
179
+ * and "answer this questionnaire item from these facts".
180
+ *
181
+ * Haiku is the right tier: the task is bounded, the finding is handed to the
182
+ * model rather than discovered by it, and the call count scales with findings
183
+ * (one per file batch, many per scan). Pinned to a dated release deliberately
184
+ * — this one runs on OUR key against user-visible output, and a silent model
185
+ * swap underneath a filter that can *hide* a real vulnerability is not a
186
+ * change we want to arrive unannounced.
187
+ */
188
+ declare const MODEL_TRIAGE = "claude-haiku-4-5-20251001";
189
+ /**
190
+ * Last time a human checked these against the current model line-up.
191
+ *
192
+ * `scripts/check-model-ids.js` FAILS once this is more than
193
+ * MODEL_REVIEW_INTERVAL_DAYS old. That is deliberate: a warning in CI is a
194
+ * warning nobody reads, and "we fell two generations behind without noticing"
195
+ * is the exact failure this module exists to prevent.
196
+ *
197
+ * To clear it: re-read https://docs.claude.com/en/docs/about-claude/models,
198
+ * update the IDs above if the line-up moved, and set today's date here.
199
+ */
200
+ declare const MODEL_POLICY_REVIEWED = "2026-09-15";
201
+ /** How long a review stays fresh before CI asks for another one. */
202
+ declare const MODEL_REVIEW_INTERVAL_DAYS = 180;
203
+ /**
204
+ * Sampling is pinned to 0 at every call site, and extended thinking is
205
+ * deliberately NOT enabled at any of them.
206
+ *
207
+ * Both follow from the same requirement: a user who scans the same unchanged
208
+ * commit twice must get the same letter grade, with no explanation needed for
209
+ * why it moved. Extended thinking requires temperature 1, so enabling it
210
+ * would trade that guarantee away. If a future call site does not feed a
211
+ * grade, it is free to make the opposite choice — but it should say so.
212
+ */
213
+ declare const MODEL_TEMPERATURE = 0;
214
+
84
215
  /**
85
216
  * Real-world consequence descriptions for VC### rules.
86
217
  *
@@ -516,7 +647,14 @@ declare const insecureDirectObjectReference: CustomRule;
516
647
  declare const freeRules: CustomRule[];
517
648
  declare const allRules: CustomRule[];
518
649
  declare const allCustomRules: CustomRule[];
519
- declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[]): Finding[];
650
+ declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[],
651
+ /**
652
+ * Cross-file facts for the project being scanned, from
653
+ * buildProjectContext(). Optional: callers that scan a single file with no
654
+ * project around it (the MCP server, the editor extension, a pasted
655
+ * snippet) pass nothing, and every rule must still work.
656
+ */
657
+ project?: ProjectContext): Finding[];
520
658
 
521
659
  /**
522
660
  * Rule-set sizes as plain numbers, importable without dragging the rules in.
@@ -925,4 +1063,4 @@ declare function getObjectProperty(node: ObjectExpression, key: string): {
925
1063
  /** Does this CallExpression spread an expression `matcher` returns true for? */
926
1064
  declare function callSpreads(call: CallExpression, matcher: (node: Node) => boolean): boolean;
927
1065
 
928
- export { type AIFilterResult, type AppRoute, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, entitlementFromWebStorage, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
1066
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, type ProjectContext, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildProjectContext, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, entitlementFromWebStorage, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, parseSupabaseConfig, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseFunctionName, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,62 @@
1
1
  import { ParseResult } from '@babel/parser';
2
2
  import { File, Node, CallExpression, ObjectExpression, BinaryExpression } from '@babel/types';
3
3
 
4
+ /**
5
+ * Cross-file facts a rule cannot learn from the file it is scanning.
6
+ *
7
+ * Rules are deliberately single-file: `check(content, filePath)` sees one file
8
+ * and nothing else. That keeps them fast, order-independent and honest about
9
+ * what they can prove, and it is the right default. But some questions are
10
+ * genuinely answered in a different file, and answering them by guessing from
11
+ * the current one is worse than not answering at all.
12
+ *
13
+ * ProjectContext is the narrow exception: a small set of facts computed ONCE
14
+ * over the whole file list before any rule runs, then handed to every rule.
15
+ * It is intentionally not "here is every file" — that would let rules re-parse
16
+ * the project 214 times and quietly become a cross-file analyser, which the
17
+ * roadmap explicitly rules out as an unwinnable race against CodeQL.
18
+ *
19
+ * Every field is optional and every consumer must behave correctly when the
20
+ * context is absent, because most callers (the MCP server, the VS Code
21
+ * extension, single-file scans) have no project to build one from.
22
+ */
23
+ /** Parsed facts about the project being scanned. */
24
+ interface ProjectContext {
25
+ /**
26
+ * Supabase Edge Functions and whether the PLATFORM verifies a JWT before
27
+ * the function runs, from `supabase/config.toml`. Keyed by function name —
28
+ * the directory under `supabase/functions/`.
29
+ *
30
+ * A missing entry means "not declared", which is not the same as false:
31
+ * Supabase's own default is `verify_jwt = true`, but a function absent from
32
+ * config.toml may simply be undeclared, so callers must treat absent as
33
+ * unknown rather than assuming either way.
34
+ */
35
+ supabaseEdgeVerifyJwt?: Map<string, boolean>;
36
+ }
37
+ /**
38
+ * Parse `supabase/config.toml` for per-function `verify_jwt` settings.
39
+ *
40
+ * Deliberately a line scanner rather than a TOML parser. Only two constructs
41
+ * matter, adding a TOML dependency to a package that ships in a browser bundle
42
+ * is a poor trade for that, and a malformed config should yield fewer facts
43
+ * rather than an exception during a scan.
44
+ */
45
+ declare function parseSupabaseConfig(toml: string): Map<string, boolean>;
46
+ /** The function name for a path under `supabase/functions/<name>/…`. */
47
+ declare function supabaseFunctionName(filePath: string): string | null;
48
+ /**
49
+ * Build the context from the files about to be scanned.
50
+ *
51
+ * Cheap by construction: it reads a fixed, tiny set of paths rather than
52
+ * walking content, so adding a fact here costs one more lookup, not another
53
+ * pass over the project.
54
+ */
55
+ declare function buildProjectContext(files: Array<{
56
+ path: string;
57
+ content: string;
58
+ }>): ProjectContext;
59
+
4
60
  type Severity = "critical" | "high" | "medium" | "low" | "info";
5
61
  type Confidence = "high" | "medium" | "low";
6
62
  interface Finding {
@@ -66,13 +122,21 @@ interface RuleMatch {
66
122
  snippet: string;
67
123
  fix?: string;
68
124
  }
125
+
69
126
  interface CustomRule {
70
127
  id: string;
71
128
  title: string;
72
129
  severity: Severity;
73
130
  category: string;
74
131
  description: string;
75
- check: (content: string, filePath: string) => RuleMatch[];
132
+ /**
133
+ * Optional third argument: cross-file facts computed once per scan. Optional
134
+ * on purpose — every existing rule ignores it and still satisfies this type,
135
+ * and every caller that has no project (single-file scans, the MCP server,
136
+ * the editor extension) can omit it. A rule that uses it must behave
137
+ * correctly when it is undefined.
138
+ */
139
+ check: (content: string, filePath: string, project?: ProjectContext) => RuleMatch[];
76
140
  }
77
141
 
78
142
  /**
@@ -81,6 +145,73 @@ interface CustomRule {
81
145
  */
82
146
  declare function getSnippet(content: string, line: number, contextLines?: number): string;
83
147
 
148
+ /**
149
+ * Claude model IDs — the single place they are written down.
150
+ *
151
+ * There used to be three copies of "which model do we call", in three
152
+ * packages, each with its own literal. One of them (`ai-analyzer.ts`) sat on
153
+ * `claude-sonnet-4-5-20250514` for long enough that the model went two
154
+ * generations stale without anyone noticing, because nothing in the repo
155
+ * pointed at it. That is the same duplication defect that produced three
156
+ * copies of `calculateGrade` and two of `NON_APP_PATH_PATTERNS`.
157
+ *
158
+ * The lesson recorded in docs/BACKLOG.md applies exactly:
159
+ * "Import, don't restate — a shared function makes drift unexpressible,
160
+ * whereas a guard only catches it afterwards."
161
+ *
162
+ * So: import from here. `scripts/check-model-ids.js` fails CI on any Claude
163
+ * model literal written anywhere else, and on a stale review date below.
164
+ */
165
+ /**
166
+ * Deep analysis — open-ended discovery over up to 50KB of source at a time.
167
+ *
168
+ * Why Sonnet and not Haiku: this call *invents* findings rather than judging
169
+ * ones it was handed, and whatever it returns is pushed onto the finding list
170
+ * that `calculateGrade()` scores. A wrong finding here becomes a wrong letter
171
+ * grade shown to someone who, by construction, cannot tell a bogus finding
172
+ * from a real one — the audience is non-expert developers. It also runs on the
173
+ * *user's* own ANTHROPIC_API_KEY in the CLI (see `analyzeWithAI`), so the
174
+ * cost of the stronger model is not ours to optimise away.
175
+ */
176
+ declare const MODEL_ANALYSIS = "claude-sonnet-5";
177
+ /**
178
+ * High-volume narrow judgment — "is this specific finding a false positive?"
179
+ * and "answer this questionnaire item from these facts".
180
+ *
181
+ * Haiku is the right tier: the task is bounded, the finding is handed to the
182
+ * model rather than discovered by it, and the call count scales with findings
183
+ * (one per file batch, many per scan). Pinned to a dated release deliberately
184
+ * — this one runs on OUR key against user-visible output, and a silent model
185
+ * swap underneath a filter that can *hide* a real vulnerability is not a
186
+ * change we want to arrive unannounced.
187
+ */
188
+ declare const MODEL_TRIAGE = "claude-haiku-4-5-20251001";
189
+ /**
190
+ * Last time a human checked these against the current model line-up.
191
+ *
192
+ * `scripts/check-model-ids.js` FAILS once this is more than
193
+ * MODEL_REVIEW_INTERVAL_DAYS old. That is deliberate: a warning in CI is a
194
+ * warning nobody reads, and "we fell two generations behind without noticing"
195
+ * is the exact failure this module exists to prevent.
196
+ *
197
+ * To clear it: re-read https://docs.claude.com/en/docs/about-claude/models,
198
+ * update the IDs above if the line-up moved, and set today's date here.
199
+ */
200
+ declare const MODEL_POLICY_REVIEWED = "2026-09-15";
201
+ /** How long a review stays fresh before CI asks for another one. */
202
+ declare const MODEL_REVIEW_INTERVAL_DAYS = 180;
203
+ /**
204
+ * Sampling is pinned to 0 at every call site, and extended thinking is
205
+ * deliberately NOT enabled at any of them.
206
+ *
207
+ * Both follow from the same requirement: a user who scans the same unchanged
208
+ * commit twice must get the same letter grade, with no explanation needed for
209
+ * why it moved. Extended thinking requires temperature 1, so enabling it
210
+ * would trade that guarantee away. If a future call site does not feed a
211
+ * grade, it is free to make the opposite choice — but it should say so.
212
+ */
213
+ declare const MODEL_TEMPERATURE = 0;
214
+
84
215
  /**
85
216
  * Real-world consequence descriptions for VC### rules.
86
217
  *
@@ -516,7 +647,14 @@ declare const insecureDirectObjectReference: CustomRule;
516
647
  declare const freeRules: CustomRule[];
517
648
  declare const allRules: CustomRule[];
518
649
  declare const allCustomRules: CustomRule[];
519
- declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[]): Finding[];
650
+ declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[],
651
+ /**
652
+ * Cross-file facts for the project being scanned, from
653
+ * buildProjectContext(). Optional: callers that scan a single file with no
654
+ * project around it (the MCP server, the editor extension, a pasted
655
+ * snippet) pass nothing, and every rule must still work.
656
+ */
657
+ project?: ProjectContext): Finding[];
520
658
 
521
659
  /**
522
660
  * Rule-set sizes as plain numbers, importable without dragging the rules in.
@@ -925,4 +1063,4 @@ declare function getObjectProperty(node: ObjectExpression, key: string): {
925
1063
  /** Does this CallExpression spread an expression `matcher` returns true for? */
926
1064
  declare function callSpreads(call: CallExpression, matcher: (node: Node) => boolean): boolean;
927
1065
 
928
- export { type AIFilterResult, type AppRoute, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, entitlementFromWebStorage, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
1066
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, type ProjectContext, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildProjectContext, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, entitlementFromWebStorage, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, parseSupabaseConfig, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseFunctionName, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
package/dist/index.js CHANGED
@@ -45,6 +45,13 @@ function getSnippet(content, line, contextLines = 2) {
45
45
  return out.join("\n");
46
46
  }
47
47
 
48
+ // src/models.ts
49
+ var MODEL_ANALYSIS = "claude-sonnet-5";
50
+ var MODEL_TRIAGE = "claude-haiku-4-5-20251001";
51
+ var MODEL_POLICY_REVIEWED = "2026-09-15";
52
+ var MODEL_REVIEW_INTERVAL_DAYS = 180;
53
+ var MODEL_TEMPERATURE = 0;
54
+
48
55
  // src/rule-impacts.ts
49
56
  var RULE_IMPACTS = {
50
57
  VC001: "An attacker who finds this key in your source code or client bundle can use your API with your credentials, potentially reading or modifying user data and racking up usage charges.",
@@ -284,6 +291,42 @@ function classifyExposure(filePath) {
284
291
  return "unknown";
285
292
  }
286
293
 
294
+ // src/project-context.ts
295
+ var TOML_FN_SECTION_RE = /^\s*\[functions\.(?:"([^"]+)"|([A-Za-z0-9._-]+))\]\s*$/;
296
+ var TOML_VERIFY_JWT_RE = /^\s*verify_jwt\s*=\s*(true|false)\s*(?:#.*)?$/i;
297
+ function parseSupabaseConfig(toml) {
298
+ const out = /* @__PURE__ */ new Map();
299
+ let current = null;
300
+ for (const line of toml.split(/\r?\n/)) {
301
+ const section = line.match(TOML_FN_SECTION_RE);
302
+ if (section) {
303
+ current = section[1] ?? section[2];
304
+ continue;
305
+ }
306
+ if (/^\s*\[/.test(line)) {
307
+ current = null;
308
+ continue;
309
+ }
310
+ if (!current) continue;
311
+ const verify = line.match(TOML_VERIFY_JWT_RE);
312
+ if (verify) out.set(current, verify[1].toLowerCase() === "true");
313
+ }
314
+ return out;
315
+ }
316
+ function supabaseFunctionName(filePath) {
317
+ const m = filePath.match(/(?:^|\/)supabase\/functions\/([^/]+)\//);
318
+ return m ? m[1] : null;
319
+ }
320
+ function buildProjectContext(files) {
321
+ const ctx = {};
322
+ const config = files.find((f) => /(?:^|\/)supabase\/config\.toml$/.test(f.path));
323
+ if (config) {
324
+ const parsed = parseSupabaseConfig(config.content);
325
+ if (parsed.size > 0) ctx.supabaseEdgeVerifyJwt = parsed;
326
+ }
327
+ return ctx;
328
+ }
329
+
287
330
  // src/vendored.ts
288
331
  var NON_APP_PATH_PATTERNS = [
289
332
  // 1. vendored UI component libraries
@@ -1032,6 +1075,7 @@ var SERVER_SIDE_CONTENT_RE = /\b(?:req|request)\.(?:body|query|params|headers|co
1032
1075
  function isServerSideFile(filePath, content) {
1033
1076
  if (isTestFile(filePath)) return false;
1034
1077
  if (SERVER_SIDE_PATH_RE.test(filePath)) return true;
1078
+ if (content && /^\s*["']use server["']/m.test(content)) return true;
1035
1079
  if (content && SERVER_SIDE_CONTENT_RE.test(content)) return true;
1036
1080
  return false;
1037
1081
  }
@@ -1335,7 +1379,7 @@ var missingAuthMiddleware = {
1335
1379
  severity: "high",
1336
1380
  category: "Authentication",
1337
1381
  description: "API routes without authentication checks allow unauthorized access.",
1338
- check(content, filePath) {
1382
+ check(content, filePath, project) {
1339
1383
  if (!isServerSideFile(filePath, content)) return [];
1340
1384
  const routePatterns = [
1341
1385
  // Express/Hono style
@@ -1343,6 +1387,27 @@ var missingAuthMiddleware = {
1343
1387
  // Next.js API routes — named function declaration
1344
1388
  /export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|PATCH|DELETE)\s*\(/gi
1345
1389
  ];
1390
+ const VERCEL_API_FN_RE = /(?:^|\/)api\/[^/]+\.(?:m?[jt]s)$/;
1391
+ const isNextTree = /(?:^|\/)(?:src\/)?(?:app|pages)\//.test(filePath);
1392
+ if (VERCEL_API_FN_RE.test(filePath) && !isNextTree) {
1393
+ routePatterns.push(
1394
+ /export\s+default\s+(?:async\s+)?(?:function\b|\()/g,
1395
+ /module\.exports\s*=\s*(?:async\s+)?(?:function\b|\()/g
1396
+ );
1397
+ }
1398
+ if (/^\s*["']use server["']/m.test(content)) {
1399
+ routePatterns.push(
1400
+ /export\s+(?:async\s+)?function\s+\w+\s*\(/g,
1401
+ /export\s+const\s+\w+\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?\(/g
1402
+ );
1403
+ }
1404
+ const EDGE_FN_DIR_RE = /(?:^|\/)(?:netlify\/(?:edge-)?functions|functions|edge-functions)\/[^/]+\/?[^/]*\.(?:m?[jt]s)$/;
1405
+ if (EDGE_FN_DIR_RE.test(filePath) && !SUPABASE_EDGE_FN_RE.test(filePath)) {
1406
+ routePatterns.push(
1407
+ /(?:exports\s*\.\s*handler|export\s+const\s+handler)\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?(?:function\b|\()/g,
1408
+ /export\s+default\s+(?:async\s+)?(?:function\b|\()/g
1409
+ );
1410
+ }
1346
1411
  if (/(?:^|\/)(?:src\/)?app\/(?:.*\/)?route\.(?:m?[jt]sx?)$/.test(filePath)) {
1347
1412
  routePatterns.push(
1348
1413
  /export\s+const\s+(?:GET|POST|PUT|PATCH|DELETE)\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?(?:function\b|\()/g
@@ -1383,8 +1448,24 @@ var missingAuthMiddleware = {
1383
1448
  /\b(?:protect|guard)\(/i,
1384
1449
  /\.use\([^)]*(?:auth|session|protect|requireAuth)/i
1385
1450
  ];
1386
- const hasAuth = authPatterns.some((p) => p.test(codeOnly));
1387
- if (hasAuth) return [];
1451
+ const APP_LEVEL_AUTH = [
1452
+ /\.use\([^)]*(?:auth|session|protect|requireAuth)/i,
1453
+ /\bpassport\b/i,
1454
+ /\bclerk\b/i,
1455
+ /\bwithAuth\b/i
1456
+ ];
1457
+ if (APP_LEVEL_AUTH.some((p) => p.test(codeOnly))) return [];
1458
+ const handlerAuthPatterns = authPatterns.filter(
1459
+ (p) => !APP_LEVEL_AUTH.some((a) => a.source === p.source)
1460
+ );
1461
+ const maskedForScope = maskComments(content);
1462
+ const handlerHasAuth = (index) => {
1463
+ const bodyStart = maskedForScope.indexOf("{", index);
1464
+ const probe = bodyStart === -1 ? index : bodyStart + 1;
1465
+ const scope = enclosingHandler(maskedForScope, probe);
1466
+ if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeOnly));
1467
+ return handlerAuthPatterns.some((p) => p.test(scope));
1468
+ };
1388
1469
  const matches = [];
1389
1470
  for (const pattern of routePatterns) {
1390
1471
  matches.push(
@@ -1398,21 +1479,31 @@ var missingAuthMiddleware = {
1398
1479
  );
1399
1480
  }
1400
1481
  if (matches.length === 0 && SUPABASE_EDGE_FN_RE.test(filePath) && isDenoEdgeEntry(codeOnly) && !isPublicByDesignEdgePath(filePath)) {
1401
- const withoutCors = stripCorsHeaderList(codeOnly);
1402
- const hasWeakHint = EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));
1403
- if (!hasWeakHint) {
1404
- matches.push(
1405
- ...findMatches(
1406
- content,
1407
- DENO_EDGE_ENTRY_RE,
1408
- missingAuthMiddleware,
1409
- filePath,
1410
- () => "This edge function does not establish who is calling it. Read the caller's token from the Authorization header and resolve it (`const { data: { user } } = await supabase.auth.getUser(token)`), or build the Supabase client with that token so row-level security scopes every query to the caller. If the endpoint is public by design, add an inline `// VC003-OK: <reason>` comment above the handler to silence."
1411
- )
1412
- );
1482
+ const fnName = supabaseFunctionName(filePath);
1483
+ const verifyJwt = fnName && project?.supabaseEdgeVerifyJwt ? project.supabaseEdgeVerifyJwt.get(fnName) : void 0;
1484
+ if (verifyJwt !== true) {
1485
+ const withoutCors = stripCorsHeaderList(codeOnly);
1486
+ const hasWeakHint = verifyJwt === false ? false : EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));
1487
+ if (!hasWeakHint) {
1488
+ matches.push(
1489
+ ...findMatches(
1490
+ content,
1491
+ DENO_EDGE_ENTRY_RE,
1492
+ missingAuthMiddleware,
1493
+ filePath,
1494
+ () => "This edge function does not establish who is calling it. Read the caller's token from the Authorization header and resolve it (`const { data: { user } } = await supabase.auth.getUser(token)`), or build the Supabase client with that token so row-level security scopes every query to the caller. If the endpoint is public by design, add an inline `// VC003-OK: <reason>` comment above the handler to silence."
1495
+ )
1496
+ );
1497
+ }
1413
1498
  }
1414
1499
  }
1415
- return filterSilenced(matches, content, "VC003");
1500
+ const lineStarts = [0];
1501
+ for (let i = 0; i < content.length; i++) {
1502
+ if (content[i] === "\n") lineStarts.push(i + 1);
1503
+ }
1504
+ const indexOfLine = (line) => lineStarts[Math.max(0, Math.min(line - 1, lineStarts.length - 1))];
1505
+ const unauthenticated = matches.filter((m) => !handlerHasAuth(indexOfLine(m.line)));
1506
+ return filterSilenced(unauthenticated, content, "VC003");
1416
1507
  }
1417
1508
  };
1418
1509
  var supabaseNoRLS = {
@@ -8851,7 +8942,7 @@ var allCustomRules = [
8851
8942
  entitlementFromWebStorage,
8852
8943
  accountStateFromWebStorage
8853
8944
  ];
8854
- function runCustomRules(content, filePath, disabledRules = [], tier = "free", extraRules = []) {
8945
+ function runCustomRules(content, filePath, disabledRules = [], tier = "free", extraRules = [], project) {
8855
8946
  const findings = [];
8856
8947
  if (/function runScan\(files\)|export function runCustomRules/.test(content) && /const (?:rules|allRules)\s*[:=]/.test(content) && /findMatches/.test(content)) {
8857
8948
  return findings;
@@ -8873,7 +8964,7 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
8873
8964
  const ruleset = tier === "pro" && extraRules.length > 0 ? [...freeRules, ...extraRules] : freeRules;
8874
8965
  for (const rule of ruleset) {
8875
8966
  if (disabledRules.includes(rule.id)) continue;
8876
- const matches = rule.check(content, filePath);
8967
+ const matches = rule.check(content, filePath, project);
8877
8968
  const compliance = complianceMap[rule.id];
8878
8969
  const vendored = vendoredFile && isVendoredFinding({ file: filePath, rule: rule.id, category: rule.category });
8879
8970
  for (const match of matches) {
@@ -9036,7 +9127,7 @@ async function filterFalsePositives(findings, fileContents) {
9036
9127
  const prompt = buildReviewPrompt(batch, content);
9037
9128
  const response = await client.messages.create(
9038
9129
  {
9039
- model: "claude-haiku-4-5-20251001",
9130
+ model: MODEL_TRIAGE,
9040
9131
  max_tokens: 1024,
9041
9132
  // Pinned, NOT left to the API default of 1.0. This is a binary
9042
9133
  // classification (real vs. false positive), not generation — there
@@ -9048,7 +9139,7 @@ async function filterFalsePositives(findings, fileContents) {
9048
9139
  // variance source that was ours to control. See
9049
9140
  // scripts/fp-filter-repeatability.cjs for the measured flip rate,
9050
9141
  // and the assertion in ai-fp-filter.test.ts that keeps it pinned.
9051
- temperature: 0,
9142
+ temperature: MODEL_TEMPERATURE,
9052
9143
  system: REVIEW_SYSTEM_PROMPT,
9053
9144
  messages: [{ role: "user", content: prompt }]
9054
9145
  },
@@ -9564,6 +9655,11 @@ function extractScriptUrls(html, pageUrl, limit = 12) {
9564
9655
  }
9565
9656
  export {
9566
9657
  FREE_RULE_COUNT,
9658
+ MODEL_ANALYSIS,
9659
+ MODEL_POLICY_REVIEWED,
9660
+ MODEL_REVIEW_INTERVAL_DAYS,
9661
+ MODEL_TEMPERATURE,
9662
+ MODEL_TRIAGE,
9567
9663
  NON_APP_PATH_PATTERNS,
9568
9664
  PRO_RULE_COUNT,
9569
9665
  RULE_IMPACTS,
@@ -9574,6 +9670,7 @@ export {
9574
9670
  androidDebuggable,
9575
9671
  assessHeaders,
9576
9672
  blockingMainThread,
9673
+ buildProjectContext,
9577
9674
  buildTaintMap,
9578
9675
  calculateGrade,
9579
9676
  callSpreads,
@@ -9750,6 +9847,7 @@ export {
9750
9847
  overlyPermissiveIAM,
9751
9848
  parseFile,
9752
9849
  parseScanTarget,
9850
+ parseSupabaseConfig,
9753
9851
  pathTraversal,
9754
9852
  pickleDeserialization,
9755
9853
  piiInLogs,
@@ -9787,6 +9885,7 @@ export {
9787
9885
  ssti,
9788
9886
  stripeWebhookUnprotected,
9789
9887
  supabaseAnonAdmin,
9888
+ supabaseFunctionName,
9790
9889
  supabaseNoRLS,
9791
9890
  syncFileOps,
9792
9891
  terraformStateExposed,