xploitscan-shared-rules 1.21.0 → 1.22.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
  /**
@@ -516,7 +580,14 @@ declare const insecureDirectObjectReference: CustomRule;
516
580
  declare const freeRules: CustomRule[];
517
581
  declare const allRules: CustomRule[];
518
582
  declare const allCustomRules: CustomRule[];
519
- declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[]): Finding[];
583
+ declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[],
584
+ /**
585
+ * Cross-file facts for the project being scanned, from
586
+ * buildProjectContext(). Optional: callers that scan a single file with no
587
+ * project around it (the MCP server, the editor extension, a pasted
588
+ * snippet) pass nothing, and every rule must still work.
589
+ */
590
+ project?: ProjectContext): Finding[];
520
591
 
521
592
  /**
522
593
  * Rule-set sizes as plain numbers, importable without dragging the rules in.
@@ -925,4 +996,4 @@ declare function getObjectProperty(node: ObjectExpression, key: string): {
925
996
  /** Does this CallExpression spread an expression `matcher` returns true for? */
926
997
  declare function callSpreads(call: CallExpression, matcher: (node: Node) => boolean): boolean;
927
998
 
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 };
999
+ 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, 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
  /**
@@ -516,7 +580,14 @@ declare const insecureDirectObjectReference: CustomRule;
516
580
  declare const freeRules: CustomRule[];
517
581
  declare const allRules: CustomRule[];
518
582
  declare const allCustomRules: CustomRule[];
519
- declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[]): Finding[];
583
+ declare function runCustomRules(content: string, filePath: string, disabledRules?: string[], tier?: "free" | "pro", extraRules?: CustomRule[],
584
+ /**
585
+ * Cross-file facts for the project being scanned, from
586
+ * buildProjectContext(). Optional: callers that scan a single file with no
587
+ * project around it (the MCP server, the editor extension, a pasted
588
+ * snippet) pass nothing, and every rule must still work.
589
+ */
590
+ project?: ProjectContext): Finding[];
520
591
 
521
592
  /**
522
593
  * Rule-set sizes as plain numbers, importable without dragging the rules in.
@@ -925,4 +996,4 @@ declare function getObjectProperty(node: ObjectExpression, key: string): {
925
996
  /** Does this CallExpression spread an expression `matcher` returns true for? */
926
997
  declare function callSpreads(call: CallExpression, matcher: (node: Node) => boolean): boolean;
927
998
 
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 };
999
+ 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, 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
@@ -284,6 +284,42 @@ function classifyExposure(filePath) {
284
284
  return "unknown";
285
285
  }
286
286
 
