xploitscan-shared-rules 1.35.1 → 1.35.2

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 {
@@ -1405,6 +1406,15 @@ declare const unmeasuredQualityRules: QualityRule[];
1405
1406
  declare function scanQuality(files: {
1406
1407
  path: string;
1407
1408
  content: string;
1408
- }[], rules?: QualityRule[]): Finding[];
1409
+ }[], rules?: QualityRule[],
1410
+ /**
1411
+ * A context already built for these files. Building one parses every file
1412
+ * into a Babel AST and holds them all at once, so a caller that needs the
1413
+ * context for its own reasons — the measurement harness counts how many
1414
+ * files each rule class applies to — would otherwise pay for two of them
1415
+ * side by side. The AST cache is an LRU of 256 and the harness runs 1,200
1416
+ * files per repository, so nothing is reused between the two passes.
1417
+ */
1418
+ prebuilt?: QualityContext): Finding[];
1409
1419
 
1410
1420
  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 };
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 {
@@ -1405,6 +1406,15 @@ declare const unmeasuredQualityRules: QualityRule[];
1405
1406
  declare function scanQuality(files: {
1406
1407
  path: string;
1407
1408
  content: string;
1408
- }[], rules?: QualityRule[]): Finding[];
1409
+ }[], rules?: QualityRule[],
1410
+ /**
1411
+ * A context already built for these files. Building one parses every file
1412
+ * into a Babel AST and holds them all at once, so a caller that needs the
1413
+ * context for its own reasons — the measurement harness counts how many
1414
+ * files each rule class applies to — would otherwise pay for two of them
1415
+ * side by side. The AST cache is an LRU of 256 and the harness runs 1,200
1416
+ * files per repository, so nothing is reused between the two passes.
1417
+ */
1418
+ prebuilt?: QualityContext): Finding[];
1409
1419
 
1410
1420
  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 };
package/dist/index.js CHANGED
@@ -12336,28 +12336,70 @@ function setterName(callee) {
12336
12336
  function isPropertyRead(node) {
12337
12337
  return node.type === "MemberExpression" || node.type === "OptionalMemberExpression";
12338
12338
  }
12339
+ function unwrap(node) {
12340
+ let cur = node;
12341
+ while (cur && (cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSTypeAssertion" || cur.type === "TSSatisfiesExpression" || cur.type === "ParenthesizedExpression")) {
12342
+ cur = cur.expression;
12343
+ }
12344
+ return cur;
12345
+ }
12346
+ function chainParsesBody(node, code) {
12347
+ let cur = unwrap(node);
12348
+ while (cur) {
12349
+ if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12350
+ const callee = unwrap(cur.callee);
12351
+ if (callee && (callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier") {
12352
+ const method = callee.property.name;
12353
+ if (method === "json") return true;
12354
+ if (method === "then" || method === "catch") {
12355
+ const cb = cur.arguments[0];
12356
+ if (cb && (cb.type === "ArrowFunctionExpression" || cb.type === "FunctionExpression") && /\.json\s*\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)))) {
12357
+ return true;
12358
+ }
12359
+ }
12360
+ cur = unwrap(callee.object);
12361
+ continue;
12362
+ }
12363
+ cur = unwrap(cur.callee);
12364
+ continue;
12365
+ }
12366
+ if (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12367
+ cur = unwrap(cur.object);
12368
+ continue;
12369
+ }
12370
+ return false;
12371
+ }
12372
+ return false;
12373
+ }
12374
+ function boundNames(id, into) {
12375
+ if (id.type === "Identifier") {
12376
+ into.add(id.name);
12377
+ return;
12378
+ }
12379
+ if (id.type === "ObjectPattern") {
12380
+ for (const prop of id.properties) {
12381
+ if (prop.type === "ObjectProperty") boundNames(prop.value, into);
12382
+ else if (prop.type === "RestElement") boundNames(prop.argument, into);
12383
+ }
12384
+ }
12385
+ }
12339
12386
  function parsedBodyBindings(unit, code) {
12340
12387
  const names = /* @__PURE__ */ new Set();
12388
+ const record = (id, init) => {
12389
+ if (!id) return;
12390
+ const awaited = unwrap(init);
12391
+ if (!awaited || awaited.type !== "AwaitExpression") return;
12392
+ if (!chainParsesBody(awaited.argument, code)) return;
12393
+ boundNames(id, names);
12394
+ };
12341
12395
  unit.traverse({
12342
12396
  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);
12397
+ record(decl.node.id, decl.node.init);
12398
+ },
12399
+ // `let data; data = await res.json();` — the same read, not a declaration.
12400
+ AssignmentExpression(assign) {
12401
+ if (assign.node.operator !== "=") return;
12402
+ record(assign.node.left, assign.node.right);
12361
12403
  },
12362
12404
  // The promise-chain spelling, which is the shipped defect's own:
12363
12405
  // fetch(u).then(r => r.json()).then(data => setRows(data.rows || []))
@@ -12375,19 +12417,21 @@ function parsedBodyBindings(unit, code) {
12375
12417
  if (!cb) return;
12376
12418
  if (cb.type !== "ArrowFunctionExpression" && cb.type !== "FunctionExpression") return;
12377
12419
  const param = cb.params[0];
12378
- if (param && param.type === "Identifier") names.add(param.name);
12420
+ if (param) boundNames(param, names);
12379
12421
  }
12380
12422
  });
12381
12423
  return names;
12382
12424
  }
