Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Refactor

Blue Mousea69aea8090d7
diff --git a/src/captcha.ts b/src/captcha.ts
index 59d7e3bba..0150140a0 100644
--- a/src/captcha.ts
+++ b/src/captcha.ts
@@ -8,6 +8,10 @@ const WORKER_URL = isDevelopment ? './pow-worker.js' : 'https://cap.swetrix.com/
const MSG_IDENTIFIER = 'swetrix-captcha'
const CAPTCHA_TOKEN_LIFETIME = 300 // seconds (5 minutes).
+// Main-thread fallback limits (same as worker)
+const MAX_ITERATIONS = 100_000_000 // 100 million attempts
+const TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes
+
const ENDPOINTS = {
GENERATE: '/generate',
VERIFY: '/verify',
@@ -188,17 +192,32 @@ const solveChallenge = async (challenge: PowChallenge): Promise<void> => {
return
}
- powWorker.onmessage = async (event: MessageEvent<PowResult | PowProgress>) => {
+ powWorker.onmessage = async (
+ event: MessageEvent<
+ PowResult | PowProgress | { type: 'timeout'; reason: string } | { type: 'error'; message?: string }
+ >,
+ ) => {
const data = event.data
if (data.type === 'progress') {
- updateProgress(data.attempts, data.hashRate)
+ updateProgress((data as PowProgress).attempts, (data as PowProgress).hashRate)
+ return
+ }
+
+ if (data.type === 'timeout') {
+ // Worker timed out or hit max iterations
+ console.error('PoW worker timeout:', (data as { type: 'timeout'; reason: string }).reason)
+ sendMessageToLoader(IFRAME_MESSAGE_TYPES.FAILURE)
+ activateAction(ACTION.failure)
+ powWorker?.terminate()
+ powWorker = null
+ resolve()
return
}
if (data.type === 'result') {
// Worker found the solution
- const token = await verifySolution(challenge.challenge, data.nonce, data.solution)
+ const token = await verifySolution(challenge.challenge, (data as PowResult).nonce, (data as PowResult).solution)
if (token) {
sendMessageToLoader(IFRAME_MESSAGE_TYPES.SUCCESS, { token })
@@ -209,7 +228,28 @@ const solveChallenge = async (challenge: PowChallenge): Promise<void> => {
powWorker?.terminate()
powWorker = null
resolve()
+ return
}
+
+ // Handle error message from worker
+ if (data.type === 'error') {
+ const errorData = data as { type: 'error'; message?: string }
+ console.error('PoW worker error message:', errorData.message || 'Unknown error')
+ sendMessageToLoader(IFRAME_MESSAGE_TYPES.FAILURE)
+ activateAction(ACTION.failure)
+ powWorker?.terminate()
+ powWorker = null
+ resolve()
+ return
+ }
+
+ // Fallback for unexpected message types
+ console.warn('PoW worker received unexpected message type:', (data as { type?: unknown }).type, 'Raw data:', data)
+ sendMessageToLoader(IFRAME_MESSAGE_TYPES.FAILURE)
+ activateAction(ACTION.failure)
+ powWorker?.terminate()
+ powWorker = null
+ resolve()
}
powWorker.onerror = (error) => {
@@ -250,7 +290,16 @@ const solveInMainThread = async (challenge: PowChallenge): Promise<void> => {
return true
}
- while (true) {
+ while (nonce < MAX_ITERATIONS) {
+ // Check overall timeout
+ const elapsedMs = Date.now() - startTime
+ if (elapsedMs >= TIMEOUT_MS) {
+ console.error(`PoW main-thread timeout: ${TIMEOUT_MS}ms elapsed after ${nonce} attempts`)
+ sendMessageToLoader(IFRAME_MESSAGE_TYPES.FAILURE)
+ activateAction(ACTION.failure)
+ return
+ }
+
const input = `${challengeStr}:${nonce}`
const hash = await sha256(input)
@@ -277,6 +326,11 @@ const solveInMainThread = async (challenge: PowChallenge): Promise<void> => {
await new Promise((r) => setTimeout(r, 0))
}
}
+
+ // Max iterations reached without finding solution
+ console.error(`PoW main-thread max iterations reached: ${MAX_ITERATIONS} attempts`)
+ sendMessageToLoader(IFRAME_MESSAGE_TYPES.FAILURE)
+ activateAction(ACTION.failure)
}
document.addEventListener('DOMContentLoaded', () => {
diff --git a/src/pow-worker.ts b/src/pow-worker.ts
index e969ad30b..8a2ded452 100644
--- a/src/pow-worker.ts
+++ b/src/pow-worker.ts
@@ -2,9 +2,16 @@ export {}
// PoW Worker - Computes the proof-of-work solution in a background thread
+// Maximum allowed difficulty to prevent excessive computation
+const MAX_DIFFICULTY = 32
+
+// Default maximum iterations to prevent infinite loops (100 million)
+const DEFAULT_MAX_ITERATIONS = 100_000_000
+
interface PowChallenge {
challenge: string
difficulty: number
+ maxIterations?: number // Optional: maximum iterations before timeout (default: 100 million)
}
interface PowResult {
@@ -19,7 +26,20 @@ interface PowProgress {
hashRate: number
}
-type PowMessage = PowResult | PowProgress
+interface PowTimeout {
+ type: 'timeout'
+ reason: string
+ attempts: number
+ elapsedMs: number
+ hashRate: number
+}
+
+interface PowError {
+ type: 'error'
+ message: string
+}
+
+type PowMessage = PowResult | PowProgress | PowTimeout | PowError
// SHA-256 implementation using SubtleCrypto
async function sha256(message: string): Promise<string> {
@@ -41,12 +61,12 @@ function hasValidPrefix(hash: string, difficulty: number): boolean {
}
// Solve the PoW challenge
-async function solveChallenge(challenge: string, difficulty: number): Promise<void> {
+async function solveChallenge(challenge: string, difficulty: number, maxIterations: number): Promise<void> {
let nonce = 0
const startTime = Date.now()
const progressInterval = 10000 // Report progress every 10k attempts
- while (true) {
+ while (nonce < maxIterations) {
const input = `${challenge}:${nonce}`
const hash = await sha256(input)
@@ -65,7 +85,8 @@ async function solveChallenge(challenge: string, difficulty: number): Promise<vo
// Report progress periodically
if (nonce % progressInterval === 0) {
- const elapsed = (Date.now() - startTime) / 1000
+ const elapsedMs = Date.now() - startTime
+ const elapsed = elapsedMs / 1000
const hashRate = Math.round(nonce / elapsed)
const progress: PowProgress = {
type: 'progress',
@@ -75,11 +96,83 @@ async function solveChallenge(challenge: string, difficulty: number): Promise<vo
self.postMessage(progress)
}
}
+
+ // Max iterations reached - send timeout message
+ const elapsedMs = Date.now() - startTime
+ const elapsed = elapsedMs / 1000
+ const hashRate = elapsed > 0 ? Math.round(nonce / elapsed) : 0
+ const timeout: PowTimeout = {
+ type: 'timeout',
+ reason: `Maximum iterations reached (${maxIterations.toLocaleString()})`,
+ attempts: nonce,
+ elapsedMs,
+ hashRate,
+ }
+ self.postMessage(timeout)
}
// Listen for messages from the main thread
self.onmessage = async (event: MessageEvent<PowChallenge>) => {
- const { challenge, difficulty } = event.data
- await solveChallenge(challenge, difficulty)
-}
+ // Validate event.data exists
+ if (!event.data) {
+ const error: PowError = {
+ type: 'error',
+ message: 'Invalid message: event.data is missing or empty',
+ }
+ self.postMessage(error)
+ return
+ }
+
+ const { challenge, difficulty, maxIterations } = event.data
+
+ // Validate challenge is provided and is a non-empty string
+ if (typeof challenge !== 'string' || challenge.length === 0) {
+ const error: PowError = {
+ type: 'error',
+ message: 'Invalid message: challenge must be a non-empty string',
+ }
+ self.postMessage(error)
+ return
+ }
+
+ // Validate difficulty is a positive integer within acceptable range
+ if (typeof difficulty !== 'number' || !Number.isInteger(difficulty)) {
+ const error: PowError = {
+ type: 'error',
+ message: 'Invalid message: difficulty must be an integer',
+ }
+ self.postMessage(error)
+ return
+ }
+
+ if (difficulty < 1 || difficulty > MAX_DIFFICULTY) {
+ const error: PowError = {
+ type: 'error',
+ message: `Invalid message: difficulty must be between 1 and ${MAX_DIFFICULTY}`,
+ }
+ self.postMessage(error)
+ return
+ }
+ // Validate maxIterations if provided
+ const effectiveMaxIterations = maxIterations ?? DEFAULT_MAX_ITERATIONS
+ if (typeof effectiveMaxIterations !== 'number' || !Number.isInteger(effectiveMaxIterations)) {
+ const error: PowError = {
+ type: 'error',
+ message: 'Invalid message: maxIterations must be an integer',
+ }
+ self.postMessage(error)
+ return
+ }
+
+ if (effectiveMaxIterations < 1) {
+ const error: PowError = {
+ type: 'error',
+ message: 'Invalid message: maxIterations must be at least 1',
+ }
+ self.postMessage(error)
+ return
+ }
+
+ await solveChallenge(challenge, difficulty, effectiveMaxIterations)
+}