xploitscan-shared-rules 1.18.0 → 1.20.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
@@ -34,6 +34,26 @@ interface Finding {
34
34
  * itself by arriving with the flag already set.
35
35
  */
36
36
  vendored?: boolean;
37
+ /**
38
+ * The URL that reaches this finding's file, when one does.
39
+ *
40
+ * Severity is not a property of a line of code, it is a property of who can
41
+ * reach it: a hardcoded secret in `app/api/webhooks/stripe/route.ts` is
42
+ * reachable by anyone who can send a POST, while the same secret in a build
43
+ * script is not reachable at all.
44
+ *
45
+ * Advisory label for renderers, on the same terms as `vendored` above —
46
+ * `calculateGrade` never reads it, so a finding cannot raise or lower its own
47
+ * score by arriving with this set. It is populated from the file's declared
48
+ * route only; a helper imported BY a handler is reachable too, but proving
49
+ * that needs an import graph, and guessing would attach a confident wrong URL
50
+ * to a real finding.
51
+ */
52
+ route?: {
53
+ path: string;
54
+ kind: "page" | "api";
55
+ framework: string;
56
+ };
37
57
  }
38
58
  interface RuleMatch {
39
59
  rule: string;
@@ -324,17 +344,6 @@ declare function detectFramework(files: {
324
344
  content: string;
325
345
  }[]): DetectedFramework[];
326
346
  type VibePlatform = "lovable" | "bolt" | "replit" | "cursor" | "v0" | "claude-code";
327
- /**
328
- * Detect the AI coding platform / scaffold behind a project from tell-tale
329
- * files, dependencies, and generated-comment headers.
330
- *
331
- * Deliberately high-precision: signals are mostly exact config-file paths
332
- * (`.replit`, `.cursorrules`, `.bolt/`) plus a couple of unambiguous content
333
- * markers (`lovable-tagger`, `bolt.new`, `v0.dev`). A plain framework project
334
- * with none of these returns `[]` — we never guess a platform, because a wrong
335
- * "Detected: X" label reads worse than none. Returns every platform detected
336
- * (a Lovable app opened in Cursor legitimately reports both).
337
- */
338
347
  declare function detectPlatform(files: {
339
348
  path: string;
340
349
  content: string;
@@ -486,6 +495,8 @@ declare const graphqlCSRFDisabled: CustomRule;
486
495
  declare const llmOutputToSink: CustomRule;
487
496
  declare const secretInLLMPrompt: CustomRule;
488
497
  declare const webhookMissingIdempotency: CustomRule;
498
+ declare const entitlementFromWebStorage: CustomRule;
499
+ declare const accountStateFromWebStorage: CustomRule;
489
500
  declare const middlewareMatcherExcludesApi: CustomRule;
490
501
  declare const hardcodedCreditCard: CustomRule;
491
502
  declare const hardcodedSSN: CustomRule;
@@ -533,9 +544,9 @@ declare function runCustomRules(content: string, filePath: string, disabledRules
533
544
  /** Rules any caller gets, including anonymous and free-tier CLI users. */
534
545
  declare const FREE_RULE_COUNT = 30;
535
546
  /** Rules gated behind a paid plan and served from the API, never bundled. */
536
- declare const PRO_RULE_COUNT = 182;
547
+ declare const PRO_RULE_COUNT = 184;
537
548
  /** The full catalog. FREE_RULE_COUNT + PRO_RULE_COUNT, asserted in the test. */
538
- declare const TOTAL_RULE_COUNT = 212;
549
+ declare const TOTAL_RULE_COUNT = 214;
539
550
 
540
551
  interface FilteredFinding {
541
552
  finding: Finding;
@@ -608,6 +619,83 @@ declare function scanEntropy(files: {
608
619
  content: string;
609
620
  }[]): Finding[];
610
621
 
622
+ /**
623
+ * Route-table extraction — what URL, if any, reaches a given source file.
624
+ *
625
+ * WHY A SCANNER WANTS THIS. Severity is not a property of a line of code, it is
626
+ * a property of who can reach it. A hardcoded secret in
627
+ * `src/app/api/webhooks/stripe/route.ts` is reachable by anyone who can send a
628
+ * POST; the same secret in a build script is not reachable at all. Nothing in
629
+ * the finding itself carries that distinction, and a scanner that only reads
630
+ * files cannot invent it.
631
+ *
632
+ * Attaching a route to a finding turns "hardcoded secret in a file you have to
633
+ * go look up" into "hardcoded secret reachable at POST /api/webhooks/stripe".
634
+ *
635
+ * EVERY GATE BELOW EXISTS BECAUSE IT FIRED. Measured against real repositories:
636
+ *
637
+ * - `src/pages/*.tsx` is NOT Next routing in a Vite app. Lovable, Bolt and
638
+ * Base44 ship a plain `src/pages/` component folder; matching it invented
639
+ * 38 phantom routes in one repo, with case-duplicate pairs (/about AND
640
+ * /About) and entries like /Index and /NotFound that do not exist.
641
+ * - A config file is not a dependency. That same repo carries a stray unused
642
+ * `next.config.js` with no `next` in package.json; trusting the file
643
+ * re-invented all 38.
644
+ * - `app.get("/download", ...)` inside THIS repo's own rule-override examples
645
+ * produced phantom Express routes in a package with no express dependency.
646
+ * A scanner scanning a scanner finds "routes" in its documentation samples.
647
+ * - The homepage went missing from every Next project using `src/`: the
648
+ * pattern required `app/<seg>/page.tsx` or a TOP-LEVEL `app/page.tsx`, so
649
+ * nested `src/app/page.tsx` matched neither and "/" — the single most
650
+ * important route in any app — was silently absent.
651
+ *
652
+ * A phantom route is worse than a missing one: it attaches a confident, wrong
653
+ * URL to a real finding. Hence every framework's conventions are gated on that
654
+ * framework actually being a declared dependency.
655
+ *
656
+ * Accuracy at the time of writing, against hand-counted ground truth:
657
+ * Next App Router (this repo's web package) 135/135, "/" included
658
+ * React Router (a Lovable app) 40/40, 0 missed, 0 extra
659
+ * TanStack Start (a Lovable app) 6/6
660
+ * Flask (a Python dashboard) 53/53
661
+ */
662
+ type RouteFramework = "next-app" | "next-pages" | "react-router" | "tanstack-router" | "flask-fastapi" | "express";
663
+ interface AppRoute {
664
+ /** URL path, e.g. "/api/webhooks/stripe". */
665
+ path: string;
666
+ /** `api` is a data endpoint; `page` renders a document. */
667
+ kind: "page" | "api";
668
+ /** Contains a parameter segment, so it cannot be fetched without a value. */
669
+ dynamic: boolean;
670
+ framework: RouteFramework;
671
+ /** Repo-relative file that declares it. */
672
+ source: string;
673
+ }
674
+ interface RouteTable {
675
+ frameworks: RouteFramework[];
676
+ routes: AppRoute[];
677
+ }
678
+ interface SourceFile {
679
+ path: string;
680
+ content: string;
681
+ }
682
+ /**
683
+ * Extract every route the given files declare.
684
+ *
685
+ * Pure: takes file contents, touches no filesystem, so it runs identically in
686
+ * the CLI, the API and a test.
687
+ */
688
+ declare function extractRoutes(files: SourceFile[]): RouteTable;
689
+ /**
690
+ * The route a given file is reachable at, if any.
691
+ *
692
+ * Matches on the declaring file only. A helper imported BY a route handler is
693
+ * reachable too, but proving that needs an import graph — claiming it from a
694
+ * filename match would attach confident, wrong URLs to real findings, which is
695
+ * the failure mode every gate above exists to prevent.
696
+ */
697
+ declare function routeForFile(table: RouteTable, filePath: string): AppRoute | undefined;
698
+
611
699
  /**
612
700
  * URL recon — what can be learned about a deployed app from what it already
613
701
  * serves the public.
@@ -837,4 +925,4 @@ declare function getObjectProperty(node: ObjectExpression, key: string): {
837
925
  /** Does this CallExpression spread an expression `matcher` returns true for? */
838
926
  declare function callSpreads(call: CallExpression, matcher: (node: Node) => boolean): boolean;
839
927
 
840
- export { type AIFilterResult, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, RULE_IMPACTS, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
928
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, entitlementFromWebStorage, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
package/dist/index.d.ts CHANGED
@@ -34,6 +34,26 @@ interface Finding {
34
34
  * itself by arriving with the flag already set.
35
35
  */
36
36
  vendored?: boolean;
37
+ /**
38
+ * The URL that reaches this finding's file, when one does.
39
+ *
40
+ * Severity is not a property of a line of code, it is a property of who can
41
+ * reach it: a hardcoded secret in `app/api/webhooks/stripe/route.ts` is
42
+ * reachable by anyone who can send a POST, while the same secret in a build
43
+ * script is not reachable at all.
44
+ *
45
+ * Advisory label for renderers, on the same terms as `vendored` above —
46
+ * `calculateGrade` never reads it, so a finding cannot raise or lower its own
47
+ * score by arriving with this set. It is populated from the file's declared
48
+ * route only; a helper imported BY a handler is reachable too, but proving
49
+ * that needs an import graph, and guessing would attach a confident wrong URL
50
+ * to a real finding.
51
+ */
52
+ route?: {
53
+ path: string;
54
+ kind: "page" | "api";
55
+ framework: string;
56
+ };
37
57
  }
38
58
  interface RuleMatch {
39
59
  rule: string;
@@ -324,17 +344,6 @@ declare function detectFramework(files: {
324
344
  content: string;
325
345
  }[]): DetectedFramework[];
326
346
  type VibePlatform = "lovable" | "bolt" | "replit" | "cursor" | "v0" | "claude-code";
327
- /**
328
- * Detect the AI coding platform / scaffold behind a project from tell-tale
329
- * files, dependencies, and generated-comment headers.
330
- *
331
- * Deliberately high-precision: signals are mostly exact config-file paths
332
- * (`.replit`, `.cursorrules`, `.bolt/`) plus a couple of unambiguous content
333
- * markers (`lovable-tagger`, `bolt.new`, `v0.dev`). A plain framework project
334
- * with none of these returns `[]` — we never guess a platform, because a wrong
335
- * "Detected: X" label reads worse than none. Returns every platform detected
336
- * (a Lovable app opened in Cursor legitimately reports both).
337
- */
338
347
  declare function detectPlatform(files: {
339
348
  path: string;
340
349
  content: string;
@@ -486,6 +495,8 @@ declare const graphqlCSRFDisabled: CustomRule;
486
495
  declare const llmOutputToSink: CustomRule;
487
496
  declare const secretInLLMPrompt: CustomRule;
488
497
  declare const webhookMissingIdempotency: CustomRule;
498
+ declare const entitlementFromWebStorage: CustomRule;
499
+ declare const accountStateFromWebStorage: CustomRule;
489
500
  declare const middlewareMatcherExcludesApi: CustomRule;
490
501
  declare const hardcodedCreditCard: CustomRule;
491
502
  declare const hardcodedSSN: CustomRule;
@@ -533,9 +544,9 @@ declare function runCustomRules(content: string, filePath: string, disabledRules
533
544
  /** Rules any caller gets, including anonymous and free-tier CLI users. */
534
545
  declare const FREE_RULE_COUNT = 30;
535
546
  /** Rules gated behind a paid plan and served from the API, never bundled. */
536
- declare const PRO_RULE_COUNT = 182;
547
+ declare const PRO_RULE_COUNT = 184;
537
548
  /** The full catalog. FREE_RULE_COUNT + PRO_RULE_COUNT, asserted in the test. */
538
- declare const TOTAL_RULE_COUNT = 212;
549
+ declare const TOTAL_RULE_COUNT = 214;
539
550
 
540
551
  interface FilteredFinding {
541
552
  finding: Finding;
@@ -608,6 +619,83 @@ declare function scanEntropy(files: {
608
619
  content: string;
609
620
  }[]): Finding[];
610
621
 
622
+ /**
623
+ * Route-table extraction — what URL, if any, reaches a given source file.
624
+ *
625
+ * WHY A SCANNER WANTS THIS. Severity is not a property of a line of code, it is
626
+ * a property of who can reach it. A hardcoded secret in
627
+ * `src/app/api/webhooks/stripe/route.ts` is reachable by anyone who can send a
628
+ * POST; the same secret in a build script is not reachable at all. Nothing in
629
+ * the finding itself carries that distinction, and a scanner that only reads
630
+ * files cannot invent it.
631
+ *
632
+ * Attaching a route to a finding turns "hardcoded secret in a file you have to
633
+ * go look up" into "hardcoded secret reachable at POST /api/webhooks/stripe".
634
+ *
635
+ * EVERY GATE BELOW EXISTS BECAUSE IT FIRED. Measured against real repositories:
636
+ *
637
+ * - `src/pages/*.tsx` is NOT Next routing in a Vite app. Lovable, Bolt and
638
+ * Base44 ship a plain `src/pages/` component folder; matching it invented
639
+ * 38 phantom routes in one repo, with case-duplicate pairs (/about AND
640
+ * /About) and entries like /Index and /NotFound that do not exist.
641
+ * - A config file is not a dependency. That same repo carries a stray unused
642
+ * `next.config.js` with no `next` in package.json; trusting the file
643
+ * re-invented all 38.
644
+ * - `app.get("/download", ...)` inside THIS repo's own rule-override examples
645
+ * produced phantom Express routes in a package with no express dependency.
646
+ * A scanner scanning a scanner finds "routes" in its documentation samples.
647
+ * - The homepage went missing from every Next project using `src/`: the
648
+ * pattern required `app/<seg>/page.tsx` or a TOP-LEVEL `app/page.tsx`, so
649
+ * nested `src/app/page.tsx` matched neither and "/" — the single most
650
+ * important route in any app — was silently absent.
651
+ *
652
+ * A phantom route is worse than a missing one: it attaches a confident, wrong
653
+ * URL to a real finding. Hence every framework's conventions are gated on that
654
+ * framework actually being a declared dependency.
655
+ *
656
+ * Accuracy at the time of writing, against hand-counted ground truth:
657
+ * Next App Router (this repo's web package) 135/135, "/" included
658
+ * React Router (a Lovable app) 40/40, 0 missed, 0 extra
659
+ * TanStack Start (a Lovable app) 6/6
660
+ * Flask (a Python dashboard) 53/53
661
+ */
662
+ type RouteFramework = "next-app" | "next-pages" | "react-router" | "tanstack-router" | "flask-fastapi" | "express";
663
+ interface AppRoute {
664
+ /** URL path, e.g. "/api/webhooks/stripe". */
665
+ path: string;
666
+ /** `api` is a data endpoint; `page` renders a document. */
667
+ kind: "page" | "api";
668
+ /** Contains a parameter segment, so it cannot be fetched without a value. */
669
+ dynamic: boolean;
670
+ framework: RouteFramework;
671
+ /** Repo-relative file that declares it. */
672
+ source: string;
673
+ }
674
+ interface RouteTable {
675
+ frameworks: RouteFramework[];
676
+ routes: AppRoute[];
677
+ }
678
+ interface SourceFile {
679
+ path: string;
680
+ content: string;
681
+ }
682
+ /**
683
+ * Extract every route the given files declare.
684
+ *
685
+ * Pure: takes file contents, touches no filesystem, so it runs identically in
686
+ * the CLI, the API and a test.
687
+ */
688
+ declare function extractRoutes(files: SourceFile[]): RouteTable;
689
+ /**
690
+ * The route a given file is reachable at, if any.
691
+ *
692
+ * Matches on the declaring file only. A helper imported BY a route handler is
693
+ * reachable too, but proving that needs an import graph — claiming it from a
694
+ * filename match would attach confident, wrong URLs to real findings, which is
695
+ * the failure mode every gate above exists to prevent.
696
+ */
697
+ declare function routeForFile(table: RouteTable, filePath: string): AppRoute | undefined;
698
+
611
699
  /**
612
700
  * URL recon — what can be learned about a deployed app from what it already
613
701
  * serves the public.
@@ -837,4 +925,4 @@ declare function getObjectProperty(node: ObjectExpression, key: string): {
837
925
  /** Does this CallExpression spread an expression `matcher` returns true for? */
838
926
  declare function callSpreads(call: CallExpression, matcher: (node: Node) => boolean): boolean;
839
927
 
840
- export { type AIFilterResult, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, RULE_IMPACTS, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
928
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, type Confidence, type CustomRule, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, type ParsedFile, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, accountStateFromWebStorage, allCustomRules, allRules, androidDebuggable, assessHeaders, blockingMainThread, buildTaintMap, calculateGrade, callSpreads, callbackHell, classifyExposure, clickjacking, clientComponentSecret, clientSideAuth, commandInjection, complianceMap, consoleLogProduction, corsLocalhost, corsServerless, corsWildcard, dangerousInnerHTML, deprecatedTLS, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, djangoDebug, dockerCopySensitive, dockerLatestTag, dockerRunAsRoot, dockerTooManyPorts, dockerfileADDInsteadOfCOPY, dockerfileMissingHealthcheck, dockerfileUnverifiedShellPipe, ecbModeEncryption, electronNavigationUnrestricted, emptyCatchBlock, entitlementFromWebStorage, envNotGitignored, evalUsage, eventListenerLeak, exposedAdminRoutes, exposedAuthSecret, exposedDBCredentials, exposedDatabaseStudio, exposedDebugMode, exposedDockerPorts, exposedEnvFile, exposedGitDir, exposedServerActions, exposedSourceMaps, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, findSourceMapRefs, firebaseClientConfig, flaskSecretKey, freeRules, getObjectProperty, getSnippet, ghaExpressionInjection, ghaPermissionsWriteAll, ghaPullRequestTargetCheckout, ghaThirdPartyActionWithSecrets, githubActionsInjection, graphqlCSRFDisabled, graphqlIntrospection, graphqlNoComplexityLimit, graphqlNoDepthLimit, hardcodedAlgoliaAdminKey, hardcodedAnthropicKey, hardcodedCloudflareToken, hardcodedCohereKey, hardcodedCreditCard, hardcodedDatadogKey, hardcodedDiscordToken, hardcodedEncryptionKey, hardcodedFastlyToken, hardcodedFireworksKey, hardcodedFlyToken, hardcodedGCPServiceAccount, hardcodedGitHubPAT, hardcodedGitLabToken, hardcodedGroqKey, hardcodedHighlightKey, hardcodedIPAllowlist, hardcodedIntercomToken, hardcodedJWTSecret, hardcodedLinearKey, hardcodedLogtailToken, hardcodedLoopsKey, hardcodedMailgunKey, hardcodedMistralKey, hardcodedNetlifyToken, hardcodedNotionKey, hardcodedOAuthSecret, hardcodedPineconeKey, hardcodedPlivoToken, hardcodedPostmarkKey, hardcodedQdrantKey, hardcodedRailwayToken, hardcodedReplicateKey, hardcodedResendKey, hardcodedSSN, hardcodedSecrets, hardcodedSendGridKey, hardcodedSentryAuthToken, hardcodedShopifyToken, hardcodedSlackToken, hardcodedSupabaseServiceRole, hardcodedTogetherKey, hardcodedTwilioKey, hardcodedVaultToken, hardcodedVercelToken, hardcodedWeaviateKey, hostHeaderRedirect, httpRequestSmuggling, insecureCookies, insecureDeepLink, insecureDeserialization, insecureDirectObjectReference, insecureElectronWindow, insecureFileUpload, insecureGRPC, insecureHTTPMethods, insecurePasswordReset, insecureRandomness, insecureWebSocket, ipcPathTraversal, isCalleeNamed, isMethodCall, isPrivateAddress, isVendoredFinding, isVendoredPath, javaDeserialization, jwtAlgConfusion, k8sNoResourceLimits, k8sPrivileged, k8sSecretNotEncrypted, lambdaWithoutVPC, largeBundleImport, llmCallNoMaxTokens, llmOutputAsHTML, llmOutputToSink, llmPromptInjection, llmSystemPromptInjection, logInjection, magicNumbers, massAssignment, middlewareMatcherExcludesApi, missingAIRateLimit, missingAuthMiddleware, missingAuthRateLimit, missingBruteForce, missingCSP, missingCSRF, missingCertPinning, missingCloudTrail, missingContentDisposition, missingDBEncryption, missingErrorBoundary, missingFileSizeLimits, missingHSTS, missingHTTPS, missingLockFile, missingOAuthState, missingPagination, missingRequestSizeLimit, missingRequestValidation, missingSRI, missingSecurityMeta, nPlusOneQuery, nextPublicSecret, noRateLimiting, normalizeScanPath, nosqlInjection, openRedirectParams, overlyPermissiveIAM, parseFile, parseScanTarget, pathTraversal, pickleDeserialization, piiInLogs, prototypePollution, pyDjangoAllowedHostsWildcard, pyDjangoMarkSafe, pyJWTDecodeWeakConfig, pyJinja2AutoescapeOff, pyParamikoAutoAdd, pyRequestsVerifyFalse, pyTempfileMktemp, raceCondition, rdsPubliclyAccessible, reflectedCORSOrigin, regexDos, routeForFile, runCustomRules, s3BucketNoEncryption, scanEntropy, secretInBundleConfig, secretInCLIArgument, secretInErrorResponse, secretInHTMLAttribute, secretInLLMPrompt, secretInURLParam, secretLoggedToConsole, secretsInCI, securityGroupAllInbound, sensitiveAsyncStorage, sensitiveLocalStorage, sensitiveURLParams, sessionFixation, sqlInjection, ssrfVulnerability, ssti, stripeWebhookUnprotected, supabaseAnonAdmin, supabaseNoRLS, syncFileOps, terraformStateExposed, timingAttack, todoLeftInCode, unencryptedPII, unpinnedGitHubAction, unprotectedAPIRoutes, unprotectedDownload, unsafeObjectAssign, unsanitizedFilenames, unsanitizedHTMLExport, unvalidatedAPIParams, unvalidatedEventData, unvalidatedRedirect, vectorStoreQueryNoUserFilter, vectorStoreUpsertNoMetadata, vendoredReason, visitBinary, visitCalls, vulnerableDependencies, weakHashing, weakPasswordRequirements, weakRSAKeySize, webhookMissingIdempotency, webhookSignatureVerification, xssVulnerability, xxeVulnerability };
package/dist/index.js CHANGED
@@ -258,7 +258,9 @@ var RULE_IMPACTS = {
258
258
  VC209: "Webhooks are delivered at-least-once. Without de-duplicating on the event id, a retried or replayed delivery re-runs the side effect \u2014 a customer is charged twice, a record is duplicated, or an entitlement is granted again. Stripe and Svix both retry on any non-2xx, so this fires in normal operation, not just under attack.",
259
259
  VC210: "If your auth middleware skips /api, those routes run with no gate unless each one re-checks auth itself. It is the most common way a Next.js app ends up with publicly callable API routes that everyone assumed the middleware was protecting.",
260
260
  VC211: "A real credit card number in source is cardholder data sitting in git history, CI logs, and every backup \u2014 a direct PCI-DSS violation. Anyone with repo access can read it, and it cannot be un-leaked once committed; the card must be treated as compromised.",
261
- VC212: "A hardcoded Social Security Number is regulated PII permanently embedded in your git history and backups. It exposes a real person to identity theft, and its presence in source can trigger breach-notification and privacy-law obligations the moment the repo is accessed."
261
+ VC212: "A hardcoded Social Security Number is regulated PII permanently embedded in your git history and backups. It exposes a real person to identity theft, and its presence in source can trigger breach-notification and privacy-law obligations the moment the repo is accessed.",
262
+ VC213: "Anything read from localStorage belongs to the user, not to you. If a plan, role or permission is read from browser storage and branched on, unlocking the feature takes one line in devtools \u2014 no exploit, no tooling, just typing. Every paid tier and admin panel gated this way is open to anyone who opens the console.",
263
+ VC214: "Browser storage is per-device and per-profile, so per-account state kept there resets on a fresh login, cleared cookies, a private window or a second machine \u2014 and the app greets a long-standing customer as brand new. It is not a security hole, it is a trust one: the product visibly does not remember who you are."
262
264
  };
263
265
 
264
266
  // src/exposure.ts
@@ -4061,10 +4063,14 @@ function detectFramework(files) {
4061
4063
  if (frameworks.size === 0) frameworks.add("unknown");
4062
4064
  return [...frameworks];
4063
4065
  }
4066
+ function describesRatherThanUses(lowerPath) {
4067
+ return /(^|\/)(public|static|assets|fixtures|__fixtures__|testdata|test-fixtures)\//.test(lowerPath) || /\.(md|mdx|txt|rst)$/.test(lowerPath);
4068
+ }
4064
4069
  function detectPlatform(files) {
4065
4070
  const platforms = /* @__PURE__ */ new Set();
4066
- for (const { path, content } of files) {
4071
+ for (const { path, content: rawContent } of files) {
4067
4072
  const p = path.toLowerCase();
4073
+ const content = describesRatherThanUses(p) ? "" : rawContent;
4068
4074
  if (/(^|\/)lovable\.config\./.test(p) || /lovable-tagger/i.test(content) || /lovable\.dev/i.test(content)) {
4069
4075
  platforms.add("lovable");
4070
4076
  }
@@ -5031,8 +5037,13 @@ var complianceMap = {
5031
5037
  // VC211–VC212: hardcoded sensitive personal data (PII) in source
5032
5038
  VC211: { owasp: "A02:2021", cwe: "CWE-540" },
5033
5039
  // hardcoded credit card number
5034
- VC212: { owasp: "A02:2021", cwe: "CWE-540" }
5040
+ VC212: { owasp: "A02:2021", cwe: "CWE-540" },
5035
5041
  // hardcoded US SSN
5042
+ // VC213–VC214: account state held in browser storage
5043
+ VC213: { owasp: "A01:2021", cwe: "CWE-602" },
5044
+ // entitlement from web storage (client-side enforcement)
5045
+ VC214: { owasp: "A04:2021", cwe: "CWE-1188" }
5046
+ // per-account state from web storage (insecure default state)
5036
5047
  };
5037
5048
  var consoleLogProduction = {
5038
5049
  id: "VC097",
@@ -7830,6 +7841,74 @@ var webhookMissingIdempotency = {
7830
7841
  }], content, "VC209");
7831
7842
  }
7832
7843
  };
7844
+ var ENTITLEMENT_KEY_RE = /(is_?admin|admin|role|is_?pro\b|premium|is_?paid|paid|plan|tier|subscri|entitle|licen[cs]e|permission|owner|is_?verified|credits?|quota)/i;
7845
+ var LIFECYCLE_KEY_RE = /(onboard|first[_-]?time|has[_-]?seen|seen[_-]?|dismiss|welcome|tour|intro|visited|new[_-]?user|completed[_-]?setup)/i;
7846
+ var USED_AS_CONDITION_RE = /===|!==|==|!=|\?|&&|\|\||if\s*\(|return\s/;
7847
+ function webStorageReads(content, keyRe) {
7848
+ const out = [];
7849
+ const re = /(?:localStorage|sessionStorage)\s*\.\s*getItem\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g;
7850
+ for (const m of content.matchAll(re)) {
7851
+ if (m.index === void 0) continue;
7852
+ if (!keyRe.test(m[1])) continue;
7853
+ const lineStart = content.lastIndexOf("\n", m.index) + 1;
7854
+ let lineEnd = content.indexOf("\n", m.index);
7855
+ if (lineEnd === -1) lineEnd = content.length;
7856
+ if (!USED_AS_CONDITION_RE.test(content.slice(lineStart, lineEnd))) continue;
7857
+ out.push({ key: m[1], index: m.index });
7858
+ }
7859
+ return out;
7860
+ }
7861
+ var entitlementFromWebStorage = {
7862
+ id: "VC213",
7863
+ title: "Entitlement or role read from browser storage",
7864
+ severity: "high",
7865
+ category: "Authorization",
7866
+ description: "A plan, role, or permission read from localStorage / sessionStorage and branched on is a client-side authorization check. The store belongs to the user: typing `localStorage.setItem('isPro','true')` into devtools grants the feature. Entitlement must be decided by the server on every request that depends on it.",
7867
+ check(content, filePath) {
7868
+ if (!/\.(jsx?|tsx?|vue|svelte)$/.test(filePath)) return [];
7869
+ if (isTestFile(filePath)) return [];
7870
+ const hits = webStorageReads(content, ENTITLEMENT_KEY_RE);
7871
+ if (hits.length === 0) return [];
7872
+ const first = hits[0];
7873
+ const line = lineNumberAt(content, first.index);
7874
+ return filterSilenced([{
7875
+ rule: "VC213",
7876
+ title: entitlementFromWebStorage.title,
7877
+ severity: "high",
7878
+ category: "Authorization",
7879
+ file: filePath,
7880
+ line,
7881
+ snippet: getSnippet(content, line),
7882
+ fix: `"${first.key}" is read from browser storage and branched on. A user can set it to anything. Decide entitlement server-side \u2014 from the session, a token claim, or a database read \u2014 and treat the cached copy as a display hint only. If this value is already re-verified on the server before anything is granted, add an inline \`// VC213-OK: <reason>\` comment.`
7883
+ }], content, "VC213");
7884
+ }
7885
+ };
7886
+ var accountStateFromWebStorage = {
7887
+ id: "VC214",
7888
+ title: "Per-account state decided by browser storage alone",
7889
+ severity: "info",
7890
+ category: "Logic",
7891
+ description: "Onboarding, 'first time here', 'already seen' and similar per-ACCOUNT state read only from localStorage / sessionStorage. Browser storage is per-device and per-profile: it is wiped by a fresh login, cleared cookies, a private window, a container tab, or simply a second machine \u2014 so the app greets an established user as brand new. Only fires in files that are already auth-aware, because a purely anonymous banner dismissal is the correct use of local storage.",
7892
+ check(content, filePath) {
7893
+ if (!/\.(jsx?|tsx?|vue|svelte)$/.test(filePath)) return [];
7894
+ if (isTestFile(filePath)) return [];
7895
+ if (!/isSignedIn|useAuth|useUser|useSession|currentUser|getServerSession|session\?\.|auth\(\)|clerk/i.test(content)) return [];
7896
+ const hits = webStorageReads(content, LIFECYCLE_KEY_RE);
7897
+ if (hits.length === 0) return [];
7898
+ const first = hits[0];
7899
+ const line = lineNumberAt(content, first.index);
7900
+ return filterSilenced([{
7901
+ rule: "VC214",
7902
+ title: accountStateFromWebStorage.title,
7903
+ severity: "info",
7904
+ category: "Logic",
7905
+ file: filePath,
7906
+ line,
7907
+ snippet: getSnippet(content, line),
7908
+ fix: `"${first.key}" describes the ACCOUNT but is stored per-browser, so it resets on a new login, a cleared cookie, a private window, or another machine \u2014 and the user is treated as new again. Derive it from server state (has this user ever completed the action?) and keep browser storage for the per-device half, like "I closed this box". If this really is per-device by design, add an inline \`// VC214-OK: <reason>\` comment.`
7909
+ }], content, "VC214");
7910
+ }
7911
+ };
7833
7912
  var middlewareMatcherExcludesApi = {
7834
7913
  id: "VC210",
7835
7914
  title: "Auth middleware matcher excludes API routes",
@@ -8697,7 +8776,10 @@ var allCustomRules = [
8697
8776
  graphqlCSRFDisabled,
8698
8777
  // VC211–VC212: hardcoded sensitive personal data (PII)
8699
8778
  hardcodedCreditCard,
8700
- hardcodedSSN
8779
+ hardcodedSSN,
8780
+ // VC213–VC214: state that belongs to the account, kept in the browser
8781
+ entitlementFromWebStorage,
8782
+ accountStateFromWebStorage
8701
8783
  ];
8702
8784
  function runCustomRules(content, filePath, disabledRules = [], tier = "free", extraRules = []) {
8703
8785
  const findings = [];
@@ -8716,7 +8798,7 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
8716
8798
  }
8717
8799
  }
8718
8800
  if (maxLineLen > 5e4) return findings;
8719
- if (/onboarding|demo-data|example-vulnerable|code-sample/i.test(filePath)) return findings;
8801
+ if (/demo-data|example-vulnerable|code-sample/i.test(filePath)) return findings;
8720
8802
  const vendoredFile = isVendoredPath(filePath);
8721
8803
  const ruleset = tier === "pro" && extraRules.length > 0 ? [...freeRules, ...extraRules] : freeRules;
8722
8804
  for (const rule of ruleset) {
@@ -8749,8 +8831,8 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
8749
8831
 
8750
8832
  // src/rule-counts.ts
8751
8833
  var FREE_RULE_COUNT = 30;
8752
- var PRO_RULE_COUNT = 182;
8753
- var TOTAL_RULE_COUNT = 212;
8834
+ var PRO_RULE_COUNT = 184;
8835
+ var TOTAL_RULE_COUNT = 214;
8754
8836
 
8755
8837
  // src/ai-fp-filter.ts
8756
8838
  import Anthropic from "@anthropic-ai/sdk";
@@ -9132,6 +9214,112 @@ function scanEntropy(files) {
9132
9214
  return findings;
9133
9215
  }
9134
9216
 
9217
+ // src/routes.ts
9218
+ var API_RE = /^\/api(\/|$)|^\/_|\.(json|js|xml|txt|ico)$/;
9219
+ var DYNAMIC_RE = /:[A-Za-z_]|\[[^\]]+\]|<[^>]+>|\$[A-Za-z_]|\*/;
9220
+ function hasDep(files, name) {
9221
+ const pkg = files.find(
9222
+ (f) => f.path === "package.json" || f.path.endsWith("/package.json")
9223
+ );
9224
+ if (!pkg) return false;
9225
+ try {
9226
+ const json = JSON.parse(pkg.content);
9227
+ return Boolean({ ...json.dependencies ?? {}, ...json.devDependencies ?? {} }[name]);
9228
+ } catch {
9229
+ return false;
9230
+ }
9231
+ }
9232
+ function normalize(p) {
9233
+ if (!p.startsWith("/")) return "";
9234
+ if (p.length > 1 && p.endsWith("/")) return p.replace(/\/+$/, "");
9235
+ return p;
9236
+ }
9237
+ function extractRoutes(files) {
9238
+ const routes = /* @__PURE__ */ new Map();
9239
+ const frameworks = /* @__PURE__ */ new Set();
9240
+ const add = (raw, framework, source, kindOverride) => {
9241
+ const path = normalize(raw);
9242
+ if (!path || routes.has(path)) return;
9243
+ routes.set(path, {
9244
+ path,
9245
+ // The URL prefix is a fallback, not the authority. A Next `route.ts` is a
9246
+ // handler wherever it lives: /free-trust-page/claim/start/route.ts is an
9247
+ // endpoint, not a page, and calling it a page mislabels what an attacker
9248
+ // would actually hit.
9249
+ kind: kindOverride ?? (API_RE.test(path) ? "api" : "page"),
9250
+ dynamic: DYNAMIC_RE.test(path),
9251
+ framework,
9252
+ source
9253
+ });
9254
+ frameworks.add(framework);
9255
+ };
9256
+ const isNext = hasDep(files, "next");
9257
+ const isExpress = hasDep(files, "express") || hasDep(files, "hono") || hasDep(files, "koa");
9258
+ const isTanstack = hasDep(files, "@tanstack/react-router") || hasDep(files, "@tanstack/react-start");
9259
+ if (isTanstack) {
9260
+ const gen = files.find((f) => f.path.endsWith("routeTree.gen.ts"));
9261
+ if (gen) {
9262
+ for (const m of gen.content.matchAll(/'(\/[A-Za-z0-9_\-/$.]*)'/g)) {
9263
+ if (m[1].split("/").some((seg) => seg.startsWith("_"))) continue;
9264
+ add(m[1], "tanstack-router", gen.path);
9265
+ }
9266
+ }
9267
+ }
9268
+ for (const file of files) {
9269
+ const rel = file.path;
9270
+ if (isNext) {
9271
+ const page = rel.match(/(?:^|\/)app\/(?:(.*)\/)?page\.(tsx?|jsx?)$/);
9272
+ if (page) {
9273
+ const segs = (page[1] ?? "").split("/").filter(Boolean).filter((s) => !/^\(.*\)$/.test(s));
9274
+ add("/" + segs.join("/"), "next-app", rel);
9275
+ }
9276
+ const handler = rel.match(/(?:^|\/)app\/(?:(.*)\/)?route\.(tsx?|jsx?)$/);
9277
+ if (handler) {
9278
+ const segs = (handler[1] ?? "").split("/").filter(Boolean).filter((s) => !/^\(.*\)$/.test(s));
9279
+ add("/" + segs.join("/"), "next-app", rel, "api");
9280
+ }
9281
+ const pages = rel.match(/(?:^|\/)pages\/(.+)\.(tsx?|jsx?)$/);
9282
+ if (pages && !/^_/.test(pages[1].split("/").pop() ?? "")) {
9283
+ const p = "/" + pages[1].replace(/\/index$/, "").replace(/^index$/, "");
9284
+ add(p === "/" ? "/" : p, "next-pages", rel);
9285
+ }
9286
+ }
9287
+ if (!/\.(tsx?|jsx?|mjs|cjs|py)$/.test(rel)) continue;
9288
+ const src = file.content;
9289
+ for (const m of src.matchAll(/<Route\s[^>]*path\s*=\s*["'`]([^"'`]+)["'`]/g)) {
9290
+ add(m[1].startsWith("/") ? m[1] : "/" + m[1], "react-router", rel);
9291
+ }
9292
+ if (/createBrowserRouter|createHashRouter|useRoutes/.test(src)) {
9293
+ for (const m of src.matchAll(/path\s*:\s*["'`]([^"'`]+)["'`]/g)) {
9294
+ add(m[1].startsWith("/") ? m[1] : "/" + m[1], "react-router", rel);
9295
+ }
9296
+ }
9297
+ for (const m of src.matchAll(
9298
+ /@\w+\.(?:route|get|post|put|patch|delete)\(\s*["']([^"']+)["']/g
9299
+ )) {
9300
+ add(m[1], "flask-fastapi", rel);
9301
+ }
9302
+ for (const m of src.matchAll(/add_url_rule\(\s*["']([^"']+)["']/g)) {
9303
+ add(m[1], "flask-fastapi", rel);
9304
+ }
9305
+ if (isExpress) {
9306
+ for (const m of src.matchAll(
9307
+ /\b(?:app|router)\.(?:get|post|put|patch|delete|all)\(\s*["'`]([^"'`]+)["'`]/g
9308
+ )) {
9309
+ add(m[1], "express", rel);
9310
+ }
9311
+ }
9312
+ }
9313
+ return {
9314
+ frameworks: [...frameworks],
9315
+ routes: [...routes.values()].sort((a, b) => a.path.localeCompare(b.path))
9316
+ };
9317
+ }
9318
+ function routeForFile(table, filePath) {
9319
+ const norm = filePath.replace(/^\.\//, "");
9320
+ return table.routes.find((r) => r.source === norm || r.source.endsWith("/" + norm));
9321
+ }
9322
+
9135
9323
  // src/url-recon.ts
9136
9324
  var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
9137
9325
  "localhost",
@@ -9310,6 +9498,7 @@ export {
9310
9498
  PRO_RULE_COUNT,
9311
9499
  RULE_IMPACTS,
9312
9500
  TOTAL_RULE_COUNT,
9501
+ accountStateFromWebStorage,
9313
9502
  allCustomRules,
9314
9503
  allRules,
9315
9504
  androidDebuggable,
@@ -9347,6 +9536,7 @@ export {
9347
9536
  ecbModeEncryption,
9348
9537
  electronNavigationUnrestricted,
9349
9538
  emptyCatchBlock,
9539
+ entitlementFromWebStorage,
9350
9540
  envNotGitignored,
9351
9541
  evalUsage,
9352
9542
  eventListenerLeak,
@@ -9361,6 +9551,7 @@ export {
9361
9551
  exposedServerActions,
9362
9552
  exposedSourceMaps,
9363
9553
  exposedStackTraces,
9554
+ extractRoutes,
9364
9555
  extractScriptUrls,
9365
9556
  filterFalsePositives,
9366
9557
  findSourceMapRefs,
@@ -9504,6 +9695,7 @@ export {
9504
9695
  rdsPubliclyAccessible,
9505
9696
  reflectedCORSOrigin,
9506
9697
  regexDos,
9698
+ routeForFile,
9507
9699
  runCustomRules,
9508
9700
  s3BucketNoEncryption,
9509
9701
  scanEntropy,