Skip to content

🤖 Code Audit: 31 potential issue(s) found #172

Description

@asmit25805

Code Audit Report

All findings are reviewed for confidence before posting.
Please verify each finding before acting on it.

Repository: FoundZiGu/GuJumpgate
Findings: 31 issue(s) found — 🔴 2 critical · 🟠 8 high · 🟡 13 medium · 🔵 8 low


1. 🐛 Syntax error: missing closing bracket in header lookup

Field Details
Severity 🔴 Critical
Type Bug
File cloudflare-temp-email-utils.js
Location decodeMimeBody function definition (truncated part)
Confidence 99%

Problem:
The line const transferEncoding = String(headers['content-transfer-encoding' is missing a closing bracket ] (and likely a closing parenthesis). This results in a syntax error that prevents the entire module from loading, causing runtime failures wherever the utility is imported.

Suggested Fix:
Add the missing closing bracket and parenthesis: const transferEncoding = String(headers['content-transfer-encoding']); (or include any additional processing that follows). Ensure the rest of the function body is correctly closed.


2. 🐛 Incomplete function causing syntax error

Field Details
Severity 🔴 Critical
Type Bug
File hotmail-utils.js
Location function normalizeMailAddress (around line 260)
Confidence 95%

Problem:
The file ends abruptly inside the normalizeMailAddress function (rawValue.fro is incomplete). This results in a syntax error that prevents the module from loading, breaking all dependent code.

Suggested Fix:
Complete the implementation of normalizeMailAddress and ensure the function ends with a proper closing brace and return statement. For example, finish the property list and add return '' or appropriate value, then close the function with }.


3. 🔒 Insufficient scheme validation allows non‑HTTP URLs

Field Details
Severity 🟠 High
Type Security
File cloudmail-utils.js
Location normalizeCloudMailBaseUrl
Confidence 95%

Problem:
The function normalizeCloudMailBaseUrl accepts any scheme that matches the generic regex /^[a-zA-Z][a-zA-Z\d+-.]*:///. This permits URLs such as "javascript://..." or "data://..." to be parsed and later used as a base URL. When such a URL is passed to joinCloudMailUrl, it can lead to unexpected origins (e.g., "null") or enable injection attacks if the resulting URL is later used in network requests. The lack of strict http/https validation is a security risk.

Suggested Fix:
Restrict accepted schemes to http and https only. For example, replace the generic regex with a check like: if (!/^(https?:)///i.test(value)) return ''; or explicitly whitelist allowed protocols before constructing the URL. Additionally, consider rejecting URLs that contain potentially dangerous schemes and return an empty string or throw an error.


4. 🔒 Potential SSRF via unvalidated API base URL

Field Details
Severity 🟠 High
Type Security
File gopay-utils.js
Location function normalizeGpcHelperBaseUrl
Confidence 94%

Problem:
The function only validates that the URL has an http/https protocol but does not restrict the hostname. An attacker could supply a malicious internal address (e.g., http://169.254.169.254) which would be accepted and later used for API calls, enabling Server‑Side Request Forgery.

Suggested Fix:
Add hostname validation (whitelist allowed domains or enforce a specific pattern) and reject URLs that point to private IP ranges or unexpected hosts.


5. 🔒 Potential Regular Expression Denial of Service (ReDoS)

Field Details
Severity 🟠 High
Type Security
File hotmail-utils.js
Location function extractCodeByRulePatterns
Confidence 80%

Problem:
The function builds a RegExp from user‑provided patterns (options.codePatterns). Complex or malicious patterns can cause catastrophic backtracking, leading to CPU exhaustion.

Suggested Fix:
Validate and limit the complexity of incoming regex patterns. Consider using a safe regex library, impose a maximum length on the pattern string, and reject patterns with excessive quantifiers. Alternatively, run the regex matching in a sandboxed worker with a timeout.


6. 🔒 Potential URL Injection Vulnerability

Field Details
Severity 🟠 High
Type Security
File luckmail-utils.js
Location normalizeLuckmailBaseUrl
Confidence 95%

Problem:
The normalizeLuckmailBaseUrl function does not properly validate the input URL, which could lead to a URL injection vulnerability. An attacker could potentially inject malicious URLs, leading to security issues.

Suggested Fix:
Use a more robust URL validation library, such as URLValidator, to ensure that the input URL is properly validated and sanitized.


7. 🐛 Incorrect credential extraction logic

Field Details
Severity 🟠 High
Type Bug
File mail-provider-utils.js
Location parseHiddenEmailCredential
Confidence 96%

Problem:
The function parseHiddenEmailCredential returns the entire raw string as credential when a separator (----) is present, instead of extracting the substring after the separator. This results in the credential containing the email part and separator, which is likely unintended and can cause downstream processing errors.

Suggested Fix:
Change the credential extraction to use the substring after the separator: const credential = separatorIndex >= 0 ? raw.slice(separatorIndex + 4) : '';


8. 🐛 crypto.randomUUID may be undefined in Node environments

Field Details
Severity 🟠 High
Type Bug
File mail2925-utils.js
Location normalizeMail2925Account
Confidence 95%

Problem:
The function uses crypto.randomUUID() to generate a fallback ID, but the global crypto object is only available in browsers. In Node.js, crypto is a module and not defined globally, causing a ReferenceError at runtime when account.id is missing.

Suggested Fix:
Import the Node.js crypto module when running in a non-browser environment, e.g., const { randomUUID } = require('crypto'); and use randomUUID() instead of crypto.randomUUID(). Alternatively, check for the existence of globalThis.crypto and fallback to a safe UUID generator.


9. 🔒 Plain‑text password handling

Field Details
Severity 🟠 High
Type Security
File paypal-utils.js
Location normalizePayPalAccount
Confidence 81%

Problem:
The normalizePayPalAccount function stores the password field as a plain string without any hashing or encryption. If the resulting objects are persisted or logged, the raw password could be exposed, leading to credential leakage.

Suggested Fix:
Never store raw passwords. Require callers to provide a hashed password (e.g., using bcrypt) before calling normalizePayPalAccount, or integrate a hashing step inside the function and store only the hash.


10. 🔒 JWT generated with alg='none' and no signature

Field Details
Severity 🟠 High
Type Security
File background/cpa-api.js
Location buildSyntheticCodexIdToken
Confidence 94%

Problem:
The function buildSyntheticCodexIdToken creates a JWT where the header specifies alg: 'none' and the signature part is the literal string synthetic. If this token is ever accepted by a service that validates JWTs, an attacker could forge tokens with arbitrary payloads, leading to privilege escalation or unauthorized access.

Suggested Fix:
Replace the use of the 'none' algorithm with a proper signing algorithm (e.g., HS256) and generate a cryptographic signature using a secret key. If a signature is not required for internal use, ensure the token is never sent to external services that perform JWT verification.


11. 🔒 Potential HTTP header injection via unsanitized auth values

Field Details
Severity 🟡 Medium
Type Security
File cloudflare-temp-email-utils.js
Location buildCloudflareTempEmailHeaders
Confidence 88%

Problem:
The function copies adminAuth and customAuth values directly from user‑provided configuration into HTTP headers (x-admin-auth and x-custom-auth). If an attacker can influence these values, they could inject newline characters or other control sequences, leading to malformed headers or header injection attacks when the headers are sent with a request.

Suggested Fix:
Validate and sanitize the auth strings before adding them to the headers. For example, reject values containing CR (\r) or LF (\n) characters and enforce a whitelist of allowed characters (e.g., alphanumerics, hyphens, underscores).


12. 🐛 Non-object payloads are treated as successful responses

Field Details
Severity 🟡 Medium
Type Bug
File gopay-utils.js
Location function isGpcUnifiedResponseOk
Confidence 92%

Problem:
The function returns true when the payload is not an object (e.g., a string or null). This can cause callers to assume a request succeeded even when the response is malformed, potentially hiding errors and leading to incorrect application flow.

Suggested Fix:
Add an explicit check that the payload is an object and return false for non-object values, or at least treat undefined/null as failure.


13. 🔒 Action segment is not URL‑encoded, allowing path manipulation

Field Details
Severity 🟡 Medium
Type Security
File gopay-utils.js
Location function buildGpcTaskActionUrl
Confidence 88%

Problem:
The action parameter is trimmed and concatenated into the URL without encoding. If an attacker supplies a value containing slashes or URL‑encoded characters, it could alter the request path (e.g., "../delete") and potentially trigger unintended API endpoints.

Suggested Fix:
Encode the action segment using encodeURIComponent after sanitising it, or validate against an allowlist of known actions before constructing the URL.


14. 🐛 Truthiness conversion treats non-boolean values as true

Field Details
Severity 🟡 Medium
Type Bug
File icloud-utils.js
Location normalizeBooleanMap (line ~55)
Confidence 85%

Problem:
The function converts any value to a boolean using Boolean(value). Strings like "false" or numbers like 0 become true/false incorrectly, which can lead to unexpected behavior when the map is used to filter email sets.

Suggested Fix:
Explicitly check for boolean values or known truthy strings, e.g., result[normalizedKey] = value === true || value === 'true';.


15. 🐛 Potential NaN Issue

Field Details
Severity 🟡 Medium
Type Bug
File luckmail-utils.js
Location normalizeLuckmailPurchaseId
Confidence 90%

Problem:
The normalizeLuckmailPurchaseId function does not handle NaN (Not a Number) values properly, which could lead to unexpected behavior. If the input value is NaN, the function will return an empty string, which may not be the intended behavior.

Suggested Fix:
Add a check for NaN values and handle them accordingly, such as returning a default value or throwing an error.


16. 🔒 Potential SSRF vector via unchecked base URL

Field Details
Severity 🟡 Medium
Type Security
File mail-provider-utils.js
Location normalizeIcloudApiBaseUrl
Confidence 88%

Problem:
normalizeIcloudApiBaseUrl accepts an arbitrary string, prepends https:// if no scheme is present, and returns a normalized URL without further validation of the hostname. If this URL is later used for network requests, an attacker could supply a malicious host (e.g., internal IP) leading to Server‑Side Request Forgery (SSRF).

Suggested Fix:
Add validation to ensure the hostname is within an allowed whitelist or matches expected patterns before returning the URL, and reject or sanitize any disallowed hosts.


17. 🐛 Incorrect fallback for options.now using logical OR

Field Details
Severity 🟡 Medium
Type Bug
File mail2925-utils.js
Location pickMail2925AccountForRun
Confidence 92%

Problem:
The code computes const now = normalizeTimestamp(options.now) || Date.now();. If options.now is 0 (a valid timestamp), normalizeTimestamp returns 0, but the || operator treats 0 as falsy and substitutes Date.now(), unintentionally shifting the reference time.

Suggested Fix:
Replace the logical OR with nullish coalescing to preserve zero values: const now = normalizeTimestamp(options.now) ?? Date.now();.


18. 🐛 Mailbox normalization only supports INBOX and Junk

Field Details
Severity 🟡 Medium
Type Bug
File microsoft-email.js
Location normalizeMailboxLabel / normalizeMailboxId
Confidence 96%

Problem:
The functions normalizeMailboxLabel and normalizeMailboxId map any mailbox name that does not match the Junk pattern to "INBOX" and "inbox" respectively. This discards legitimate mailbox identifiers such as "Sent", "Drafts", or custom folders, causing API calls to request the wrong folder and potentially lose or misinterpret messages.

Suggested Fix:
Update the normalization logic to preserve recognized mailbox names or to return the original value when it does not match the Junk pattern. For example, have normalizeMailboxLabel return the trimmed input (capitalized) if it doesn't match the Junk regex, and adjust normalizeMailboxId to map known folder names to their API identifiers while falling back to the original lower‑cased name for custom folders.


19. 🔒 Overly permissive generic 6‑digit code extraction

Field Details
Severity 🟡 Medium
Type Security
File microsoft-email.js
Location extractVerificationCode
Confidence 88%

Problem:
The fallback regex CODE_PATTERN = /\b(\d{6})\b/ matches any six‑digit number in the email body. This can incorrectly treat unrelated numbers (e.g., dates, order IDs) as verification codes, potentially leading to accidental acceptance of wrong codes or leaking of sensitive numeric data.

Suggested Fix:
Restrict the generic pattern to contexts where a code is expected, such as requiring surrounding keywords (e.g., "code", "verification", "OTP") or limiting matches to lines that contain the word "code". Alternatively, remove the generic fallback and rely only on the more specific patterns, returning an empty string when no explicit match is found.


20. 💡 Deduplication keyed by ID may retain duplicate emails

Field Details
Severity 🟡 Medium
Type Suggestion
File paypal-utils.js
Location normalizePayPalAccounts
Confidence 92%

Problem:
The function dedupes accounts using a Map keyed by the generated or provided id. When two accounts share the same email but lack an explicit id, each call to normalizePayPalAccount creates a new UUID, causing both entries to be kept despite representing the same logical account. This can lead to duplicate records and inconsistent state.

Suggested Fix:
Deduplicate based on the normalized email address instead of the id. For example, use deduped.set(normalized.email, normalized) and return deduped.values().


21. 🔒 Potential XSS via unsanitized node identifiers in failure labels

Field Details
Severity 🟡 Medium
Type Security
File background/account-run-history.js
Location resolveFailureLabel / buildFailureLabel
Confidence 92%

Problem:
The functions resolveFailureLabel and buildFailureLabel construct human‑readable failure messages by interpolating failedNodeId (or values derived from it) directly into template strings (e.g., 节点 ${getNodeDisplayName(failedNodeId, state)} 失败). No sanitisation or escaping is performed. If an attacker can influence the failedNodeId value (e.g., via crafted input that ends up in the persisted run history), the resulting string could be injected into the UI and executed as HTML/JavaScript, leading to cross‑site scripting (XSS) when the label is rendered in a web page.

Suggested Fix:
Sanitise or escape any dynamic values that are inserted into UI strings. For example, create a utility escapeHtml that replaces <, >, &, ", and ' with HTML entities before embedding the value, or ensure that the UI layer treats the label as plain text (e.g., using textContent instead of innerHTML). Additionally, validate failedNodeId against an allowlist of expected characters (e.g., alphanumerics, underscores, hyphens, periods, colons) before using it in UI output.


22. 🐛 Duplicate function definition overwrites earlier implementation

Field Details
Severity 🟡 Medium
Type Bug
File background/auto-run-controller.js
Location function isPhoneNumberSupplyExhaustedFailure
Confidence 95%

Problem:
The file defines isPhoneNumberSupplyExhaustedFailure twice with different parameter names and logic. The second definition overwrites the first, discarding the more detailed detection logic and potentially causing incorrect error handling.

Suggested Fix:
Rename one of the functions (e.g., isPhoneNumberSupplyExhaustedFailureDetailed) or merge the logic into a single implementation, ensuring only one definition exists.


23. 🐛 Falsy non‑string values (e.g., 0) are incorrectly treated as empty

Field Details
Severity 🟡 Medium
Type Bug
File background/cpa-api.js
Location firstNonEmpty
Confidence 88%

Problem:
firstNonEmpty normalizes each argument with normalizeString, which converts the value to a string using String(value || ''). Because 0 is falsy, it becomes an empty string, causing legitimate numeric zero values to be ignored. This can lead to unexpected behavior when numeric identifiers or timestamps are passed.

Suggested Fix:
Modify normalizeString to preserve numeric zero, e.g., String(value !== undefined && value !== null ? value : '').trim(), or adjust firstNonEmpty to handle non‑string values without coercing falsy numbers to empty.


24. ⚡ Inefficient sorting to find latest message

Field Details
Severity 🔵 Low
Type Performance
File hotmail-utils.js
Location function getLatestHotmailMessage
Confidence 85%

Problem:
getLatestHotmailMessage sorts the entire messages array to pick the newest message, which is O(n log n). For large arrays this is unnecessary work.

Suggested Fix:
Replace the sort with a single pass that tracks the message with the maximum receivedDateTime. Example: iterate through the array, keep the message with the highest timestamp, and return it.


25. 🐛 Empty catch block swallows URL parsing errors

Field Details
Severity 🔵 Low
Type Bug
File icloud-utils.js
Location normalizeIcloudHost (line ~10)
Confidence 92%

Problem:
When host contains '://', the code attempts new URL(host). If the string is not a valid URL, an exception is thrown and silently ignored, leaving host unchanged. This can mask malformed inputs and make debugging difficult.

Suggested Fix:
Add proper error handling inside the catch block, e.g., log the error or fallback to a safe value, and ensure host is set to an empty string on failure.


26. ⚡ Unnecessary array allocation when converting Set to Set

Field Details
Severity 🔵 Low
Type Performance
File icloud-utils.js
Location toNormalizedEmailSet (line ~70)
Confidence 81%

Problem:
When values is a Set, the code creates an intermediate array via Array.from before constructing a new Set, resulting in extra memory allocation and iteration.

Suggested Fix:
Iterate directly over the original Set to build the new Set, e.g., const result = new Set(); for (const item of values) { result.add(String(item || '').trim().toLowerCase()); } return result;.


27. ⚡ Potential Performance Issue

Field Details
Severity 🔵 Low
Type Performance
File luckmail-utils.js
Location buildLuckmailBaselineCursor
Confidence 85%

Problem:
The buildLuckmailBaselineCursor function sorts the input array of mails, which could lead to performance issues for large input arrays. A more efficient approach would be to use a data structure that allows for efficient sorting, such as a heap or a balanced binary search tree.

Suggested Fix:
Consider using a more efficient data structure or algorithm for sorting the input array, such as a heap or a balanced binary search tree.


28. ⚡ Repeated full normalization of account lists

Field Details
Severity 🔵 Low
Type Performance
File paypal-utils.js
Location findPayPalAccount / upsertPayPalAccountInList
Confidence 88%

Problem:
Both findPayPalAccount and upsertPayPalAccountInList call normalizePayPalAccounts(accounts) each time they are invoked, which iterates over the entire list, normalizes each entry, and deduplicates it. If these functions are used frequently on large lists, this results in unnecessary O(n) work on every call.

Suggested Fix:
Cache the normalized list outside the function or accept a pre‑normalized list as an argument. Alternatively, expose a separate normalizeAndCache utility and reuse the cached result within these functions.


29. 🐛 getAutoRunRoundRetryCount can return NaN when summary is undefined

Field Details
Severity 🔵 Low
Type Bug
File background/auto-run-controller.js
Location function getAutoRunRoundRetryCount
Confidence 90%

Problem:
The function computes Math.max(0, Number(summary?.attempts || 0) - 1). If summary is undefined, summary?.attempts is undefined, Number(undefined) yields NaN, and Math.max returns NaN. Callers expecting a numeric retry count may receive NaN, leading to unexpected behavior.

Suggested Fix:
Provide a default object or guard against undefined summary, e.g., const attempts = Number(summary?.attempts ?? 0); return Math.max(0, attempts - 1);.


30. ⚡ Unnecessary array allocation in buildAutoRunRoundSummaries

Field Details
Severity 🔵 Low
Type Performance
File background/auto-run-controller.js
Location function buildAutoRunRoundSummaries
Confidence 85%

Problem:
The function creates an array of length totalRuns using Array.from and then maps each index to a normalized summary. This allocates an intermediate array solely for iteration, which can be avoided for large totalRuns.

Suggested Fix:
Replace with a simple loop that pushes normalized summaries into a result array, reducing temporary allocations.


31. ⚡ Inefficient string concatenation when encoding large JSON payloads

Field Details
Severity 🔵 Low
Type Performance
File background/cpa-api.js
Location encodeBase64UrlJson
Confidence 82%

Problem:
The fallback branch of encodeBase64UrlJson builds a binary string by iterating over a Uint8Array and concatenating characters (binary += String.fromCharCode(byte)). This results in O(n²) time for large payloads due to repeated string allocations.

Suggested Fix:
Replace the manual loop with String.fromCharCode(...bytes) using spread syntax (if size permits) or use TextDecoder to convert the Uint8Array directly to a string before calling btoa. For example: const binary = new TextDecoder().decode(bytes);


About this report

This report was generated using Llama 3.3 70B.
Only findings with ≥80% confidence are included.
False positives are possible — use your own judgment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions