Repository navigation
Integrate Twitter Proxy and credential store - #1930
Conversation
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughAdds an in-process Twitter "account proxy" with encrypted credential support, transaction-ID generation, a proxy request handler (retries, error classification, Discord alerts), build/test defines for encrypted blobs, credential tooling/scripts, and related bindings/logging/config updates. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Worker as Worker (Cloudflare)
participant Cred as Credentials Module
participant XAPI as api.x.com
participant Discord as Discord Webhook
Client->>Worker: request (path, headers, query)
activate Worker
Worker->>Cred: initCredentials(CREDENTIAL_KEY?) / getRandomTwitterAccount()
activate Cred
Cred-->>Worker: account (authToken, csrfToken, username)
deactivate Cred
Worker->>XAPI: proxied request (cookies, x-csrf-token, x-client-transaction-id)
activate XAPI
XAPI-->>Worker: upstream response (body, status, headers)
deactivate XAPI
alt parsed JSON indicates API errors and retries left
Worker->>Worker: vaporize username, pick another account, retry (up to max attempts)
else error and EXCEPTION_DISCORD_WEBHOOK set
Worker->>Discord: POST alert (username, endpoint, errors, variables)
Discord-->>Worker: webhook response
end
Worker-->>Client: proxied response (modified body, status, headers)
deactivate Worker
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 19
🧹 Nitpick comments (1)
vitest.config.mts (1)
10-10: Consider adding one proxy-enabled test profile.With
miniflare: {}and empty credential globals, account-proxy code paths are likely untested by default. A dedicated suite/config with a testCREDENTIAL_KEY(or mock binding) would keep proxy behavior covered.Also applies to: 38-40
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@vitest.config.mts` at line 10, Add a new Vitest test profile in vitest.config.mts that enables Miniflare with proxy credentials so account-proxy paths are exercised; specifically add a profile (e.g., name "proxy-enabled" or "with-credentials") that sets miniflare to a config object including a mock CREDENTIAL_KEY binding (or test credential globals) instead of an empty object, and ensure tests intended to exercise account-proxy behavior run under this profile; update any references to miniflare: {} to include this new profile so proxy code paths are covered during CI/local test runs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/workflows/deploy.yml:
- Around line 28-33: After the curl download of credentials.enc.json, add a
fail-fast validation that parses credentials.enc.json and verifies it contains
non-empty "ciphertext" and "iv" properties; if either is missing or empty, exit
non‑zero so the workflow fails fast. Locate the job step that runs the curl (the
"Fetch encrypted credentials from R2" step) and insert a small validation
command (e.g., using jq or a short node/pwsh check) that reads
credentials.enc.json, ensures .ciphertext and .iv exist and are not empty
strings, and calls exit 1 when validation fails so downstream steps
(inlining/decryption) cannot run with a bad bundle.
In `@esbuild.config.mjs`:
- Around line 75-85: The current try/catch around reading/parsing
credentials.enc.json treats any error (including malformed JSON or missing
expected fields) as "file missing" and silently falls back to empty credentials;
change the error handling so only a missing-file error (err.code === 'ENOENT')
triggers the empty fallback and all other errors rethrow or cause the build to
fail. Specifically, update the block that reads
fs.readFileSync('credentials.enc.json', 'utf-8') and sets
defines['ENCRYPTED_CREDENTIALS'] / defines['CREDENTIALS_IV'] to catch the fs
ENOENT case and handle it as before, but validate JSON.parse and the presence of
enc.ciphertext/enc.iv and throw a new error (or rethrow) on malformed content so
the build fails rather than shipping empty credentials.
In `@src/providers/twitter/accountProxy.ts`:
- Around line 7-11: The hasTwitterAccountProxy function incorrectly treats
whitespace-only CREDENTIAL_KEY as valid; update the capability check in
hasTwitterAccountProxy to trim env.CREDENTIAL_KEY (e.g., use
env.CREDENTIAL_KEY?.trim()) before testing length, so
Boolean(env?.CREDENTIAL_KEY && env.CREDENTIAL_KEY.length > 0) becomes a trimmed
check, and keep the existing TwitterProxy presence check unchanged.
In `@src/providers/twitter/fetch.ts`:
- Line 11: The module-scoped flag wasAccountProxyDisabled must be made
request-scoped: remove the top-level declaration and instead declare and
initialize let wasAccountProxyDisabled = false inside the twitterFetch function
so it resets on every call; update any references in the NSFW retry logic and in
the retry helper blocks (the code paths around the account-proxy disable/check
logic) to use the local variable, ensuring the per-request retry behavior is
independent across concurrent calls.
In `@src/providers/twitter/proxy/allowlist.ts`:
- Around line 47-49: The current branch decision uses apiUrl.includes('graphql')
which can match query strings or hostnames; change it to inspect the parsed URL
pathname segments instead (e.g., use url.pathname or split url.pathname by '/'
and check segments) when deciding the GraphQL branch for the logic around apiUrl
and url.pathname; ensure both occurrences (the block checking
ALLOWLIST_GRAPHQL_QUERY and the similar block at lines ~60-62) use the pathname
check and then compare the last segment (query) against ALLOWLIST_GRAPHQL_QUERY
so only real path components trigger the GraphQL allowlist branch.
- Line 54: The allowlist check using ALLOWLIST_PATH.some(endpoint =>
endpointPath.startsWith(endpoint)) is too permissive and allows lookalike paths;
change the matching logic in allowlist.ts to only allow exact matches or matches
at a segment boundary (e.g., endpoint === endpointPath OR endpointPath
startsWith endpoint + '/' ), or implement a boundary-safe regex using
^(endpoint)(/|$) so lookalike suffixes are rejected; update the code that
computes the boolean (the some callback referencing ALLOWLIST_PATH and
endpointPath) accordingly and normalize trailing slashes before comparison if
necessary.
In `@src/providers/twitter/proxy/cookies.ts`:
- Around line 5-7: The cookie parsing currently uses const [name, value] =
cookie.trim().split('=') which drops any '=' characters in the cookie value;
update the logic that builds map from cookies so the name is the substring
before the first '=' and the value is the rest of the string after that first
'=' (preserving any additional '=' characters). Locate the parsing snippet that
references cookie, map, and the split expression and replace it with logic that
finds the first '=' (e.g., indexOf) and uses substring (or joins split.slice(1))
to assign name and the full value, handling missing '=' by treating value as an
empty string before assigning map[name] = value.
In `@src/providers/twitter/proxy/credentials.ts`:
- Around line 36-55: The current initOnce async IIFE can settle as a rejected
promise and never be retried; modify the initialization closure (the async
function assigned to initOnce) to catch any errors during decryption/JSON
parsing and reset initOnce = undefined before rethrowing the error so subsequent
calls can retry; specifically wrap the body that imports the crypto key/decrypts
and sets credentialStore (references: initOnce, credentialKey, CREDENTIALS_IV,
ENCRYPTED_CREDENTIALS, credentialStore) in a try/catch and in the catch set
initOnce = undefined then throw the caught error.
In `@src/providers/twitter/proxy/discord.ts`:
- Around line 44-50: Remove the sensitive payload logging and instead log
delivery status: stop calling console.log('body', body) and do not serialize or
print the `body` variable; after calling fetch to
`env.EXCEPTION_DISCORD_WEBHOOK` capture the result in `discordResponse` and log
only non-sensitive delivery info such as `discordResponse.status` or
`discordResponse.ok` (and, on error or non-2xx response, optionally log
`discordResponse.text()` for debugging), and ensure the catch handler logs the
error but never the original `body`.
In `@src/providers/twitter/proxy/filter.ts`:
- Around line 4-36: filterObject currently uses string.includes(filter) which
overmatches substrings and causes unrelated fields to be redacted; update filter
logic in filterObject to match the proxy username as a whole token rather than
any substring: replace includes(filter) checks with a safe whole-word/username
match (use an escaped RegExp built from filter with word-boundaries or check
equality against tokens and consider both plain and '@' prefixed variants),
apply this when testing string values (the checks that currently read typeof v
=== 'string' && v.includes(filter) and typeof obj === 'string' &&
obj.includes(filter)), and keep the rest of the traversal (originalKeys, result)
unchanged so only true username occurrences cause removal.
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 82-98: The handler currently decodes rawBody and then proceeds to
JSON.parse(decodedBody) (inside the try where json = JSON.parse(decodedBody)),
which causes non-JSON passthrough bodies (e.g., live_video_stream) to hit the
JSON validation and "No data was sent" heuristic before the passthrough branch
runs; move the passthrough handling logic so it executes immediately after
rawBody is computed (after const rawBody = textDecoder.decode(...)) and before
any JSON.parse or error-classification logic (so check the passthrough condition
using rawBody/decodedBody and return/send the passthrough response early),
ensuring the JSON.parse, classifyAPIErrors, and retry/synthetic 502 path are
only reached for intended JSON responses (apply same change for the other
occurrence around the JSON.parse block referenced in the diff).
- Around line 11-12: Change the default so proxy account usernames are redacted:
set the redactUsername flag default to true (replace const redactUsername =
false with true) and allow explicit cleartext via an opt-in debug flag (e.g.,
process.env.DEBUG_PROXY_USER or a passed-in option checked where redactUsername
is used). Update every logging/webhook emission that currently interpolates the
username (references to redactUsername and the logger/webhook calls around lines
noted) to use a small helper like redactUsernameValue(username, redactUsername)
that returns a masked string unless debug is enabled; ensure the same behavior
is applied to the webhook payload construction and any alert/log lines (the
other occurrences you flagged) so usernames are only included when the debug
override is present.
- Around line 30-37: The request.body stream is one-shot and is consumed by the
first fetch; buffer it once before entering the retry loop and attach
independent copies per attempt: read the original Request body into a durable
buffer (e.g., await request.arrayBuffer() or await
request.clone().arrayBuffer()), store it in a variable (e.g., bodyBuffer), then
remove direct use of request.body in newRequestInit and instead set
newRequestInit.body for each fetch attempt to a fresh copy derived from
bodyBuffer (e.g., new Uint8Array(bodyBuffer) or bodyBuffer.slice(0)); handle the
case where request.body is null/undefined and preserve headers like Content-Type
when reconstructing the per-attempt RequestInit (referencing newRequestInit,
request, and the retry loop around fetch).
In `@src/providers/twitter/proxy/transaction/cubic.ts`:
- Around line 25-33: The binary-search loop using while (start < end) with start
= mid / end = mid can livelock due to floating-point rounding; update the loop
that calls Cubic.calculate(this.curves[0], this.curves[2], mid) and returns
Cubic.calculate(this.curves[1], this.curves[3], mid) to exit when the interval
is sufficiently small or after a max number of iterations: change the condition
to loop while (end - start) > EPSILON (choose e.g. 1e-12) and/or add a
maxIterations counter (e.g. 50-100) that breaks the loop, and keep comparing
Math.abs(time - xEst) < TOL before returning; ensure you reference the same
start, end, mid variables and preserve the existing return behavior when the
tolerance hit.
In `@src/providers/twitter/proxy/transaction/utils.ts`:
- Around line 20-45: floatToHex currently drops the "0" and any negative sign
(floatToHex(0) returns '' and negatives lose '-'), so update floatToHex to
preserve sign and return "0" for zero: at the start, capture sign = xInput < 0 ?
'-' : '' and work with x = Math.abs(xInput); if x === 0 return '0'; after the
integer conversion loop, if result is empty push '0' before handling the
fractional part; at the end, return sign + result.join(''); this will ensure
convertRotationToMatrix() negative outputs and zero values are encoded
correctly.
In `@tools/add_csrf.mjs`:
- Around line 42-44: The getCsrfToken() logic currently returns an empty string
when no ct0 value is found and callers persist that, overwriting valid tokens;
change getCsrfToken() to return null (or throw) instead of '' when set-cookie is
missing or ct0 not matched (the code using setCookie and the /ct0=(.*?);/
regex), and update the callers that currently assign the result (the code around
lines 56-64 that similarly parses ct0) to check for null/throw and preserve the
existing token or fail fast rather than overwriting with an empty string.
In `@tools/change_country.ts`:
- Around line 148-180: The loop over accounts currently only calls sleep inside
the catch path, so successful iterations run back-to-back and trigger rate
limits; after each account is processed (after the getSettings/setCountry flow
inside the for loop, e.g., after the console.log confirming updated.country_code
or after processing when no change was needed), insert an await sleep(...) pause
(use the same sleep function already used in the catch) — consider a small fixed
delay (e.g., 2000 ms) or a randomized delay to better pace requests; keep
existing 429 handling as-is and do not change
clientTransaction.generateTransactionId, getSettings, or setCountry logic.
In `@tools/credential-tools.mjs`:
- Around line 48-55: The code writes the generated key with default permissions
and prints it to stdout; change the writeFileSync(KEY_PATH, ...) call to create
the file with mode 0o600 (e.g., pass an options object { encoding: 'utf-8',
mode: 0o600 }) so only the owner can read/write, and remove or gate the
console.log lines that echo the key (keyB64url) behind an explicit
--show-key/confirm flag; refer to rawKey, keyB64url, KEY_PATH, and writeFileSync
to locate and update the implementation.
In `@tools/stripcredentials.mjs`:
- Around line 31-35: When building stripped from accounts (the accounts.map
block that creates const stripped), validate each cred object before emitting:
ensure cred.username, cred.authToken and cred.csrfToken exist and are strings
(or non-empty as required), and either filter out malformed entries or throw/log
a clear error that includes which account index or identifier is bad; implement
the check before mapping (e.g., filter or an early validation loop) so stripping
never produces malformed credentials and failures are surfaced immediately.
---
Nitpick comments:
In `@vitest.config.mts`:
- Line 10: Add a new Vitest test profile in vitest.config.mts that enables
Miniflare with proxy credentials so account-proxy paths are exercised;
specifically add a profile (e.g., name "proxy-enabled" or "with-credentials")
that sets miniflare to a config object including a mock CREDENTIAL_KEY binding
(or test credential globals) instead of an empty object, and ensure tests
intended to exercise account-proxy behavior run under this profile; update any
references to miniflare: {} to include this new profile so proxy code paths are
covered during CI/local test runs.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: d4282f78-8629-4d61-b2ac-38eadc1aded7
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (29)
.github/workflows/deploy.yml.gitignorecredentials.example.jsonesbuild.config.mjspackage.jsonsrc/experiments.tssrc/providers/twitter/accountProxy.tssrc/providers/twitter/conversation.tssrc/providers/twitter/fetch.tssrc/providers/twitter/proxy/allowlist.tssrc/providers/twitter/proxy/cookies.tssrc/providers/twitter/proxy/credentials.tssrc/providers/twitter/proxy/discord.tssrc/providers/twitter/proxy/errors.tssrc/providers/twitter/proxy/filter.tssrc/providers/twitter/proxy/globals.d.tssrc/providers/twitter/proxy/handler.tssrc/providers/twitter/proxy/transaction/cubic.tssrc/providers/twitter/proxy/transaction/transaction.tssrc/providers/twitter/proxy/transaction/utils.tssrc/providers/twitter/proxy/types.tssrc/worker.tstest/helpers/harness.tstools/add_csrf.mjstools/change_country.tstools/credential-tools.mjstools/stripcredentials.mjsvitest.config.mtswrangler.example.toml
| const rawKey = randomBytes(32); | ||
| keyB64url = rawKey.toString('base64url'); | ||
| writeFileSync(KEY_PATH, keyB64url + '\n', 'utf-8'); | ||
| console.log('\nNew encryption key written to .credential-key'); | ||
| console.log('Set Worker secret: wrangler secret put CREDENTIAL_KEY'); | ||
| console.log('Paste this value (base64url, one line):\n'); | ||
| console.log(keyB64url); | ||
| console.log(''); |
There was a problem hiding this comment.
Write .credential-key with restricted permissions.
The decryption key is currently written with the process default mode, which can leave it readable by other users on shared machines. Since this key unlocks every proxied account, create the file as 0600 and avoid echoing it unless the operator explicitly asks for it.
Proposed hardening
- writeFileSync(KEY_PATH, keyB64url + '\n', 'utf-8');
+ writeFileSync(KEY_PATH, keyB64url + '\n', { encoding: 'utf-8', mode: 0o600 });📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const rawKey = randomBytes(32); | |
| keyB64url = rawKey.toString('base64url'); | |
| writeFileSync(KEY_PATH, keyB64url + '\n', 'utf-8'); | |
| console.log('\nNew encryption key written to .credential-key'); | |
| console.log('Set Worker secret: wrangler secret put CREDENTIAL_KEY'); | |
| console.log('Paste this value (base64url, one line):\n'); | |
| console.log(keyB64url); | |
| console.log(''); | |
| const rawKey = randomBytes(32); | |
| keyB64url = rawKey.toString('base64url'); | |
| writeFileSync(KEY_PATH, keyB64url + '\n', { encoding: 'utf-8', mode: 0o600 }); | |
| console.log('\nNew encryption key written to .credential-key'); | |
| console.log('Set Worker secret: wrangler secret put CREDENTIAL_KEY'); | |
| console.log('Paste this value (base64url, one line):\n'); | |
| console.log(keyB64url); | |
| console.log(''); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tools/credential-tools.mjs` around lines 48 - 55, The code writes the
generated key with default permissions and prints it to stdout; change the
writeFileSync(KEY_PATH, ...) call to create the file with mode 0o600 (e.g., pass
an options object { encoding: 'utf-8', mode: 0o600 }) so only the owner can
read/write, and remove or gate the console.log lines that echo the key
(keyB64url) behind an explicit --show-key/confirm flag; refer to rawKey,
keyB64url, KEY_PATH, and writeFileSync to locate and update the implementation.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 163-165: The vaporization branch currently calls
JSON.parse(decodedBody) again inside the rawBody.includes(username) check,
risking an unguarded parse error that can abort retries; update the logic so you
only filter and re-stringify the already-successfully-parsed object (use the
parsed variable from the guarded JSON.parse path) or first attempt a safe
JSON.parse and only then call filterObject and assign decodedBody =
JSON.stringify(filtered) (preserve use of rawBody, decodedBody, username, and
filterObject identifiers), i.e., move the vaporization step into the
successful-parse path or add a isParsed/object truth check before calling
JSON.parse(decodedBody) again.
- Around line 71-104: The code currently lets exceptions from
getRandomTwitterAccount() and fetch(newRequest) escape the retry loop; wrap the
account selection and the entire fetch flow in a try/catch inside the do/while
so credential-store errors and transport failures are caught, set errors = true
(or increment attempts) and continue to the next iteration to trigger account
rotation/retry; specifically wrap calls to getRandomTwitterAccount(),
ClientTransaction.create()/transaction.generateTransactionId(), and await
fetch(newRequest) in a single try block, handle errors in the catch by logging
the error, cleaning/setting any headers as needed, marking errors=true (or
updating attempts) and continue so the existing 502/retry logic executes and
only rethrow after attempts are exhausted.
- Around line 85-98: The x-client-transaction-id header is being reused across
retry attempts and GET is hardcoded; before calling
needsTransactionId(requestPath) handling, remove any existing
'x-client-transaction-id' from headers, then inside the needsTransactionId
branch clear the header immediately before the try, call
ClientTransaction.create(attempts > 1) and pass request.method (not the string
'GET') into transaction.generateTransactionId(request.method, requestPath), and
ensure that on any failure you do not leave a stale header (remove it in the
catch) before assigning newRequestInit.headers.
In `@src/providers/twitter/proxy/transaction/transaction.ts`:
- Line 112: The shared regex INDICES_REGEX has the global flag and its lastIndex
advances across uses; inside getIndices() reset INDICES_REGEX.lastIndex = 0
before starting the exec()/scan loop so each call (including retries via
ClientTransaction.create()) scans from the start of the string, preserving
correct matches; update getIndices() to set INDICES_REGEX.lastIndex = 0
immediately before the while/for that calls INDICES_REGEX.exec().
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 1ae78fc5-7e6e-45e4-9bfa-929049aa6821
📒 Files selected for processing (3)
src/providers/twitter/proxy/errors.tssrc/providers/twitter/proxy/handler.tssrc/providers/twitter/proxy/transaction/transaction.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/providers/twitter/proxy/errors.ts
| do { | ||
| errors = false; | ||
| const { authToken, csrfToken, username } = getRandomTwitterAccount(); | ||
| let newCookies = `auth_token=${authToken}`; | ||
| if (apiUrl.includes('graphql')) { | ||
| existingCookies = existingCookies?.replace(/ct0=(.+?);/, '') || ''; | ||
| newCookies = `auth_token=${authToken}; ct0=${csrfToken}; `; | ||
| headers.set('x-csrf-token', csrfToken); | ||
| } | ||
| const cookies = mergeCookies(existingCookies?.toString(), newCookies); | ||
|
|
||
| headers.set('Cookie', cookies); | ||
| headers.delete('Accept-Encoding'); | ||
|
|
||
| if (needsTransactionId(apiUrl)) { | ||
| try { | ||
| const transaction = await ClientTransaction.create(attempts > 1).catch(err => { | ||
| throw err; | ||
| }); | ||
| const transactionId = await transaction.generateTransactionId('GET', requestPath); | ||
| console.log('Generated transaction ID:', transactionId); | ||
| headers.set('x-client-transaction-id', transactionId); | ||
| } catch (e) { | ||
| console.log('Error generating transaction ID:', e); | ||
| } | ||
| } | ||
|
|
||
| newRequestInit.headers = headers; | ||
|
|
||
| const newRequest = new Request(apiUrl, newRequestInit); | ||
| const startTime = performance.now(); | ||
| response = await fetch(newRequest); | ||
| const endTime = performance.now(); | ||
| console.log(`Fetch completed in ${endTime - startTime}ms`); |
There was a problem hiding this comment.
Catch setup/transport failures inside the retry loop.
getRandomTwitterAccount() throws when the credential store is empty (src/providers/twitter/proxy/credentials.ts:58-65), and fetch(newRequest) can reject too. Both happen before the JSON try/catch, so the handler skips the retry/502 path and fails the whole request with an uncaught exception instead of rotating accounts or exhausting attempts.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/providers/twitter/proxy/handler.ts` around lines 71 - 104, The code
currently lets exceptions from getRandomTwitterAccount() and fetch(newRequest)
escape the retry loop; wrap the account selection and the entire fetch flow in a
try/catch inside the do/while so credential-store errors and transport failures
are caught, set errors = true (or increment attempts) and continue to the next
iteration to trigger account rotation/retry; specifically wrap calls to
getRandomTwitterAccount(),
ClientTransaction.create()/transaction.generateTransactionId(), and await
fetch(newRequest) in a single try block, handle errors in the catch by logging
the error, cleaning/setting any headers as needed, marking errors=true (or
updating attempts) and continue so the existing 502/retry logic executes and
only rethrow after attempts are exhausted.
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (6)
src/providers/twitter/proxy/handler.ts (5)
50-57:⚠️ Potential issue | 🟠 MajorRetries will reuse an exhausted request body.
request.bodyis a one-shot stream. After the firstfetch(newRequest), later attempts of requests with a body will send an empty payload or fail. Buffer once before the loop and attach a fresh copy per attempt.Proposed fix
+ const bufferedBody = + request.method === 'GET' || request.method === 'HEAD' + ? undefined + : await request.clone().arrayBuffer(); + const newRequestInit: RequestInit = { method: request.method, headers, - body: request.body, + body: bufferedBody, redirect: request.redirect, integrity: request.integrity, signal: request.signal }; @@ - const newRequest = new Request(apiUrl, newRequestInit); + const newRequest = new Request(apiUrl, { + ...newRequestInit, + body: bufferedBody ? bufferedBody.slice(0) : undefined + });In the Fetch API, is `Request.body` a one-shot `ReadableStream` that cannot be reused across multiple `fetch()` calls, and what is the recommended retry pattern for requests with a body?Also applies to: 96-98
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 50 - 57, The retry loop currently reuses request.body (a one-shot ReadableStream) via newRequestInit, causing empty bodies on retries; change the code to read/buffer the body once before the retry loop (e.g., into an ArrayBuffer/Uint8Array or string) and then for each retry create newRequestInit with a fresh copy of that buffered payload (assigning a fresh ReadableStream or the buffered bytes) instead of reusing request.body; update all places that build newRequestInit (including the block using newRequestInit and the similar block around lines referencing 96-98) so every fetch attempt gets its own fresh body instance.
67-69:⚠️ Potential issue | 🟠 MajorKeep setup and transport failures inside the retry path.
getRandomTwitterAccount()andfetch(newRequest)still throw before the guarded JSON block, so the handler skips account rotation and the synthetic 502 entirely. Wrap the whole attempt body in an outertry/catchand count that attempt before continuing.Also applies to: 96-99
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 67 - 69, The retry loop currently only catches JSON parsing errors, so calls like getRandomTwitterAccount() and fetch(newRequest) can throw and bypass account rotation/synthetic 502; wrap the entire per-attempt body (the code between do { ... } while and the JSON guard) in an outer try/catch so any exception from getRandomTwitterAccount(), fetch(newRequest), etc. is caught, increment the attempt counter and set errors=true or perform account rotation/synthetic 502 logic before continuing; specifically update the handler in handler.ts to enclose the whole attempt in try/catch around the block that uses getRandomTwitterAccount() and fetch(newRequest) and ensure the catch triggers the same retry bookkeeping as the existing guarded JSON catch (so retries, account rotation, and synthetic 502 behavior remain consistent).
81-91:⚠️ Potential issue | 🟠 MajorRebuild
x-client-transaction-idon every attempt.
headersis reused across retries, so a transaction ID from a previous attempt can survive when generation later fails. This block also hashes'GET'for every request. Clear the header before each attempt and passrequest.methodintogenerateTransactionId().Proposed fix
+ headers.delete('x-client-transaction-id'); if (needsTransactionId(apiUrl)) { try { - const transaction = await ClientTransaction.create(attempts > 1).catch(err => { - throw err; - }); - const transactionId = await transaction.generateTransactionId('GET', requestPath); + const transaction = await ClientTransaction.create(attempts > 1); + const transactionId = await transaction.generateTransactionId(request.method, requestPath); console.log('Generated transaction ID:', transactionId); headers.set('x-client-transaction-id', transactionId); } catch (e) { + headers.delete('x-client-transaction-id'); console.log('Error generating transaction ID:', e); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 81 - 91, The x-client-transaction-id header is being reused across retries and the code always hashes the literal 'GET'; before each attempt (inside the needsTransactionId(...) block) explicitly remove/clear headers.set('x-client-transaction-id', undefined) or headers.delete('x-client-transaction-id') so a stale ID cannot survive, then call ClientTransaction.create(...) and invoke transaction.generateTransactionId(request.method, requestPath) (use request.method instead of 'GET') and set the header only on success; keep the try/catch around ClientTransaction.create and generateTransactionId to avoid leaving a header from prior attempts.
102-103:⚠️ Potential issue | 🟠 MajorShort-circuit raw passthroughs before JSON processing.
live_video_streamcan still flow throughJSON.parse()andtwitterResponseLooksEmpty()before the raw passthrough branch, so a valid non-JSON body gets retried until the synthetic 502. Line 161 also reparsesdecodedBodyoutside the guarded parse path. Return passthrough bodies immediately afterrawBodyis read, and only filter the already-parsed JSON object.Also applies to: 111-166
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 102 - 103, The handler currently assigns rawBody and then sets decodedBody and continues into JSON.parse and twitterResponseLooksEmpty paths, which lets non-JSON passthroughs (e.g., bodies containing "live_video_stream") get retried; after assigning rawBody (variable rawBody) immediately detect the passthrough marker (e.g., "live_video_stream") and short-circuit by returning the raw response/passthrough before any JSON.parse or calls to twitterResponseLooksEmpty(), and ensure later code uses the already-parsed JSON object (parsedDecodedBody) instead of reparsing decodedBody; update the flow around decodedBody/rawBody and any later use sites so passthroughs are returned instantly and parsed JSON is reused.
10-10:⚠️ Potential issue | 🟠 MajorRedact proxy usernames by default.
Keeping
redactUsernamefalse still exposes the credential pool in logs, and Line 140 sends the raw username to Discord regardless of the flag. Apply one redaction helper before both log and webhook emission, and make cleartext an explicit debug opt-in.Also applies to: 114-115, 140-140
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` at line 10, Change the default of the redactUsername flag to true and ensure the redaction helper is applied to the username before any logging or webhook emission: update the const redactUsername to true, call the existing redaction helper (use the same helper used elsewhere in the file) right before every place usernames are logged and right before the webhook payload is composed/sent so raw usernames are never emitted, and add an explicit debug opt-in flag (e.g., DEBUG_SHOW_USERNAMES or showCleartextUsernames) that must be true to bypass redaction for debugging only; also ensure the code path that sends the username to Discord (the webhook emission) uses the redacted value unless the debug opt-in is enabled.src/providers/twitter/proxy/allowlist.ts (1)
6-8:⚠️ Potential issue | 🟠 MajorUse pathname segments for the GraphQL check.
apiUrl.includes('graphql')can match the query string, so a non-GraphQL endpoint can still enter the transaction-ID branch. Decide fromurl.pathnamesegments and derive the operation name from those same segments.Proposed fix
export function needsTransactionId(apiUrl: string): boolean { const url = new URL(apiUrl); + const parts = url.pathname.split('/').filter(Boolean); + const graphqlIndex = parts.indexOf('graphql'); - if (apiUrl.includes('graphql')) { - const query = url.pathname.split('/').pop(); - return TRANSACTION_ID_QUERIES.some(endpoint => endpoint === query); + if (graphqlIndex >= 0) { + const query = parts[graphqlIndex + 2]; + return TRANSACTION_ID_QUERIES.includes(query ?? ''); } return false; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/allowlist.ts` around lines 6 - 8, Replace the fragile apiUrl.includes('graphql') check with a check against the URL pathname segments: split url.pathname into segments, ensure one of the segments equals 'graphql' (so we only treat real graphQL routes), then derive the operation name from the same segments (e.g., the final segment) into the existing query variable and use TRANSACTION_ID_QUERIES.some(endpoint => endpoint === query) for the comparison; update the logic that currently uses apiUrl and url.pathname so all decisions come from the pathname segments to avoid matching query strings.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 69-75: The picked credential from getRandomTwitterAccount must be
validated before use: ensure authToken is a non-empty string and, when
apiUrl.includes('graphql'), csrfToken is also present; if validation fails
(authToken missing or csrfToken missing for graphql), skip this credential and
trigger the retry path (or throw to be caught by the existing retry loop)
instead of building cookies like `auth_token=undefined`; update the logic around
getRandomTwitterAccount, authToken, csrfToken, username, existingCookies and
headers to perform these checks, log a concise warning when skipping a malformed
record, and only set headers.set('x-csrf-token', csrfToken) and newCookies with
ct0 when csrfToken is valid.
- Around line 40-43: proxyTwitterRequest currently accepts arbitrary request.url
paths allowing an authenticated proxy; restrict it to a fixed allowlist of X API
endpoints by validating requestPath inside proxyTwitterRequest against known
endpoints used by twitterFetch (e.g., the same fixed paths built from
Constants.TWITTER_API_ROOT and the three internal call sites). If requestPath is
not in the allowlist, return a 403/400 response. Use the unique symbol
proxyTwitterRequest to implement the check and reference twitterFetch and
Constants.TWITTER_API_ROOT to derive or document the exact allowed paths so
future callers cannot supply user-controlled URLs.
In `@tools/stripcredentials.mjs`:
- Around line 24-29: The current presence/type check around the variable
accounts allows an empty array through and later causes runtime failures; update
the condition that currently reads if (!accounts) to explicitly reject empty
arrays (e.g., require Array.isArray(accounts) && accounts.length > 0) and, when
it fails, log a clear error (include that accounts must be a non-empty array)
and call process.exit(1) so the script fails fast; make the change where
accounts is validated in the stripcredentials logic.
- Around line 74-76: Replace the shallow copy of the entire raw payload with an
explicit allowlist when building out so unrelated sensitive fields in raw are
not carried into credentials.json; instead of const out = { ...raw }, construct
out = { twitter: { accounts: stripped }, <any other allowed keys> } (explicitly
list only the safe fields you want to keep), remove delete out.accounts, and
ensure the variable names out, raw, stripped and the twitter.accounts shape are
preserved so existing callers still work.
In `@wrangler.example.toml`:
- Line 12: Update the misleading comment in wrangler.example.toml to clearly
separate local dev vs production env var configuration: state that .env and
.dev.vars are only used by wrangler dev (local), and that production must set
sensitive values like CREDENTIAL_KEY and EXCEPTION_DISCORD_WEBHOOK via `wrangler
secret put` or non-sensitive values in the `[vars]` section of wrangler.toml;
also note the behavioral consequence (in-process proxy will be skipped and code
in src/providers/twitter/fetch.ts that falls back to direct X API calls will
execute if those production vars are missing).
---
Duplicate comments:
In `@src/providers/twitter/proxy/allowlist.ts`:
- Around line 6-8: Replace the fragile apiUrl.includes('graphql') check with a
check against the URL pathname segments: split url.pathname into segments,
ensure one of the segments equals 'graphql' (so we only treat real graphQL
routes), then derive the operation name from the same segments (e.g., the final
segment) into the existing query variable and use
TRANSACTION_ID_QUERIES.some(endpoint => endpoint === query) for the comparison;
update the logic that currently uses apiUrl and url.pathname so all decisions
come from the pathname segments to avoid matching query strings.
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 50-57: The retry loop currently reuses request.body (a one-shot
ReadableStream) via newRequestInit, causing empty bodies on retries; change the
code to read/buffer the body once before the retry loop (e.g., into an
ArrayBuffer/Uint8Array or string) and then for each retry create newRequestInit
with a fresh copy of that buffered payload (assigning a fresh ReadableStream or
the buffered bytes) instead of reusing request.body; update all places that
build newRequestInit (including the block using newRequestInit and the similar
block around lines referencing 96-98) so every fetch attempt gets its own fresh
body instance.
- Around line 67-69: The retry loop currently only catches JSON parsing errors,
so calls like getRandomTwitterAccount() and fetch(newRequest) can throw and
bypass account rotation/synthetic 502; wrap the entire per-attempt body (the
code between do { ... } while and the JSON guard) in an outer try/catch so any
exception from getRandomTwitterAccount(), fetch(newRequest), etc. is caught,
increment the attempt counter and set errors=true or perform account
rotation/synthetic 502 logic before continuing; specifically update the handler
in handler.ts to enclose the whole attempt in try/catch around the block that
uses getRandomTwitterAccount() and fetch(newRequest) and ensure the catch
triggers the same retry bookkeeping as the existing guarded JSON catch (so
retries, account rotation, and synthetic 502 behavior remain consistent).
- Around line 81-91: The x-client-transaction-id header is being reused across
retries and the code always hashes the literal 'GET'; before each attempt
(inside the needsTransactionId(...) block) explicitly remove/clear
headers.set('x-client-transaction-id', undefined) or
headers.delete('x-client-transaction-id') so a stale ID cannot survive, then
call ClientTransaction.create(...) and invoke
transaction.generateTransactionId(request.method, requestPath) (use
request.method instead of 'GET') and set the header only on success; keep the
try/catch around ClientTransaction.create and generateTransactionId to avoid
leaving a header from prior attempts.
- Around line 102-103: The handler currently assigns rawBody and then sets
decodedBody and continues into JSON.parse and twitterResponseLooksEmpty paths,
which lets non-JSON passthroughs (e.g., bodies containing "live_video_stream")
get retried; after assigning rawBody (variable rawBody) immediately detect the
passthrough marker (e.g., "live_video_stream") and short-circuit by returning
the raw response/passthrough before any JSON.parse or calls to
twitterResponseLooksEmpty(), and ensure later code uses the already-parsed JSON
object (parsedDecodedBody) instead of reparsing decodedBody; update the flow
around decodedBody/rawBody and any later use sites so passthroughs are returned
instantly and parsed JSON is reused.
- Line 10: Change the default of the redactUsername flag to true and ensure the
redaction helper is applied to the username before any logging or webhook
emission: update the const redactUsername to true, call the existing redaction
helper (use the same helper used elsewhere in the file) right before every place
usernames are logged and right before the webhook payload is composed/sent so
raw usernames are never emitted, and add an explicit debug opt-in flag (e.g.,
DEBUG_SHOW_USERNAMES or showCleartextUsernames) that must be true to bypass
redaction for debugging only; also ensure the code path that sends the username
to Discord (the webhook emission) uses the redacted value unless the debug
opt-in is enabled.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: b5f4af9f-5270-4082-93a5-a607f2d91d42
📒 Files selected for processing (5)
src/providers/twitter/proxy/allowlist.tssrc/providers/twitter/proxy/handler.tssrc/providers/twitter/proxy/transaction/utils.tstools/stripcredentials.mjswrangler.example.toml
🚧 Files skipped from review as they are similar to previous changes (1)
- src/providers/twitter/proxy/transaction/utils.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/providers/twitter/fetch.ts (2)
147-148: Inconsistent header mutation: should use spread copy like the in-process path.Line 147 assigns
headers2 = headers(reference), then mutates it at line 148. This modifies the originalheadersobject. Compare to line 163 which correctly uses{ ...headers }to create a copy. While this may not cause bugs in the current flow, it's inconsistent and could cause issues ifheadersis reused after a retry.Suggested fix for consistency
if (useElongator && typeof c.env?.TwitterProxy !== 'undefined') { const performanceStart = performance.now(); - const headers2 = headers; + const headers2 = { ...headers }; headers2['x-twitter-auth-type'] = 'OAuth2Session';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/fetch.ts` around lines 147 - 148, The code currently does a reference assignment const headers2 = headers and then mutates headers2['x-twitter-auth-type'] which also mutates the original headers object; change this to create a shallow copy (e.g., use the same pattern as on line 163 with { ...headers }) so headers2 is a new object before setting headers2['x-twitter-auth-type'] to 'OAuth2Session' — update the assignment for headers2 in src/providers/twitter/fetch.ts accordingly to avoid mutating the original headers during retries.
165-179:initCredentialscall is not covered by the timeout wrapper.On a cold isolate, the first call to
initCredentialsperforms AES-GCM decryption which could take non-trivial time. Since it's called beforewithTimeout, this operation isn't subject to the request timeout protection. Subsequent calls return immediately due to the idempotent caching.This is likely acceptable since crypto operations are typically fast, but worth noting for debugging slow cold starts.
If you want timeout coverage for the initial decryption, you could move the init inside the timeout:
} else if (useElongator && c.env?.CREDENTIAL_KEY) { const performanceStart = performance.now(); const headers2 = { ...headers }; headers2['x-twitter-auth-type'] = 'OAuth2Session'; - await initCredentials(c.env.CREDENTIAL_KEY); apiRequest = await withTimeout((signal: AbortSignal) => - proxyTwitterRequest( + initCredentials(c.env.CREDENTIAL_KEY).then(() => proxyTwitterRequest( new Request(url, { ... }), { ... } - ) + )) );Alternatively, keep as-is if the current behavior is acceptable.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/fetch.ts` around lines 165 - 179, initCredentials is invoked before withTimeout, so the initial AES‑GCM decryption on cold isolates isn't subject to the request timeout; move the initCredentials call inside the withTimeout callback so both initCredentials(...) and the subsequent proxyTwitterRequest(...) run under the same timeout/signal. Inside the withTimeout((signal: AbortSignal) => { ... }) callback, first await initCredentials(c.env.CREDENTIAL_KEY) and then call proxyTwitterRequest(new Request(..., { signal, ... }), { CREDENTIAL_KEY: c.env.CREDENTIAL_KEY, EXCEPTION_DISCORD_WEBHOOK: c.env.EXCEPTION_DISCORD_WEBHOOK }); ensure you preserve the existing method, headers2, body and error handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/providers/twitter/fetch.ts`:
- Around line 147-148: The code currently does a reference assignment const
headers2 = headers and then mutates headers2['x-twitter-auth-type'] which also
mutates the original headers object; change this to create a shallow copy (e.g.,
use the same pattern as on line 163 with { ...headers }) so headers2 is a new
object before setting headers2['x-twitter-auth-type'] to 'OAuth2Session' —
update the assignment for headers2 in src/providers/twitter/fetch.ts accordingly
to avoid mutating the original headers during retries.
- Around line 165-179: initCredentials is invoked before withTimeout, so the
initial AES‑GCM decryption on cold isolates isn't subject to the request
timeout; move the initCredentials call inside the withTimeout callback so both
initCredentials(...) and the subsequent proxyTwitterRequest(...) run under the
same timeout/signal. Inside the withTimeout((signal: AbortSignal) => { ... })
callback, first await initCredentials(c.env.CREDENTIAL_KEY) and then call
proxyTwitterRequest(new Request(..., { signal, ... }), { CREDENTIAL_KEY:
c.env.CREDENTIAL_KEY, EXCEPTION_DISCORD_WEBHOOK: c.env.EXCEPTION_DISCORD_WEBHOOK
}); ensure you preserve the existing method, headers2, body and error handling.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 56234732-341a-4c73-bea1-95a9fde1078b
📒 Files selected for processing (2)
.github/workflows/deploy.ymlsrc/providers/twitter/fetch.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- .github/workflows/deploy.yml
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/providers/twitter/proxy/handler.ts (1)
50-57:⚠️ Potential issue | 🟠 MajorBuffer the request body once before retrying.
newRequestInit.body = request.bodyreuses the original stream across attempts. After the firstfetch(newRequest), that body is consumed, so any retried non-GET request will no longer send the original payload.Is a Fetch API `Request.body` stream reusable across multiple `fetch()` attempts, or is it consumed after first use? Please cite the relevant `bodyUsed` / stream semantics from the Fetch standard or Cloudflare Workers docs.Also applies to: 99-101
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 50 - 57, The code assigns request.body directly into newRequestInit so the stream is consumed on first fetch and breaks retries; buffer the body once up-front (e.g., read request.arrayBuffer()/text()/json() or use Request.clone() to extract a reusable ArrayBuffer/Uint8Array) before building newRequestInit, then set newRequestInit.body to that buffered payload for all retry attempts (apply this change wherever newRequestInit.body = request.body appears, e.g., in the handler where newRequestInit and fetch(newRequest) are used) and ensure GET/HEAD requests keep no body.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/twitter/proxy/handler.ts`:
- Line 115: The retry logic increments attempts before checking success, causing
a successful 5th try to be treated as a failure; update the loop so that you
only evaluate the attempts > 4 synthetic-502 branch when the current response
actually failed (or increment attempts only on failure). Concretely, in the
retry block that uses the attempts variable (the branch that currently does
"attempts++; if (attempts > 4) return 502"), change the flow to: if response is
successful return it immediately; otherwise increment attempts and then if
(attempts > 4) return the synthetic 502; apply the exact same fix to the other
retry loop that also checks attempts > 4.
- Around line 142-144: Wrap the call to sendDiscordAlert (executed when
env.EXCEPTION_DISCORD_WEBHOOK && errors) in its own try/catch so any exception
it throws is caught and not propagated to the outer handler; in the catch block
log the alert failure (using the module's logger or console.error) including
context (username, requestPath, error) and do not rethrow so notification
failures are ignored instead of triggering a proxy retry.
---
Duplicate comments:
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 50-57: The code assigns request.body directly into newRequestInit
so the stream is consumed on first fetch and breaks retries; buffer the body
once up-front (e.g., read request.arrayBuffer()/text()/json() or use
Request.clone() to extract a reusable ArrayBuffer/Uint8Array) before building
newRequestInit, then set newRequestInit.body to that buffered payload for all
retry attempts (apply this change wherever newRequestInit.body = request.body
appears, e.g., in the handler where newRequestInit and fetch(newRequest) are
used) and ensure GET/HEAD requests keep no body.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 3b1eb418-ec7c-490c-b2ba-33cbf469f5c3
📒 Files selected for processing (2)
src/providers/twitter/proxy/handler.tstools/add_csrf.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
- tools/add_csrf.mjs
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
tools/add_csrf.mjs (1)
15-46:⚠️ Potential issue | 🟠 MajorFail fast when the ct0 refresh request itself fails.
401/403/5xxcurrently collapse into the samenullpath as “no ct0 found”, so Line 61 can silently keep a stalecsrfTokenand Line 69 still reports the account as activated. That masks expired or banned accounts instead of surfacing them.Proposed fix
async function getCsrfToken(account) { const response = await fetch( @@ } ); + + if (!response.ok) { + throw new Error(`Failed to refresh ct0 for @${account.username}: HTTP ${response.status}`); + } const setCookie = response.headers.get('set-cookie'); if (!setCookie) return null; const match = setCookie.match(/ct0=(.*?);/); const ct0 = match?.[1];🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tools/add_csrf.mjs` around lines 15 - 46, The code currently treats any fetch failure (401/403/5xx) the same as “no ct0 found” which hides auth issues; after the fetch (the response variable returned by the GET to TweetDetail) add a fail-fast check on response.ok (or response.status >= 400) and throw or return an explicit error containing response.status and optionally response.text() so callers can distinguish expired/banned accounts from “no ct0”; ensure this change is applied where you later read response.headers.get('set-cookie') / match ct0 so that setCookie/ct0 paths only run for successful responses.
🧹 Nitpick comments (3)
src/embed/activity.ts (1)
387-387: Avoid logging full decoded snowcode payload in the request path.Line 387 logs the entire decoded object, which broadens identifier exposure in logs (e.g., handle/status params). Prefer redacted/summarized fields only.
Proposed change
- console.log('snowcode params', JSON.stringify(decoded)); + console.log( + 'snowcode params', + JSON.stringify({ + hasLanguage: !!decoded.l, + hasAuthorHandle: !!decoded.h, + textOnly: !!decoded.t, + forceMosaic: !!decoded.m, + mediaNumber: decoded.n ?? null + }) + );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/embed/activity.ts` at line 387, The console.log('snowcode params', JSON.stringify(decoded)) call is exposing the full decoded snowcode payload; remove that full dump and instead log only required non-sensitive fields (e.g., decoded.id, decoded.status) or a single summarized/redacted string; implement or call a small sanitizer (e.g., redactSnowcode / sanitizeSnowcodePayload) to mask identifiers before logging, and switch to the app logger (e.g., processLogger.debug) instead of console.log to keep logging consistent. Ensure you update the code paths where variable decoded is used (in src/embed/activity.ts) so only sanitized data is emitted.src/providers/twitter/fetch.ts (1)
159-179: Consider consistent header handling between proxy paths.The CREDENTIAL_KEY path correctly creates a shallow copy of headers with
{ ...headers }(line 161), while the TwitterProxy path directly assignsheaders2 = headers(line 147), which mutates the originalheadersobject when settingx-twitter-auth-type.This inconsistency could cause subtle issues if the code is later modified to use
headersafter the TwitterProxy path. Consider aligning both paths:♻️ Suggested fix for consistent header handling
if (useElongator && typeof c.env?.TwitterProxy !== 'undefined') { const performanceStart = performance.now(); - const headers2 = headers; + const headers2 = { ...headers }; headers2['x-twitter-auth-type'] = 'OAuth2Session';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/fetch.ts` around lines 159 - 179, The branch that handles the CREDENTIAL_KEY path creates a shallow copy of headers before mutating it, but the TwitterProxy branch assigns headers2 = headers and mutates the original headers when adding 'x-twitter-auth-type', risking unintended side-effects; update the TwitterProxy path (the block that sets headers2 and calls proxyTwitterRequest/new Request) to create a shallow copy (e.g., headers2 = { ...headers }) before setting 'x-twitter-auth-type' so both proxy paths handle headers consistently and avoid mutating the original headers object.tools/add_csrf.mjs (1)
72-73: Write the credential store atomically.Overwriting the live file in place can leave
credentials.jsontruncated if the process dies during Line 73. A temp-file write plus rename is safer here.Proposed fix
- const next = { ...data, twitter: { accounts: updated } }; - fs.writeFileSync(credPath, JSON.stringify(next, null, 2) + '\n', 'utf8'); + const next = { ...data, twitter: { ...data.twitter, accounts: updated } }; + const tmpPath = `${credPath}.tmp`; + fs.writeFileSync(tmpPath, JSON.stringify(next, null, 2) + '\n', 'utf8'); + fs.renameSync(tmpPath, credPath);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tools/add_csrf.mjs` around lines 72 - 73, Replace the in-place write at fs.writeFileSync(credPath, ...) with an atomic write: serialize the updated object (the next variable that contains twitter.accounts updated) to a temporary file (e.g., credPath + '.tmp' or use a unique temp name), fs.writeFileSync the temp file, then fs.renameSync the temp file to credPath so the rename is atomic; ensure the temp write uses the same encoding and add a fs.fsync if desired before renaming to guarantee data is flushed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/user.ts`:
- Line 29: The console.log("flags", JSON.stringify(flags)) call leaks the entire
flags object; replace it with a safe, minimal log: either gate this output
behind a non-production debug flag (e.g., if (isDev) ...) or build an
allowlisted subset by extracting only specific keys from the flags variable
(e.g., const safeFlags = { flagA: flags.flagA, flagB: flags.flagB }) and log
that instead; update the call that currently uses console.log('flags',
JSON.stringify(flags)) to log only safeFlags (or use debug-only logging) so
sensitive/internal flag values are not written to logs.
In `@tools/add_csrf.mjs`:
- Around line 15-39: The fetch call that sets "const response = await
fetch(...)" in tools/add_csrf.mjs has no deadline; wrap it with an
AbortController (create controller before the fetch, pass controller.signal into
the fetch options) and start a timeout (e.g., 10s) that calls controller.abort()
on expiry, then ensure the timeout is cleared after the fetch completes (use
finally or try/catch/finally around the await fetch) so hung connections are
aborted and the timer is cleaned up.
---
Duplicate comments:
In `@tools/add_csrf.mjs`:
- Around line 15-46: The code currently treats any fetch failure (401/403/5xx)
the same as “no ct0 found” which hides auth issues; after the fetch (the
response variable returned by the GET to TweetDetail) add a fail-fast check on
response.ok (or response.status >= 400) and throw or return an explicit error
containing response.status and optionally response.text() so callers can
distinguish expired/banned accounts from “no ct0”; ensure this change is applied
where you later read response.headers.get('set-cookie') / match ct0 so that
setCookie/ct0 paths only run for successful responses.
---
Nitpick comments:
In `@src/embed/activity.ts`:
- Line 387: The console.log('snowcode params', JSON.stringify(decoded)) call is
exposing the full decoded snowcode payload; remove that full dump and instead
log only required non-sensitive fields (e.g., decoded.id, decoded.status) or a
single summarized/redacted string; implement or call a small sanitizer (e.g.,
redactSnowcode / sanitizeSnowcodePayload) to mask identifiers before logging,
and switch to the app logger (e.g., processLogger.debug) instead of console.log
to keep logging consistent. Ensure you update the code paths where variable
decoded is used (in src/embed/activity.ts) so only sanitized data is emitted.
In `@src/providers/twitter/fetch.ts`:
- Around line 159-179: The branch that handles the CREDENTIAL_KEY path creates a
shallow copy of headers before mutating it, but the TwitterProxy branch assigns
headers2 = headers and mutates the original headers when adding
'x-twitter-auth-type', risking unintended side-effects; update the TwitterProxy
path (the block that sets headers2 and calls proxyTwitterRequest/new Request) to
create a shallow copy (e.g., headers2 = { ...headers }) before setting
'x-twitter-auth-type' so both proxy paths handle headers consistently and avoid
mutating the original headers object.
In `@tools/add_csrf.mjs`:
- Around line 72-73: Replace the in-place write at fs.writeFileSync(credPath,
...) with an atomic write: serialize the updated object (the next variable that
contains twitter.accounts updated) to a temporary file (e.g., credPath + '.tmp'
or use a unique temp name), fs.writeFileSync the temp file, then fs.renameSync
the temp file to credPath so the rename is atomic; ensure the temp write uses
the same encoding and add a fs.fsync if desired before renaming to guarantee
data is flushed.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: f50ddd17-51c6-4a6d-b2a8-711c0b5c0530
📒 Files selected for processing (8)
src/embed/activity.tssrc/embed/status.tssrc/providers/twitter/fetch.tssrc/providers/twitter/proxy/handler.tssrc/user.tstools/add_csrf.mjstools/stripcredentials.mjswrangler.example.toml
✅ Files skipped from review due to trivial changes (3)
- src/embed/status.ts
- wrangler.example.toml
- tools/stripcredentials.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
- src/providers/twitter/proxy/handler.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/providers/twitter/proxy/handler.ts (1)
81-87: Remove redundant header delete and catch-rethrow pattern.Line 81 already deletes
x-client-transaction-idunconditionally, making the delete at line 83 redundant. Additionally, the.catch(err => { throw err; })at lines 85-87 adds no value—it catches and immediately re-throws.Suggested cleanup
headers.delete('x-client-transaction-id'); if (needsTransactionId(apiUrl)) { - headers.delete('x-client-transaction-id'); try { - const transaction = await ClientTransaction.create(attempts > 1).catch(err => { - throw err; - }); + const transaction = await ClientTransaction.create(attempts > 1); const transactionId = await transaction.generateTransactionId(request.method, requestPath); console.log('Generated transaction ID:', transactionId); headers.set('x-client-transaction-id', transactionId); } catch (e) { - headers.delete('x-client-transaction-id'); console.log('Error generating transaction ID:', e); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 81 - 87, Remove the redundant headers.delete('x-client-transaction-id') (already called before the needsTransactionId check) and simplify the ClientTransaction creation by removing the useless .catch(err => { throw err; }) wrapper; instead just await ClientTransaction.create(attempts > 1) inside the needsTransactionId branch so errors propagate naturally. Ensure you keep the needsTransactionId(apiUrl) check, the attempts usage, and the transaction variable name as in the current handler.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 81-87: Remove the redundant
headers.delete('x-client-transaction-id') (already called before the
needsTransactionId check) and simplify the ClientTransaction creation by
removing the useless .catch(err => { throw err; }) wrapper; instead just await
ClientTransaction.create(attempts > 1) inside the needsTransactionId branch so
errors propagate naturally. Ensure you keep the needsTransactionId(apiUrl)
check, the attempts usage, and the transaction variable name as in the current
handler.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 3b39900d-f597-41e2-814c-4ec92560c6b4
📒 Files selected for processing (4)
src/providers/twitter/conversation.tssrc/providers/twitter/proxy/credentials.tssrc/providers/twitter/proxy/handler.tssrc/realms/twitter/routes/status.ts
💤 Files with no reviewable changes (1)
- src/realms/twitter/routes/status.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/providers/twitter/conversation.ts
- src/providers/twitter/proxy/credentials.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/providers/twitter/proxy/handler.ts (1)
81-95: Remove redundant code in transaction ID handling.
- Line 83
headers.delete('x-client-transaction-id')is redundant since line 81 already deletes it- Lines 85-87:
.catch(err => { throw err })is a no-op that just re-throwsProposed cleanup
headers.delete('x-client-transaction-id'); if (needsTransactionId(apiUrl)) { - headers.delete('x-client-transaction-id'); try { - const transaction = await ClientTransaction.create(attempts > 1).catch(err => { - throw err; - }); + const transaction = await ClientTransaction.create(attempts > 1); const transactionId = await transaction.generateTransactionId(request.method, requestPath);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 81 - 95, Remove the redundant and noop operations around transaction-id handling: delete the duplicate headers.delete('x-client-transaction-id') (keep only the first call before the needsTransactionId check), and remove the unnecessary .catch(err => { throw err }) on ClientTransaction.create; instead await ClientTransaction.create(attempts > 1) directly inside the try block, then call transaction.generateTransactionId(request.method, requestPath) and set the header; keep the surrounding try/catch that logs and deletes the header on error.src/providers/twitter/proxy/credentials.ts (1)
6-24: Consider extracting shared base64 decoding logic.
base64UrlToBytesandbase64ToBytesshare identical conversion logic (lines 9-14 and 18-23). You could extract the shared part:function binaryStringToBytes(binary: string): Uint8Array { const out = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { out[i] = binary.charCodeAt(i); } return out; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/credentials.ts` around lines 6 - 24, base64UrlToBytes and base64ToBytes duplicate the logic that converts an atob-produced binary string into a Uint8Array; extract that shared logic into a helper like binaryStringToBytes(binary: string): Uint8Array and have both base64UrlToBytes and base64ToBytes call it (keep the URL-specific padding/replacement in base64UrlToBytes and only call atob once per function), removing the duplicated for-loop from both functions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/providers/twitter/proxy/credentials.ts`:
- Around line 6-24: base64UrlToBytes and base64ToBytes duplicate the logic that
converts an atob-produced binary string into a Uint8Array; extract that shared
logic into a helper like binaryStringToBytes(binary: string): Uint8Array and
have both base64UrlToBytes and base64ToBytes call it (keep the URL-specific
padding/replacement in base64UrlToBytes and only call atob once per function),
removing the duplicated for-loop from both functions.
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 81-95: Remove the redundant and noop operations around
transaction-id handling: delete the duplicate
headers.delete('x-client-transaction-id') (keep only the first call before the
needsTransactionId check), and remove the unnecessary .catch(err => { throw err
}) on ClientTransaction.create; instead await ClientTransaction.create(attempts
> 1) directly inside the try block, then call
transaction.generateTransactionId(request.method, requestPath) and set the
header; keep the surrounding try/catch that logs and deletes the header on
error.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 81c837b4-0eb4-4671-92e1-99c2912fe625
📒 Files selected for processing (2)
src/providers/twitter/proxy/credentials.tssrc/providers/twitter/proxy/handler.ts
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (4)
tools/credential-tools.mjs (1)
50-55:⚠️ Potential issue | 🟠 MajorHarden key handling (file perms + stdout secret leak).
Line 50 writes
.credential-keywith default permissions, and Lines 51-55 print the raw decryption key. This can leak the master key on shared machines/CI logs.Proposed hardening
- writeFileSync(KEY_PATH, keyB64url + '\n', 'utf-8'); + writeFileSync(KEY_PATH, keyB64url + '\n', { encoding: 'utf-8', mode: 0o600 }); console.log('\nNew encryption key written to .credential-key'); console.log('Set Worker secret: wrangler secret put CREDENTIAL_KEY'); - console.log('Paste this value (base64url, one line):\n'); - console.log(keyB64url); - console.log(''); + console.log('Read the key from .credential-key and store it securely.');🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tools/credential-tools.mjs` around lines 50 - 55, The script currently writes the raw key with writeFileSync(KEY_PATH, ...) using default perms and prints keyB64url to stdout, risking key leakage; change the file write to set restrictive permissions (mode 0o600/0600) when creating KEY_PATH (use the writeFileSync options or a separate chmod) and remove any console.log that prints keyB64url; instead print only guidance (e.g., that the key was written and how to set the wrangler secret) or, if needed, output the key to a secure channel, but do not emit keyB64url to stdout. Ensure references: writeFileSync, KEY_PATH, keyB64url, and all console.log lines that currently print the key are updated.src/providers/twitter/proxy/handler.ts (3)
120-195:⚠️ Potential issue | 🟠 MajorPassthrough endpoints are still being validated as JSON first.
Lines 193-195 restore raw bodies for
translation.jsonandlive_video_stream, but only afterJSON.parse(...),classifyAPIErrors(...), andtwitterResponseLooksEmpty(...)have already run. A valid non-JSON passthrough response will still churn through the retry path before this branch executes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 120 - 195, The passthrough paths for translation.json and live_video_stream are being handled too late — code currently attempts JSON.parse, classifyAPIErrors, and twitterResponseLooksEmpty before falling back to rawBody; move the early-exit/restore logic so that when apiUrl.includes('translation.json') || apiUrl.includes('live_video_stream') is true you set decodedBody = rawBody and skip the JSON parsing/validation/retry logic (i.e., perform this check before calling JSON.parse(decodedBody), jsonHasTruthyErrorsProperty, classifyAPIErrors, and twitterResponseLooksEmpty in handler.ts).
67-69:⚠️ Potential issue | 🟠 MajorSetup and transport failures still bypass the retry loop.
getRandomTwitterAccount()at Line 69,ClientTransaction.create(...),new Request(...), andfetch(...)still run before the guarded JSON-processing block. If any of those throws, the handler exits immediately instead of rotating accounts and falling back to the synthetic 502 after retries are exhausted.Also applies to: 93-116
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 67 - 69, The retry loop currently lets exceptions from getRandomTwitterAccount(), ClientTransaction.create(...), new Request(...), and fetch(...) escape and abort retries; move those calls inside a try/catch that sets errors = true and continues the do/while so the handler rotates accounts and eventually returns the synthetic 502 after retries; specifically wrap the getRandomTwitterAccount() call and the subsequent ClientTransaction.create, Request construction, and fetch invocation in a single try block (inside the existing do loop) and in the catch set errors = true (and capture/log the exception) then continue to the next iteration so only the guarded JSON-processing block determines success/failure.
50-57:⚠️ Potential issue | 🟠 MajorRetries still reuse a one-shot request body.
Lines 50-57 store
request.bodydirectly innewRequestInit, then Line 114 rebuilds a newRequestfrom that same stream on every attempt. After the firstfetch, any non-GET retry will be sent with an exhausted body or fail during request construction.Suggested fix
const headers = new Headers(request.headers); headers.delete('x-guest-token'); let existingCookies = request.headers.get('Cookie'); + const bufferedBody = + request.method === 'GET' || request.method === 'HEAD' + ? undefined + : await request.clone().arrayBuffer(); const newRequestInit: RequestInit = { method: request.method, headers, - body: request.body, + body: undefined, redirect: request.redirect, integrity: request.integrity, signal: request.signal }; @@ - const newRequest = new Request(apiUrl, newRequestInit); + const newRequest = new Request(apiUrl, { + ...newRequestInit, + body: bufferedBody ? bufferedBody.slice(0) : undefined + });Also applies to: 114-116
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/providers/twitter/proxy/handler.ts` around lines 50 - 57, The retry code reuses the original request.body stream (stored in newRequestInit) so subsequent fetch attempts fail because the body is already consumed; change the handler to eagerly read and buffer the request body once (e.g., into an ArrayBuffer/Uint8Array or string) when creating newRequestInit (or detect GET/HEAD and leave body null), then for each retry reconstruct the Request using that buffered body instead of request.body; also avoid reusing the original request.signal across attempts by creating a fresh AbortController/signal per attempt when building the Request so retries have a fresh cancellable signal.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/providers/twitter/proxy/transaction/transaction.ts`:
- Around line 79-97: The code assumes form.action is absolute; instead resolve
the action against the current page base so relative actions like "/x/migrate"
become absolute. After you read the form (variable form) compute a base URL (use
the page/response URL available in scope, e.g. resp.url or the original request
URL) and replace actionUrl assignment with something like actionUrl = new
URL((form.attr('action') || '/x/migrate'), base).toString(); then use that
resolved actionUrl for building the GET query and for cachedFetch (and when
method === 'POST' build body from inputs as before). Ensure all places that use
actionUrl (the GET branch where you append URLSearchParams and the cachedFetch
call) use the resolved absolute URL.
In `@tools/credential-tools.mjs`:
- Around line 35-37: Wrap the JSON.parse call so malformed JSON in the
credentials file is handled explicitly: surround reading/parsing
(readFileSync(PLAINTEXT_PATH) and JSON.parse(...)) with a try/catch, and on
catch emit a clear controlled error (including PLAINTEXT_PATH) via your CLI
logger/console.error and exit with a non‑zero code (e.g., process.exit(1));
ensure the subsequent check that uses parsed/twitter/accounts only runs when
parsing succeeded.
---
Duplicate comments:
In `@src/providers/twitter/proxy/handler.ts`:
- Around line 120-195: The passthrough paths for translation.json and
live_video_stream are being handled too late — code currently attempts
JSON.parse, classifyAPIErrors, and twitterResponseLooksEmpty before falling back
to rawBody; move the early-exit/restore logic so that when
apiUrl.includes('translation.json') || apiUrl.includes('live_video_stream') is
true you set decodedBody = rawBody and skip the JSON parsing/validation/retry
logic (i.e., perform this check before calling JSON.parse(decodedBody),
jsonHasTruthyErrorsProperty, classifyAPIErrors, and twitterResponseLooksEmpty in
handler.ts).
- Around line 67-69: The retry loop currently lets exceptions from
getRandomTwitterAccount(), ClientTransaction.create(...), new Request(...), and
fetch(...) escape and abort retries; move those calls inside a try/catch that
sets errors = true and continues the do/while so the handler rotates accounts
and eventually returns the synthetic 502 after retries; specifically wrap the
getRandomTwitterAccount() call and the subsequent ClientTransaction.create,
Request construction, and fetch invocation in a single try block (inside the
existing do loop) and in the catch set errors = true (and capture/log the
exception) then continue to the next iteration so only the guarded
JSON-processing block determines success/failure.
- Around line 50-57: The retry code reuses the original request.body stream
(stored in newRequestInit) so subsequent fetch attempts fail because the body is
already consumed; change the handler to eagerly read and buffer the request body
once (e.g., into an ArrayBuffer/Uint8Array or string) when creating
newRequestInit (or detect GET/HEAD and leave body null), then for each retry
reconstruct the Request using that buffered body instead of request.body; also
avoid reusing the original request.signal across attempts by creating a fresh
AbortController/signal per attempt when building the Request so retries have a
fresh cancellable signal.
In `@tools/credential-tools.mjs`:
- Around line 50-55: The script currently writes the raw key with
writeFileSync(KEY_PATH, ...) using default perms and prints keyB64url to stdout,
risking key leakage; change the file write to set restrictive permissions (mode
0o600/0600) when creating KEY_PATH (use the writeFileSync options or a separate
chmod) and remove any console.log that prints keyB64url; instead print only
guidance (e.g., that the key was written and how to set the wrangler secret) or,
if needed, output the key to a secure channel, but do not emit keyB64url to
stdout. Ensure references: writeFileSync, KEY_PATH, keyB64url, and all
console.log lines that currently print the key are updated.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 4f0c03a8-b948-47a4-a5c7-6c12d778d7af
📒 Files selected for processing (3)
src/providers/twitter/proxy/handler.tssrc/providers/twitter/proxy/transaction/transaction.tstools/credential-tools.mjs
| const form = $('form[name="f"]').length | ||
| ? $('form[name="f"]') | ||
| : $('form[action="https://x.com/x/migrate"]'); | ||
| if (form.length) { | ||
| const actionUrl = form.attr('action') || 'https://x.com/x/migrate'; | ||
| const method = (form.attr('method') || 'POST').toUpperCase(); | ||
| const inputs = form.find('input').toArray(); | ||
| const data: Record<string, string> = {}; | ||
| inputs.forEach(input => { | ||
| const name = $(input).attr('name'); | ||
| const val = $(input).attr('value') || ''; | ||
| if (name) data[name] = val; | ||
| }); | ||
| if (method === 'GET') { | ||
| const url = actionUrl + '?' + new URLSearchParams(data).toString(); | ||
| resp = await cachedFetch(url); | ||
| } else { | ||
| const body = new URLSearchParams(data).toString(); | ||
| resp = await cachedFetch(actionUrl, { |
There was a problem hiding this comment.
Resolve the migration form action against the current page URL.
Lines 79-97 assume the migration form uses an absolute https://x.com/x/migrate action. If X returns /x/migrate instead, the fallback selector misses it and cachedFetch(actionUrl, ...) receives a relative URL, which breaks the migration hop and prevents ClientTransaction.create() from initializing.
Suggested fix
- const form = $('form[name="f"]').length
- ? $('form[name="f"]')
- : $('form[action="https://x.com/x/migrate"]');
+ const form = $('form[name="f"]').length
+ ? $('form[name="f"]')
+ : $('form[action*="/x/migrate"]');
if (form.length) {
- const actionUrl = form.attr('action') || 'https://x.com/x/migrate';
+ const actionUrl = new URL(form.attr('action') || '/x/migrate', resp.url || homeUrl).toString();
const method = (form.attr('method') || 'POST').toUpperCase();
const inputs = form.find('input').toArray();
const data: Record<string, string> = {};
@@
if (method === 'GET') {
- const url = actionUrl + '?' + new URLSearchParams(data).toString();
- resp = await cachedFetch(url);
+ const nextUrl = new URL(actionUrl);
+ nextUrl.search = new URLSearchParams(data).toString();
+ resp = await cachedFetch(nextUrl.toString());
} else {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/providers/twitter/proxy/transaction/transaction.ts` around lines 79 - 97,
The code assumes form.action is absolute; instead resolve the action against the
current page base so relative actions like "/x/migrate" become absolute. After
you read the form (variable form) compute a base URL (use the page/response URL
available in scope, e.g. resp.url or the original request URL) and replace
actionUrl assignment with something like actionUrl = new
URL((form.attr('action') || '/x/migrate'), base).toString(); then use that
resolved actionUrl for building the GET query and for cachedFetch (and when
method === 'POST' build body from inputs as before). Ensure all places that use
actionUrl (the GET branch where you append URLSearchParams and the cachedFetch
call) use the resolved absolute URL.
| const plaintext = readFileSync(PLAINTEXT_PATH, 'utf-8'); | ||
| const parsed = JSON.parse(plaintext); | ||
| if (!parsed?.twitter?.accounts || !Array.isArray(parsed.twitter.accounts)) { |
There was a problem hiding this comment.
Handle invalid credentials.json explicitly.
Line 36 can throw on malformed JSON and bypass your normal CLI error flow. Return a controlled error message and exit code.
Proposed fix
const plaintext = readFileSync(PLAINTEXT_PATH, 'utf-8');
- const parsed = JSON.parse(plaintext);
+ let parsed;
+ try {
+ parsed = JSON.parse(plaintext);
+ } catch (err) {
+ console.error(`Invalid JSON in ${PLAINTEXT_PATH}: ${err.message}`);
+ process.exit(1);
+ }
if (!parsed?.twitter?.accounts || !Array.isArray(parsed.twitter.accounts)) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tools/credential-tools.mjs` around lines 35 - 37, Wrap the JSON.parse call so
malformed JSON in the credentials file is handled explicitly: surround
reading/parsing (readFileSync(PLAINTEXT_PATH) and JSON.parse(...)) with a
try/catch, and on catch emit a clear controlled error (including PLAINTEXT_PATH)
via your CLI logger/console.error and exit with a non‑zero code (e.g.,
process.exit(1)); ensure the subsequent check that uses parsed/twitter/accounts
only runs when parsing succeeded.
Adds encrypted credential store, elongator tools, github actions pipeline with credentials stored in R2. Use integrated elongator for account proxying.
Summary by CodeRabbit
New Features
Chores
Docs/Logging