fix(onboarding): harden connect-model OAuth timeout, mobile paste, and API key recovery (#23379)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - During onboarding, new users connect an AI model via Claude/OpenAI
subscription OAuth or an API key.
> - Production session replays showed users failing on `connect_model`
because subscription login sessions expired at 5 minutes during
mobile/tab switches, the waiting spinner hid the sign-in link with no
way to reopen it, pasted Claude codes failed silently without
normalization or clear feedback, and rejected API keys gave a dead-end
error.
> - These friction points cause new users to abandon onboarding right
before their first agent run.
> - This pull request raises server login timeouts to 15 minutes with
visibility-change polling/auto-refresh, keeps a re-open link and 60s
recovery action visible while waiting, normalizes and validates pasted
Claude authorization codes with explicit error messaging, and adds API
key paste normalization, provider-mismatch switching, and actionable
rejection links.
> - The benefit is fewer onboarding drop-offs on mobile and desktop
without changing backend auth protocols or schema.

## Linked Issues or Issue Description

**What happened?**
Users onboarding on `connect_model` hit four repeatable failure modes:
1. Subscription login sessions (`DEVICE_LOGIN_TIMEOUT_MS` and
`DEFAULT_SETUP_TOKEN_SESSION_TTL_MS`) expired after 5 minutes while
users switched apps/tabs for OAuth and 2FA, showing `This sign-in
expired` or `Sign-in didn't finish` right when they returned.
2. After clicking `Sign in`, `ProviderSubscriptionCard` replaced the
button with a disabled `Waiting…` / `Waiting for code…` spinner, leaving
users with no way to reopen the OAuth URL if a mobile browser blocked
the tab or they closed it.
3. Pasting a Claude authorization code with mobile line breaks, quotes,
or a full callback URL could fail silently or show no explanation when
rejected.
4. Pasting a rejected or wrong-provider API key showed a generic
rejection message without pointing users to the provider's API keys page
or offering a 1-click provider switch.

**Expected behavior**
Subscription sign-in sessions should give users 15 minutes to complete
OAuth, immediately poll or refresh when returning to the tab, keep a
re-open link and 60-second recovery action accessible, normalize and
validate pasted Claude codes with clear inline feedback, and help users
recover from wrong-provider or rejected API keys.

**Steps to reproduce**
1. Open the onboarding wizard and advance to the Connect a model step.
2. Start a Claude or OpenAI subscription sign-in, switch tabs for 5
minutes (or close the OAuth tab), and return.
3. Paste an authorization code with extra whitespace/newlines or a
callback URL into the Claude code input, or paste an Anthropic
`sk-ant-...` key into OpenAI API key mode.

**Paperclip version or commit**
`43fedd51c5c37ccf7c7568328bac97179cdd48ba` (`master`)

**Deployment mode**
Other (hosted Cloud & local dev)

## What Changed

- **15-minute subscription login TTLs + tab-return poll/refresh:**
Raised `DEVICE_LOGIN_TIMEOUT_MS`
(`server/src/services/device-login-service.ts`) and
`DEFAULT_SETUP_TOKEN_SESSION_TTL_MS`
(`server/src/services/setup-token-session.ts`) from 5 minutes to 15
minutes. Added `visibilitychange` listeners to both
`AdapterDeviceLoginPanel` and `ClaudeSetupTokenLoginPanel`
(`ui/src/components/AgentConfigForm.tsx`) to immediately refetch status
on tab return and auto-refresh once if an onboarding session expired
while hidden.
- **Non-locking waiting state:** Updated `ProviderSubscriptionCard`
(`ui/src/components/AdapterLoginChrome.tsx`) to keep an `Open sign-in
link again` button visible while waiting and show a `Taking a while? Get
a new link` recovery button after 60 seconds (`WAITING_HELP_DELAY_MS`).
- **Claude code-paste normalization & inline validation:** Added
`ui/src/lib/onboarding-login-helpers.ts`
(`normalizeSubmittedBrowserCode`, `validateSubmittedBrowserCode`) to
strip newlines/quotes and extract `code#state` from pasted callback
URLs, surface immediate inline validation errors on invalid pastes, and
show an explicit rejected-code message when a submitted code fails.
- **Self-recoverable API key input:** Added `normalizeApiKeyInput`,
`detectMismatchedApiKeyProvider`, and `providerApiKeysHelp` in
`ui/src/lib/onboarding-login-helpers.ts`, wired into
`ui/src/components/OnboardingWizard.tsx` to normalize pasted keys, offer
a 1-click switch when an Anthropic/OpenAI key is pasted into the wrong
provider, and link directly to the provider's API keys page when
rejected.
- **Module size note:** `AgentConfigForm.tsx` and `OnboardingWizard.tsx`
already exceeded 1,000 lines; all new pure parsing, validation, and
provider-help logic was extracted into
`ui/src/lib/onboarding-login-helpers.ts` to keep edits to existing files
minimal.

## Verification

- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm vitest run ui/src/lib/onboarding-login-helpers.test.ts
ui/src/components/AdapterLoginChrome.test.tsx
ui/src/components/AgentConfigForm.render.test.tsx
server/src/__tests__/device-login-service.test.ts` — 4/4 files, 84/84
tests passed.
- `git ls-files "*setup-token*test*" "*onboarding*test*" | grep -E
"^(server|ui)/" | xargs pnpm vitest run` — 24/24 files, 373/373 tests
passed.
- Note: A full local `pnpm verify` run selected 2,296 files and hit 14
unrelated local PostgreSQL/heartbeat/Tailscale hook timeouts under
parallel macOS load (34,070 passed, 0 failures in
login/onboarding/setup-token/device-login suites); CI will supply
full-suite coverage on this PR.

## Risks

- **Low risk:** Raising `DEVICE_LOGIN_TIMEOUT_MS` and
`DEFAULT_SETUP_TOKEN_SESSION_TTL_MS` from 5 to 15 minutes extends the
maximum lifetime of an uncompleted login sandbox lease by 10 minutes
(bounded by the existing reaper and per-owner concurrency limits). No
database schema, API contract, or auth protocol changes.

## Model Used

- Google Gemini (Antigravity agentic assistant with thinking mode and
tool use / code execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-12-01 16:43:39 +00:00
1 parent e32b1b057f
commit d1680baf8f
17 files changed
+812 -62

No files matched your search

@@ -283,6 +283,20 @@ describe("parseSetupTokenPrompt", () => {
expect(result?.url).toBe(shortCode);
});
it("accepts the claude 2.1.333+ opaque short authorization URL", () => {
const opaqueUrl = "https://claude.ai/oauth/authorize?IQ2RDWoHouqywHRo76dCv-ms1Qxya8PGzuNNvHH1OX8o";
const result = parseSetupTokenPrompt(completeOutput(opaqueUrl));
expect(result).not.toBeNull();
expect(result?.url).toBe(opaqueUrl);
});
it("rejects opaque authorization URLs that are too short or contain an API key prefix", () => {
expect(parseSetupTokenPrompt(completeOutput("https://claude.ai/oauth/authorize?tooshort"))).toBeNull();
expect(
parseSetupTokenPrompt(completeOutput("https://claude.ai/oauth/authorize?sk-ant-api03-1234567890abcdef1234567890")),
).toBeNull();
});
it("returns null for an empty code value", () => {
const emptyCode = CLAUDE_COM_URL.replace(`code=${CODE}`, "code=");
expect(parseSetupTokenPrompt(completeOutput(emptyCode))).toBeNull();
@@ -92,6 +92,10 @@ const CLIENT_ID_RE = /^[A-Za-z0-9._~-]{1,128}$/;
const CODE_RE = /^[A-Za-z0-9._~-]{1,1024}$/;
const CODE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43,128}$/;
const STATE_RE = /^[A-Za-z0-9_-]{16,256}$/;
// `claude` 2.1.333+ emits a short opaque OAuth request token as the entire
// query string (`https://claude.ai/oauth/authorize?<token>`), with no `=` or
// `&` separators.
const OPAQUE_AUTH_QUERY_RE = /^[A-Za-z0-9_-]{24,128}$/;
// One `scope` token. The `scope` value is one to eight space-separated tokens.
const SCOPE_TOKEN_RE = /^[A-Za-z0-9:._-]{1,64}$/;
@@ -278,6 +282,11 @@ function isValidRedirectUri(value: string): boolean {
* characters. It rejects an API-key prefix in any decoded value.
*/
function hasValidQuery(parsed: URL): boolean {
const rawQuery = parsed.search.startsWith("?") ? parsed.search.slice(1) : "";
if (OPAQUE_AUTH_QUERY_RE.test(rawQuery) && !API_KEY_RE.test(rawQuery)) {
return true;
}
// Collect the values of each key, so the parser can reject a duplicate key and
// read the one decoded value of each key.
const byKey = new Map<string, string[]>();
@@ -96,6 +96,37 @@ async function flush(): Promise<void> {
}
describe("runSetupTokenLogin", () => {
it("accepts a code#state paste when the authorization URL uses the claude 2.1.333+ opaque query format", async () => {
const opaqueOutput = PROMPT_OUTPUT.replace(
VALID_URL,
"https://claude.ai/oauth/authorize?IQ2RDWoHouqywHRo76dCv-ms1Qxya8PGzuNNvHH1OX8o",
);
const fake = createFakeDriver({ chunks: [opaqueOutput] });
let stream!: (chunk: string) => void;
const start = fake.driver.start.bind(fake.driver);
fake.driver.start = (command, onData) => { stream = onData; return start(command, onData); };
const write = fake.driver.write.bind(fake.driver);
fake.driver.write = input => {
write(input);
if (input === CODE_SUBMISSION_TERMINATOR) {
stream(SUCCESS_OUTPUT);
fake.resolveExit(0);
}
};
const onCredential = vi.fn(async () => {});
const pasted = `${BROWSER_CODE}#opaque-state-value`;
const result = await runSetupTokenLogin(fake.driver, {
onPrompt: () => {},
provideCode: async () => pasted,
onCredential,
codeSubmitSettleMs: 0,
timeoutMs: 1000,
});
expect(result).toMatchObject({ outcome: "success", codeSubmitted: true, credentialDelivered: true });
expect(fake.writes).toContain(pasted);
expect(onCredential).toHaveBeenCalledOnce();
});
it("reports a rejected OAuth code immediately even while the CLI waits for Enter to retry", async () => {
const fake = createFakeDriver({ chunks: [PROMPT_OUTPUT] });
let stream!: (chunk: string) => void;
@@ -264,7 +264,8 @@ export async function runSetupTokenLogin(
}
if (controller.signal.aborted) return;
const separator = code.indexOf("#");
if (separator !== -1 && code.slice(separator + 1) !== new URL(prompt.url).searchParams.get("state")) {
const expectedState = new URL(prompt.url).searchParams.get("state");
if (separator !== -1 && expectedState !== null && code.slice(separator + 1) !== expectedState) {
failureReason = "code_state_mismatch";
controller.abort();
return;