xploitscan-shared-rules 1.31.0 → 1.32.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
@@ -1375,6 +1375,21 @@ declare const QUALITY_EXAMPLES: Record<string, QualityExample>;
1375
1375
  * separately.
1376
1376
  */
1377
1377
  declare const qualityRules: QualityRule[];
1378
+ /**
1379
+ * Rules that are written and tested but NOT run by default.
1380
+ *
1381
+ * `qualityRules` above is a claim about precision: every rule in it was
1382
+ * measured against a corpus that contained the thing it looks for, and the
1383
+ * numbers are in NARROWINGS.md. A rule whose false-positive rate is unmeasured
1384
+ * has not earned that claim, and putting it in the default set would quietly
1385
+ * spend the catalogue's credibility on an unknown.
1386
+ *
1387
+ * So they live here instead, exported so they can be run deliberately —
1388
+ * `scanQuality(files, [...qualityRules, ...unmeasuredQualityRules])` — against
1389
+ * a corpus that can actually produce a denominator. Moving one up is a
1390
+ * measurement, not a decision.
1391
+ */
1392
+ declare const unmeasuredQualityRules: QualityRule[];
1378
1393
  /**
1379
1394
  * Run the quality catalogue over a whole file set.
1380
1395
  *
@@ -1386,4 +1401,4 @@ declare function scanQuality(files: {
1386
1401
  content: string;
1387
1402
  }[], rules?: QualityRule[]): Finding[];
1388
1403
 
1389
- export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildProjectContext, buildTaintMap, calculateGrade, callSpreads, callbackHell, checkIntent, classifyExposure, classifyStatement, 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, harvestIntent, 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, maskComments, 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, proOnlyRules, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, qualityRules, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, scanQuality, 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 };
1404
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildProjectContext, buildTaintMap, calculateGrade, callSpreads, callbackHell, checkIntent, classifyExposure, classifyStatement, 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, harvestIntent, 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, maskComments, 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, proOnlyRules, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, qualityRules, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, scanQuality, 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, unmeasuredQualityRules, 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
@@ -1375,6 +1375,21 @@ declare const QUALITY_EXAMPLES: Record<string, QualityExample>;
1375
1375
  * separately.
1376
1376
  */
1377
1377
  declare const qualityRules: QualityRule[];
