xploitscan-shared-rules 1.35.1 → 1.36.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
@@ -1278,8 +1278,9 @@ declare function callSpreads(call: CallExpression, matcher: (node: Node) => bool
1278
1278
  * EVERY RULE HERE EARNED ITS PLACE BY SURVIVING AN ATTACK. Each began as a
1279
1279
  * real defect found in this product, was then handed to an adversarial review
1280
1280
  * whose only job was to find legitimate code that would trip it, and ships
1281
- * only with the narrowing that survived. Four candidates did not survive and
1282
- * are not here. The precision bar is the product: a noisy rule trains people
1281
+ * only with the narrowing that survived. Six candidates did not survive and
1282
+ * are not here; the last two are written up at the end of NARROWINGS.md, so
1283
+ * that proposing them again costs an argument rather than a round. The precision bar is the product: a noisy rule trains people
1283
1284
  * to ignore the tool, which is worse than having no rule at all.
1284
1285
  */
1285
1286
  interface QualityRule {
@@ -1341,6 +1342,19 @@ declare function buildQualityContext(files: {
1341
1342
  path: string;
1342
1343
  content: string;
1343
1344
  }[]): QualityContext;
1345
+ /** Line number for a byte offset, 1-based. Offsets survive maskComments. */
1346
+ /**
1347
+ * The gate a client-side rule applies before it looks at a file, named once.
1348
+ *
1349
+ * Four rules spelled these three conditions out, and the measurement harness
1350
+ * made a fifth copy that dropped `!isServer` — so `src/api/hooks/useThing.ts`
1351
+ * counted toward a denominator no client rule would ever run on, and counted
1352
+ * again on the server side. A denominator that does not match its numerator is
1353
+ * the one thing that harness exists not to produce.
1354
+ */
1355
+ declare function isClientTarget(file: QualityFile): boolean;
1356
+ /** The server-side counterpart. */
1357
+ declare function isServerTarget(file: QualityFile): boolean;
1344
1358
 
1345
1359
  /**
1346
1360
  * Worked examples for the quality catalogue, one vulnerable/safe pair per rule.
@@ -1402,9 +1416,18 @@ declare const unmeasuredQualityRules: QualityRule[];
1402
1416
  * Parallel to scanEntropy and scanDependencies: an engine, not a rule, because
1403
1417
  * most of these need more than the single file the rule contract allows.
1404
1418
  */
1405
- declare function scanQuality(files: {
1419
+ declare function scanQuality(
1420
+ /**
1421
+ * The files to scan, or a context already built for them. Building one
1422
+ * parses every file into a Babel AST and holds them all at once, so a caller
1423
+ * that needs the context for its own reasons — the measurement harness counts
1424
+ * how many files each rule class applies to — should hand it over rather than
1425
+ * pay for a second one. Taking either here, instead of a third parameter,
1426
+ * means there is no pair of arguments that can disagree.
1427
+ */
1428
+ input: {
1406
1429
  path: string;
1407
1430
  content: string;
1408
- }[], rules?: QualityRule[]): Finding[];
1431
+ }[] | QualityContext, rules?: QualityRule[]): Finding[];
1409
1432
 
1410
- 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, buildQualityContext, 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 };
1433
+ 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, buildQualityContext, 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, isClientTarget, isMethodCall, isPrivateAddress, isServerTarget, 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
@@ -1278,8 +1278,9 @@ declare function callSpreads(call: CallExpression, matcher: (node: Node) => bool
1278
1278
  * EVERY RULE HERE EARNED ITS PLACE BY SURVIVING AN ATTACK. Each began as a
1279
1279
  * real defect found in this product, was then handed to an adversarial review
1280
1280
  * whose only job was to find legitimate code that would trip it, and ships
1281
- * only with the narrowing that survived. Four candidates did not survive and
1282
- * are not here. The precision bar is the product: a noisy rule trains people
1281
+ * only with the narrowing that survived. Six candidates did not survive and
1282
+ * are not here; the last two are written up at the end of NARROWINGS.md, so
1283
+ * that proposing them again costs an argument rather than a round. The precision bar is the product: a noisy rule trains people
1283
1284
  * to ignore the tool, which is worse than having no rule at all.
1284
1285
  */
1285
1286
  interface QualityRule {
@@ -1341,6 +1342,19 @@ declare function buildQualityContext(files: {
1341
1342
  path: string;
1342
1343
  content: string;
1343
1344
  }[]): QualityContext;
1345
+ /** Line number for a byte offset, 1-based. Offsets survive maskComments. */
1346
+ /**
1347
+ * The gate a client-side rule applies before it looks at a file, named once.
1348
+ *
1349
+ * Four rules spelled these three conditions out, and the measurement harness
1350
+ * made a fifth copy that dropped `!isServer` — so `src/api/hooks/useThing.ts`
1351
+ * counted toward a denominator no client rule would ever run on, and counted
1352
+ * again on the server side. A denominator that does not match its numerator is
1353
+ * the one thing that harness exists not to produce.
1354
+ */
1355
+ declare function isClientTarget(file: QualityFile): boolean;
1356
+ /** The server-side counterpart. */
1357
+ declare function isServerTarget(file: QualityFile): boolean;
1344
1358
 
1345
1359
  /**
1346
1360
  * Worked examples for the quality catalogue, one vulnerable/safe pair per rule.
@@ -1402,9 +1416,18 @@ declare const unmeasuredQualityRules: QualityRule[];
1402
1416
  * Parallel to scanEntropy and scanDependencies: an engine, not a rule, because
1403
1417
  * most of these need more than the single file the rule contract allows.
1404
1418
  */
1405
- declare function scanQuality(files: {
1419
+ declare function scanQuality(
1420
+ /**
1421
+ * The files to scan, or a context already built for them. Building one
1422
+ * parses every file into a Babel AST and holds them all at once, so a caller
1423
+ * that needs the context for its own reasons — the measurement harness counts
1424
+ * how many files each rule class applies to — should hand it over rather than
1425
+ * pay for a second one. Taking either here, instead of a third parameter,
1426
+ * means there is no pair of arguments that can disagree.
1427
+ */
1428
+ input: {
1406
1429
  path: string;
1407
1430
  content: string;
1408
- }[], rules?: QualityRule[]): Finding[];
1431
+ }[] | QualityContext, rules?: QualityRule[]): Finding[];
1409
1432
 
1410
- 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, buildQualityContext, 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 };
1433
+ 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, buildQualityContext, 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, isClientTarget, isMethodCall, isPrivateAddress, isServerTarget, 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
@@ -10105,6 +10105,12 @@ function buildQualityContext(files) {
10105
10105
  });
10106
10106
  return { files: built, byPath: new Map(built.map((f) => [f.path, f])) };
10107
10107
  }
10108
+ function isClientTarget(file) {
10109
+ return !file.excluded && file.isClient && !file.isServer;
10110
+ }
10111
+ function isServerTarget(file) {
10112
+ return !file.excluded && file.isServer;
10113
+ }
10108
10114
  function lineAt(content, index) {
10109
10115
  let line = 1;
10110
10116
  for (let i = 0; i < index && i < content.length; i++) {
@@ -12319,6 +12325,55 @@ var unassociatedLabel = {
12319
12325
 
12320
12326
  // src/quality/rules/failed-read-empty-state.ts
12321
12327
  import _traverse4 from "@babel/traverse";
12328
+ import { getBindingIdentifiers } from "@babel/types";
12329
+
12330
+ // src/quality/rules/scope.ts
12331
+ function unwrap(node) {
12332
+ let cur = node;
12333
+ while (cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSTypeAssertion" || cur.type === "TSSatisfiesExpression") {
12334
+ cur = cur.expression;
12335
+ }
12336
+ return cur;
12337
+ }
12338
+ function calleeName3(node) {
12339
+ if (node.type !== "CallExpression" && node.type !== "OptionalCallExpression") return null;
12340
+ const c = node.callee;
12341
+ if (c.type === "Identifier") return c.name;
12342
+ if ((c.type === "MemberExpression" || c.type === "OptionalMemberExpression") && c.property.type === "Identifier") {
12343
+ return c.property.name;
12344
+ }
12345
+ return null;
12346
+ }
12347
+ function useStateBinding(at, name) {
12348
+ const binding = at.scope.getBinding(name);
12349
+ if (!binding) return void 0;
12350
+ const decl = binding.path;
12351
+ if (!decl.isVariableDeclarator()) return void 0;
12352
+ const id = decl.node.id;
12353
+ const init = decl.node.init;
12354
+ if (id.type !== "ArrayPattern") return void 0;
12355
+ if (!init || calleeName3(init) !== "useState") return void 0;
12356
+ const first = id.elements[0];
12357
+ if (!first || first.type !== "Identifier" || first.name !== name) return void 0;
12358
+ const second = id.elements[1];
12359
+ return {
12360
+ initial: init.arguments[0],
12361
+ setter: second && second.type === "Identifier" ? second.name : null,
12362
+ decl
12363
+ };
12364
+ }
12365
+ function isEmptyInitial(node) {
12366
+ if (!node) return false;
12367
+ if (node.type === "ArrayExpression") return node.elements.length === 0;
12368
+ if (node.type === "ObjectExpression") return node.properties.length === 0;
12369
+ if (node.type === "StringLiteral") return node.value === "";
12370
+ if (node.type === "TemplateLiteral") {
12371
+ return node.quasis.length === 1 && node.quasis[0].value.raw === "";
12372
+ }
12373
+ return false;
12374
+ }
12375
+
12376
+ // src/quality/rules/failed-read-empty-state.ts
12322
12377
  var traverse4 = typeof _traverse4 === "function" ? _traverse4 : _traverse4.default;
12323
12378
  var READ_ERROR_PATH_SIGNALS = ERROR_PATH_SIGNALS.filter(
12324
12379
  (re) => re.source !== /\.catch\s*\(/.source
@@ -12336,28 +12391,57 @@ function setterName(callee) {
12336
12391
  function isPropertyRead(node) {
12337
12392
  return node.type === "MemberExpression" || node.type === "OptionalMemberExpression";
12338
12393
  }
12394
+ function mentionsJsonParse(node, code) {
12395
+ return /\.json\s*\(/.test(code.slice(nodeStart(node), nodeEnd(node)));
12396
+ }
12397
+ function chainParsesBody(node, code) {
12398
+ let cur = unwrap(node);
12399
+ for (; ; ) {
12400
+ if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12401
+ const callee = unwrap(cur.callee);
12402
+ if ((callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier") {
12403
+ const method = callee.property.name;
12404
+ if (method === "json") return true;
12405
+ if (method === "then" || method === "catch") {
12406
+ const cb = cur.arguments[0];
12407
+ if (cb && (cb.type === "ArrowFunctionExpression" || cb.type === "FunctionExpression") && /\.json\s*\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)))) {
12408
+ return true;
12409
+ }
12410
+ }
12411
+ cur = unwrap(callee.object);
12412
+ continue;
12413
+ }
12414
+ cur = callee;
12415
+ continue;
12416
+ }
12417
+ if (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12418
+ cur = unwrap(cur.object);
12419
+ continue;
12420
+ }
12421
+ return false;
12422
+ }
12423
+ return false;
12424
+ }
12425
+ function boundNames(id, into) {
12426
+ for (const name of Object.keys(getBindingIdentifiers(id))) into.add(name);
12427
+ }
12339
12428
  function parsedBodyBindings(unit, code) {
12340
12429
  const names = /* @__PURE__ */ new Set();
12430
+ const record = (id, init) => {
12431
+ if (!id || !init) return;
12432
+ const awaited = unwrap(init);
12433
+ if (awaited.type !== "AwaitExpression") return;
12434
+ if (!chainParsesBody(awaited.argument, code)) return;
12435
+ boundNames(id, names);
12436
+ };
12341
12437
  unit.traverse({
12342
12438
  VariableDeclarator(decl) {
12343
- const init = decl.node.init;
12344
- if (!init || init.type !== "AwaitExpression") return;
12345
- const arg = init.argument;
12346
- if (arg.type !== "CallExpression" && arg.type !== "OptionalCallExpression") return;
12347
- const callee = arg.callee;
12348
- if (callee.type !== "MemberExpression" && callee.type !== "OptionalMemberExpression")
12349
- return;
12350
- if (callee.property.type !== "Identifier") return;
12351
- const method = callee.property.name;
12352
- let isBody = method === "json";
12353
- if (!isBody && method === "then") {
12354
- const cb = arg.arguments[0];
12355
- if (cb && (cb.type === "ArrowFunctionExpression" || cb.type === "FunctionExpression")) {
12356
- isBody = /\.json\s*\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)));
12357
- }
12358
- }
12359
- if (!isBody) return;
12360
- if (decl.node.id.type === "Identifier") names.add(decl.node.id.name);
12439
+ record(decl.node.id, decl.node.init);
12440
+ },
12441
+ // `let data; data = await res.json();` — the same read, not a declaration.
12442
+ AssignmentExpression(assign) {
12443
+ if (assign.node.operator !== "=") return;
12444
+ record(assign.node.left, assign.node.right);
12361
12445
  },
12362
12446
  // The promise-chain spelling, which is the shipped defect's own:
12363
12447
  // fetch(u).then(r => r.json()).then(data => setRows(data.rows || []))
@@ -12370,26 +12454,24 @@ function parsedBodyBindings(unit, code) {
12370
12454
  return;
12371
12455
  if (callee.property.type !== "Identifier" || callee.property.name !== "then") return;
12372
12456
  const receiver = callee.object;
12373
- if (!/\.json\s*\(/.test(code.slice(nodeStart(receiver), nodeEnd(receiver)))) return;
12457
+ if (!mentionsJsonParse(receiver, code)) return;
12374
12458
  const cb = call.node.arguments[0];
12375
12459
  if (!cb) return;
12376
12460
  if (cb.type !== "ArrowFunctionExpression" && cb.type !== "FunctionExpression") return;
12377
12461
  const param = cb.params[0];
12378
- if (param && param.type === "Identifier") names.add(param.name);
12462
+ if (param) boundNames(param, names);
12379
12463
  }
12380
12464
  });
12381
12465
  return names;
12382
12466
  }
12383
12467
  function derivesFromParsedBody(node, bodies, code) {
12384
- let cur = node;
12385
- while (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12386
- cur = cur.object;
12468
+ let cur = unwrap(node);
12469
+ while (cur && (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression")) {
12470
+ cur = unwrap(cur.object);
12387
12471
  }
12388
12472
  if (cur.type === "Identifier") return bodies.has(cur.name);
12389
- if (cur.type === "AwaitExpression" || cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12390
- return /\.json\s*\(/.test(code.slice(nodeStart(cur), nodeEnd(cur)));
12391
- }
12392
- return false;
12473
+ if (cur.type === "AwaitExpression") cur = unwrap(cur.argument);
12474
+ return chainParsesBody(cur, code);
12393
12475
  }
12394
12476
  function emptyFallbackArgument(node) {
12395
12477
  if (node.type !== "LogicalExpression") return null;
@@ -12431,7 +12513,7 @@ var failedReadEmptyState = {
12431
12513
  category: "Correctness",
12432
12514
  description: "This loader turns a failed or unexpected response into an empty list and renders it, so the page shows the same thing it would show a brand-new account: no sessions, no scans, no members. Nothing tells the user the request failed, and anything they do next \u2014 including saving \u2014 acts on data the app never actually received.",
12433
12515
  fix: "Check the response before using it: on a non-2xx, or a body without the field you expected, set an error state and render that instead of the empty state. Keep the `|| []` only for a response you have already confirmed arrived.",
12434
- precisionNotes: "Client files only, and only a unit containing the literal global `fetch(` \u2014 throwing clients (ky, wretch, ofetch) reject on non-2xx, so `|| []` after them is correct, and in-file wrappers that check `.ok` and rethrow leave their callers containing no `fetch(` at all. The empty fallback must be `|| []`/`?? []`/`{}` over a PROPERTY READ passed straight to a `setX` state setter: `setRows(rows || [])` defaults a value the component already holds, and a pure helper's argument is never rendered. The unit is the effect callback, or the outermost non-component function \u2014 the nearest function cannot see the `.catch` below it, and the whole component would let an unrelated toast.error exonerate a broken loader. Exoneration is QA002's ERROR_PATH_SIGNALS with `.catch(` REMOVED: for a write a `.catch` means the author handled it, for a read `.catch(() => setLoaded(true))` is the defect itself. The defaulted value must come from a body the unit itself parsed \u2014 `await res.json()`, a `.then` off a receiver containing `.json(`, or the inline `(await res.json()).rows` \u2014 because a unit can hold more than one read, and a nearby real fetch was found satisfying the clause for a fallback belonging to a throwing helper. Measured at 6 fires over 5 sites in 437 .tsx files with zero false positives, then across 168 third-party repositories and 16,601 files: 8 fires over 5 repositories, every one re-read in full and every one real.",
12516
+ precisionNotes: "Client files only, and only a unit containing the literal global `fetch(` \u2014 throwing clients (ky, wretch, ofetch) reject on non-2xx, so `|| []` after them is correct, and in-file wrappers that check `.ok` and rethrow leave their callers containing no `fetch(` at all. The empty fallback must be `|| []`/`?? []`/`{}` over a PROPERTY READ passed straight to a `setX` state setter: `setRows(rows || [])` defaults a value the component already holds, and a pure helper's argument is never rendered. The unit is the effect callback, or the outermost non-component function \u2014 the nearest function cannot see the `.catch` below it, and the whole component would let an unrelated toast.error exonerate a broken loader. Exoneration is QA002's ERROR_PATH_SIGNALS with `.catch(` REMOVED: for a write a `.catch` means the author handled it, for a read `.catch(() => setLoaded(true))` is the defect itself. The defaulted value must come from a body the unit itself parsed \u2014 `await res.json()`, a `.then` off a receiver containing `.json(`, or the inline `(await res.json()).rows` \u2014 because a unit can hold more than one read, and a nearby real fetch was found satisfying the clause for a fallback belonging to a throwing helper. Measured at 6 fires over 5 sites in 437 .tsx files with zero false positives, then across 168 third-party repositories: 8 fires over 5 of them, every one re-read in full and every one real. That is a precision result, not a recall one \u2014 the client files those repositories hold are about a third of them, and the parsed-body clause recognised only one spelling of the read at the time it was measured.",
12435
12517
  check(ctx) {
12436
12518
  const hits = [];
12437
12519
  for (const file of ctx.files) {
@@ -12439,16 +12521,18 @@ var failedReadEmptyState = {
12439
12521
  if (!file.isClient) continue;
12440
12522
  if (file.isServer) continue;
12441
12523
  if (/^\s*["']use server["']/m.test(file.code)) continue;
12524
+ if (!file.code.includes("fetch")) continue;
12442
12525
  const parsed = file.parsed;
12443
12526
  if (!parsed) continue;
12444
- const reported = /* @__PURE__ */ new Set();
12527
+ const examined = /* @__PURE__ */ new Set();
12445
12528
  traverse4(parsed.ast, {
12446
12529
  CallExpression(path) {
12447
12530
  if (!isFetchCallee(path.node.callee)) return;
12448
12531
  const unit = unitFor(path);
12449
12532
  if (!unit) return;
12450
12533
  const start = nodeStart(unit.node);
12451
- if (reported.has(start)) return;
12534
+ if (examined.has(start)) return;
12535
+ examined.add(start);
12452
12536
  const unitSource = file.code.slice(start, nodeEnd(unit.node));
12453
12537
  if (READ_ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;
12454
12538
  const bodies = parsedBodyBindings(unit, file.code);
@@ -12467,7 +12551,6 @@ var failedReadEmptyState = {
12467
12551
  }
12468
12552
  });
12469
12553
  if (!hit) return;
12470
- reported.add(start);
12471
12554
  const { line, setter } = hit;
12472
12555
  hits.push({
12473
12556
  file: file.path,
@@ -12484,6 +12567,20 @@ var failedReadEmptyState = {
12484
12567
  // src/quality/rules/autosave-armed-by-failed-load.ts
12485
12568
  import _traverse5 from "@babel/traverse";
12486
12569
  var traverse5 = typeof _traverse5 === "function" ? _traverse5 : _traverse5.default;
12570
+ function writerTouchesEmptyState(writers) {
12571
+ for (const writer of writers) {
12572
+ let found = false;
12573
+ writer.traverse({
12574
+ Identifier(id) {
12575
+ if (found) return;
12576
+ if (!id.isReferencedIdentifier()) return;
12577
+ if (isEmptyInitial(useStateBinding(id, id.node.name)?.initial)) found = true;
12578
+ }
12579
+ });
12580
+ if (found) return true;
12581
+ }
12582
+ return false;
12583
+ }
12487
12584
  var PERSISTENT_WRITE = /\bfetch\s*\([^)]{0,400}?method\s*:\s*["'`](?:POST|PUT|PATCH)["'`]|\blocalStorage\s*\.\s*setItem\s*\(|\bsessionStorage\s*\.\s*setItem\s*\(/is;
12488
12585
  var EMPTY_INITIAL = /\buseState\s*(?:<[^>]*>)?\s*\(\s*(?:\[\s*\]|\{\s*\}|""|''|``)\s*\)/;
12489
12586
  function calleeIdentifier(node) {
@@ -12540,32 +12637,14 @@ var autosaveArmedByFailedLoad = {
12540
12637
  category: "Correctness",
12541
12638
  description: "The flag that permits this component to write the user's state back is set in a `finally`, so a load that failed arms it exactly like one that succeeded \u2014 while the component is still holding the empty values it initialised with. Opening the page during a blip is enough to write those empties over whatever the user had saved, and the write looks like any other.",
12542
12639
  fix: "Set the arming flag on the success path only, and record the failure in its own state. The component can stay readable and interactive; it just must not write anything back until a load actually succeeds.",
12543
- precisionNotes: 'Fires on the ARMING, not on a missing guard: the shipped defect had a guard (`if (stateLoaded && !stateLoadFailed) saveState()`), and a rule keyed on unguarded writes would have missed it while reporting every correct autosave. Requires all of: a client file; a `useEffect` whose body reaches a persistent write (fetch with POST/PUT/PATCH, or localStorage/sessionStorage.setItem) either directly or through a same-file callback it names; that write gated on an identifier; a `set<Identifier>` for that same identifier called inside a `finally` block; and at least one `useState` in the file initialised to an empty literal \u2014 `[]`, `{}` or `""`, never `0`, because the empty literal is what turns "wrote too early" into "erased what was there". The join between the finally-set flag and the write\'s guard is the whole narrowing: `finally { setLoading(false) }` is everywhere and correct, and is only reportable when that same flag is what permits the write. The value matters too \u2014 a `finally` that sets the flag back to the literal `useState` started it as is a reset and cannot arm anything, which is what separates this from the hundreds of correct `finally` blocks around it. Measured across 168 third-party repositories and 16,601 files: 0 fires.',
12640
+ precisionNotes: 'Fires on the ARMING, not on a missing guard: the shipped defect had a guard (`if (stateLoaded && !stateLoadFailed) saveState()`), and a rule keyed on unguarded writes would have missed it while reporting every correct autosave. Requires all of: a client file; a `useEffect` whose body reaches a persistent write (fetch with POST/PUT/PATCH, or localStorage/sessionStorage.setItem) either directly or through a same-file callback it names; that write gated on an identifier; a `set<Identifier>` for that same identifier called inside a `finally` block; and at least one `useState` in the file initialised to an empty literal \u2014 `[]`, `{}` or `""`, never `0`, because the empty literal is what turns "wrote too early" into "erased what was there". The join between the finally-set flag and the write\'s guard is the whole narrowing: `finally { setLoading(false) }` is everywhere and correct, and is only reportable when that same flag is what permits the write. The value matters too \u2014 a `finally` that sets the flag back to the literal `useState` started it as is a reset and cannot arm anything, which is what separates this from the hundreds of correct `finally` blocks around it. Measured across 168 third-party repositories: 0 fires. The denominator is the client files among them, not the whole corpus.',
12544
12641
  check(ctx) {
12545
12642
  const hits = [];
12546
12643
  for (const file of ctx.files) {
12547
- if (file.excluded) continue;
12548
- if (!file.isClient) continue;
12549
- if (file.isServer) continue;
12644
+ if (!isClientTarget(file)) continue;
12550
12645
  const parsed = file.parsed;
12551
12646
  if (!parsed) continue;
12552
12647
  if (!EMPTY_INITIAL.test(file.code)) continue;
12553
- const initialValues = /* @__PURE__ */ new Map();
12554
- traverse5(parsed.ast, {
12555
- VariableDeclarator(decl) {
12556
- const id = decl.node.id;
12557
- const init = decl.node.init;
12558
- if (!id || id.type !== "ArrayPattern") return;
12559
- if (!init || init.type !== "CallExpression") return;
12560
- const callee = init.callee;
12561
- const name = callee.type === "Identifier" ? callee.name : callee.type === "MemberExpression" && callee.property.type === "Identifier" ? callee.property.name : null;
12562
- if (name !== "useState") return;
12563
- const first = id.elements[0];
12564
- const arg = init.arguments[0];
12565
- if (!first || first.type !== "Identifier" || !arg) return;
12566
- initialValues.set(first.name, arg);
12567
- }
12568
- });
12569
12648
  const armedInFinally = /* @__PURE__ */ new Map();
12570
12649
  traverse5(parsed.ast, {
12571
12650
  TryStatement(path) {
@@ -12577,29 +12656,32 @@ var autosaveArmedByFailedLoad = {
12577
12656
  if (!name) return;
12578
12657
  const state = stateFromSetter(name);
12579
12658
  if (!state) return;
12580
- if (setsBackToInitial(call.node, initialValues.get(state))) return;
12659
+ if (setsBackToInitial(call.node, useStateBinding(call, state)?.initial)) return;
12581
12660
  armedInFinally.set(state, nodeStart(call.node));
12582
12661
  }
12583
12662
  });
12584
12663
  }
12585
12664
  });
12586
12665
  if (armedInFinally.size === 0) continue;
12587
- const writingFunctions = /* @__PURE__ */ new Set();
12666
+ const writingFunctions = /* @__PURE__ */ new Map();
12588
12667
  traverse5(parsed.ast, {
12589
12668
  Function(path) {
12590
12669
  const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
12591
12670
  if (!PERSISTENT_WRITE.test(src)) return;
12671
+ const deps = [];
12592
12672
  let owner = path.parentPath;
12593
12673
  for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {
12594
12674
  const node = owner.node;
12595
12675
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
12596
- writingFunctions.add(node.id.name);
12676
+ writingFunctions.set(node.id.name, [path, ...deps]);
12597
12677
  break;
12598
12678
  }
12599
12679
  if (node.type !== "CallExpression") break;
12680
+ const depArg = owner.get("arguments.1");
12681
+ if (depArg && depArg.node) deps.push(depArg);
12600
12682
  }
12601
12683
  const n = path.node;
12602
- if (n.id && n.id.name) writingFunctions.add(n.id.name);
12684
+ if (n.id && n.id.name) writingFunctions.set(n.id.name, [path, ...deps]);
12603
12685
  }
12604
12686
  });
12605
12687
  const reported = /* @__PURE__ */ new Set();
@@ -12611,8 +12693,15 @@ var autosaveArmedByFailedLoad = {
12611
12693
  const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));
12612
12694
  const names = identifiersIn(cb);
12613
12695
  const writesDirectly = PERSISTENT_WRITE.test(body);
12614
- const writesViaCallback = [...writingFunctions].some((fn) => names.has(fn));
12615
- if (!writesDirectly && !writesViaCallback) return;
12696
+ const calledWriters = [...writingFunctions.entries()].filter(([fn]) => names.has(fn)).flatMap(([, paths]) => paths);
12697
+ if (!writesDirectly && calledWriters.length === 0) return;
12698
+ const effectDeps = path.get("arguments.1");
12699
+ const writers = [
12700
+ ...writesDirectly ? [cb] : [],
12701
+ ...calledWriters,
12702
+ ...effectDeps && effectDeps.node ? [effectDeps] : []
12703
+ ];
12704
+ if (!writerTouchesEmptyState(writers)) return;
12616
12705
  for (const [state, armLine] of armedInFinally) {
12617
12706
  if (!names.has(state)) continue;
12618
12707
  if (reported.has(state)) continue;
@@ -12639,7 +12728,7 @@ var DURABLE_WRITE = /\b(?:INSERT\s+INTO\b|UPDATE\s+\w+\s+SET\b|DELETE\s+FROM\b)|
12639
12728
  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;
12640
12729
  var BOOKKEEPING = /analytics|telemetry|track|metric|event|beacon|log|audit|ping/i;
12641
12730
  var DIRECT_ENV_TEST = /\bprocess\s*\.\s*env\b|\bDeno\s*\.\s*env\s*\.\s*get\s*\(/;
12642
- function calleeName3(node) {
12731
+ function calleeName4(node) {
12643
12732
  if (node.type !== "CallExpression") return null;
12644
12733
  const c = node.callee;
12645
12734
  if (c.type === "Identifier") return c.name;
@@ -12661,11 +12750,11 @@ function successPayloadShape(ret, source, offset) {
12661
12750
  if (!arg || arg.type !== "CallExpression") return null;
12662
12751
  const text = source.slice(nodeStart(ret) - offset, nodeEnd(ret) - offset);
12663
12752
  if (/status\s*:\s*[45]\d\d|,\s*\{\s*status\s*:\s*[45]\d\d/.test(text)) return null;
12664
- const name = calleeName3(arg);
12753
+ const name = calleeName4(arg);
12665
12754
  if (name !== "json" && name !== "Response" && name !== "NextResponse") return null;
12666
12755
  const first = arg.arguments[0];
12667
12756
  if (!first) return null;
12668
- if (first.type === "CallExpression" && calleeName3(first) === "stringify") {
12757
+ if (first.type === "CallExpression" && calleeName4(first) === "stringify") {
12669
12758
  return keyShape(first.arguments[0]);
12670
12759
  }
12671
12760
  return keyShape(first);
@@ -12841,13 +12930,11 @@ var staleResponseWins = {
12841
12930
  category: "Correctness",
12842
12931
  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.",
12843
12932
  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.",
12844
- 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.',
12933
+ 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: three distinct defects now, across two codebases \u2014 two in this product, and one found across 168 third-party repositories, verified real, with no false positives beside it. Precise on everything it has been run against; still rare. Shipped at medium for that reason.',
12845
12934
  check(ctx) {
12846
12935
  const hits = [];
12847
12936
  for (const file of ctx.files) {
12848
- if (file.excluded) continue;
12849
- if (!file.isClient) continue;
12850
- if (file.isServer) continue;
12937
+ if (!isClientTarget(file)) continue;
12851
12938
  const parsed = file.parsed;
12852
12939
  if (!parsed) continue;
12853
12940
  traverse7(parsed.ast, {
@@ -12892,7 +12979,10 @@ var staleResponseWins = {
12892
12979
  for (const ident2 of interpolated) {
12893
12980
  if (!derivesFromDep(ident2, deps, cb, file.code)) continue;
12894
12981
  if (new RegExp(`\\b${ident2}\\b`).test(afterCall)) continue;
12895
- if (![...deps].some((d) => userDriven(d, file.code))) continue;
12982
+ const driving = [...deps].filter(
12983
+ (d) => derivesFromDep(ident2, /* @__PURE__ */ new Set([d]), cb, file.code)
12984
+ );
12985
+ if (!driving.some((d) => userDriven(d, cb))) continue;
12896
12986
  hit = { line: lineAt(file.content, nodeStart(inner.node)), ident: ident2 };
12897
12987
  return;
12898
12988
  }
@@ -12911,10 +13001,26 @@ var staleResponseWins = {
12911
13001
  return hits;
12912
13002
  }
12913
13003
  };
12914
- function userDriven(dep, code) {
12915
- const setter = `set${dep.charAt(0).toUpperCase()}${dep.slice(1)}`;
12916
- if (!new RegExp(`\\[\\s*${dep}\\s*,\\s*${setter}\\s*\\]\\s*=\\s*useState`).test(code)) return false;
12917
- return new RegExp(`on(?:Change|Click|Input|Select)\\s*=\\s*\\{[^}]{0,200}\\b${setter}\\b`, "s").test(code);
13004
+ function userDriven(dep, at) {
13005
+ const binding = useStateBinding(at, dep);
13006
+ const setter = binding?.setter;
13007
+ if (!setter) return false;
13008
+ const owner = binding.decl.getFunctionParent() ?? binding.decl.scope.path;
13009
+ let wired = false;
13010
+ owner.traverse({
13011
+ JSXAttribute(attr) {
13012
+ if (wired) return;
13013
+ const name = attr.node.name;
13014
+ if (name.type !== "JSXIdentifier") return;
13015
+ if (!/^on(?:Change|Click|Input|Select)$/.test(name.name)) return;
13016
+ attr.traverse({
13017
+ Identifier(id) {
13018
+ if (id.node.name === setter) wired = true;
13019
+ }
13020
+ });
13021
+ }
13022
+ });
13023
+ return wired;
12918
13024
  }
12919
13025
 
12920
13026
  // src/quality/rules/lost-update-counter.ts
@@ -13435,8 +13541,8 @@ var qualityRules = [
13435
13541
  var unmeasuredQualityRules = [
13436
13542
  lostUpdateCounter
13437
13543
  ];
13438
- function scanQuality(files, rules = qualityRules) {
13439
- const ctx = buildQualityContext(files);
13544
+ function scanQuality(input, rules = qualityRules) {
13545
+ const ctx = Array.isArray(input) ? buildQualityContext(input) : input;
13440
13546
  const findings = [];
13441
13547
  for (const rule of rules) {
13442
13548
  let hits;
@@ -13620,8 +13726,10 @@ export {
13620
13726
  insecureWebSocket,
13621
13727
  ipcPathTraversal,
13622
13728
  isCalleeNamed,
13729
+ isClientTarget,
13623
13730
  isMethodCall,
13624
13731
  isPrivateAddress,
13732
+ isServerTarget,
13625
13733
  isVendoredFinding,
13626
13734
  isVendoredPath,
13627
13735
  javaDeserialization,