|
| 1 | +/** |
| 2 | + * Session-level shared state — extracted from CloudflareStateTracker. |
| 3 | + * |
| 4 | + * Contains Maps and Sets that are shared across all tabs in a session. |
| 5 | + * Individual tabs reference this state through their tab runtimes. |
| 6 | + * The session-level state outlives any individual tab. |
| 7 | + */ |
| 8 | +import { Effect, Exit, Scope } from 'effect'; |
| 9 | + |
| 10 | +import { runForkInServer } from '../../otel-runtime.js'; |
| 11 | +import type { CdpSessionId, TargetId, CloudflareConfig, CloudflareType } from '../../shared/cloudflare-detection.js'; |
| 12 | +import { isInterstitialType } from '../../shared/cloudflare-detection.js'; |
| 13 | +import type { CFEvents } from './cloudflare-event-emitter.js'; |
| 14 | +import { DetectionRegistry } from './cf-detection-registry.js'; |
| 15 | + |
| 16 | +export class SessionSolverState { |
| 17 | + readonly registry: DetectionRegistry; |
| 18 | + readonly iframeToPage = new Map<TargetId, TargetId>(); |
| 19 | + readonly knownPages = new Map<TargetId, CdpSessionId>(); |
| 20 | + readonly bindingSolvedTargets = new Set<TargetId>(); |
| 21 | + /** CF OOPIF targetIds from completed solves — filtered out of future detection polls. */ |
| 22 | + readonly solvedCFTargetIds = new Set<string>(); |
| 23 | + /** |
| 24 | + * Page targetIds that have successfully solved an EMBEDDED TURNSTILE. |
| 25 | + * See CloudflareStateTracker.solvedPages JSDoc for full rationale. |
| 26 | + * DO NOT ADD INTERSTITIAL SOLVES — multi-phase (Int→Emb) flows will break. |
| 27 | + */ |
| 28 | + readonly solvedPages = new Set<TargetId>(); |
| 29 | + readonly pendingIframes = new Map<TargetId, { iframeCdpSessionId: CdpSessionId; iframeTargetId: TargetId }>(); |
| 30 | + readonly pendingRechallengeCount = new Map<TargetId, number>(); |
| 31 | + /** Per-page reload count for widget-not-rendered recovery. Reset on solve. */ |
| 32 | + readonly widgetReloadCount = new Map<TargetId, number>(); |
| 33 | + /** Per-page cleanup scopes — finalizers remove solvedCFTargetIds entries when page is destroyed. */ |
| 34 | + private readonly pageCleanupScopes = new Map<TargetId, Scope.Closeable>(); |
| 35 | + config: Required<CloudflareConfig> = { maxAttempts: 3, attemptTimeout: 30000, recordingMarkers: true }; |
| 36 | + destroyed = false; |
| 37 | + /** Per-page accumulator of solved/failed phases for compound summary labels. */ |
| 38 | + private readonly summaryPhases = new Map<TargetId, { type: string; label: string }[]>(); |
| 39 | + |
| 40 | + constructor(protected events: CFEvents) { |
| 41 | + this.registry = new DetectionRegistry((active, signal) => { |
| 42 | + const duration = Date.now() - active.startTime; |
| 43 | + |
| 44 | + if (signal === 'verified_session_close') { |
| 45 | + const phaseLabel = '⊘'; |
| 46 | + runForkInServer(Effect.logInfo(`Scope finalizer fallback: verified_session_close for ${active.pageTargetId}`)); |
| 47 | + this.pushPhase(active.pageTargetId, active.info.type, phaseLabel); |
| 48 | + const compoundLabel = this.buildCompoundLabel(active.pageTargetId); |
| 49 | + this.events.emitFailed(active, 'verified_session_close', duration, phaseLabel, compoundLabel, |
| 50 | + { cf_verified: true }); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + const failLabel = `✗ ${signal}`; |
| 55 | + runForkInServer(Effect.logInfo(`Scope finalizer fallback: emitting failed for orphaned detection on ${active.pageTargetId}`)); |
| 56 | + this.pushPhase(active.pageTargetId, active.info.type, failLabel); |
| 57 | + const compoundLabel = this.buildCompoundLabel(active.pageTargetId); |
| 58 | + this.events.emitFailed(active, signal, duration, failLabel, compoundLabel); |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + /** Register a page target → CDP session mapping. Creates cleanup scope. */ |
| 63 | + registerPage(targetId: TargetId, cdpSessionId: CdpSessionId): void { |
| 64 | + this.knownPages.set(targetId, cdpSessionId); |
| 65 | + if (!this.pageCleanupScopes.has(targetId)) { |
| 66 | + this.pageCleanupScopes.set(targetId, Scope.makeUnsafe()); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + /** Add OOPIF target ID to solvedCFTargetIds with scope-bound cleanup. */ |
| 71 | + addSolvedCFTarget(oopifId: string, pageTargetId: TargetId): Effect.Effect<void> { |
| 72 | + return Effect.suspend(() => { |
| 73 | + const scope = this.pageCleanupScopes.get(pageTargetId); |
| 74 | + if (!scope) return Effect.void; |
| 75 | + this.solvedCFTargetIds.add(oopifId); |
| 76 | + return Scope.addFinalizer(scope, Effect.sync(() => { |
| 77 | + this.solvedCFTargetIds.delete(oopifId); |
| 78 | + })); |
| 79 | + }); |
| 80 | + } |
| 81 | + |
| 82 | + /** Synchronous variant — used where we're outside an Effect generator. */ |
| 83 | + addSolvedCFTargetSync(oopifId: string, pageTargetId: TargetId): void { |
| 84 | + const scope = this.pageCleanupScopes.get(pageTargetId); |
| 85 | + if (!scope) return; |
| 86 | + this.solvedCFTargetIds.add(oopifId); |
| 87 | + Effect.runSync(Scope.addFinalizer(scope, Effect.sync(() => { |
| 88 | + this.solvedCFTargetIds.delete(oopifId); |
| 89 | + }))); |
| 90 | + } |
| 91 | + |
| 92 | + /** Look up page target by iframe CDP session. */ |
| 93 | + findPageByIframeSession(iframeCdpSessionId: CdpSessionId): TargetId | undefined { |
| 94 | + return this.registry.findByIframeSession(iframeCdpSessionId); |
| 95 | + } |
| 96 | + |
| 97 | + pushPhase(targetId: TargetId, type: string, label: string): void { |
| 98 | + if (!this.summaryPhases.has(targetId)) this.summaryPhases.set(targetId, []); |
| 99 | + this.summaryPhases.get(targetId)!.push({ type, label }); |
| 100 | + } |
| 101 | + |
| 102 | + /** |
| 103 | + * Build compound summary label from accumulated phases. |
| 104 | + * Interstitial phases: Int✓Int→ (no space). Embedded: Emb→. |
| 105 | + * Space between groups: Int✓Int→ Emb→ |
| 106 | + */ |
| 107 | + buildCompoundLabel(targetId: TargetId): string { |
| 108 | + const phases = this.summaryPhases.get(targetId) || []; |
| 109 | + const intParts = phases |
| 110 | + .filter(p => isInterstitialType(p.type as CloudflareType)) |
| 111 | + .map(p => `Int${p.label}`); |
| 112 | + const embParts = phases |
| 113 | + .filter(p => !isInterstitialType(p.type as CloudflareType)) |
| 114 | + .map(p => `Emb${p.label}`); |
| 115 | + const parts: string[] = []; |
| 116 | + if (intParts.length) parts.push(intParts.join('')); |
| 117 | + if (embParts.length) parts.push(embParts.join('')); |
| 118 | + return parts.join(' '); |
| 119 | + } |
| 120 | + |
| 121 | + /** |
| 122 | + * Clean up all state for a destroyed page target. |
| 123 | + * Registry.unregister() closes the detection's scope, whose finalizer |
| 124 | + * emits session_close fallback if unresolved. |
| 125 | + */ |
| 126 | + unregisterPage(targetId: TargetId): Effect.Effect<void> { |
| 127 | + const self = this; |
| 128 | + return Effect.fn('cf.state.unregisterPage')(function*() { |
| 129 | + yield* Effect.annotateCurrentSpan({ 'cf.target_id': targetId }); |
| 130 | + yield* self.registry.unregister(targetId); |
| 131 | + |
| 132 | + self.knownPages.delete(targetId); |
| 133 | + self.iframeToPage.delete(targetId); |
| 134 | + for (const [iframeId, pageId] of self.iframeToPage) { |
| 135 | + if (pageId === targetId) self.iframeToPage.delete(iframeId); |
| 136 | + } |
| 137 | + self.bindingSolvedTargets.delete(targetId); |
| 138 | + self.solvedPages.delete(targetId); |
| 139 | + self.pendingIframes.delete(targetId); |
| 140 | + self.pendingRechallengeCount.delete(targetId); |
| 141 | + self.widgetReloadCount.delete(targetId); |
| 142 | + self.summaryPhases.delete(targetId); |
| 143 | + |
| 144 | + const cleanupScope = self.pageCleanupScopes.get(targetId); |
| 145 | + if (cleanupScope) { |
| 146 | + yield* Scope.close(cleanupScope, Exit.void); |
| 147 | + self.pageCleanupScopes.delete(targetId); |
| 148 | + } |
| 149 | + })(); |
| 150 | + } |
| 151 | + |
| 152 | + /** Emit cf.failed for orphaned detections and clean up all state. */ |
| 153 | + destroy(): Effect.Effect<void> { |
| 154 | + this.destroyed = true; |
| 155 | + return Effect.gen((function*(this: SessionSolverState) { |
| 156 | + yield* this.registry.destroyAll(); |
| 157 | + this.iframeToPage.clear(); |
| 158 | + this.knownPages.clear(); |
| 159 | + this.bindingSolvedTargets.clear(); |
| 160 | + |
| 161 | + for (const scope of this.pageCleanupScopes.values()) { |
| 162 | + yield* Scope.close(scope, Exit.void); |
| 163 | + } |
| 164 | + this.pageCleanupScopes.clear(); |
| 165 | + |
| 166 | + this.solvedCFTargetIds.clear(); |
| 167 | + this.solvedPages.clear(); |
| 168 | + this.pendingIframes.clear(); |
| 169 | + this.widgetReloadCount.clear(); |
| 170 | + this.summaryPhases.clear(); |
| 171 | + }).bind(this)); |
| 172 | + } |
| 173 | +} |
0 commit comments