12383
12425
  function derivesFromParsedBody(node, bodies, code) {
12384
- let cur = node;
12385
- while (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12386
- cur = cur.object;
12426
+ let cur = unwrap(node);
12427
+ while (cur && (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression")) {
12428
+ cur = unwrap(cur.object);
12387
12429
  }
12430
+ if (!cur) return false;
12388
12431
  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)));
12432
+ if (cur.type === "AwaitExpression") return chainParsesBody(cur.argument, code);
12433
+ if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12434
+ return chainParsesBody(cur, code);
12391
12435
  }
12392
12436
  return false;
12393
12437
  }
@@ -12431,7 +12475,7 @@ var failedReadEmptyState = {
12431
12475
  category: "Correctness",
12432
12476
  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
12477
  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.",
12478
+ 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
12479
  check(ctx) {
12436
12480
  const hits = [];
12437
12481
  for (const file of ctx.files) {
@@ -12441,14 +12485,15 @@ var failedReadEmptyState = {
12441
12485
  if (/^\s*["']use server["']/m.test(file.code)) continue;
12442
12486
  const parsed = file.parsed;
12443
12487
  if (!parsed) continue;
12444
- const reported = /* @__PURE__ */ new Set();
12488
+ const examined = /* @__PURE__ */ new Set();
12445
12489
  traverse4(parsed.ast, {
12446
12490
  CallExpression(path) {
12447
12491
  if (!isFetchCallee(path.node.callee)) return;
12448
12492
  const unit = unitFor(path);
12449
12493
  if (!unit) return;
12450
12494
  const start = nodeStart(unit.node);
12451
- if (reported.has(start)) return;
12495
+ if (examined.has(start)) return;
12496
+ examined.add(start);
12452
12497
  const unitSource = file.code.slice(start, nodeEnd(unit.node));
12453
12498
  if (READ_ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;
12454
12499
  const bodies = parsedBodyBindings(unit, file.code);
@@ -12467,7 +12512,6 @@ var failedReadEmptyState = {
12467
12512
  }
12468
12513
  });
12469
12514
  if (!hit) return;
12470
- reported.add(start);
12471
12515
  const { line, setter } = hit;
12472
12516
  hits.push({
12473
12517
  file: file.path,
@@ -12497,6 +12541,22 @@ function isEffectCall2(node) {
12497
12541
  const name = calleeIdentifier(node);
12498
12542
  return name === "useEffect" || name === "useLayoutEffect";
12499
12543
  }
12544
+ function initialFor(call, state) {
12545
+ const binding = call.scope.getBinding(state);
12546
+ if (!binding) return void 0;
12547
+ const decl = binding.path;
12548
+ if (!decl.isVariableDeclarator()) return void 0;
12549
+ const id = decl.node.id;
12550
+ const init = decl.node.init;
12551
+ if (!id || id.type !== "ArrayPattern") return void 0;
12552
+ if (!init || init.type !== "CallExpression") return void 0;
12553
+ const callee = init.callee;
12554
+ const name = callee.type === "Identifier" ? callee.name : callee.type === "MemberExpression" && callee.property.type === "Identifier" ? callee.property.name : null;
12555
+ if (name !== "useState") return void 0;
12556
+ const first = id.elements[0];
12557
+ if (!first || first.type !== "Identifier" || first.name !== state) return void 0;
12558
+ return init.arguments[0];
12559
+ }
12500
12560
  function sameLiteral(a, b) {
12501
12561
  if (!a || !b || a.type !== b.type) return false;
12502
12562
  switch (a.type) {
@@ -12540,7 +12600,7 @@ var autosaveArmedByFailedLoad = {
12540
12600
  category: "Correctness",
12541
12601
  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
12602
  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.',
12603
+ 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
12604
  check(ctx) {
12545
12605
  const hits = [];
12546
12606
  for (const file of ctx.files) {
@@ -12550,22 +12610,6 @@ var autosaveArmedByFailedLoad = {
12550
12610
  const parsed = file.parsed;
12551
12611
  if (!parsed) continue;
12552
12612
  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
12613
  const armedInFinally = /* @__PURE__ */ new Map();
12570
12614
  traverse5(parsed.ast, {
12571
12615
  TryStatement(path) {
@@ -12577,7 +12621,7 @@ var autosaveArmedByFailedLoad = {
12577
12621
  if (!name) return;
12578
12622
  const state = stateFromSetter(name);
12579
12623
  if (!state) return;
12580
- if (setsBackToInitial(call.node, initialValues.get(state))) return;
12624
+ if (setsBackToInitial(call.node, initialFor(call, state))) return;
12581
12625
  armedInFinally.set(state, nodeStart(call.node));
12582
12626
  }
12583
12627
  });
@@ -12841,7 +12885,7 @@ var staleResponseWins = {
12841
12885
  category: "Correctness",
12842
12886
  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
12887
  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.',
12888
+ 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
12889
  check(ctx) {
12846
12890
  const hits = [];
12847
12891
  for (const file of ctx.files) {
@@ -13435,8 +13479,8 @@ var qualityRules = [
13435
13479
  var unmeasuredQualityRules = [
13436
13480
  lostUpdateCounter
13437
13481
  ];
13438
- function scanQuality(files, rules = qualityRules) {
13439
- const ctx = buildQualityContext(files);
13482
+ function scanQuality(files, rules = qualityRules, prebuilt) {
13483
+ const ctx = prebuilt ?? buildQualityContext(files);
13440
13484
  const findings = [];
13441
13485
  for (const rule of rules) {
13442
13486
  let hits;