Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(auth): detect cookie-based session during CLI setup flow (#904)

Jiayuan Zhang8d3cb21c032c
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 4dfc6fd2d6..2c2f987f34 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -198,6 +198,10 @@ export class ApiClient {
await this.fetch("/auth/logout", { method: "POST" });
}
+ async issueCliToken(): Promise<{ token: string }> {
+ return this.fetch("/api/cli-token", { method: "POST" });
+ }
+
async getMe(): Promise<User> {
return this.fetch("/api/me");
}
diff --git a/packages/views/auth/login-page.test.tsx b/packages/views/auth/login-page.test.tsx
index 0e9c0ed5f4..722071cb06 100644
--- a/packages/views/auth/login-page.test.tsx
+++ b/packages/views/auth/login-page.test.tsx
@@ -13,6 +13,7 @@ const mockApiListWorkspaces = vi.hoisted(() => vi.fn());
const mockApiVerifyCode = vi.hoisted(() => vi.fn());
const mockApiSetToken = vi.hoisted(() => vi.fn());
const mockApiGetMe = vi.hoisted(() => vi.fn());
+const mockApiIssueCliToken = vi.hoisted(() => vi.fn());
const mockSetQueryData = vi.hoisted(() => vi.fn());
vi.mock("@tanstack/react-query", async () => {
@@ -58,6 +59,7 @@ vi.mock("@multica/core/api", () => ({
verifyCode: mockApiVerifyCode,
setToken: mockApiSetToken,
getMe: mockApiGetMe,
+ issueCliToken: mockApiIssueCliToken,
},
}));
@@ -88,7 +90,8 @@ describe("LoginPage", () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.clearAllMocks();
- // Default: no existing session
+ // Default: no existing session (getMe rejects when no auth)
+ mockApiGetMe.mockRejectedValue(new Error("unauthorized"));
localStorage.clear();
// Reset window.location for tests that change it
Object.defineProperty(window, "location", {
@@ -385,11 +388,14 @@ describe("LoginPage", () => {
it("shows cli_confirm step when existing session + cliCallback", async () => {
localStorage.setItem("multica_token", "existing-jwt");
- mockApiGetMe.mockResolvedValueOnce({
- id: "u-1",
- email: "[email protected]",
- name: "Test User",
- });
+ // Cookie attempt fails first, then localStorage fallback succeeds
+ mockApiGetMe
+ .mockRejectedValueOnce(new Error("no cookie"))
+ .mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Test User",
+ });
render(
<LoginPage
@@ -414,11 +420,14 @@ describe("LoginPage", () => {
it("CLI authorize button redirects to callback URL", async () => {
localStorage.setItem("multica_token", "existing-jwt");
- mockApiGetMe.mockResolvedValueOnce({
- id: "u-1",
- email: "[email protected]",
- name: "Test User",
- });
+ // Cookie attempt fails, localStorage fallback succeeds
+ mockApiGetMe
+ .mockRejectedValueOnce(new Error("no cookie"))
+ .mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Test User",
+ });
const onTokenObtained = vi.fn();
render(
@@ -446,11 +455,14 @@ describe("LoginPage", () => {
it("'Use a different account' returns to email step", async () => {
localStorage.setItem("multica_token", "existing-jwt");
- mockApiGetMe.mockResolvedValueOnce({
- id: "u-1",
- email: "[email protected]",
- name: "Test User",
- });
+ // Cookie attempt fails, localStorage fallback succeeds
+ mockApiGetMe
+ .mockRejectedValueOnce(new Error("no cookie"))
+ .mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Test User",
+ });
render(
<LoginPage
@@ -475,6 +487,65 @@ describe("LoginPage", () => {
).toBeInTheDocument();
});
+ // -------------------------------------------------------------------------
+ // CLI callback — cookie-based session (no localStorage token)
+ // -------------------------------------------------------------------------
+
+ it("detects cookie-based session and shows cli_confirm when no localStorage token", async () => {
+ // No localStorage token — getMe succeeds via HttpOnly cookie
+ mockApiGetMe.mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Cookie User",
+ });
+
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ cliCallback={{ url: "http://localhost:9876/callback", state: "abc" }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText(/authorize cli/i)).toBeInTheDocument();
+ });
+ expect(screen.getByText(/[email protected]/)).toBeInTheDocument();
+ });
+
+ it("CLI authorize with cookie session calls issueCliToken and redirects", async () => {
+ // No localStorage token — getMe succeeds via cookie
+ mockApiGetMe.mockResolvedValueOnce({
+ id: "u-1",
+ email: "[email protected]",
+ name: "Cookie User",
+ });
+ mockApiIssueCliToken.mockResolvedValueOnce({ token: "fresh-jwt" });
+ const onTokenObtained = vi.fn();
+
+ render(
+ <LoginPage
+ onSuccess={onSuccess}
+ onTokenObtained={onTokenObtained}
+ cliCallback={{ url: "http://localhost:9876/callback", state: "abc" }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText(/authorize cli/i)).toBeInTheDocument();
+ });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: /^authorize$/i }));
+
+ await waitFor(() => {
+ expect(mockApiIssueCliToken).toHaveBeenCalled();
+ expect(onTokenObtained).toHaveBeenCalled();
+ expect(window.location.href).toContain(
+ "http://localhost:9876/callback?token=fresh-jwt&state=abc",
+ );
+ });
+ });
+
// -------------------------------------------------------------------------
// CLI callback — code verification redirects
// -------------------------------------------------------------------------
diff --git a/packages/views/auth/login-page.tsx b/packages/views/auth/login-page.tsx
index c64398e896..89d04b1fd1 100644
--- a/packages/views/auth/login-page.tsx
+++ b/packages/views/auth/login-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useEffect, useCallback, type ReactNode } from "react";
+import { useState, useEffect, useCallback, useRef, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import {
Card,
@@ -102,23 +102,43 @@ export function LoginPage({
const [loading, setLoading] = useState(false);
const [cooldown, setCooldown] = useState(0);
const [existingUser, setExistingUser] = useState<User | null>(null);
+ // Tracks how the existing session was detected so handleCliAuthorize
+ // uses the matching token source (cookie → issueCliToken, localStorage → direct).
+ const authSourceRef = useRef<"cookie" | "localStorage">("cookie");
- // Check for existing session when CLI callback is present
+ // Check for existing session when CLI callback is present.
+ // Prioritises cookie auth (= current browser session) to avoid authorising
+ // the CLI with a stale or mismatched localStorage token.
useEffect(() => {
if (!cliCallback) return;
- const token = localStorage.getItem("multica_token");
- if (!token) return;
- api.setToken(token);
+ // Ensure no stale bearer token interferes — we want to test the cookie first.
+ api.setToken(null);
+
api
.getMe()
.then((user) => {
+ authSourceRef.current = "cookie";
setExistingUser(user);
setStep("cli_confirm");
})
.catch(() => {
- api.setToken(null);
- localStorage.removeItem("multica_token");
+ // Cookie auth failed — fall back to localStorage token
+ const token = localStorage.getItem("multica_token");
+ if (!token) return;
+
+ api.setToken(token);
+ api
+ .getMe()
+ .then((user) => {
+ authSourceRef.current = "localStorage";
+ setExistingUser(user);
+ setStep("cli_confirm");
+ })
+ .catch(() => {
+ api.setToken(null);
+ localStorage.removeItem("multica_token");
+ });
});
}, [cliCallback]);
@@ -203,13 +223,32 @@ export function LoginPage({
}
};
- const handleCliAuthorize = () => {
+ const handleCliAuthorize = async () => {
if (!cliCallback) return;
- const token = localStorage.getItem("multica_token");
- if (!token) return;
setLoading(true);
- onTokenObtained?.();
- redirectToCliCallback(cliCallback.url, token, cliCallback.state);
+
+ try {
+ let token: string;
+
+ if (authSourceRef.current === "localStorage") {
+ // Session was detected via localStorage — reuse that token directly.
+ const stored = localStorage.getItem("multica_token");
+ if (!stored) throw new Error("token missing");
+ token = stored;
+ } else {
+ // Session was detected via cookie — obtain a bearer token from the server.
+ const res = await api.issueCliToken();
+ token = res.token;
+ }
+
+ onTokenObtained?.();
+ redirectToCliCallback(cliCallback.url, token, cliCallback.state);
+ } catch {
+ setError("Failed to authorize CLI. Please log in again.");
+ setExistingUser(null);
+ setStep("email");
+ setLoading(false);
+ }
};
const handleGoogleLogin = () => {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index d8a52df51f..9a3f536a42 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -153,6 +153,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
// --- User-scoped routes (no workspace context required) ---
r.Get("/api/me", h.GetMe)
r.Patch("/api/me", h.UpdateMe)
+ r.Post("/api/cli-token", h.IssueCliToken)
r.Post("/api/upload-file", h.UploadFile)
r.Route("/api/workspaces", func(r chi.Router) {
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index b0405f99a5..8f97ec1674 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -390,6 +390,31 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
})
}
+// IssueCliToken returns a fresh JWT for the authenticated user.
+// This allows cookie-authenticated browser sessions to obtain a bearer token
+// that can be handed off to the CLI via the cli_callback redirect.
+func (h *Handler) IssueCliToken(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ user, err := h.Queries.GetUser(r.Context(), parseUUID(userID))
+ if err != nil {
+ writeError(w, http.StatusNotFound, "user not found")
+ return
+ }
+
+ tokenString, err := h.issueJWT(user)
+ if err != nil {
+ slog.Warn("cli-token: failed to issue JWT", append(logger.RequestAttrs(r), "error", err, "user_id", userID)...)
+ writeError(w, http.StatusInternalServerError, "failed to generate token")
+ return
+ }
+
+ writeJSON(w, http.StatusOK, map[string]string{"token": tokenString})
+}
+
func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
auth.ClearAuthCookies(w)
writeJSON(w, http.StatusOK, map[string]string{"message": "logged out"})