paseo-plugin-account-switcher 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,80 @@
1
+ import { spawn } from "node:child_process";
2
+ import { lstat, realpath } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { readRegistry } from "./store";
5
+ import { assertManagedCommand, buildAccountEnv, prepareProfile } from "./profiles";
6
+ import { atomicWrite } from "./files";
7
+
8
+ class LauncherError extends Error {}
9
+ let loginCompletion: { path: string; loginToken: string } | undefined;
10
+ async function finishLogin(exitCode: number): Promise<void> {
11
+ if (loginCompletion) await atomicWrite(loginCompletion.path, JSON.stringify({ loginToken: loginCompletion.loginToken, exitCode, finishedAt: new Date().toISOString() }));
12
+ }
13
+
14
+ async function main(): Promise<void> {
15
+ const executable = resolve(process.argv[1]), root = dirname(dirname(executable));
16
+ const provider = basename(executable) === "claude-launcher" ? "claude" : basename(executable) === "codex-launcher" ? "codex" : null;
17
+ if (!provider) throw new LauncherError("Unknown account launcher.");
18
+ let registry;
19
+ try { registry = await readRegistry(root); } catch { throw new LauncherError("Account registry is missing or corrupt; launch refused."); }
20
+ const command = registry.commands[provider];
21
+ if (!command?.[0] || !isAbsolute(command[0]) || [join(root, "bin", "claude-launcher"), join(root, "bin", "codex-launcher")].includes(resolve(command[0]))) throw new LauncherError("Original provider command is unavailable; launch refused.");
22
+ let args = process.argv.slice(2), env = { ...process.env };
23
+ const login = args[0] === "--account-switcher-login", agentId = env.PASEO_AGENT_ID;
24
+ const binding = agentId ? registry.bindings.find(candidate => candidate.agentId === agentId && candidate.provider === provider) : undefined;
25
+ const accountId = login ? args[1] : binding?.launchAccountId ?? binding?.currentAccountId;
26
+ if (login && (!accountId || (args.length !== 2 && !(provider === "codex" && args.length === 3 && args[2] === "--browser")))) throw new LauncherError("Invalid account login arguments.");
27
+ const account = accountId ? registry.accounts.find(candidate => candidate.id === accountId && candidate.provider === provider) : undefined;
28
+ if (accountId && !account) throw new LauncherError("Assigned account profile is unavailable; launch refused.");
29
+ if (login && account?.source !== "managed") throw new LauncherError("Only managed account profiles support this login command.");
30
+ if (!login && account?.loginToken) throw new LauncherError("Account login is still in progress; launch refused.");
31
+ if (account?.source === "managed") {
32
+ if (!/^[a-zA-Z0-9_-]+$/.test(account.id) || resolve(account.home) !== join(root, "accounts", account.id, provider)) throw new LauncherError("Assigned account profile path is invalid; launch refused.");
33
+ if (login) {
34
+ if (!account.loginToken) throw new LauncherError("Start this account login from Paseo before running the login launcher.");
35
+ loginCompletion = { path: join(root, "logins", `${account.id}.json`), loginToken: account.loginToken };
36
+ }
37
+ try { await assertManagedCommand(provider, [...command.slice(1), ...args]); }
38
+ catch { throw new LauncherError("Provider arguments override account isolation; launch refused."); }
39
+ try {
40
+ if (!(await lstat(account.home)).isDirectory() || await realpath(account.home) !== join(await realpath(root), "accounts", account.id, provider)) throw new Error();
41
+ } catch { throw new LauncherError("Assigned account profile is missing or redirected; launch refused. Restore the profile or select another account."); }
42
+ try { await prepareProfile({ provider, home: account.home, sourceHome: registry.sourceHomes[provider], sourceEnvironment: registry.sourceEnvironment[provider] }); } catch { throw new LauncherError("Account profile preparation failed; inspect shared provider configuration."); }
43
+ env = buildAccountEnv(provider, account.home, env);
44
+ }
45
+ if (login) args = provider === "claude" ? ["auth", "login", "--claudeai"] : args[2] === "--browser" ? ["login"] : ["login", "--device-auth"];
46
+ const child = spawn(command[0], [...command.slice(1), ...args], { env, stdio: "inherit" });
47
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
48
+ const forward = new Map<NodeJS.Signals, () => void>();
49
+ for (const signal of signals) { const handler = () => { child.kill(signal); }; forward.set(signal, handler); process.on(signal, handler); }
50
+ let receipt: Promise<void> = Promise.resolve();
51
+ const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolveExit, reject) => {
52
+ child.once("error", () => reject(new LauncherError("Could not start the configured provider CLI.")));
53
+ child.once("spawn", () => {
54
+ if (!login && binding && account && agentId) {
55
+ receipt = atomicWrite(join(root, "receipts", `${encodeURIComponent(agentId)}.json`), JSON.stringify({ accountId: account.id, launchToken: binding.launchToken, pid: child.pid, at: new Date().toISOString() }));
56
+ // A receipt failure cannot be treated as a successful identity switch.
57
+ receipt.catch(() => { child.kill("SIGTERM"); });
58
+ }
59
+ });
60
+ child.once("close", (code, signal) => resolveExit({ code, signal }));
61
+ });
62
+ const result = await exited;
63
+ await receipt;
64
+ await finishLogin(result.code ?? 1);
65
+ for (const [signal, handler] of forward) process.removeListener(signal, handler);
66
+ if (login && provider === "codex" && result.code !== 0) {
67
+ const quoted = `'${executable.replace(/'/g, `'\\''`)}'`;
68
+ process.stderr.write(`\nDevice login can require enabling device-code authentication in ChatGPT security settings. For browser login on this host, run:\n${quoted} --account-switcher-login ${account!.id} --browser\n`);
69
+ }
70
+ if (result.signal) { process.kill(process.pid, result.signal); return; }
71
+ process.exitCode = result.code ?? 1;
72
+ }
73
+
74
+ main().catch(async error => {
75
+ await finishLogin(1).catch(() => {});
76
+ const safe = error instanceof LauncherError ? error.message : "Account launcher failed.";
77
+ // Only errors constructed above leave this process. Filesystem/parse failures remain private.
78
+ process.stderr.write(`Account switcher: ${safe}\n`);
79
+ process.exitCode = 1;
80
+ });
@@ -0,0 +1,119 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ export type LoginProcessOptions = {
4
+ command: string[]; args: string[]; env: NodeJS.ProcessEnv; cwd: string;
5
+ receiptPath: string; loginToken: string;
6
+ onData: (stream: "stdout" | "stderr", data: string) => void;
7
+ onExit: (code: number, receiptWritten: boolean) => void;
8
+ };
9
+ export type LoginProcess = { ready(): Promise<void>; start(): void; write(data: string): void; stop(code?: number): Promise<void> };
10
+ export type CreateLoginProcess = (options: LoginProcessOptions) => LoginProcess;
11
+
12
+ // The IPC pipe is an OS-owned parent-liveness signal. Even an abrupt daemon exit
13
+ // closes it, so this supervisor can stop the native process before recording exit.
14
+ // No authentication output, URLs, or codes are written to the receipt.
15
+ const supervisor = String.raw`
16
+ const {spawn}=require('node:child_process');
17
+ const fs=require('node:fs'),path=require('node:path');
18
+ let child,config={receiptPath:process.argv[1],loginToken:process.argv[2]},launched=false,finished=false,stopping=false,forcedCode,killTimer,deadline;
19
+ function kill(signal){if(!child?.pid)return;try{if(process.platform==='win32')child.kill(signal);else process.kill(-child.pid,signal);}catch(error){if(error.code!=='ESRCH')throw error;}}
20
+ let finalizing=false;
21
+ function finish(code){
22
+ if(finished||finalizing)return;finalizing=true;clearTimeout(killTimer);
23
+ // A leader can exit while a descendant ignores TERM. Kill and observe the
24
+ // entire isolated group before claiming that credential writes have stopped.
25
+ try{kill('SIGKILL');}catch{}
26
+ const until=Date.now()+3000;
27
+ function confirm(){
28
+ let alive=false;if(process.platform!=='win32'&&child?.pid)try{process.kill(-child.pid,0);alive=true;}catch(error){if(error.code!=='ESRCH')alive=true;}
29
+ if(alive){if(Date.now()>=until)return process.exit(1);return setTimeout(confirm,20);}
30
+ record(code);
31
+ }
32
+ confirm();
33
+ }
34
+ function record(code){
35
+ if(finished)return;finished=true;clearTimeout(deadline);
36
+ let receiptWritten=false;
37
+ if(config)try{const target=config.receiptPath;fs.mkdirSync(path.dirname(target),{recursive:true,mode:0o700});const temporary=target+'.'+process.pid+'.tmp';fs.writeFileSync(temporary,JSON.stringify({loginToken:config.loginToken,exitCode:forcedCode??code,finishedAt:new Date().toISOString()}),{mode:0o600});fs.renameSync(temporary,target);receiptWritten=true;}catch{}
38
+ if(process.connected)process.send({type:'exit',code:forcedCode??code,receiptWritten},()=>process.exit(0));else process.exit(0);
39
+ }
40
+ function stop(code=1){
41
+ if(stopping||finished)return;stopping=true;forcedCode=code;
42
+ if(!child)return finish(1);
43
+ try{kill('SIGTERM');}catch{}
44
+ killTimer=setTimeout(()=>{try{kill('SIGKILL');}catch{}},500);
45
+ // Do not claim exit or write a receipt without observing the native close event.
46
+ deadline=setTimeout(()=>process.exit(1),4000);
47
+ }
48
+ process.on('disconnect',()=>stop(1));process.on('SIGTERM',()=>stop(1));process.on('SIGINT',()=>stop(1));
49
+ process.on('message',message=>{
50
+ if(message?.type==='stop')return stop(message.code===0?0:1);
51
+ if(message?.type!=='start'||launched||stopping)return;
52
+ launched=true;config={...config,...message};
53
+ try{
54
+ child=spawn(config.command[0],[...config.command.slice(1),...config.args],{env:config.env,cwd:config.cwd,stdio:['pipe','pipe','pipe'],detached:process.platform!=='win32',windowsHide:true});
55
+ child.stdout.pipe(process.stdout);child.stderr.pipe(process.stderr);process.stdin.pipe(child.stdin);
56
+ child.stdin.on('error',()=>{});child.once('error',()=>finish(1));child.once('close',code=>finish(code??1));
57
+ }catch{finish(1);}
58
+ });
59
+ if(!process.connected)stop(1);else process.send({type:'ready'});
60
+ `;
61
+
62
+ export const createLoginProcess: CreateLoginProcess = options => {
63
+ const child = spawn(process.execPath, ["-e", supervisor, options.receiptPath, options.loginToken], {
64
+ cwd: options.cwd, env: options.env, stdio: ["pipe", "pipe", "pipe", "ipc"], windowsHide: true,
65
+ });
66
+ let receipt: { code: number; receiptWritten: boolean } | undefined;
67
+ let exited = false;
68
+ let acknowledge!: () => void, rejectReady!: () => void;
69
+ const ready = new Promise<void>((resolve,reject) => { acknowledge=resolve;rejectReady=()=>reject(new Error("Could not start the sign-in watchdog.")); });
70
+ void ready.catch(()=>{});
71
+ const closed = new Promise<void>(resolve => {
72
+ child.once("close", () => {
73
+ exited = true;
74
+ rejectReady();
75
+ options.onExit(receipt?.code ?? 1, receipt?.receiptWritten ?? false);
76
+ resolve();
77
+ });
78
+ });
79
+ child.on("error", rejectReady);
80
+ child.stdin!.on("error", () => {});
81
+ child.stdout!.setEncoding("utf8").on("data", data => options.onData("stdout", data));
82
+ child.stderr!.setEncoding("utf8").on("data", data => options.onData("stderr", data));
83
+ child.on("message", message => {
84
+ if (message && typeof message === "object" && "type" in message && message.type === "ready") acknowledge();
85
+ if (message && typeof message === "object" && "type" in message && message.type === "exit") {
86
+ const value = message as Record<string, unknown>;
87
+ receipt = { code: value.code === 0 ? 0 : 1, receiptWritten: value.receiptWritten === true };
88
+ }
89
+ });
90
+ let spawned = false, requested = false;
91
+ const start = () => { if (spawned && requested && child.connected) child.send({ type: "start", command: options.command, args: options.args,
92
+ env: options.env, cwd: options.cwd }, () => {}); };
93
+ child.once("spawn", () => { spawned = true; start(); });
94
+ return {
95
+ async ready() {
96
+ let timer: ReturnType<typeof setTimeout> | undefined;
97
+ try { await Promise.race([ready,new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(new Error("The sign-in watchdog did not start in time.")),5000);})]); }
98
+ finally { clearTimeout(timer); }
99
+ },
100
+ start() { requested = true; start(); },
101
+ write(data) {
102
+ if (exited || !child.stdin!.writable) throw new Error("The sign-in process is no longer available.");
103
+ child.stdin!.write(data);
104
+ },
105
+ async stop(code = 1) {
106
+ if (!exited) {
107
+ if (child.connected) child.send({ type: "stop", code }, () => {});
108
+ else child.kill("SIGTERM");
109
+ }
110
+ let timer: ReturnType<typeof setTimeout> | undefined;
111
+ try {
112
+ await Promise.race([closed, new Promise<never>((_, reject) => {
113
+ timer = setTimeout(() => reject(new Error("Could not confirm that sign-in stopped. Try again shortly.")), 5000);
114
+ })]);
115
+ if (!receipt?.receiptWritten) throw new Error("Could not confirm that sign-in stopped. Try again shortly.");
116
+ } finally { clearTimeout(timer); }
117
+ },
118
+ };
119
+ };
@@ -0,0 +1,167 @@
1
+ import { lstat, mkdir, realpath } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import type { LoginSession } from "../shared/contracts";
4
+ import type { Registry, StoredAccount } from "./store";
5
+ import { accountCommand, accountEnvironment } from "./auth";
6
+ import { assertManagedCommand, prepareProfile } from "./profiles";
7
+ import { createLoginProcess, type CreateLoginProcess, type LoginProcess } from "./login-process";
8
+
9
+ type Entry = {
10
+ value: LoginSession; process?: LoginProcess; timer?: ReturnType<typeof setTimeout>;
11
+ buffer: string; nativeLoginId?: string; nativeSuccess: boolean; stopped: boolean;
12
+ pendingCompletions: Array<Record<string, unknown>>; finishing?: Promise<void>;
13
+ };
14
+ export type LoginDependencies = {
15
+ createProcess?: CreateLoginProcess; timeoutMs?: number;
16
+ finish: (accountId: string, sessionId: string, successful: boolean) => Promise<boolean>;
17
+ };
18
+ const stale = () => new Error("This sign-in attempt is no longer active. Start sign-in again.");
19
+ const clearDetails = (value: LoginSession) => { value.authorizationUrl = null; value.userCode = null; value.canSubmitCode = false; };
20
+ function loginUrl(value: unknown, provider: "claude" | "codex", mode?: "device" | "browser"): string | null {
21
+ if (typeof value !== "string" || value.length > 16384 || /[\u0000-\u0020\u007f]/.test(value)) return null;
22
+ try {
23
+ const url = new URL(value);
24
+ const hosts = provider === "claude" ? ["claude.ai", "claude.com", "platform.claude.com", "console.anthropic.com"] : ["auth.openai.com"];
25
+ if (url.protocol !== "https:" || url.username || url.password || url.port || !hosts.includes(url.hostname)) return null;
26
+ if (provider === "claude" && (url.pathname !== (url.hostname === "claude.com" ? "/cai/oauth/authorize" : "/oauth/authorize") || !url.searchParams.get("state") || !url.searchParams.get("code_challenge"))) return null;
27
+ if (provider === "codex" && url.pathname !== (mode === "device" ? "/codex/device" : "/oauth/authorize")) return null;
28
+ return url.toString();
29
+ } catch { return null; }
30
+ }
31
+
32
+ export class LoginSessions {
33
+ private readonly entries = new Map<string, Entry>();
34
+ private disposed = false;
35
+ constructor(private readonly dependencies: LoginDependencies) {}
36
+ async start(account: StoredAccount, registry: Registry, root: string, sessionId: string, mode: "device" | "browser" = "device", beforeLaunch?: () => Promise<void>): Promise<LoginSession> {
37
+ if (this.disposed) throw new Error("Account sign-in is shutting down. Try again shortly.");
38
+ if (account.source !== "managed") throw new Error("Add a separate account for isolated sign-in.");
39
+ const command = accountCommand(registry, account.provider);
40
+ await assertManagedCommand(account.provider, command.slice(1));
41
+ if (!(await lstat(account.home)).isDirectory() || await realpath(account.home) !== join(await realpath(root), "accounts", account.id, account.provider)) throw new Error("The isolated account profile is missing or redirected.");
42
+ await prepareProfile({ provider: account.provider, home: account.home, sourceHome: registry.sourceHomes[account.provider], sourceEnvironment: registry.sourceEnvironment[account.provider] });
43
+ const cwd = join(root, "login", account.id); await mkdir(cwd, { recursive: true, mode: 0o700 });
44
+ if (this.disposed) throw new Error("Account sign-in is shutting down. Try again shortly.");
45
+ const duration = Math.min(this.dependencies.timeoutMs ?? 15 * 60_000, 15 * 60_000);
46
+ const entry: Entry = { value: { id: sessionId, accountId: account.id, provider: account.provider,
47
+ mode: account.provider === "claude" ? "browser" : mode, status: "starting", authorizationUrl: null,
48
+ userCode: null, canSubmitCode: false, error: null, expiresAt: new Date(Date.now() + duration).toISOString() },
49
+ buffer: "", nativeSuccess: false, stopped: false, pendingCompletions: [] };
50
+ this.entries.set(account.id, entry);
51
+ const env = { ...accountEnvironment(account, registry), BROWSER: "/usr/bin/true", NO_COLOR: "1", TERM: "dumb" };
52
+ try {
53
+ entry.process = (this.dependencies.createProcess ?? createLoginProcess)({ command,
54
+ args: account.provider === "claude" ? ["auth", "login", "--claudeai"] : ["app-server", "--stdio"], env, cwd,
55
+ receiptPath: join(root, "logins", `${account.id}.json`), loginToken: sessionId,
56
+ onData: (stream, data) => this.receive(entry, stream, data),
57
+ onExit: (code, receiptWritten) => {
58
+ entry.stopped = true; clearTimeout(entry.timer); clearDetails(entry.value); entry.buffer = ""; entry.pendingCompletions = [];
59
+ const successful = code === 0 && (account.provider === "claude" || entry.nativeSuccess);
60
+ entry.finishing = (async () => {
61
+ if (receiptWritten) {
62
+ entry.value.status = "verifying";
63
+ const ready = await this.dependencies.finish(account.id, sessionId, successful);
64
+ if (successful && ready) { entry.value.status = "complete"; entry.value.error = null; return; }
65
+ }
66
+ entry.value.status = "error";
67
+ entry.value.error ??= receiptWritten ? "Sign-in was not completed. Start sign-in again." : "Sign-in stopped unexpectedly. Wait a moment, then cancel this attempt before trying again.";
68
+ })().catch(() => { entry.value.status = "error"; entry.value.error = "Could not verify sign-in. Check the account and try again."; });
69
+ },
70
+ });
71
+ // Establish the crash watchdog before persisting a login reservation. The
72
+ // native CLI cannot start until that reservation has been committed.
73
+ await entry.process.ready();
74
+ await beforeLaunch?.();
75
+ if (entry.stopped || this.disposed) throw new Error("Sign-in stopped before launch.");
76
+ entry.process.start();
77
+ entry.timer = setTimeout(() => { void this.fail(entry, "Sign-in expired. Start sign-in again."); }, duration);
78
+ entry.timer.unref();
79
+ if (account.provider === "codex") entry.process.write(JSON.stringify({ id: 1, method: "initialize", params: {
80
+ clientInfo: { name: "paseo_account_switcher", title: "Paseo Account Switcher", version: "0.1.0" }, capabilities: null,
81
+ } }) + "\n");
82
+ return structuredClone(entry.value);
83
+ } catch {
84
+ clearTimeout(entry.timer);
85
+ if (entry.process) await entry.process.stop();
86
+ this.entries.delete(account.id);
87
+ throw new Error("Could not start account sign-in. Check the provider CLI and try again.");
88
+ }
89
+ }
90
+ private receive(entry: Entry, stream: "stdout" | "stderr", data: string) {
91
+ if (entry.stopped || entry.value.status === "error" || stream !== "stdout") return;
92
+ if (entry.buffer.length + data.length > 128 * 1024) { void this.fail(entry, "The provider returned an unsupported sign-in response. Update the CLI and try again."); return; }
93
+ entry.buffer += data;
94
+ if (entry.value.provider === "claude") {
95
+ // The official CLI prints its manual-redirect URL; keep only this URL.
96
+ const plain = entry.buffer.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
97
+ for (const candidate of plain.match(/https:\/\/[^\s<>\x1b]+(?=[\s<>\x1b])/g) ?? []) {
98
+ const url = loginUrl(candidate, "claude");
99
+ if (url && entry.value.status === "starting") { entry.value.authorizationUrl = url; entry.value.canSubmitCode = true; entry.value.status = "waiting"; }
100
+ }
101
+ return;
102
+ }
103
+ let newline: number;
104
+ while ((newline = entry.buffer.indexOf("\n")) !== -1) {
105
+ const line = entry.buffer.slice(0, newline); entry.buffer = entry.buffer.slice(newline + 1);
106
+ if (!line.trim()) continue;
107
+ let message: Record<string, unknown>;
108
+ try { message = JSON.parse(line); if (!message || typeof message !== "object") throw new Error(); }
109
+ catch { void this.fail(entry, "The provider returned an unsupported sign-in response. Update Codex and try again."); return; }
110
+ if (message.id === 1) {
111
+ if (message.error || !message.result) { void this.fail(entry, "Could not initialize Codex sign-in. Update Codex and try again."); return; }
112
+ entry.process?.write(JSON.stringify({ method: "initialized" }) + "\n");
113
+ entry.process?.write(JSON.stringify({ id: 2, method: "account/login/start", params: { type: entry.value.mode === "device" ? "chatgptDeviceCode" : "chatgpt" } }) + "\n");
114
+ } else if (message.id === 2) {
115
+ const result = message.result as Record<string, unknown> | undefined;
116
+ const expected = entry.value.mode === "device" ? "chatgptDeviceCode" : "chatgpt";
117
+ const url = loginUrl(expected === "chatgptDeviceCode" ? result?.verificationUrl : result?.authUrl, "codex", entry.value.mode);
118
+ if (message.error || result?.type !== expected || typeof result.loginId !== "string" || !result.loginId || !url || expected === "chatgptDeviceCode" && (typeof result.userCode !== "string" || !/^[A-Za-z0-9-]{3,64}$/.test(result.userCode))) {
119
+ void this.fail(entry, entry.value.mode === "device" ? "Device sign-in is unavailable. Enable device code login in ChatGPT security settings, or use browser sign-in on the daemon host." : "Could not start browser sign-in. Try device sign-in or check the provider CLI."); return;
120
+ }
121
+ entry.nativeLoginId = result.loginId; entry.value.authorizationUrl = url;
122
+ entry.value.userCode = expected === "chatgptDeviceCode" ? result.userCode as string : null; entry.value.status = "waiting";
123
+ for (const pending of entry.pendingCompletions.splice(0)) this.completed(entry, pending);
124
+ } else if (message.method === "account/login/completed") {
125
+ const params = message.params as Record<string, unknown> | undefined;
126
+ if (!params || typeof params.loginId !== "string") continue;
127
+ if (entry.nativeLoginId) this.completed(entry, params);
128
+ else if (entry.pendingCompletions.length < 8) entry.pendingCompletions.push({loginId:params.loginId,success:params.success});
129
+ }
130
+ }
131
+ }
132
+ private completed(entry: Entry, params: Record<string, unknown>) {
133
+ if (entry.stopped || entry.value.status === "verifying" || params.loginId !== entry.nativeLoginId) return;
134
+ if (params.success !== true) { void this.fail(entry, "The provider did not complete sign-in. Start sign-in again."); return; }
135
+ entry.nativeSuccess = true; entry.value.status = "verifying"; clearDetails(entry.value);
136
+ void entry.process?.stop(0).catch(() => { entry.value.status = "error"; entry.value.error = "Could not confirm that sign-in finished. Try checking again shortly."; });
137
+ }
138
+ private async fail(entry: Entry, message: string) {
139
+ entry.value.status = "error"; entry.value.error = message; clearDetails(entry.value); entry.buffer = ""; entry.pendingCompletions = []; clearTimeout(entry.timer);
140
+ try { await entry.process?.stop(); } catch { entry.value.error = "Could not confirm that sign-in stopped. Try canceling again shortly."; }
141
+ }
142
+ has(accountId: string, sessionId: string): boolean { return this.entries.get(accountId)?.value.id === sessionId; }
143
+ status(accountId: string, sessionId: string): LoginSession {
144
+ const entry = this.entries.get(accountId); if (!entry || entry.value.id !== sessionId) throw stale();
145
+ return structuredClone(entry.value);
146
+ }
147
+ submit(accountId: string, sessionId: string, input: string): LoginSession {
148
+ const entry = this.entries.get(accountId); if (!entry || entry.value.id !== sessionId) throw stale();
149
+ if (!entry.value.canSubmitCode || entry.value.status !== "waiting" || !entry.value.authorizationUrl || entry.stopped) throw new Error("This sign-in attempt is not waiting for a code.");
150
+ const code = input.trim();
151
+ if (code.length > 2048 || !/^[A-Za-z0-9_-]+#[A-Za-z0-9_-]+$/.test(code) || code.split("#")[1] !== new URL(entry.value.authorizationUrl).searchParams.get("state")) throw new Error("Use the complete sign-in code from this attempt, including the part after #.");
152
+ entry.value.status = "verifying"; entry.value.canSubmitCode = false;
153
+ entry.process?.write(code + "\n");
154
+ return structuredClone(entry.value);
155
+ }
156
+ async cancel(accountId: string, sessionId: string): Promise<void> {
157
+ const entry = this.entries.get(accountId); if (!entry || entry.value.id !== sessionId) throw stale();
158
+ entry.value.error = "Sign-in canceled."; clearDetails(entry.value); entry.buffer = ""; entry.pendingCompletions = []; clearTimeout(entry.timer);
159
+ if (!entry.stopped && entry.nativeLoginId) entry.process?.write(JSON.stringify({ id: 3, method: "account/login/cancel", params: { loginId: entry.nativeLoginId } }) + "\n");
160
+ await entry.process?.stop(); await entry.finishing;
161
+ entry.value.status = "error"; clearDetails(entry.value);
162
+ }
163
+ async close(): Promise<void> {
164
+ this.disposed = true;
165
+ await Promise.allSettled([...this.entries].map(([id, entry]) => this.cancel(id, entry.value.id)));
166
+ }
167
+ }
@@ -0,0 +1,5 @@
1
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
2
+
3
+ // Paseo installs npm packages without devDependencies, so server code cannot
4
+ // name `@getpaseo/client` types directly. The host-provided SDK entry carries the same type.
5
+ export type PaseoApi = PluginHandlerContext["paseo"];
@@ -0,0 +1,138 @@
1
+ import { lstat, mkdir, readFile, realpath, symlink, rm } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import TOML from "@iarna/toml";
5
+ import type { Provider } from "../shared/contracts";
6
+ import { atomicWrite, isMissing } from "./files";
7
+
8
+ const AUTH_ENV = ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", "CLAUDE_SECURESTORAGE_CONFIG_DIR", "ANTHROPIC_PROFILE", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "OPENAI_API_KEY", "OPENAI_BASE_URL", "CODEX_API_KEY", "CODEX_API_BASE_URL", "OPENAI_ORG_ID", "OPENAI_ORGANIZATION"];
9
+ AUTH_ENV.push("CLAUDE_CODE_OAUTH_REFRESH_TOKEN","CLAUDE_CODE_OAUTH_SCOPES","CLAUDE_CODE_OAUTH_CLIENT_ID","CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR","CLAUDE_CODE_HOST_CREDS_FILE","ANTHROPIC_CUSTOM_HEADERS");
10
+ AUTH_ENV.push("CLAUDE_BG_AUTH_SNAPSHOT_PATH","GATEWAY_TOKEN_FILE_DESCRIPTOR","WEBSOCKET_AUTH_FILE_DESCRIPTOR","SESSION_INGRESS_TOKEN_FILE","ANTHROPIC_UNIX_SOCKET","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR");
11
+
12
+ export function assertSubscriptionEnvironment(provider: Provider, environment: Record<string, unknown>): void {
13
+ const conflicting = AUTH_ENV.some(key => {
14
+ // Claude's supported credential namespace is handled separately by discovery.
15
+ if (key === "CLAUDE_SECURESTORAGE_CONFIG_DIR") return false;
16
+ const codexKey = key.startsWith("OPENAI_") || key.startsWith("CODEX_");
17
+ if ((provider === "codex") !== codexKey) return false;
18
+ const value = environment[key];
19
+ if (value === undefined || value === null || value === "") return false;
20
+ if (key.startsWith("CLAUDE_CODE_USE_") && /^(0|false)$/i.test(String(value))) return false;
21
+ return true;
22
+ });
23
+ if (conflicting) throw new Error(`${provider === "claude" ? "Claude" : "Codex"} authentication overrides in environment variables are incompatible with subscription accounts. Remove them from the provider settings and daemon environment.`);
24
+ }
25
+ const AUTH_CONFIG_KEYS = /(^|\.)(model_provider|model_providers|chatgpt_base_url|forced_login_method|forced_chatgpt_workspace_id|cli_auth_credentials_store|sqlite_home|codex_home)(\.|$)/;
26
+ function assertClaudeSettings(settings: Record<string, unknown>) {
27
+ if (settings.apiKeyHelper || Object.keys(settings.env ?? {}).some(key => [...AUTH_ENV,"CLAUDE_CONFIG_DIR","CODEX_HOME"].includes(key))) throw new Error("Claude settings contain authentication overrides.");
28
+ }
29
+ function assertCodexSettings(config: Record<string, unknown>) {
30
+ if (config.model_provider && config.model_provider !== "openai" || config.chatgpt_base_url || config.forced_chatgpt_workspace_id || config.forced_login_method && config.forced_login_method !== "chatgpt") throw new Error("Codex settings override the provider or authentication.");
31
+ const openai = (config.model_providers as Record<string,Record<string,unknown>>|undefined)?.openai;
32
+ if (openai && ["base_url","env_key","experimental_bearer_token","http_headers","env_http_headers"].some(key=>openai[key]) || openai?.requires_openai_auth === false) throw new Error("Codex settings override OpenAI authentication.");
33
+ for (const profile of Object.values(config.profiles ?? {})) if (profile && typeof profile === "object") assertCodexSettings(profile as Record<string,unknown>);
34
+ }
35
+
36
+ export async function assertManagedCommand(provider:Provider,args:string[]):Promise<void> {
37
+ for(let i=0;i<args.length;i++) {
38
+ const arg=args[i];
39
+ if(provider==="codex") {
40
+ const value=arg==="-c"||arg==="--config"?args[++i]:arg.startsWith("--config=")?arg.slice(9):arg.startsWith("-c")&&arg.length>2?arg.slice(2):null;
41
+ if(value && AUTH_CONFIG_KEYS.test(value.split("=")[0].trim().replaceAll('"',''))) throw new Error("CLI arguments override account isolation.");
42
+ if(arg==="--oss"||arg==="--local-provider"||arg.startsWith("--local-provider=")) throw new Error("This profile only supports a ChatGPT subscription.");
43
+ } else if(arg==="--settings"||arg.startsWith("--settings=")) {
44
+ const value=arg==="--settings"?args[++i]:arg.slice(11);
45
+ if(!value)throw new Error("Claude settings are empty.");
46
+ const text=value.trim().startsWith("{")?value:await readFile(value,"utf8");
47
+ assertClaudeSettings(JSON.parse(text));
48
+ }
49
+ }
50
+ }
51
+
52
+ export function buildAccountEnv(provider: Provider, home: string, base: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
53
+ const env = { ...base };
54
+ for (const key of AUTH_ENV) delete env[key];
55
+ for (const key of ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_SSE_PORT", "CLAUDE_AGENT_SDK_VERSION"]) delete env[key];
56
+ if (provider === "claude") env.CLAUDE_CONFIG_DIR = home;
57
+ else env.CODEX_HOME = home;
58
+ return env;
59
+ }
60
+
61
+ async function linkDirectory(home: string, sourceHome: string, name: string, create: boolean): Promise<void> {
62
+ const source = join(sourceHome, name), target = join(home, name);
63
+ if (create) await mkdir(source, { recursive: true, mode: 0o700 });
64
+ try { await lstat(source); } catch (error) { if (isMissing(error)) return; throw error; }
65
+ try {
66
+ if (await realpath(target) !== await realpath(source)) throw new Error(`Profile directory conflict: ${name}`);
67
+ } catch (error) {
68
+ if (!isMissing(error)) throw error;
69
+ await symlink(source, target);
70
+ }
71
+ }
72
+
73
+ async function readOptional(path: string): Promise<string | null> {
74
+ try { return await readFile(path, "utf8"); } catch (error) { if (isMissing(error)) return null; throw error; }
75
+ }
76
+
77
+ async function writeChanged(path: string, text: string): Promise<void> {
78
+ if (await readOptional(path) !== text) await atomicWrite(path, text);
79
+ }
80
+
81
+ function record(value: unknown): value is Record<string, unknown> {
82
+ return value !== null && typeof value === "object" && !Array.isArray(value);
83
+ }
84
+
85
+ export async function prepareProfile({ provider, home, sourceHome, sourceEnvironment=process.env }: { provider: Provider; home: string; sourceHome: string;sourceEnvironment?:NodeJS.ProcessEnv }): Promise<void> {
86
+ if (resolve(home) === resolve(sourceHome)) return;
87
+ await mkdir(home, { recursive: true, mode: 0o700 });
88
+ if (provider === "codex") {
89
+ for (const name of ["sessions", "archived_sessions", "thread-writer-locks", ".tmp"]) await linkDirectory(home, sourceHome, name, true);
90
+ for (const name of ["skills", "rules", "memories", "plugins", "vendor_imports"]) await linkDirectory(home, sourceHome, name, false);
91
+ const text = await readOptional(join(sourceHome, "config.toml"));
92
+ const config = text === null ? {} : TOML.parse(text);
93
+ assertCodexSettings(config);
94
+ config.cli_auth_credentials_store = "file";
95
+ config.sqlite_home = typeof config.sqlite_home === "string" ? resolve(sourceHome,config.sqlite_home) : sourceHome;
96
+ await writeChanged(join(home, "config.toml"), TOML.stringify(config));
97
+ for (const name of ["AGENTS.md", "AGENTS.override.md"]) {
98
+ const text = await readOptional(join(sourceHome, name));
99
+ if (text !== null) await writeChanged(join(home, name), text); else await rm(join(home,name),{force:true});
100
+ }
101
+ } else {
102
+ for (const name of ["projects", "file-history"]) await linkDirectory(home, sourceHome, name, true);
103
+ for (const name of ["skills", "commands", "agents", "plugins", "rules", "CLAUDE.md"]) await linkDirectory(home, sourceHome, name, false);
104
+ const text = await readOptional(join(sourceHome, "settings.json"));
105
+ if (text !== null) {
106
+ const settings = JSON.parse(text);
107
+ assertClaudeSettings(settings);
108
+ await writeChanged(join(home, "settings.json"), JSON.stringify(settings, null, 2));
109
+ } else await rm(join(home,"settings.json"),{force:true});
110
+ // Claude keeps account metadata in this file too. Copy only user settings,
111
+ // never oauthAccount or other login fields, and avoid writes when unchanged.
112
+ const sourceConfig = (await readOptional(join(sourceHome,".config.json")))
113
+ ?? (await readOptional(join(sourceHome === join(homedir(),".claude") && !sourceEnvironment.CLAUDE_CONFIG_DIR ? homedir() : sourceHome,".claude.json")));
114
+ if (sourceConfig !== null) {
115
+ const shared = JSON.parse(sourceConfig);
116
+ const legacy = await readOptional(join(home,".config.json"));
117
+ const target = join(home, legacy === null ? ".claude.json" : ".config.json");
118
+ const before = legacy ?? await readOptional(target);
119
+ const own = before === null ? {} : JSON.parse(before);
120
+ const original = JSON.stringify(own);
121
+ for (const key of ["mcpServers","hasCompletedOnboarding","theme","preferredNotifChannel","verbose","editorMode"]) {
122
+ if (Object.hasOwn(shared,key)) own[key]=shared[key];
123
+ else delete own[key];
124
+ }
125
+ // Project records contain trust decisions, session history and usage for
126
+ // this profile. Inherit ordinary MCP configuration only; local values win.
127
+ if (record(shared.projects)) {
128
+ const projects = record(own.projects) ? own.projects : {};
129
+ own.projects = Object.fromEntries([...new Set([...Object.keys(shared.projects), ...Object.keys(projects)])].map(path => {
130
+ const sharedProject = shared.projects[path];
131
+ const settings = record(sharedProject) ? Object.fromEntries(["mcpServers", "mcpContextUris"].filter(key => Object.hasOwn(sharedProject, key)).map(key => [key, sharedProject[key]])) : {};
132
+ return [path, { ...settings, ...(record(projects[path]) ? projects[path] : {}) }];
133
+ }));
134
+ }
135
+ if (JSON.stringify(own)!==original) await atomicWrite(target,JSON.stringify(own,null,2));
136
+ }
137
+ }
138
+ }
@@ -0,0 +1,80 @@
1
+ import { readFile, mkdir } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import { z } from "zod";
5
+ import { AccountSchema, BindingSchema, type Provider, type AccountState } from "../shared/contracts";
6
+ import { atomicWrite, isMissing } from "./files";
7
+
8
+ export const StoredAccountSchema = AccountSchema.extend({ home: z.string(), identityKey: z.string().nullable(), generation: z.number().int(), loginToken:z.string().nullable().default(null) });
9
+ export type StoredAccount = z.infer<typeof StoredAccountSchema>;
10
+ const StoredBindingSchema = BindingSchema.extend({ launchAccountId: z.string().nullable(), launchToken: z.string().nullable(), registrationObserved:z.boolean().default(false) });
11
+ export type StoredBinding = z.infer<typeof StoredBindingSchema>;
12
+ const CommandsSchema = z.object({ claude: z.array(z.string()).nullable(), codex: z.array(z.string()).nullable() });
13
+ export const RegistrySchema = z.object({
14
+ version: z.literal(1), accounts: z.array(StoredAccountSchema), bindings: z.array(StoredBindingSchema),
15
+ defaults: z.object({claude:z.string().nullable(),codex:z.string().nullable()}),
16
+ sourceHomes: z.object({claude:z.string(),codex:z.string()}),
17
+ sourceEnvironment: z.object({claude:z.object({CLAUDE_CONFIG_DIR:z.string().optional(),CLAUDE_SECURESTORAGE_CONFIG_DIR:z.string().optional()}),codex:z.object({CODEX_HOME:z.string().optional()})}).default({claude:{},codex:{}}),
18
+ commands: CommandsSchema, originalCommands: CommandsSchema,
19
+ integration: z.object({enabled:z.boolean(),error:z.string().nullable()}),
20
+ });
21
+ export type Registry = z.infer<typeof RegistrySchema>;
22
+ export async function readRegistry(root: string): Promise<Registry> {
23
+ return RegistrySchema.parse(JSON.parse(await readFile(join(root, "registry.json"), "utf8")));
24
+ }
25
+ export function accountFrom(registry: Registry, id: string): StoredAccount {
26
+ const account = registry.accounts.find(a => a.id === id);
27
+ if (!account) throw new Error("Account not found.");
28
+ return account;
29
+ }
30
+ export class AccountStore {
31
+ private queue: Promise<unknown> = Promise.resolve();
32
+ constructor(readonly root: string) {}
33
+ async initialize(sourceHomes: Registry["sourceHomes"]): Promise<void> {
34
+ await mkdir(this.root, { recursive:true, mode:0o700 });
35
+ try {
36
+ await this.change(state => {
37
+ for (const account of state.accounts) {
38
+ const providerName = account.provider === "claude" ? "Claude" : "Codex";
39
+ // Translate only the original generated label; preserve all user labels.
40
+ if (account.source === "system" && account.label === `Поточний CLI · ${providerName}`) account.label = `Current CLI · ${providerName}`;
41
+ }
42
+ });
43
+ return;
44
+ } catch(error) { if(!isMissing(error)) throw new Error("The account registry is damaged; automatic recovery is disabled."); }
45
+ const now = new Date().toISOString();
46
+ await atomicWrite(join(this.root,"registry.json"),JSON.stringify({
47
+ version:1, sourceHomes, accounts: (["claude","codex"] as const).map(provider=>({
48
+ id:`system-${provider}`,provider,label:`Current CLI · ${provider === "claude"?"Claude":"Codex"}`,
49
+ source:"system",home:sourceHomes[provider],email:null,plan:null,authStatus:"unknown",createdAt:now,identityKey:null,generation:0,
50
+ })), bindings:[], defaults:{claude:null,codex:null}, commands:{claude:null,codex:null},originalCommands:{claude:null,codex:null},integration:{enabled:false,error:null},
51
+ },null,2));
52
+ }
53
+ read(): Promise<Registry> { return readRegistry(this.root); }
54
+ async change<T>(operation:(registry:Registry)=>T|Promise<T>): Promise<T> {
55
+ const task=this.queue.catch(()=>{}).then(async()=>{const registry=await this.read();const before=JSON.stringify(registry);const value=await operation(registry);const validated=RegistrySchema.parse(registry);if(JSON.stringify(validated)!==before)await atomicWrite(join(this.root,"registry.json"),JSON.stringify(validated,null,2));return value;});
56
+ this.queue=task; return task;
57
+ }
58
+ async snapshot():Promise<AccountState> {
59
+ const state=await this.read();
60
+ return { accounts:state.accounts.map(a=>AccountSchema.parse(a)),bindings:state.bindings.map(b=>BindingSchema.parse(b)),defaults:state.defaults,integration:state.integration };
61
+ }
62
+ async add(provider:Provider,label:string):Promise<StoredAccount> {
63
+ return this.change(state=>{const account:StoredAccount={id:randomUUID(),provider,label:label.trim(),source:"managed",home:"",email:null,plan:null,authStatus:"needs_auth",createdAt:new Date().toISOString(),identityKey:null,generation:0,loginToken:null};account.home=join(this.root,"accounts",account.id,provider);state.accounts.push(account);return account;});
64
+ }
65
+ async remove(id:string,beforeRemove?:(account:StoredAccount,registry:Registry)=>Promise<void>):Promise<void> {
66
+ await this.change(async state=>{const account=accountFrom(state,id);if(account.source==="system")throw new Error("The current CLI account cannot be removed.");if(state.bindings.some(b=>[b.currentAccountId,b.pendingAccountId,b.launchAccountId].includes(id))||Object.values(state.defaults).includes(id))throw new Error("The account is used by an agent or selected as the default.");await beforeRemove?.(account,state);state.accounts=state.accounts.filter(a=>a.id!==id);});
67
+ }
68
+ async prepare(agentId:string,provider:Provider,accountId:string|null):Promise<StoredBinding> {
69
+ return this.change(state=>{
70
+ if(accountId&&accountFrom(state,accountId).provider!==provider)throw new Error("The account belongs to another provider.");
71
+ let binding=state.bindings.find(b=>b.agentId===agentId);
72
+ if(!binding){binding={agentId,provider,currentAccountId:`system-${provider}`,pendingAccountId:null,status:"ready",error:null,launchAccountId:`system-${provider}`,launchToken:null,registrationObserved:true};state.bindings.push(binding);}
73
+ if(binding.status==="switching")throw new Error("An account switch is already in progress.");
74
+ binding.pendingAccountId=accountId===binding.currentAccountId?null:accountId;binding.error=null;binding.status="ready";binding.launchToken=null;binding.registrationObserved=true;return binding;
75
+ });
76
+ }
77
+ async updateIdentity(id:string,update:Pick<StoredAccount,"identityKey"|"email"|"plan"|"authStatus">,expected?:Pick<StoredAccount,"generation"|"loginToken">):Promise<StoredAccount> {
78
+ return this.change(state=>{const account=accountFrom(state,id);if(expected&&(account.generation!==expected.generation||account.loginToken!==expected.loginToken))return account;if(account.identityKey!==update.identityKey)account.generation++;Object.assign(account,update);return account;});
79
+ }
80
+ }