1378
+ /**
1379
+ * Rules that are written and tested but NOT run by default.
1380
+ *
1381
+ * `qualityRules` above is a claim about precision: every rule in it was
1382
+ * measured against a corpus that contained the thing it looks for, and the
1383
+ * numbers are in NARROWINGS.md. A rule whose false-positive rate is unmeasured
1384
+ * has not earned that claim, and putting it in the default set would quietly
1385
+ * spend the catalogue's credibility on an unknown.
1386
+ *
1387
+ * So they live here instead, exported so they can be run deliberately —
1388
+ * `scanQuality(files, [...qualityRules, ...unmeasuredQualityRules])` — against
1389
+ * a corpus that can actually produce a denominator. Moving one up is a
1390
+ * measurement, not a decision.
1391
+ */
1392
+ declare const unmeasuredQualityRules: QualityRule[];
1378
1393
  /**
1379
1394
  * Run the quality catalogue over a whole file set.
1380
1395
  *
@@ -1386,4 +1401,4 @@ declare function scanQuality(files: {
1386
1401
  content: string;
1387
1402
  }[], rules?: QualityRule[]): Finding[];
1388
1403
 
1389
- export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildProjectContext, buildTaintMap, calculateGrade, callSpreads, callbackHell, checkIntent, classifyExposure, classifyStatement, 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, harvestIntent, 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, maskComments, 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, proOnlyRules, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, qualityRules, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, scanQuality, 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 };
1404
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildProjectContext, buildTaintMap, calculateGrade, callSpreads, callbackHell, checkIntent, classifyExposure, classifyStatement, 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, harvestIntent, 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, maskComments, 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, proOnlyRules, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, qualityRules, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, scanQuality, 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, unmeasuredQualityRules, 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
@@ -12516,6 +12516,380 @@ var autosaveArmedByFailedLoad = {
12516
12516
  }
12517
12517
  };
12518
12518
 
12519
+ // src/quality/rules/config-skipped-work.ts
12520
+ import _traverse6 from "@babel/traverse";
12521
+ var traverse6 = typeof _traverse6 === "function" ? _traverse6 : _traverse6.default;
12522
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
12523
+ var DURABLE_WRITE = /\b(?:INSERT\s+INTO|UPDATE\s+\w|DELETE\s+FROM)\b|\bprisma\s*\.\s*\w+\s*\.\s*(?:create|createMany|update|updateMany|delete|deleteMany|upsert)\s*\(|\.from\s*\([^)]*\)\s*\.\s*(?:insert|update|delete|upsert)\s*\(|\b(?:db|tx|trx)\s*\.\s*(?:insert|update|delete)\s*\(/i;
12524
+ var EXTERNAL_MUTATION = /\b\w+\s*\.\s*\w+\s*\.\s*(?:create|send|update|delete|cancel|charge|capture|refund)\s*\(|\bfetch\s*\([^)]{0,300}?method\s*:\s*["'`](?:POST|PUT|PATCH|DELETE)["'`]/is;
12525
+ var BOOKKEEPING = /analytics|telemetry|track|metric|event|beacon|log|audit|ping/i;
12526
+ var DIRECT_ENV_TEST = /\bprocess\s*\.\s*env\b|\bDeno\s*\.\s*env\s*\.\s*get\s*\(/;
12527
+ function calleeName3(node) {
12528
+ if (node.type !== "CallExpression") return null;
12529
+ const c = node.callee;
12530
+ if (c.type === "Identifier") return c.name;
12531
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12532
+ return null;
12533
+ }
12534
+ function keyShape(node) {
12535
+ if (!node || node.type !== "ObjectExpression") return null;
12536
+ const keys = [];
12537
+ for (const prop of node.properties) {
12538
+ if (prop.type === "ObjectProperty" && prop.key.type === "Identifier") keys.push(prop.key.name);
12539
+ else if (prop.type === "ObjectProperty" && prop.key.type === "StringLiteral") keys.push(prop.key.value);
12540
+ else return null;
12541
+ }
12542
+ return keys.sort().join(",");
12543
+ }
12544
+ function successPayloadShape(ret, source, offset) {
12545
+ const arg = ret.argument;
12546
+ if (!arg || arg.type !== "CallExpression") return null;
12547
+ const text = source.slice(nodeStart(ret) - offset, nodeEnd(ret) - offset);
12548
+ if (/status\s*:\s*[45]\d\d|,\s*\{\s*status\s*:\s*[45]\d\d/.test(text)) return null;
12549
+ const name = calleeName3(arg);
12550
+ if (name !== "json" && name !== "Response" && name !== "NextResponse") return null;
12551
+ const first = arg.arguments[0];
12552
+ if (!first) return null;
12553
+ if (first.type === "CallExpression" && calleeName3(first) === "stringify") {
12554
+ return keyShape(first.arguments[0]);
12555
+ }
12556
+ return keyShape(first);
12557
+ }
12558
+ var configSkippedWork = {
12559
+ id: "QA011",
12560
+ title: "Success is reported for work a missing setting skipped",
12561
+ severity: "high",
12562
+ category: "Correctness",
12563
+ description: "When this setting is absent the handler returns early \u2014 with the same success payload it returns when the work actually happened. The caller cannot tell the two apart, so a request that did nothing is reported as one that did: the row was never written, and whoever asked is told it was.",
12564
+ fix: "Answer differently when the work was skipped. Either fail with a non-2xx so the caller can retry, or return a payload that says what did not happen. Returning the success shape is only correct if the success actually occurred.",
12565
+ precisionNotes: 'The claim is not "an env var might be unset" \u2014 that is a deployment-convention judgement, and unshippable. It is "the guarded response is byte-indistinguishable from the success response", which is decidable from the file, and it is the sharpest clause: the shapes are compared as sorted top-level key sets, and a spread makes the shape undecidable so the rule declines rather than guesses. On top of that: exported POST/PUT/PATCH/DELETE only; the absence test must read process.env/Deno.env directly or test a local bound from a ZERO-ARG accessor (`getTenantDb(orgId)` is a per-tenant fact, not a config fact); the guard must DOMINATE the effects \u2014 no durable write and no external mutating call before it, at least one durable write after it, which kills both the cache-invalidation handler with no durable effect at all and the handler whose primary insert already happened; and bookkeeping vocabulary (analytics, telemetry, audit, log, metric, ping) on the route path, the accessor name or the target noun is exonerated, because a skipped audit row is the app lying about its own records rather than about the user\'s work.',
12566
+ check(ctx) {
12567
+ const hits = [];
12568
+ for (const file of ctx.files) {
12569
+ if (file.excluded) continue;
12570
+ if (!file.isServer) continue;
12571
+ if (BOOKKEEPING.test(file.path)) continue;
12572
+ const parsed = file.parsed;
12573
+ if (!parsed) continue;
12574
+ traverse6(parsed.ast, {
12575
+ Function(path) {
12576
+ const node = path.node;
12577
+ let name = node.id?.name ?? null;
12578
+ if (!name && path.parent.type === "VariableDeclarator" && path.parent.id.type === "Identifier") {
12579
+ name = path.parent.id.name;
12580
+ }
12581
+ if (!name || !MUTATING_METHODS.has(name)) return;
12582
+ const fnStart = nodeStart(path.node);
12583
+ const fnSource = file.code.slice(fnStart, nodeEnd(path.node));
12584
+ let terminal = null;
12585
+ const guards = [];
12586
+ path.traverse({
12587
+ ReturnStatement(ret) {
12588
+ const shape = successPayloadShape(ret.node, file.code, 0);
12589
+ if (shape === null) return;
12590
+ const start = nodeStart(ret.node);
12591
+ const ifPath = ret.findParent((p) => p.isIfStatement());
12592
+ if (ifPath) {
12593
+ const test = file.code.slice(nodeStart(ifPath.node.test), nodeEnd(ifPath.node.test));
12594
+ if (isConfigAbsenceTest(test, ifPath, file.code)) {
12595
+ guards.push({ shape, start, test });
12596
+ return;
12597
+ }
12598
+ }
12599
+ if (!terminal || start > terminal.start) terminal = { shape, start };
12600
+ }
12601
+ });
12602
+ if (!terminal || guards.length === 0) return;
12603
+ const term = terminal;
12604
+ for (const guard of guards) {
12605
+ if (guard.shape !== term.shape) continue;
12606
+ if (BOOKKEEPING.test(guard.test)) continue;
12607
+ const before = file.code.slice(fnStart, guard.start);
12608
+ const after = file.code.slice(guard.start, nodeEnd(path.node));
12609
+ if (DURABLE_WRITE.test(before)) continue;
12610
+ if (EXTERNAL_MUTATION.test(before)) continue;
12611
+ if (!DURABLE_WRITE.test(after)) continue;
12612
+ const writeMatch = DURABLE_WRITE.exec(after);
12613
+ if (writeMatch && BOOKKEEPING.test(after.slice(writeMatch.index, writeMatch.index + 120))) continue;
12614
+ hits.push({
12615
+ file: file.path,
12616
+ line: lineAt(file.content, guard.start),
12617
+ detail: `This early return answers with the same payload shape (\`{${guard.shape}}\`) as the handler's success return, so a caller cannot tell that the work was skipped. ${fnSource.length > 0 ? "" : ""}The write below it never runs, and whoever made the request is told it did.`
12618
+ });
12619
+ break;
12620
+ }
12621
+ }
12622
+ });
12623
+ }
12624
+ return hits;
12625
+ }
12626
+ };
12627
+ function isConfigAbsenceTest(test, ifPath, code) {
12628
+ if (DIRECT_ENV_TEST.test(test)) return true;
12629
+ const m = /^!\s*([A-Za-z_$][\w$]*)$/.exec(test.trim());
12630
+ if (!m) return false;
12631
+ const local = m[1];
12632
+ const fn = ifPath.getFunctionParent();
12633
+ if (!fn) return false;
12634
+ const scope = code.slice(nodeStart(fn.node), nodeEnd(fn.node));
12635
+ return new RegExp(`\\b(?:const|let|var)\\s+${local}\\s*=\\s*(?:await\\s+)?[A-Za-z_$][\\w$]*\\s*\\(\\s*\\)`).test(scope);
12636
+ }
12637
+
12638
+ // src/quality/rules/stale-response-wins.ts
12639
+ import _traverse7 from "@babel/traverse";
12640
+ var traverse7 = typeof _traverse7 === "function" ? _traverse7 : _traverse7.default;
12641
+ var ORDERING_GUARD = /\breturn\s*\(\s*\)\s*=>|\bAbortController\b|\bsignal\b|\bcancell?ed\b|\bignore\b|\bstale\b|\bisMounted\b|\baborted\b/i;
12642
+ var SETTER2 = /^set[A-Z][A-Za-z0-9_]*$/;
12643
+ function calleeIdentifier2(node) {
12644
+ if (node.type !== "CallExpression") return null;
12645
+ const c = node.callee;
12646
+ if (c.type === "Identifier") return c.name;
12647
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12648
+ return null;
12649
+ }
12650
+ function isEffectCall3(node) {
12651
+ const n = calleeIdentifier2(node);
12652
+ return n === "useEffect" || n === "useLayoutEffect";
12653
+ }
12654
+ function templateIdentifiers(node) {
12655
+ if (node.type !== "TemplateLiteral") return [];
12656
+ const out = [];
12657
+ for (const expr of node.expressions) {
12658
+ collectIdentifiers(expr, out);
12659
+ }
12660
+ return out;
12661
+ }
12662
+ function collectIdentifiers(node, out) {
12663
+ if (!node || typeof node !== "object") return;
12664
+ if (node.type === "Identifier") {
12665
+ out.push(node.name);
12666
+ return;
12667
+ }
12668
+ for (const key of Object.keys(node)) {
12669
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
12670
+ const v = node[key];
12671
+ if (Array.isArray(v)) v.forEach((c) => c && typeof c === "object" && collectIdentifiers(c, out));
12672
+ else if (v && typeof v === "object" && "type" in v) collectIdentifiers(v, out);
12673
+ }
12674
+ }
12675
+ function derivesFromDep(name, deps, effect, code) {
12676
+ if (deps.has(name)) return true;
12677
+ let found = false;
12678
+ const seen = /* @__PURE__ */ new Set([name]);
12679
+ const frontier = [name];
12680
+ for (let depth = 0; depth < 4 && frontier.length && !found; depth++) {
12681
+ const current = frontier.splice(0, frontier.length);
12682
+ for (const target of current) {
12683
+ effect.traverse({
12684
+ VariableDeclarator(p) {
12685
+ if (found) return;
12686
+ if (p.node.id.type !== "Identifier" || p.node.id.name !== target) return;
12687
+ if (!p.node.init) return;
12688
+ const names = [];
12689
+ collectIdentifiers(p.node.init, names);
12690
+ for (const n of names) {
12691
+ if (deps.has(n)) {
12692
+ found = true;
12693
+ return;
12694
+ }
12695
+ if (!seen.has(n)) {
12696
+ seen.add(n);
12697
+ frontier.push(n);
12698
+ }
12699
+ }
12700
+ },
12701
+ AssignmentExpression(p) {
12702
+ if (found) return;
12703
+ if (p.node.left.type !== "Identifier" || p.node.left.name !== target) return;
12704
+ const names = [];
12705
+ collectIdentifiers(p.node.right, names);
12706
+ for (const n of names) {
12707
+ if (deps.has(n)) {
12708
+ found = true;
12709
+ return;
12710
+ }
12711
+ if (!seen.has(n)) {
12712
+ seen.add(n);
12713
+ frontier.push(n);
12714
+ }
12715
+ }
12716
+ }
12717
+ });
12718
+ }
12719
+ }
12720
+ return found;
12721
+ }
12722
+ var staleResponseWins = {
12723
+ id: "QA012",
12724
+ title: "A stale response can overwrite a newer one",
12725
+ severity: "medium",
12726
+ category: "Correctness",
12727
+ description: "This effect refetches whenever the user changes their selection, and does nothing to cancel the request already in flight. Pick one thing, then another before the first answers, and the first response lands last and wins: the selector says one thing and the panel shows another. Nothing errors, the data is real \u2014 it is just the wrong data, and it stays wrong until the next interaction.",
12728
+ fix: "Return a cleanup function from the effect that makes the late response a no-op \u2014 set a `cancelled` flag the `.then` checks, or abort the request with an AbortController and pass its `signal` to fetch. React calls the cleanup before it re-runs the effect, which is exactly when the older request becomes irrelevant.",
12729
+ precisionNotes: 'Two clauses came from being wrong. The first draft asked whether the interpolated identifier was ASSIGNED INSIDE THE EFFECT, which an effect-local constant satisfies (`const base = process.env.NEXT_PUBLIC_API ?? ""`), so it fired on URLs that cannot vary between renders; what matters is that the identifier is DERIVED FROM A DEPENDENCY, since only a dependency can change mid-flight. The second: an identifier REFERENCED AGAIN AFTER the network call is the signature of code that already handles ordering \u2014 the keyed write `setCache(prev => ({ ...prev, [id]: data }))`, where out-of-order arrival is harmless, and the hand-rolled `if (latest.current === id) setScan(data)`, which is a cleanup function written by hand. Neither mentions cancelled/AbortController/signal, so nothing else excludes them. Also required: a non-empty dep array, a literal `fetch(`, a state setter after it, and the dependency must be a useState in this file wired to an onChange \u2014 the strict form, because relaxing it to "or any dep" reopens the child that fetches on a prop whose parent remounts it with a `key`, and that remount is invisible from the child\'s file. Frequency is this rule\'s weak point and is worth stating: two distinct defects, one codebase, one author. Shipped at medium for that reason.',
12730
+ check(ctx) {
12731
+ const hits = [];
12732
+ for (const file of ctx.files) {
12733
+ if (file.excluded) continue;
12734
+ if (!file.isClient) continue;
12735
+ if (file.isServer) continue;
12736
+ const parsed = file.parsed;
12737
+ if (!parsed) continue;
12738
+ traverse7(parsed.ast, {
12739
+ CallExpression(path) {
12740
+ if (!isEffectCall3(path.node)) return;
12741
+ const args = path.node.arguments;
12742
+ const cbNode = args[0];
12743
+ const depNode = args[1];
12744
+ if (!cbNode || !depNode || depNode.type !== "ArrayExpression") return;
12745
+ if (depNode.elements.length === 0) return;
12746
+ const deps = /* @__PURE__ */ new Set();
12747
+ for (const el of depNode.elements) {
12748
+ if (el && el.type === "Identifier") deps.add(el.name);
12749
+ }
12750
+ if (deps.size === 0) return;
12751
+ const cb = path.get("arguments.0");
12752
+ if (!cb || !cb.node) return;
12753
+ const bodyStart = nodeStart(cb.node);
12754
+ const bodySource = file.code.slice(bodyStart, nodeEnd(cb.node));
12755
+ if (ORDERING_GUARD.test(bodySource)) return;
12756
+ let hit = null;
12757
+ cb.traverse({
12758
+ CallExpression(inner) {
12759
+ if (hit) return;
12760
+ if (!isFetchCallee(inner.node.callee)) return;
12761
+ const url = inner.node.arguments[0];
12762
+ if (!url) return;
12763
+ const interpolated = templateIdentifiers(url);
12764
+ if (interpolated.length === 0) return;
12765
+ const callEnd = nodeEnd(inner.node);
12766
+ const afterCall = file.code.slice(callEnd, nodeEnd(cb.node));
12767
+ let setsState = false;
12768
+ cb.traverse({
12769
+ CallExpression(c) {
12770
+ if (setsState) return;
12771
+ if (nodeStart(c.node) < callEnd) return;
12772
+ const n = calleeIdentifier2(c.node);
12773
+ if (n && SETTER2.test(n)) setsState = true;
12774
+ }
12775
+ });
12776
+ if (!setsState) return;
12777
+ for (const ident2 of interpolated) {
12778
+ if (!derivesFromDep(ident2, deps, cb, file.code)) continue;
12779
+ if (new RegExp(`\\b${ident2}\\b`).test(afterCall)) continue;
12780
+ if (![...deps].some((d) => userDriven(d, file.code))) continue;
12781
+ hit = { line: lineAt(file.content, nodeStart(inner.node)), ident: ident2 };
12782
+ return;
12783
+ }
12784
+ }
12785
+ });
12786
+ if (!hit) return;
12787
+ const { line, ident } = hit;
12788
+ hits.push({
12789
+ file: file.path,
12790
+ line,
12791
+ detail: `This request's URL depends on \`${ident}\`, which changes when the user does, and the effect returns no cleanup \u2014 so a response for the previous selection can arrive after the current one and overwrite it. The screen then shows data that does not match the control above it.`
12792
+ });
12793
+ }
12794
+ });
12795
+ }
12796
+ return hits;
12797
+ }
12798
+ };
12799
+ function userDriven(dep, code) {
12800
+ const setter = `set${dep.charAt(0).toUpperCase()}${dep.slice(1)}`;
12801
+ if (!new RegExp(`\\[\\s*${dep}\\s*,\\s*${setter}\\s*\\]\\s*=\\s*useState`).test(code)) return false;
12802
+ return new RegExp(`on(?:Change|Click|Input|Select)\\s*=\\s*\\{[^}]{0,200}\\b${setter}\\b`, "s").test(code);
12803
+ }
12804
+
12805
+ // src/quality/rules/lost-update-counter.ts
12806
+ import _traverse8 from "@babel/traverse";
12807
+ var traverse8 = typeof _traverse8 === "function" ? _traverse8 : _traverse8.default;
12808
+ var COUNTER_COLUMN = /^(?:credits?|balance|stock|quantity|qty|tokens?|seats?|points?|inventory|remaining|available)$/i;
12809
+ var WRITE_CALL = /\bUPDATE\s+\w|\.\s*update\s*\(|\.\s*set\s*\(|\bprisma\s*\.\s*\w+\s*\.\s*update\b/i;
12810
+ var ATOMIC_OR_SERIALISED = /\b(?:increment|decrement)\s*:|\bsql`[^`]*\b\w+\s*[-+]\s*|\bSET\s+(\w+)\s*=\s*\1\s*[-+]|\.\s*rpc\s*\(|\btransaction\s*\(|\bBEGIN\s+IMMEDIATE\b|\bFOR\s+UPDATE\b|\block\s*\.\s*acquire\s*\(|\bmutex\b|\bredlock\b|\bWHERE[^;]{0,120}\b\w+\s*=\s*\?[^;]{0,40}\bAND\b[^;]{0,120}\bversion\b/i;
12811
+ var SCHEDULED_PATH = /(?:^|\/)(?:cron|jobs?|scheduled|tasks?|workers?)\//i;
12812
+ var INSERT_RETURNING = /\bINSERT\b[\s\S]{0,400}?\bRETURNING\b/i;
12813
+ function memberColumn(node) {
12814
+ if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") return null;
12815
+ const prop = node.property;
12816
+ if (prop.type !== "Identifier") return null;
12817
+ return COUNTER_COLUMN.test(prop.name) ? prop.name : null;
12818
+ }
12819
+ function rootObject(node) {
12820
+ let cur = node;
12821
+ while (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12822
+ cur = cur.object;
12823
+ }
12824
+ return cur.type === "Identifier" ? cur.name : null;
12825
+ }
12826
+ var MAX_PER_SCAN2 = 3;
12827
+ var lostUpdateCounter = {
12828
+ id: "QA013",
12829
+ title: "A balance is read, changed in JavaScript, and written back",
12830
+ severity: "high",
12831
+ category: "Correctness",
12832
+ description: "This reads the current value, does the arithmetic in the application, and writes the result back. Two requests that arrive together both read the same starting value and both write the same answer, so one of the two changes is lost \u2014 a spend that was never charged, or stock sold twice. The window is the round trip between the read and the write, and nothing about it shows up in development, where requests arrive one at a time.",
12833
+ fix: "Let the database do the arithmetic, so the read and the write are one statement: `UPDATE users SET credits = credits - 1 WHERE id = ? AND credits >= 1`, or the ORM's atomic form (`{ credits: { decrement: 1 } }`). Check the affected row count to find out whether it applied. A transaction or an explicit lock also works.",
12834
+ precisionNotes: "NOT ENABLED BY DEFAULT \u2014 its false-positive rate is unmeasured, not low. This repository contains no counters at all, so its 0 fires are 0 out of 0, and every other rule in this catalogue quotes a real denominator. It ships so it can be run against a corpus that contains counters. The narrowing, for when it is: the column must be on a short money/inventory allowlist, because a denormalised comment_count reconciled nightly loses an update and nobody cares, and only money and inventory make the consequence sentence true; the read local must be a DIRECT operand of `+`/`-`, so an idempotent absolute assignment computed from a plan table is not reported; exonerate on any atomic or serialised form (ORM increment/decrement, SQL arithmetic, .rpc(, a transaction, an explicit lock, FOR UPDATE, an optimistic version predicate); exonerate when the db handle is a PARAMETER of the enclosing function, because the caller opened the transaction; exonerate a read that is a RETURNING from an INSERT in the same function, since the row was created here; and skip cron and job paths, which have one invocation and no concurrent writer. Capped at one finding per file and three per scan, the volume discipline QA006 already uses.",
12835
+ check(ctx) {
12836
+ const hits = [];
12837
+ for (const file of ctx.files) {
12838
+ if (hits.length >= MAX_PER_SCAN2) break;
12839
+ if (file.excluded) continue;
12840
+ if (!file.isServer) continue;
12841
+ if (SCHEDULED_PATH.test(file.path)) continue;
12842
+ const parsed = file.parsed;
12843
+ if (!parsed) continue;
12844
+ let firedInFile = false;
12845
+ traverse8(parsed.ast, {
12846
+ BinaryExpression(path) {
12847
+ if (firedInFile || hits.length >= MAX_PER_SCAN2) return;
12848
+ const op = path.node.operator;
12849
+ if (op !== "+" && op !== "-") return;
12850
+ const left = path.node.left;
12851
+ const right = path.node.right;
12852
+ const column = memberColumn(left) ?? memberColumn(right);
12853
+ if (!column) return;
12854
+ const readLocal = rootObject(memberColumn(left) ? left : right);
12855
+ if (!readLocal) return;
12856
+ const fn = path.getFunctionParent();
12857
+ if (!fn) return;
12858
+ const fnSource = file.code.slice(nodeStart(fn.node), nodeEnd(fn.node));
12859
+ if (!WRITE_CALL.test(fnSource)) return;
12860
+ let serialised = false;
12861
+ for (let scope = fn; scope !== null && !serialised; scope = scope.getFunctionParent()) {
12862
+ const src = file.code.slice(nodeStart(scope.node), nodeEnd(scope.node));
12863
+ if (ATOMIC_OR_SERIALISED.test(src)) serialised = true;
12864
+ }
12865
+ if (serialised) return;
12866
+ if (INSERT_RETURNING.test(fnSource)) return;
12867
+ if (handleIsParameter(fn, fnSource)) return;
12868
+ if (!new RegExp(`\\b(?:const|let|var)\\s+(?:\\{[^}]*\\}|${readLocal})\\s*=\\s*await\\b`).test(fnSource)) return;
12869
+ firedInFile = true;
12870
+ hits.push({
12871
+ file: file.path,
12872
+ line: lineAt(file.content, nodeStart(path.node)),
12873
+ detail: `\`${readLocal}.${column}\` is read, changed here, and written back, so two requests that arrive together both start from the same value and one of the two changes is lost. Let the database do the arithmetic instead.`
12874
+ });
12875
+ }
12876
+ });
12877
+ }
12878
+ return hits;
12879
+ }
12880
+ };
12881
+ function handleIsParameter(fn, source) {
12882
+ const params = fn.node.params;
12883
+ for (const p of params) {
12884
+ if (p.type !== "Identifier") continue;
12885
+ if (/^(?:tx|trx|db|conn|client|transaction)$/i.test(p.name)) return true;
12886
+ if (new RegExp(`\\b${p.name}\\s*\\.\\s*(?:execute|run|query|update|insert)\\s*\\(`).test(source)) {
12887
+ return true;
12888
+ }
12889
+ }
12890
+ return false;
12891
+ }
12892
+
12519
12893
  // src/quality/examples.ts
12520
12894
  var QUALITY_EXAMPLES = {
12521
12895
  QA001: {
@@ -12641,6 +13015,94 @@ export function Checklist() {
12641
13015
  useEffect(() => {
12642
13016
  if (stateLoaded && !stateLoadFailed) saveState();
12643
13017
  }, [overrides, stateLoaded, stateLoadFailed, saveState]);
13018
+ }`
13019
+ },
13020
+ QA011: {
13021
+ path: "app/api/scans/route.ts",
13022
+ language: "typescript",
13023
+ difference: "The skipped path answers 503 with an error instead of the success payload, so the caller can tell the scan was not stored \u2014 and retry.",
13024
+ vulnerable: `export async function POST(request: Request) {
13025
+ const body = await request.json();
13026
+ const id = \`scan_\${Date.now()}\`;
13027
+
13028
+ const db = getDb();
13029
+ if (!db) {
13030
+ // No database configured \u2014 return success anyway
13031
+ return NextResponse.json({ scan: { id } });
13032
+ }
13033
+
13034
+ await db.execute({
13035
+ sql: "INSERT INTO scans (id, findings_json) VALUES (?, ?)",
13036
+ args: [id, JSON.stringify(body.findings)],
13037
+ });
13038
+
13039
+ return NextResponse.json({ scan: { id } });
13040
+ }`,
13041
+ safe: `export async function POST(request: Request) {
13042
+ const body = await request.json();
13043
+ const id = \`scan_\${Date.now()}\`;
13044
+
13045
+ const db = getDb();
13046
+ if (!db) {
13047
+ return NextResponse.json(
13048
+ { error: "Scan storage is not configured \u2014 this scan was not saved." },
13049
+ { status: 503 },
13050
+ );
13051
+ }
13052
+
13053
+ await db.execute({
13054
+ sql: "INSERT INTO scans (id, findings_json) VALUES (?, ?)",
13055
+ args: [id, JSON.stringify(body.findings)],
13056
+ });
13057
+
13058
+ return NextResponse.json({ scan: { id } });
13059
+ }`
13060
+ },
13061
+ QA012: {
13062
+ path: "app/panel/ScanPanel.tsx",
13063
+ language: "tsx",
13064
+ difference: "The effect returns a cleanup that flips `cancelled`, so React disarms the in-flight request before re-running \u2014 a response for the previous selection can no longer land last and win.",
13065
+ vulnerable: `"use client";
13066
+
13067
+ export function ScanPanel() {
13068
+ const [projectId, setProjectId] = useState("latest");
13069
+ const [scan, setScan] = useState(null);
13070
+
13071
+ useEffect(() => {
13072
+ fetch(\`/api/scans/\${projectId}\`)
13073
+ .then((r) => r.json())
13074
+ .then((d) => setScan(d.scan));
13075
+ }, [projectId]);
13076
+
13077
+ return (
13078
+ <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>
13079
+ {/* \u2026 */}
13080
+ </select>
13081
+ );
13082
+ }`,
13083
+ safe: `"use client";
13084
+
13085
+ export function ScanPanel() {
13086
+ const [projectId, setProjectId] = useState("latest");
13087
+ const [scan, setScan] = useState(null);
13088
+
13089
+ useEffect(() => {
13090
+ let cancelled = false;
13091
+ fetch(\`/api/scans/\${projectId}\`)
13092
+ .then((r) => r.json())
13093
+ .then((d) => {
13094
+ if (!cancelled) setScan(d.scan);
13095
+ });
13096
+ return () => {
13097
+ cancelled = true;
13098
+ };
13099
+ }, [projectId]);
13100
+
13101
+ return (
13102
+ <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>
13103
+ {/* \u2026 */}
13104
+ </select>
13105
+ );
12644
13106
  }`
12645
13107
  },
12646
13108
  QA002: {
@@ -12851,7 +13313,12 @@ var qualityRules = [
12851
13313
  unboundedList,
12852
13314
  unassociatedLabel,
12853
13315
  failedReadEmptyState,
12854
- autosaveArmedByFailedLoad
13316
+ autosaveArmedByFailedLoad,
13317
+ configSkippedWork,
13318
+ staleResponseWins
13319
+ ];
13320
+ var unmeasuredQualityRules = [
13321
+ lostUpdateCounter
12855
13322
  ];
12856
13323
  function scanQuality(files, rules = qualityRules) {
12857
13324
  const ctx = buildQualityContext(files);
@@ -13136,6 +13603,7 @@ export {
13136
13603
  timingAttack,
13137
13604
  todoLeftInCode,
13138
13605
  unencryptedPII,
13606
+ unmeasuredQualityRules,
13139
13607
  unpinnedGitHubAction,
13140
13608
  unprotectedAPIRoutes,
13141
13609
  unprotectedDownload,