287
+ // src/project-context.ts
288
+ var TOML_FN_SECTION_RE = /^\s*\[functions\.(?:"([^"]+)"|([A-Za-z0-9._-]+))\]\s*$/;
289
+ var TOML_VERIFY_JWT_RE = /^\s*verify_jwt\s*=\s*(true|false)\s*(?:#.*)?$/i;
290
+ function parseSupabaseConfig(toml) {
291
+ const out = /* @__PURE__ */ new Map();
292
+ let current = null;
293
+ for (const line of toml.split(/\r?\n/)) {
294
+ const section = line.match(TOML_FN_SECTION_RE);
295
+ if (section) {
296
+ current = section[1] ?? section[2];
297
+ continue;
298
+ }
299
+ if (/^\s*\[/.test(line)) {
300
+ current = null;
301
+ continue;
302
+ }
303
+ if (!current) continue;
304
+ const verify = line.match(TOML_VERIFY_JWT_RE);
305
+ if (verify) out.set(current, verify[1].toLowerCase() === "true");
306
+ }
307
+ return out;
308
+ }
309
+ function supabaseFunctionName(filePath) {
310
+ const m = filePath.match(/(?:^|\/)supabase\/functions\/([^/]+)\//);
311
+ return m ? m[1] : null;
312
+ }
313
+ function buildProjectContext(files) {
314
+ const ctx = {};
315
+ const config = files.find((f) => /(?:^|\/)supabase\/config\.toml$/.test(f.path));
316
+ if (config) {
317
+ const parsed = parseSupabaseConfig(config.content);
318
+ if (parsed.size > 0) ctx.supabaseEdgeVerifyJwt = parsed;
319
+ }
320
+ return ctx;
321
+ }
322
+
287
323
  // src/vendored.ts
288
324
  var NON_APP_PATH_PATTERNS = [
289
325
  // 1. vendored UI component libraries
@@ -1032,6 +1068,7 @@ var SERVER_SIDE_CONTENT_RE = /\b(?:req|request)\.(?:body|query|params|headers|co
1032
1068
  function isServerSideFile(filePath, content) {
1033
1069
  if (isTestFile(filePath)) return false;
1034
1070
  if (SERVER_SIDE_PATH_RE.test(filePath)) return true;
1071
+ if (content && /^\s*["']use server["']/m.test(content)) return true;
1035
1072
  if (content && SERVER_SIDE_CONTENT_RE.test(content)) return true;
1036
1073
  return false;
1037
1074
  }
@@ -1335,7 +1372,7 @@ var missingAuthMiddleware = {
1335
1372
  severity: "high",
1336
1373
  category: "Authentication",
1337
1374
  description: "API routes without authentication checks allow unauthorized access.",
1338
- check(content, filePath) {
1375
+ check(content, filePath, project) {
1339
1376
  if (!isServerSideFile(filePath, content)) return [];
1340
1377
  const routePatterns = [
1341
1378
  // Express/Hono style
@@ -1343,6 +1380,27 @@ var missingAuthMiddleware = {
1343
1380
  // Next.js API routes — named function declaration
1344
1381
  /export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|PATCH|DELETE)\s*\(/gi
1345
1382
  ];
1383
+ const VERCEL_API_FN_RE = /(?:^|\/)api\/[^/]+\.(?:m?[jt]s)$/;
1384
+ const isNextTree = /(?:^|\/)(?:src\/)?(?:app|pages)\//.test(filePath);
1385
+ if (VERCEL_API_FN_RE.test(filePath) && !isNextTree) {
1386
+ routePatterns.push(
1387
+ /export\s+default\s+(?:async\s+)?(?:function\b|\()/g,
1388
+ /module\.exports\s*=\s*(?:async\s+)?(?:function\b|\()/g
1389
+ );
1390
+ }
1391
+ if (/^\s*["']use server["']/m.test(content)) {
1392
+ routePatterns.push(
1393
+ /export\s+(?:async\s+)?function\s+\w+\s*\(/g,
1394
+ /export\s+const\s+\w+\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?\(/g
1395
+ );
1396
+ }
1397
+ const EDGE_FN_DIR_RE = /(?:^|\/)(?:netlify\/(?:edge-)?functions|functions|edge-functions)\/[^/]+\/?[^/]*\.(?:m?[jt]s)$/;
1398
+ if (EDGE_FN_DIR_RE.test(filePath) && !SUPABASE_EDGE_FN_RE.test(filePath)) {
1399
+ routePatterns.push(
1400
+ /(?:exports\s*\.\s*handler|export\s+const\s+handler)\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?(?:function\b|\()/g,
1401
+ /export\s+default\s+(?:async\s+)?(?:function\b|\()/g
1402
+ );
1403
+ }
1346
1404
  if (/(?:^|\/)(?:src\/)?app\/(?:.*\/)?route\.(?:m?[jt]sx?)$/.test(filePath)) {
1347
1405
  routePatterns.push(
1348
1406
  /export\s+const\s+(?:GET|POST|PUT|PATCH|DELETE)\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?(?:function\b|\()/g
@@ -1383,8 +1441,24 @@ var missingAuthMiddleware = {
1383
1441
  /\b(?:protect|guard)\(/i,
1384
1442
  /\.use\([^)]*(?:auth|session|protect|requireAuth)/i
1385
1443
  ];
1386
- const hasAuth = authPatterns.some((p) => p.test(codeOnly));
1387
- if (hasAuth) return [];
1444
+ const APP_LEVEL_AUTH = [
1445
+ /\.use\([^)]*(?:auth|session|protect|requireAuth)/i,
1446
+ /\bpassport\b/i,
1447
+ /\bclerk\b/i,
1448
+ /\bwithAuth\b/i
1449
+ ];
1450
+ if (APP_LEVEL_AUTH.some((p) => p.test(codeOnly))) return [];
1451
+ const handlerAuthPatterns = authPatterns.filter(
1452
+ (p) => !APP_LEVEL_AUTH.some((a) => a.source === p.source)
1453
+ );
1454
+ const maskedForScope = maskComments(content);
1455
+ const handlerHasAuth = (index) => {
1456
+ const bodyStart = maskedForScope.indexOf("{", index);
1457
+ const probe = bodyStart === -1 ? index : bodyStart + 1;
1458
+ const scope = enclosingHandler(maskedForScope, probe);
1459
+ if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeOnly));
1460
+ return handlerAuthPatterns.some((p) => p.test(scope));
1461
+ };
1388
1462
  const matches = [];
1389
1463
  for (const pattern of routePatterns) {
1390
1464
  matches.push(
@@ -1398,21 +1472,31 @@ var missingAuthMiddleware = {
1398
1472
  );
1399
1473
  }
1400
1474
  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
- );
1475
+ const fnName = supabaseFunctionName(filePath);
1476
+ const verifyJwt = fnName && project?.supabaseEdgeVerifyJwt ? project.supabaseEdgeVerifyJwt.get(fnName) : void 0;
1477
+ if (verifyJwt !== true) {
1478
+ const withoutCors = stripCorsHeaderList(codeOnly);
1479
+ const hasWeakHint = verifyJwt === false ? false : EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));
1480
+ if (!hasWeakHint) {
1481
+ matches.push(
1482
+ ...findMatches(
1483
+ content,
1484
+ DENO_EDGE_ENTRY_RE,
1485
+ missingAuthMiddleware,
1486
+ filePath,
1487
+ () => "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."
1488
+ )
1489
+ );
1490
+ }
1413
1491
  }
1414
1492
  }
1415
- return filterSilenced(matches, content, "VC003");
1493
+ const lineStarts = [0];
1494
+ for (let i = 0; i < content.length; i++) {
1495
+ if (content[i] === "\n") lineStarts.push(i + 1);
1496
+ }
1497
+ const indexOfLine = (line) => lineStarts[Math.max(0, Math.min(line - 1, lineStarts.length - 1))];
1498
+ const unauthenticated = matches.filter((m) => !handlerHasAuth(indexOfLine(m.line)));
1499
+ return filterSilenced(unauthenticated, content, "VC003");
1416
1500
  }
1417
1501
  };
1418
1502
  var supabaseNoRLS = {
@@ -8851,7 +8935,7 @@ var allCustomRules = [
8851
8935
  entitlementFromWebStorage,
8852
8936
  accountStateFromWebStorage
8853
8937
  ];
8854
- function runCustomRules(content, filePath, disabledRules = [], tier = "free", extraRules = []) {
8938
+ function runCustomRules(content, filePath, disabledRules = [], tier = "free", extraRules = [], project) {
8855
8939
  const findings = [];
8856
8940
  if (/function runScan\(files\)|export function runCustomRules/.test(content) && /const (?:rules|allRules)\s*[:=]/.test(content) && /findMatches/.test(content)) {
8857
8941
  return findings;
@@ -8873,7 +8957,7 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
8873
8957
  const ruleset = tier === "pro" && extraRules.length > 0 ? [...freeRules, ...extraRules] : freeRules;
8874
8958
  for (const rule of ruleset) {
8875
8959
  if (disabledRules.includes(rule.id)) continue;
8876
- const matches = rule.check(content, filePath);
8960
+ const matches = rule.check(content, filePath, project);
8877
8961
  const compliance = complianceMap[rule.id];
8878
8962
  const vendored = vendoredFile && isVendoredFinding({ file: filePath, rule: rule.id, category: rule.category });
8879
8963
  for (const match of matches) {
@@ -9574,6 +9658,7 @@ export {
9574
9658
  androidDebuggable,
9575
9659
  assessHeaders,
9576
9660
  blockingMainThread,
9661
+ buildProjectContext,
9577
9662
  buildTaintMap,
9578
9663
  calculateGrade,
9579
9664
  callSpreads,
@@ -9750,6 +9835,7 @@ export {
9750
9835
  overlyPermissiveIAM,
9751
9836
  parseFile,
9752
9837
  parseScanTarget,
9838
+ parseSupabaseConfig,
9753
9839
  pathTraversal,
9754
9840
  pickleDeserialization,
9755
9841
  piiInLogs,
@@ -9787,6 +9873,7 @@ export {
9787
9873
  ssti,
9788
9874
  stripeWebhookUnprotected,
9789
9875
  supabaseAnonAdmin,
9876
+ supabaseFunctionName,
9790
9877
  supabaseNoRLS,
9791
9878
  syncFileOps,
9792
9879
  terraformStateExposed,