Files
PaperClipAI/server/src/services/local-ai-browser-login.ts
T
Dotta d1680baf8f 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
2026-12-01 16:43:39 +00:00

151 lines
7.5 KiB
TypeScript

import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { open } from "node:fs/promises";
import { constants } from "node:fs";
import path from "node:path";
import { runSetupTokenLogin } from "@paperclipai/adapter-claude-local/server";
import { runDeviceLogin } from "@paperclipai/adapter-codex-local/server";
import { ensureCommandResolvable, resolveCommandForLogs } from "@paperclipai/adapter-utils/server-utils";
import { resolveCodexCommand, startAntigravityBrowserLogin } from "../vendor/paperclip-runner/index.js";
import { logger } from "../middleware/logger.js";
export type LocalBrowserLoginState = {
authorizationUrl?: string;
code?: string;
outcome?: "success" | "failure";
error?: string;
submitCode?: (code: string) => void;
submitRedirect?: (rawRedirectUrl: string) => Promise<void>;
abort: () => void | Promise<void>;
};
// Node has no built-in PTY API. Python's standard-library pty module supplies
// the terminal required by both CLIs. The Docker image already includes
// python3. This bridge forwards only bytes; provider output is never logged.
const PYTHON_PTY_BRIDGE = String.raw`
import errno, os, pty, select, signal, sys
pid, master = pty.fork()
if pid == 0:
os.execvpe(sys.argv[1], sys.argv[1:], os.environ)
def stop(_signal, _frame):
try: os.killpg(pid, signal.SIGKILL)
except ProcessLookupError: pass
sys.exit(1)
signal.signal(signal.SIGTERM, stop)
while True:
readable, _, _ = select.select([master, 0], [], [])
if 0 in readable:
data = os.read(0, 4096)
if data: os.write(master, data)
else: stop(None, None)
if master in readable:
try: data = os.read(master, 4096)
except OSError as error:
if error.errno == errno.EIO: break
raise
if not data: break
os.write(1, data)
_, status = os.waitpid(pid, 0)
sys.exit(os.waitstatus_to_exitcode(status))
`;
/** Run the same browser-code login used by sandbox connections on the local host. */
export function startLocalBrowserLogin(provider: "anthropic" | "openai" | "google", home: string): LocalBrowserLoginState {
if (provider === "google") {
return startAntigravityBrowserLogin(home, {
onFailure: (reason) => {
if (reason !== "aborted") logger.warn({ code: `ANTIGRAVITY_SIGN_IN_${reason.toUpperCase()}` }, "Google Antigravity sign-in failed");
},
});
}
const controller = new AbortController();
const state: LocalBrowserLoginState = { abort: () => controller.abort() };
const args = provider === "anthropic" ? ["setup-token"] : ["login", "--device-auth"];
let child: ChildProcessWithoutNullStreams | null = null;
const driver = {
async start(_command: string, onData: (chunk: string) => void): Promise<{ exitCode: number | null }> {
let executable = "claude";
if (provider === "openai") {
const legacyPlatform = !((process.platform === "linux" || process.platform === "darwin")
&& (process.arch === "x64" || process.arch === "arm64"));
try {
if (legacyPlatform) {
await ensureCommandResolvable("codex", home, process.env);
executable = path.resolve(home, await resolveCommandForLogs("codex", home, process.env));
} else {
executable = resolveCodexCommand();
}
} catch {
state.error = legacyPlatform
? "Codex browser sign-in requires the Codex CLI on this platform. Install Codex on this execution host and ensure codex is on Paperclip's PATH, then start sign-in again."
: "Codex browser sign-in requires an installed Codex CLI. Install Codex on this execution host or restore Paperclip's runtime dependencies, then start sign-in again.";
throw new Error("Browser login runtime unavailable");
}
}
if (controller.signal.aborted) throw new Error("Local sign-in cancelled before launch");
const env = { ...process.env,
ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "",
OPENAI_API_KEY: "", CODEX_API_KEY: "",
CLAUDE_CONFIG_DIR: provider === "anthropic" ? home : process.env.CLAUDE_CONFIG_DIR,
CODEX_HOME: provider === "openai" ? home : process.env.CODEX_HOME,
BROWSER: "true",
};
return new Promise((resolve, reject) => {
child = spawn("python3", ["-u", "-c", PYTHON_PTY_BRIDGE, executable, ...args], { env, stdio: ["pipe", "pipe", "pipe"] });
child.stdout.on("data", (bytes: Buffer) => onData(bytes.toString("utf8")));
// Provider output may contain secrets. Never log or retain stderr.
child.stderr.resume();
child.once("error", () => {
state.error = "Browser sign-in requires Python 3 and a working local terminal. Install Python 3 on this execution host, then start sign-in again.";
reject(new Error("Browser login terminal unavailable"));
});
child.once("close", (exitCode) => resolve({ exitCode }));
});
},
write(input: string) { child?.stdin.write(input); },
stop() { child?.kill("SIGTERM"); },
async dispose() { child?.kill("SIGTERM"); },
async readFile(file: string) { const { readLocalAiCredentialFile } = await import("./local-ai-credential-file.js"); return Buffer.from(await readLocalAiCredentialFile(file)); },
};
if (provider === "anthropic") {
let deliverCode: ((code: string) => void) | undefined;
const codeReady = new Promise<string>((resolve) => { deliverCode = resolve; });
state.submitCode = (code) => { deliverCode?.(code); deliverCode = undefined; };
void runSetupTokenLogin(driver, {
timeoutMs: 15 * 60_000, signal: controller.signal,
onPrompt: (prompt) => { state.authorizationUrl = prompt.url; },
provideCode: (signal) => new Promise<string>((resolve, reject) => {
const abort = () => reject(new Error("Local sign-in cancelled"));
if (signal.aborted) { abort(); return; }
signal.addEventListener("abort", abort, { once: true });
codeReady.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
}),
onCredential: async (bytes) => {
const file = await open(path.join(home, ".credentials.json"),
constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
try {
await file.writeFile(JSON.stringify({ claudeAiOauth: { accessToken: bytes.toString("utf8") } }));
} finally {
await file.close();
}
},
}).then((result) => {
state.outcome = result.outcome === "success" ? "success" : "failure";
if (result.failureReason === "code_state_mismatch") {
state.error = "That code belongs to a different sign-in. Start sign-in again and paste the code from the new tab.";
} else if (result.failureReason === "oauth_error") {
state.error = "Claude could not finish sign-in. Start sign-in again and use the code from the new sign-in tab.";
} else if (result.outcome === "timeout" && result.codeSubmitted) {
state.error = "Claude did not confirm the code in time. Start sign-in again to get a new code.";
}
})
.catch(() => { state.outcome = "failure"; });
} else {
void runDeviceLogin(driver, {
timeoutMs: 15 * 60_000, signal: controller.signal,
onPrompt: (prompt) => { state.authorizationUrl = prompt.url; state.code = prompt.code; },
}).then((result) => { state.outcome = result.outcome === "success" ? "success" : "failure"; })
.catch(() => { state.outcome = "failure"; });
}
return state;
}