Skip to content

fix(oauth): preserve hashes in Command Code callback JSON - #5413

Closed
luvs01 wants to merge 1 commit into
lidge-jun:devfrom
luvs01:codex/fix-raw-state-check-for-command-code-json
Closed

luvs01 wants to merge 1 commit into
lidge-jun:devfrom
luvs01:codex/fix-raw-state-check-for-command-code-json

Conversation

@luvs01

@luvs01 luvs01 commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

  • A generic code#state split on pasted input treated a # anywhere as an OAuth state suffix and rejected provider-specific Command Code JSON when any provider field contained #, breaking the manual-paste fallback for Command Code.

Description

  • In src/oauth/login-flow-state.ts adjust the shared manual-submit gate so Command Code manual callback JSON (inputs starting with {) is treated opaque to the generic code#state rule and exempted from the raw suffix state classification, and make stateBearing ignore those Command Code JSON cases.
  • Add a regression test in tests/oauth/oauth-manual-code.test.ts that stashes a manual slot and verifies a Command Code callback JSON containing # characters in provider-controlled fields is accepted and delivered unchanged to the waiting flow.
  • Update structure/providers-and-adapters.md to document that Command Code manual callback JSON is validated by the provider parser and remains opaque to the shared code#state parsing rule.

Testing

  • Ran the focused OAuth test: bun test tests/oauth/oauth-manual-code.test.ts, and the modified tests passed (new regression included).
  • Ran structural and hygiene checks: bun run structure:check and bun run privacy:scan, both passed.
  • Ran typecheck: bun run typecheck, which passed.
  • Ran the repository-wide bun run test; the OAuth-focused changes passed in that run but the full suite exited nonzero due to unrelated environment-sensitive failures in management-auth / Compatibility Lab / bearer-admission and some integration tests in this container; those failures are not related to the OAuth fix.

Codex Task


Devin Review

Review readiness checklist

This PR stays in draft until every box below is ticked. Tick all four boxes once the requirements are met:

  • All CI tests are green on my local testing.

  • I pushed my PR to the latest dev commit.

  • I resolved all correct Codex and CodeRabbit findings.

  • My PR is ready for review.

@github-actions github-actions Bot added intake: hygiene-blocked Deterministic PR hygiene checks failed bug Something isn't working labels Sep 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Deterministic hygiene checks failed.

  • unsponsored_surface — This changes an authentication, workflow, release-automation, or dependency surface. MAINTAINERS.md requires security review for these; ask a maintainer to apply maintainer-sponsored once they have reviewed it. Paths: src/oauth/login-flow-state.ts.

@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: lidge-jun/opencodex/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 3323c9d8-e2e8-469a-9533-c990799b4e07

📥 Commits

Reviewing files that changed from the base of the PR and between 88eac5d and b776d62.

📒 Files selected for processing (3)
  • src/oauth/login-flow-state.ts
  • structure/providers-and-adapters.md
  • tests/oauth/oauth-manual-code.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The manual login flow now accepts Command Code JSON callbacks as opaque payloads. It skips shared code#state parsing and state validation. A test verifies that embedded # characters remain unchanged.

Changes

Command Code callback handling

Layer / File(s) Summary
Opaque JSON callback flow
src/oauth/login-flow-state.ts, tests/oauth/oauth-manual-code.test.ts, structure/providers-and-adapters.md
At lines 100–106, submitManualLoginCode accepts trimmed Command Code input beginning with { and excludes it from shared state validation. The test at lines 194–213 verifies that hashes in provider fields remain unchanged. The documentation records provider-side state validation.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. (1 skipped: 1 …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: preserving hash characters in Command Code callback JSON during OAuth manual login.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

⏳ DRAFT

  • hygiene: unsponsored_surface.

What to do

  • Fix unsponsored_surface — This changes an authentication, workflow, release-automation, or dependency surface. MAINTAINERS.md requires security review for these; ask a maintainer to apply maintainer-sponsored once they have reviewed it. Paths: src/oauth/login-flow-state.ts.

Review readiness checklist

  • ✅ All CI tests are green on my local testing.
  • ✅ I pushed my PR to the latest dev commit.
  • ✅ I resolved all correct Codex and CodeRabbit findings.
  • ✅ My PR is ready for review.

✅ 4/4 boxes ticked.

This pull request was already a draft. Its draft status will be preserved after every issue above is resolved.

@github-actions
github-actions Bot marked this pull request as draft September 21, 2026 05:28
@lidge-jun

Copy link
Copy Markdown
Owner

리뷰 · 우선순위 56 / 80

Command Code 로그인은 브라우저가 돌려준 JSON을 복사해 붙일 수 있습니다. 같이 쓰는 파서는 #가 보이면 그 글을 인가코드#상태값으로 자릅니다. apiKey가 key#segment이면 # 앞만 코드로 보고, 뒤를 이번 로그인의 상태값과 비교합니다. JSON 안에 적힌 state는 보지 않습니다. 맞는 로그인인데 "상태가 안 맞다"고 거절됩니다.

이 PR은 제공자가 command-code이고 글이 {로 시작하면, 그 글을 JSON으로 두고 이 # 검사를 건너뜁니다. 붙여넣은 글은 그대로 로그인 루프로 갑니다. 상태값이 이번 시도의 것인지는 parseCommandCodeCallback이 봅니다. state가 다르면 에러를 던지고 키를 저장하지 않습니다. 테스트는 #가 든 JSON이 거절되지 않고 원문 그대로 통과하는지만 확인합니다. base는 dev입니다. types.ts와 config.ts 분할과 무관하고, 같은 수정의 다른 열린 PR은 없습니다.

PR 본문은 잘린 뒷조각이 다른 로그인 상태값과 맞을 수도 있다고 적습니다. 파서는 첫 #에서 한 번만 자릅니다. JSON은 # 뒤에 따옴표와 }가 더 붙어서, 그 뒷조각이 상태값과 글자 그대로 같기는 어렵습니다. 실제로 막히는 것은 맞는 로그인의 거절입니다.

tests/oauth/oauth-manual-code.test.ts:194 - 새 테스트는 상태값이 맞은 경우만 봅니다. {로 시작하면 공용 관문은 상태 검사를 하지 않아서, state가 틀려도 submitManualLoginCode는 성공을 돌려줍니다. /api/oauth/login/code도 200입니다. 로그인을 끝내지 않는 검사는 그 다음 루프의 parseCommandCodeCallback에 있고, 그 함수의 틀린 state 테스트는 이미 있습니다. #가 들어 있는 문자열을 붙여 넣었을 때 API가 성공만 돌려주고 루프가 그 글을 조용히 버리는 경로는 이번 테스트에 없습니다.

메인테이너의 판단이 필요한 지점

이 파일은 로그인 경로입니다. 자동 검사가 메인테이너 확인 표시(maintainer-sponsored)가 없으면 초안으로 붙잡아 둡니다. 준비 체크는 0/4입니다. 틀린 state를 붙여넣기 API에서 바로 409로 돌려줄지, 지금처럼 루프에만 맡길지 정하면 됩니다. #가 없는 JSON은 원래 루프에 맡겼습니다. 브랜치는 dev보다 커밋 2개 뒤입니다. 그 둘은 데스크톱 셸과 devlog라서 이 파일과 겹치지 않습니다.

너의 추천

수정 방향은 유지하면 됩니다. 공용 파서가 JSON 안의 #를 상태값으로 오해하지 않게 한 것이 이 패치의 이유이고, 진짜 상태 검사는 전용 파서에 남아 있습니다. 머지 전에 메인테이너가 로그인 표면을 보고 maintainer-sponsored를 붙이면 됩니다. 틀린 state를 API에서 바로 거절하는 테스트는 있으면 좋지만, 없어도 다른 로그인으로 통과하는 구멍은 보이지 않습니다. 닫을 중복 PR은 없습니다.

이 댓글은 grok-bot이 작성했습니다

@luvs01
luvs01 marked this pull request as ready for review September 21, 2026 06:09
@github-actions
github-actions Bot marked this pull request as draft September 21, 2026 06:09
@luvs01
luvs01 force-pushed the codex/fix-raw-state-check-for-command-code-json branch from b776d62 to 225eb81 Compare September 21, 2026 13:49
@luvs01

luvs01 commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator Author

The readiness checklist is complete and the branch is rebased on current dev. The remaining gate is unsponsored_surface — this PR touches a protected path and needs the maintainer-sponsored label to proceed. @lidge-jun could you review for sponsorship when convenient?

lidge-jun added a commit that referenced this pull request Sep 22, 2026
Review of the carried #5413 change found the direct CLI prompt path,
which does not go through submitManualLoginCode, accepting a raw
"key#state" paste whose state did not match: only URL- and query-shaped
input was compared. Treat a raw paste with an explicit #state suffix as
state-bearing, as the shared submit gate already does; a bare key still
needs no state. The end-to-end submit test now observes the login
promise from the start so an early failure cannot leave it unhandled.
@lidge-jun

Copy link
Copy Markdown
Owner

Carried into #5598 as a cherry-pick (225eb81), with your authorship kept, plus an end-to-end test through the shared submit path and a matching #state check on the direct CLI prompt. Thank you, @luvs01. Closing in favor of #5598.

@lidge-jun lidge-jun closed this Sep 22, 2026
lidge-jun added a commit that referenced this pull request Sep 23, 2026
…ck proxy, OAuth, remote hub docs) (#5598)

* fix(kiro): avoid mixed-script estimator allocations

(cherry picked from commit 24c3cd3)

* test(kiro): register kiro-wire-estimate in test layout

(cherry picked from commit e796b5c)

* fix(crash-guard): count unparenthesized JS frames as real throw sites

isBenignAbortTeardown only recognised parenthesized "(file:line:col)"
frames, so a genuine TypeError whose stack carries "at /abs/x.ts:1:2",
"at file:///x.ts:1:2" or a Windows drive path was folded into the
rate-limited benign-teardown summary. Scan every "at ..." frame and
treat any non-native line:col location as a JS source frame.

Hidden JSC fields (sourceURL/line/column) deliberately do not veto the
benign class: Bun can attach them to errors raised from builtin frames,
and the benign summary already records them through diagnose().

Reimplements #5286.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix(proxy): keep loopback traffic outside inherited SOCKS

(cherry picked from commit 3746991)

* fix(proxy): pin non-loopback SOCKS ownership and document the ambient noProxy scope

(cherry picked from commit 7dd72d1)

* fix(oauth): preserve hashes in command code callback JSON

(cherry picked from commit 225eb81)

* test(oauth): drive Command Code callback JSON through the shared submit path

The provider parser, not the shared code#state gate, owns the state check
for pasted Command Code callback JSON. Pin both halves end to end: a
wrong-state paste is accepted by submitManualLoginCode, rejected by the
provider loop and re-prompted without a whoami call, and the right-state
paste keeps "#" inside its fields intact through to the stored key.

Follow-up to the carried #5413 fix.

* docs(remote-hub): warn about shared-host unauthenticated loopback companion

(cherry picked from commit a0233ca)

* docs(remote-hub): align the loopback warning with the reference and cover the ported form

(cherry picked from commit b00ed1e)

* fix(oauth): drop legacy credential backup on destructive mutations

auth.json.pre-multiauth copies the whole legacy store for downgrade recovery, but removeCredential/removeAccount left it behind — and a legacy-shaped store re-created it — so logout and account deletion kept a file holding the very refresh tokens the user destroyed.

mutateStore gains a removeLegacyBackup option: it skips the one-time create and unlinks the backup after persist. Removal is best-effort (ENOENT ignored, other failures warn) because it runs after the store is persisted — a failed unlink must not report a failed logout for an account that is already gone. A stale uninstall-manifest entry is harmless: removeOwnedConfigState skips missing paths.

Covers the destructive-migration, pre-existing-backup, and stale-backup-on-migrated-store cases in oauth-store-multi tests.

(cherry picked from commit f456a4f)

* docs(structure): note legacy backup removal on destructive auth mutations

(cherry picked from commit b00133c)

* fix(oauth): only drop the downgrade backup when a credential was actually removed

removeCredential and removeAccount passed removeLegacyBackup unconditionally,
so a stale or concurrent request that returned "not-found" or false still
unlinked auth.json.pre-multiauth and still skipped creating it for a legacy
store. That backup is a whole-store copy, so a removal that deleted nothing
destroyed downgrade recovery for every provider in it.

Decide from the mutation result instead. The decision moves to just after the
mutation body, which only edits the in-memory store, so nothing has touched
disk when it is taken, and the create and remove paths stay mutually
exclusive as before. Cover both no-op results.

(cherry picked from commit 160d3ab)

* fix(oauth): drop the downgrade backup when a provider is deleted

Deleting a provider from the dashboard clears its credentials through
replaceProviderAccountSet(name, null), which bypassed the carried
logout/account-deletion rule and kept (or first created) the
auth.json.pre-multiauth copy of the deleted tokens. Treat clearing a
provider that had credentials as destructive; a no-op clear and a
non-empty replacement keep the backup. Pin the warning path when the
backup cannot be removed after the credential is already gone.

Completes the reimplementation of #4949.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix(crash-guard): log a new hidden throw site inside the benign fold window

Review of the carried #5286 frame fix found the remaining gap: a benign
teardown whose JSC hidden sourceURL/line/column names a different throw
site was still folded silently for five minutes, so a distinct fault
could vanish between summaries. Log the summary when that hidden throw
site differs from the last one logged; repeats of the same site, and
errors without one, still fold. Classification is unchanged.

* fix(proxy): merge loopback into an inherited lowercase no_proxy

Review of the carried #5430 fix: Bun's native fetch reads a non-empty
lowercase no_proxy before NO_PROXY, so with HTTP_PROXY and an inherited
no_proxy the loopback entries written to NO_PROXY never applied and
local calls could still go through the proxy. Merge the same configured
and loopback entries into an inherited no_proxy, keeping its own entries.

The non-loopback SOCKS test now uses a local proxy that drops every
connection and an IP-literal target, so it no longer waits on DNS.

* fix(oauth): keep other providers in the downgrade backup on deletion

Review of the carried #4949 change: deleting one provider removed the
whole auth.json.pre-multiauth file, so a legacy store with several
providers lost downgrade recovery for every provider the user kept
(the migrated auth.json is unreadable to an older loader). Destructive
mutations now remove only the affected provider's entry and delete the
file once it is empty. A backup entry that is not a regular file is
removed rather than followed, and the rewrite replaces the entry itself
without resolving a symlink.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix(oauth): check an explicit #state on a raw Command Code paste

Review of the carried #5413 change found the direct CLI prompt path,
which does not go through submitManualLoginCode, accepting a raw
"key#state" paste whose state did not match: only URL- and query-shaped
input was compared. Treat a raw paste with an explicit #state suffix as
state-bearing, as the shared submit gate already does; a bare key still
needs no state. The end-to-end submit test now observes the login
promise from the start so an early failure cannot leave it unhandled.

* test: tighten the carried Kiro estimate and remote-hub warning checks

Review nits on the carried #5248 and #5444 units: document that the
count-based estimator takes non-negative integer counts, pin the
pure-CJK and empty-model-id cases against the replacement-string
formula, and require the dedicated-host warning to sit inside the
danger callout in both locales rather than anywhere in the page.

* fix(crash-guard): keep the hidden throw-site read inside the handler

Re-review found that reading the hidden JSC fields for the benign fold
could throw from an unusual accessor before the rejection was logged,
escaping the process unhandledRejection listener. Make the read
best-effort, as diagnose() already is, and pin it with a Proxy whose
sourceURL getter throws.

* fix(oauth): never write the downgrade backup through a link or claim it

Re-review of the backup scrub found two gaps. backupLegacyOnce used
existsSync, which reports a dangling symlink as absent, and then copied
through it, so credentials could land outside the config directory;
it now treats any existing entry as occupied and copies exclusively.
The scrub rewrite went through the shared atomic writer, which records
the path for uninstall, so a backup this install never registered was
claimed and later deleted; it now replaces the entry through an
exclusive private temp and a rename, leaving ownership unchanged.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* test(kiro): make the pure-CJK estimate case actually zero-Latin

* fix(oauth): rewrite the downgrade backup through the shared writer

Re-review: the local temp-and-rename used for the backup scrub skipped
what the shared atomic writer guarantees (Windows ACL hardening before
the temp holds a byte, an explicit 0600 on POSIX regardless of umask,
scrub-and-unlink of a failed temp, the Windows rename retry), which
structure/config.md forbids replacing. Add a no-follow variant of that
writer that leaves the owner manifest untouched, and use it, so a
backup an earlier install left unregistered still stays unclaimed.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* docs(structure): state when an existing OAuth downgrade copy is rewritten

* fix(proxy): scope the inherited-proxy loopback bypass to exact hosts

Security review of the carried #5430 change: on the no-config.proxy path
loopback names were added to NO_PROXY for any inherited proxy, and both
matchers treat entries as domain suffixes, so "localhost" also sent any
*.localhost name direct, which need not resolve to loopback.

Add the loopback entries only when an inherited SOCKS proxy owns HTTP(S)
traffic; that proxy is applied by the in-process matcher, which now
treats a bare localhost or IP-literal entry as one host (a leading dot
still means subdomains). An inherited HTTP(S) proxy is Bun's own and is
left as it was. Tests cover *.localhost staying on the SOCKS proxy, the
no-widening cases, and the exact-match rules.

* fix(proxy): key the loopback bypass on SOCKS precedence

Security re-review: with an inherited SOCKS proxy beside an inherited
HTTP(S) proxy the fetch wrapper still applies SOCKS first, so skipping
the loopback entries in that case let local requests pass through SOCKS.
Add them whenever an inherited SOCKS proxy exists; its exact matcher
decides first, so only a request already judged loopback reaches Bun's
suffix-matching proxy. Pin the mixed case.

* fix(proxy): keep 127.0.0.1 off an inherited HTTP proxy without suffix risk

Delta review: with no config.proxy and only an inherited HTTP(S) proxy,
loopback calls such as the CLI's own management and health requests to
127.0.0.1 could go to that proxy. Add the loopback addresses there (a
URL host ending in a numeric label parses as IPv4, so Bun's suffix
matching cannot widen them) but not "localhost", which Bun would match
as *.localhost. An inherited SOCKS proxy keeps the full list, and a
process with no inherited proxy is still left untouched.

* fix(proxy): add bare localhost only when SOCKS is the sole inherited proxy

Security re-review: beside an inherited HTTP(S) proxy, a bare localhost
in process-wide NO_PROXY is also read by Bun, whose suffix matching can
send an unwrapped fetch for any *.localhost name past that proxy. Write
the full loopback list only when an inherited SOCKS proxy is the only
inherited proxy; whenever Bun applies an inherited HTTP(S) proxy, add
only the loopback addresses. The mixed case keeps 127.0.0.1 direct
through the SOCKS wrapper and sends *.localhost to SOCKS.

* fix(proxy): never add a bare localhost to an inherited lowercase no_proxy

Review: with a configured HTTP(S) proxy and an inherited lowercase
no_proxy, which Bun reads first and matches by domain suffix, adding a
bare localhost newly let *.localhost names bypass the proxy. The
lowercase value now gains the configured entries and the loopback
addresses only.

* fix(proxy): add only loopback addresses to an inherited lowercase no_proxy

Delta review: configured noProxy entries were also copied into an
inherited lowercase no_proxy, which Bun reads first and matches by
suffix; on dev that inherited value always shadowed them, so a
configured "localhost" newly let *.localhost bypass a configured proxy.
The lowercase value now gains the loopback addresses only.

* test(oauth): assert a cleared provider set as null, as getAccountSet returns

Hosted CI shard 1/4 at 00e5111: getAccountSet returns null for a
missing provider, so the two new backup tests' toBeUndefined() failed.

* fix: bypass inherited HTTP ALL_PROXY for loopback

Cover both ALL_PROXY casings and repair review notes for hub docs, Kiro fallback coverage, and OAuth backup comments.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

* fix: keep localhost direct with mixed inherited proxies

Force native direct fetch for exact localhost when the inherited SOCKS wrapper is active, and cover both ALL_PROXY casing combinations.

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>

---------

Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com>
Co-authored-by: Epinephrine <luvs01@hanmail.net>
Co-authored-by: lidge-jun <lidge-jun@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working intake: hygiene-blocked Deterministic PR hygiene checks failed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants