mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
Use browser subscription sign-in on self-hosted installations
Reuse the cloud Claude and Codex login drivers behind isolated local attempts, and present the shared browser-code UI in connection setup. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
1b0ca14343
commit
45a841bc74
22 files changed
+607
-199
No files matched your search
@@ -0,0 +1,75 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { startLocalBrowserLogin } from "./local-ai-browser-login.js";
|
||||
|
||||
const initialPath = process.env.PATH;
|
||||
let root: string | undefined;
|
||||
afterEach(async () => {
|
||||
process.env.PATH = initialPath;
|
||||
if (root) await rm(root, { recursive: true, force: true });
|
||||
root = undefined;
|
||||
});
|
||||
|
||||
async function fakeCli(name: string, source: string) {
|
||||
root ??= await mkdtemp(path.join(os.tmpdir(), "paperclip-browser-login-"));
|
||||
const bin = path.join(root, "bin");
|
||||
await mkdir(bin, { recursive: true });
|
||||
await writeFile(path.join(bin, name), `#!/bin/sh\n${source}\n`, { mode: 0o700 });
|
||||
process.env.PATH = `${bin}${path.delimiter}${initialPath}`;
|
||||
const home = path.join(root, "credential-home");
|
||||
await mkdir(home, { mode: 0o700 });
|
||||
return home;
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === "win32")("local browser subscription login", () => {
|
||||
it("surfaces a Codex device link and code from a local PTY without a user shell command", async () => {
|
||||
const home = await fakeCli("codex", [
|
||||
'printf "1. Open this link in your browser and sign in to your account\\n"',
|
||||
'printf "https://auth.openai.com/codex/device\\n"',
|
||||
'printf "2. Enter this one-time code (expires in 15 minutes)\\n"',
|
||||
'printf "ABCD-EFGHJ\\n"',
|
||||
].join("\n"));
|
||||
const login = startLocalBrowserLogin("openai", home);
|
||||
await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5000 });
|
||||
expect(login.authorizationUrl).toBe("https://auth.openai.com/codex/device");
|
||||
expect(login.code).toBe("ABCD-EFGHJ");
|
||||
});
|
||||
|
||||
it("accepts a Claude browser code and stores its token only in the attempt home", async () => {
|
||||
const url = "https://claude.com/cai/oauth/authorize?client_id=cid&code=abcdefgh&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&response_type=code&scope=user&state=0123456789abcdef";
|
||||
const home = await fakeCli("claude", [
|
||||
'printf "Welcome to Claude Code\\nOpening browser to sign in…\\nBrowser didn\x27t open? Use the url below to sign in (c to copy)\\n"',
|
||||
`printf '%s\\n' '${url}'`,
|
||||
'printf "Paste code here if prompted >\\n"',
|
||||
'read -r entered',
|
||||
'printf "✓ Long-lived authentication token created successfully!\\n\\nYour OAuth token (valid for 1 year):\\n\\nsk-ant-oat01-AAAABBBBCCCCDDDDEEEE11112222FFFFGGGG_HHHH-IIII\\n\\nStore this token securely. You won\x27t be able to see it again.\\n"',
|
||||
].join("\n"));
|
||||
const login = startLocalBrowserLogin("anthropic", home);
|
||||
await vi.waitFor(() => expect(login.authorizationUrl).toBe(url), { timeout: 5000 });
|
||||
login.submitCode?.("fixture-code");
|
||||
await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5000 });
|
||||
const credential = JSON.parse(await readFile(path.join(home, ".credentials.json"), "utf8"));
|
||||
expect(credential.claudeAiOauth.accessToken).toMatch(/^sk-ant-oat01-/);
|
||||
expect((await stat(path.join(home, ".credentials.json"))).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it("terminates the local provider process when sign-in is cancelled", async () => {
|
||||
const home = await fakeCli("codex", 'echo $$ > "$CODEX_HOME/login.pid"\nexec sleep 60');
|
||||
const login = startLocalBrowserLogin("openai", home);
|
||||
let pid = 0;
|
||||
await vi.waitFor(async () => { pid = Number(await readFile(path.join(home, "login.pid"), "utf8")); expect(pid).toBeGreaterThan(0); });
|
||||
login.abort();
|
||||
await vi.waitFor(() => expect(login.outcome).toBe("failure"));
|
||||
await vi.waitFor(() => expect(() => process.kill(pid, 0)).toThrow());
|
||||
});
|
||||
|
||||
it("returns a fixed failure without exposing provider error output", async () => {
|
||||
const home = await fakeCli("codex", 'echo "private-provider-error" >&2\nexit 1');
|
||||
const login = startLocalBrowserLogin("openai", home);
|
||||
await vi.waitFor(() => expect(login.outcome).toBe("failure"));
|
||||
expect(JSON.stringify(login)).not.toContain("private-provider-error");
|
||||
expect(login.authorizationUrl).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
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";
|
||||
|
||||
export type LocalBrowserLoginState = {
|
||||
authorizationUrl?: string;
|
||||
code?: string;
|
||||
outcome?: "success" | "failure";
|
||||
submitCode?: (code: string) => void;
|
||||
abort: () => 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", home: string): LocalBrowserLoginState {
|
||||
const controller = new AbortController();
|
||||
const state: LocalBrowserLoginState = { abort: () => controller.abort() };
|
||||
const executable = provider === "anthropic" ? "claude" : "codex";
|
||||
const args = provider === "anthropic" ? ["setup-token"] : ["login", "--device-auth"];
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
const driver = {
|
||||
start(_command: string, onData: (chunk: string) => void): Promise<{ exitCode: number | null }> {
|
||||
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", reject);
|
||||
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: 300_000, signal: controller.signal,
|
||||
onPrompt: (prompt) => { state.authorizationUrl = prompt.url; },
|
||||
provideCode: () => codeReady,
|
||||
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"; })
|
||||
.catch(() => { state.outcome = "failure"; });
|
||||
} else {
|
||||
void runDeviceLogin(driver, {
|
||||
timeoutMs: 300_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;
|
||||
}
|
||||
@@ -1,40 +1,40 @@
|
||||
import { readLocalAiCredentialFile } from "./local-ai-credential-file.js";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { readClaudeToken, readIsolatedClaudeKeychainToken, fetchClaudeQuota } from "@paperclipai/adapter-claude-local/server";
|
||||
import { readIsolatedClaudeKeychainToken } from "@paperclipai/adapter-claude-local/server";
|
||||
import { readCodexAuthInfo, fetchCodexQuota } from "@paperclipai/adapter-codex-local/server";
|
||||
import { parseGrokAuthPayload, hasUsableGrokAuthValue } from "@paperclipai/adapter-grok-local/server";
|
||||
import type { AiProvider } from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
|
||||
/** Read an owned login home, or an explicitly authorized local-operator import. */
|
||||
/** Read and verify a connection-specific login home. */
|
||||
export async function readVerifiedLocalAiCredential(provider: AiProvider, loginHome?: string): Promise<string> {
|
||||
if (provider === "openrouter") throw unprocessable("OpenRouter requires an API key.");
|
||||
if ((provider === "openai" || provider === "xai") && !loginHome)
|
||||
throw unprocessable("Start a separate local sign-in for this connection before connecting.");
|
||||
if (!loginHome) throw unprocessable(provider === "xai"
|
||||
? "Start local sign-in for this connection before connecting."
|
||||
: "Start browser sign-in for this connection before connecting.");
|
||||
try {
|
||||
if (provider === "anthropic") {
|
||||
// Never change process.env or fall back to the server account when an
|
||||
// authenticated user's isolated login is missing or invalid.
|
||||
let token: string | null = null;
|
||||
if (loginHome) {
|
||||
for (const name of [".credentials.json", "credentials.json"]) {
|
||||
const raw = await readLocalAiCredentialFile(path.join(loginHome, name)).catch(() => null);
|
||||
if (!raw) continue;
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(raw); } catch { continue; }
|
||||
const value = parsed?.claudeAiOauth?.accessToken;
|
||||
if (typeof value === "string" && value.length) { token = value; break; }
|
||||
}
|
||||
// On macOS the CLI stores the isolated login in the auth home's own
|
||||
// suffixed Keychain item rather than a credentials file. The helper
|
||||
// never consults the unsuffixed operator item.
|
||||
if (!token) token = await readIsolatedClaudeKeychainToken(loginHome);
|
||||
} else {
|
||||
token = await readClaudeToken({ allowKeychain: true });
|
||||
for (const name of [".credentials.json", "credentials.json"]) {
|
||||
const raw = await readLocalAiCredentialFile(path.join(loginHome, name)).catch(() => null);
|
||||
if (!raw) continue;
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(raw); } catch { continue; }
|
||||
const value = parsed?.claudeAiOauth?.accessToken;
|
||||
if (typeof value === "string" && value.length) { token = value; break; }
|
||||
}
|
||||
// On macOS the CLI stores the isolated login in the auth home's own
|
||||
// suffixed Keychain item rather than a credentials file. The helper
|
||||
// never consults the unsuffixed operator item.
|
||||
if (!token) token = await readIsolatedClaudeKeychainToken(loginHome);
|
||||
if (!token) throw new Error("Missing login");
|
||||
await fetchClaudeQuota(token);
|
||||
// Claude's setup-token OAuth flow requests user:inference. The usage API
|
||||
// requires user:profile and returns 403 for that valid token, so it cannot
|
||||
// serve as a sign-in check. This isolated credential is written only after
|
||||
// the provider CLI completes the code exchange successfully.
|
||||
return token;
|
||||
}
|
||||
if (provider === "openai") {
|
||||
@@ -55,8 +55,8 @@ export async function readVerifiedLocalAiCredential(provider: AiProvider, loginH
|
||||
return raw;
|
||||
} catch {
|
||||
// Provider/CLI errors may contain credential material; never return them.
|
||||
throw unprocessable(provider === "anthropic" && !loginHome
|
||||
? "Could not verify the local subscription. Run claude auth login in a terminal on the machine running Paperclip, then try Connect again."
|
||||
: "Could not verify the local subscription. Run the sign-in command shown for this connection, finish signing in, then try Connect again.");
|
||||
throw unprocessable(provider === "xai"
|
||||
? "Could not verify the local subscription. Run the sign-in command shown for this connection, finish signing in, then try Connect again."
|
||||
: "Could not verify the local subscription. Finish browser sign-in for this connection, then try Connect again.");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { and, eq, inArray, lte, sql } from "drizzle-orm";
|
||||
@@ -9,22 +10,26 @@ import { notFound, unprocessable } from "../errors.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { readVerifiedLocalAiCredential } from "./local-ai-credentials.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { startLocalBrowserLogin, type LocalBrowserLoginState } from "./local-ai-browser-login.js";
|
||||
|
||||
const LOCAL_LOGIN_METHOD = "local_subscription";
|
||||
const ATTEMPT_DURATION_MS = 30 * 60 * 1000;
|
||||
function loginHome(id: string) {
|
||||
return path.join(resolvePaperclipInstanceRoot(), "ai-local-logins", id);
|
||||
const root = resolvePaperclipInstanceRoot();
|
||||
// macOS exposes /var through a system symlink to /private/var. Credential
|
||||
// reads use O_NOFOLLOW_ANY, so generate login homes from the canonical root.
|
||||
// A fresh instance root may not exist yet; prepareHome creates it first.
|
||||
let canonicalRoot = root;
|
||||
try { canonicalRoot = realpathSync(root); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
||||
return path.join(canonicalRoot, "ai-local-logins", id);
|
||||
}
|
||||
const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
|
||||
function presentAttempt(id: string, expiresAt: Date, provider: string): LocalAiLoginAttempt {
|
||||
const directory = loginHome(id);
|
||||
return {
|
||||
sessionId: id, expiresAt: expiresAt.toISOString(),
|
||||
command: provider === "openai"
|
||||
? `(export CODEX_HOME=${shellQuote(directory)} && mkdir -p "$CODEX_HOME" && codex -c 'cli_auth_credentials_store="file"' login --device-auth)`
|
||||
: provider === "anthropic"
|
||||
? `(export CLAUDE_CONFIG_DIR=${shellQuote(directory)} && mkdir -p "$CLAUDE_CONFIG_DIR" && claude auth login)`
|
||||
: `(export GROK_HOME=${shellQuote(directory)} && mkdir -p "$GROK_HOME" && grok login --device-auth)`,
|
||||
...(provider === "xai" ? { command: `(export GROK_HOME=${shellQuote(directory)} && mkdir -p "$GROK_HOME" && grok login --device-auth)` } : {}),
|
||||
};
|
||||
}
|
||||
async function prepareHome(id: string, provider: string) {
|
||||
@@ -41,9 +46,21 @@ function sameTarget(a: AiConnectionLoginIntent, b: AiConnectionLoginIntent) {
|
||||
JSON.stringify([...a.agentIds].sort()) === JSON.stringify([...b.agentIds].sort());
|
||||
}
|
||||
|
||||
/** Local terminal sign-ins share the durable attempt/credential lifecycle, but
|
||||
* never seed their home from the operator's rotating CLI credential. */
|
||||
// Route handlers construct this service per request. Keep live browser processes
|
||||
// shared so status polling and code submission can reach the original process.
|
||||
const browserLogins = new Map<string, LocalBrowserLoginState>();
|
||||
|
||||
/** Local sign-ins share the durable attempt/credential lifecycle, but never seed
|
||||
* their home from the operator's rotating CLI credential. */
|
||||
export function localAiLoginService(db: Db) {
|
||||
function stopBrowserLogin(id: string) {
|
||||
browserLogins.get(id)?.abort();
|
||||
browserLogins.delete(id);
|
||||
}
|
||||
function ensureBrowserLogin(id: string, provider: string) {
|
||||
if (provider === "xai" || browserLogins.has(id)) return;
|
||||
browserLogins.set(id, startLocalBrowserLogin(provider as "anthropic" | "openai", loginHome(id)));
|
||||
}
|
||||
async function reapExpired() {
|
||||
// Bounded batches use the existing expires-at index. Replaying is safe.
|
||||
const rows = await db.select({ id: adapterAuthSessions.id }).from(adapterAuthSessions)
|
||||
@@ -55,6 +72,7 @@ export function localAiLoginService(db: Db) {
|
||||
const [session] = await tx.select().from(adapterAuthSessions)
|
||||
.where(eq(adapterAuthSessions.id, row.id)).for("update");
|
||||
if (!session || !session.expiresAt || session.expiresAt.getTime() > Date.now()) return;
|
||||
stopBrowserLogin(row.id);
|
||||
await rm(loginHome(row.id), { recursive: true, force: true });
|
||||
await tx.update(adapterAuthSessions).set({
|
||||
status: session.connectionId ? "authenticated" : "timed_out",
|
||||
@@ -68,7 +86,7 @@ export function localAiLoginService(db: Db) {
|
||||
if (intent.provider !== "openai" && intent.provider !== "xai" && intent.provider !== "anthropic")
|
||||
throw unprocessable("This provider does not use a separate local login home.");
|
||||
await reapExpired();
|
||||
return db.transaction(async (tx) => {
|
||||
const attempt = await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`ai-local-login:${companyId}:${userId}:${intent.provider}`}, 0))`);
|
||||
const adapterType = intent.provider === "openai" ? "codex_local" : intent.provider === "anthropic" ? "claude_local" : "grok_local";
|
||||
const [existing] = await tx.select().from(adapterAuthSessions).where(and(
|
||||
@@ -85,6 +103,7 @@ export function localAiLoginService(db: Db) {
|
||||
}
|
||||
if (!restart || existing.connectionMethod !== LOCAL_LOGIN_METHOD)
|
||||
throw unprocessable("Another sign-in is still open. Finish it, or choose Start sign-in again to replace a local attempt.");
|
||||
stopBrowserLogin(existing.id);
|
||||
await rm(loginHome(existing.id), { recursive: true, force: true });
|
||||
await tx.update(adapterAuthSessions).set({ status: "cancelled", finishedAt: new Date(), updatedAt: new Date() })
|
||||
.where(eq(adapterAuthSessions.id, existing.id));
|
||||
@@ -120,14 +139,18 @@ export function localAiLoginService(db: Db) {
|
||||
}
|
||||
return presentAttempt(id, expiresAt, intent.provider);
|
||||
});
|
||||
ensureBrowserLogin(attempt.sessionId, intent.provider);
|
||||
return attempt;
|
||||
}
|
||||
|
||||
// Read-only credential detection: never saves a connection or refreshes another
|
||||
// login. Scope and intent are checked before touching an attempt's directory.
|
||||
async function check(companyId: string, userId: string, intent: AiConnectionLoginIntent, id?: string): Promise<LocalAiLoginStatus> {
|
||||
let directory: string | undefined;
|
||||
if (id || intent.provider !== "anthropic") {
|
||||
if (!id) throw unprocessable("Start local sign-in before checking this account.");
|
||||
{
|
||||
if (!id) throw unprocessable(intent.provider === "xai"
|
||||
? "Start local sign-in before checking this account."
|
||||
: "Start browser sign-in before checking this account.");
|
||||
const [session] = await db.select().from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.id, id), eq(adapterAuthSessions.companyId, companyId),
|
||||
eq(adapterAuthSessions.startedByUserId, userId),
|
||||
@@ -143,10 +166,35 @@ export function localAiLoginService(db: Db) {
|
||||
await readVerifiedLocalAiCredential(intent.provider, directory);
|
||||
return { status: "ready" };
|
||||
} catch {
|
||||
return { status: "sign_in_required" };
|
||||
const login = id ? browserLogins.get(id) : undefined;
|
||||
return { status: "sign_in_required", authorizationUrl: login?.authorizationUrl, code: login?.code,
|
||||
...(login?.outcome === "failure" ? { error: "Sign-in ended before the account was connected. Start sign-in again." } : {}) };
|
||||
}
|
||||
}
|
||||
|
||||
async function submitCode(companyId: string, userId: string, id: string, code: string) {
|
||||
await db.transaction(async (tx) => {
|
||||
const [session] = await tx.select().from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.id, id), eq(adapterAuthSessions.companyId, companyId),
|
||||
eq(adapterAuthSessions.startedByUserId, userId), eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD),
|
||||
eq(adapterAuthSessions.adapterType, "claude_local"),
|
||||
)).for("update");
|
||||
if (!session) throw notFound("Local sign-in attempt not found.");
|
||||
if (session.status !== "waiting_for_user" || !session.expiresAt || session.expiresAt.getTime() <= Date.now())
|
||||
throw unprocessable("This sign-in attempt has expired or was cancelled. Start sign-in again.");
|
||||
const login = browserLogins.get(id);
|
||||
if (!login?.authorizationUrl || !login.submitCode || login.outcome)
|
||||
throw unprocessable("This sign-in attempt cannot accept a code. Start sign-in again.");
|
||||
const submit = login.submitCode;
|
||||
login.submitCode = undefined;
|
||||
submit(code);
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId, actorType: "user", actorId: userId, action: "ai_connection.local_login_code_submitted",
|
||||
entityType: "adapter_auth_session", entityId: id, details: { provider: "anthropic" },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function complete(companyId: string, userId: string, id: string, intent: AiConnectionLoginIntent) {
|
||||
const result = await db.transaction(async (tx) => {
|
||||
const [session] = await tx.select().from(adapterAuthSessions).where(and(
|
||||
@@ -176,6 +224,7 @@ export function localAiLoginService(db: Db) {
|
||||
return saved;
|
||||
});
|
||||
// Failed cleanup can be retried by the same completed attempt or reaper.
|
||||
stopBrowserLogin(id);
|
||||
await rm(loginHome(id), { recursive: true, force: true });
|
||||
return result;
|
||||
}
|
||||
@@ -188,6 +237,7 @@ export function localAiLoginService(db: Db) {
|
||||
eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD),
|
||||
)).for("update");
|
||||
if (!session) throw notFound("Local sign-in attempt not found.");
|
||||
stopBrowserLogin(id);
|
||||
await rm(loginHome(id), { recursive: true, force: true });
|
||||
if (!session.connectionId && session.status !== "cancelled") {
|
||||
await tx.update(adapterAuthSessions).set({
|
||||
@@ -201,5 +251,5 @@ export function localAiLoginService(db: Db) {
|
||||
}
|
||||
});
|
||||
}
|
||||
return { start, check, complete, cancel, reapExpired };
|
||||
return { start, check, submitCode, complete, cancel, reapExpired };
|
||||
}
|
||||
Reference in new issue
Block a user