⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(web): sign out and redirect to login on an expired session (#185)
Croff5a4c9893edec
diff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.jsonindex 04ba169e..b7f3ee84 100644--- a/apps/web/messages/ar/auth.json+++ b/apps/web/messages/ar/auth.json@@ -16,6 +16,7 @@"login": {"title": "مرحبًا بعودتك","subtitleVerified": "بريدك اتأكّد. سجّل دخولك عشان تكمّل.",+ "subtitleExpired": "جلستك انتهت. سجّل دخولك تاني عشان تكمّل.","subtitleReset": "كلمة مرورك اتغيّرت. سجّل دخولك بيها.","subtitleLink": "هنبعتلك رابط على بريدك يسجّل دخولك","subtitlePassword": "سجّل دخولك ببريدك أو اسم المستخدم وكلمة مرورك",diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.jsonindex 8d4b3da3..161a54eb 100644--- a/apps/web/messages/en/auth.json+++ b/apps/web/messages/en/auth.json@@ -16,6 +16,7 @@"login": {"title": "Welcome back","subtitleVerified": "Your email is confirmed. Sign in to continue.",+ "subtitleExpired": "Your session has ended. Sign in again to continue.","subtitleReset": "Your password is changed. Sign in with it.","subtitleLink": "We will email you a link that signs you in","subtitlePassword": "Sign in with your email or username and password",diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.jsonindex c39c3062..f9f233db 100644--- a/apps/web/messages/ru/auth.json+++ b/apps/web/messages/ru/auth.json@@ -16,6 +16,7 @@"login": {"title": "С возвращением","subtitleVerified": "Почта подтверждена. Войдите, чтобы продолжить.",+ "subtitleExpired": "Сессия завершена. Войдите снова, чтобы продолжить.","subtitleReset": "Пароль изменён. Войдите с ним.","subtitleLink": "Мы отправим на почту ссылку для входа","subtitlePassword": "Войдите с почтой или юзернеймом и паролем",diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.jsonindex 2aaae3bf..21e60920 100644--- a/apps/web/messages/uk/auth.json+++ b/apps/web/messages/uk/auth.json@@ -16,6 +16,7 @@"login": {"title": "З поверненням","subtitleVerified": "Пошту підтверджено. Увійдіть, щоб продовжити.",+ "subtitleExpired": "Сесію завершено. Увійдіть знову, щоб продовжити.","subtitleReset": "Пароль змінено. Увійдіть з ним.","subtitleLink": "Ми надішлемо на пошту посилання для входу","subtitlePassword": "Увійдіть з поштою або юзернеймом і паролем",diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.jsonindex 3e193469..48d1d88e 100644--- a/apps/web/messages/zh-CN/auth.json+++ b/apps/web/messages/zh-CN/auth.json@@ -16,6 +16,7 @@"login": {"title": "欢迎回来","subtitleVerified": "邮箱已验证,请登录以继续。",+ "subtitleExpired": "会话已结束,请重新登录以继续。","subtitleReset": "密码已更改,请使用新密码登录。","subtitleLink": "我们会通过邮件向你发送登录链接","subtitlePassword": "使用邮箱或用户名和密码登录",diff --git a/apps/web/src/components/session-scope.tsx b/apps/web/src/components/session-scope.tsxindex b9786ebf..efbc8256 100644--- a/apps/web/src/components/session-scope.tsx+++ b/apps/web/src/components/session-scope.tsx@@ -3,6 +3,7 @@import { useEffect, useRef } from 'react';import { useQueryClient } from '@tanstack/react-query';import { useSession } from '@/lib/auth-client';+import { markSignedIn } from '@/lib/api';// Everything cached in this tab belongs to one account. Signing in as somebody else// without a full page load (sign out and back in, a magic link opened in the same@@ -25,6 +26,7 @@ export default function SessionScope() {const before = previous.current;previous.current = userId;if (before === undefined || before === userId) return;+ if (userId) markSignedIn();queryClient.clear();}, [userId, isPending, queryClient]);diff --git a/apps/web/src/features/account/services/profile.service.ts b/apps/web/src/features/account/services/profile.service.tsindex 344bf6d8..950b6860 100644--- a/apps/web/src/features/account/services/profile.service.ts+++ b/apps/web/src/features/account/services/profile.service.ts@@ -1,9 +1,4 @@-import { API_URL } from '@/lib/api';--async function errorMessage(res: Response): Promise<string> {- const body = await res.json().catch(() => null);- return body?.error ?? `${res.status} ${res.statusText}`;-}+import { API_URL, apiFailure } from '@/lib/api';// Uploads an avatar image to the API (stored in MinIO). The API writes the new URL// to the user's image column itself and returns it, so the caller only has to read@@ -17,12 +12,12 @@ export async function uploadAvatar(file: File): Promise<{ image: string }> {credentials: 'include',body: form,});- if (!res.ok) throw new Error(await errorMessage(res));+ if (!res.ok) throw await apiFailure(res);return res.json();}// Removes the stored avatar object and clears the user's image column.export async function removeAvatar(): Promise<void> {const res = await fetch(`${API_URL}/me/avatar`, { method: 'DELETE', credentials: 'include' });- if (!res.ok) throw new Error(await errorMessage(res));+ if (!res.ok) throw await apiFailure(res);}diff --git a/apps/web/src/features/auth/components/login/AuthLoginForm.tsx b/apps/web/src/features/auth/components/login/AuthLoginForm.tsxindex af78ad0c..c7d9fb20 100644--- a/apps/web/src/features/auth/components/login/AuthLoginForm.tsx+++ b/apps/web/src/features/auth/components/login/AuthLoginForm.tsx@@ -55,6 +55,9 @@ export default function AuthLoginForm() {const authConfig = useAuthConfig();const params = useSearchParams();const justReset = params.get('reset') === '1';+ // `apiFailure` in lib/api.ts sends the browser here with ?expired=1 after the API+ // refused the session, so the screen can say why the user is back on it.+ const sessionExpired = params.get('expired') === '1';// A Google sign-in or a confirmation link that could not complete comes back here// as a redirect rather than as a rejected promise, so its reason arrives in the// query string.@@ -118,6 +121,7 @@ export default function AuthLoginForm() {const signingInWithLink = method === 'link';function subtitle() {+ if (sessionExpired) return t('login.subtitleExpired');if (justVerified) return t('login.subtitleVerified');if (justReset) return t('login.subtitleReset');if (signingInWithLink) return t('login.subtitleLink');diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex b2c67272..c4a0ff26 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -36,6 +36,55 @@ export class ApiError extends Error {}}+// Set while the session is being dropped, by the sign-out below or by the app's own+// `signOut`. Concurrent requests that all fail with 401 then trigger a single+// sign-out and a single navigation, and a sign-out the person asked for does not+// end on the expired screen.+let signingOut = false;++// Called by `signOut` in @/lib/auth-client before it drops the session: the requests+// that fail right after are the expected fallout, not a session the API refused.+export function markSigningOut(): void {+ signingOut = true;+}++// Called by SessionScope once a session appears without a page load, so a later 401+// is reacted to again. An accepted request does not prove one: /auth-config and the+// invite and share reads answer without a session.+export function markSignedIn(): void {+ signingOut = false;+}++// A 401 means the session behind the cookie is gone. The proxy only checks that a+// session cookie exists, so a stale one keeps the app open on a page where every+// request fails. Signing out is what drops the cookie; with it still set the proxy+// would bounce /login straight back into the app.+// The request is written out rather than calling `signOut()` from @/lib/auth-client:+// that module reads API_URL from this one, so importing it back here would make a+// cycle that evaluates auth-client before API_URL is assigned.+function endSession(): void {+ if (typeof window === 'undefined' || signingOut) return;+ signingOut = true;+ void fetch(`${API_URL}/api/auth/sign-out`, { method: 'POST', credentials: 'include' })+ .then((res) => {+ // Leaving with the cookie still set sends the proxy straight back into the+ // app, where the next 401 starts this over as a fresh page load.+ if (res.ok) window.location.replace('/login?expired=1');+ else signingOut = false;+ })+ .catch(() => {+ signingOut = false;+ });+}++// Turns a failed response into the error to throw, and catches an ended session on+// the way. Every request in this module reports its failure through here.+export async function apiFailure(res: Response): Promise<ApiError> {+ const body = await res.json().catch(() => null);+ if (res.status === 401) endSession();+ return new ApiError(res.status, body?.error ?? `${res.status} ${res.statusText}`, body?.code);+}+async function request<T>(path: string, init?: RequestInit): Promise<T> {const res = await fetch(`${API_URL}${path}`, {...init,@@ -49,10 +98,7 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {...init?.headers,},});- if (!res.ok) {- const body = await res.json().catch(() => null);- throw new ApiError(res.status, body?.error ?? `${res.status} ${res.statusText}`, body?.code);- }+ if (!res.ok) throw await apiFailure(res);if (res.status === 204) return undefined as T;return res.json();}@@ -531,10 +577,7 @@ export async function* streamAiAgentRun(// JSON-encoded event on its `data:` line and, on a resumable stream, the `id:` a// reconnect resumes from. Throws ApiError when the request failed before the stream.async function* readSseFrames(res: Response): AsyncGenerator<{ id: number | null; data: string }> {- if (!res.ok || !res.body) {- const err = await res.json().catch(() => null);- throw new ApiError(res.status, err?.error ?? `${res.status} ${res.statusText}`);- }+ if (!res.ok || !res.body) throw await apiFailure(res);const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();let buffer = '';for (;;) {@@ -2158,10 +2201,7 @@ async function sendAttachmentFile(const form = new FormData();form.append('file', file);const res = await fetch(`${API_URL}${path}`, { method, credentials: 'include', body: form });- if (!res.ok) {- const body = await res.json().catch(() => null);- throw new Error(body?.error ?? `${res.status} ${res.statusText}`);- }+ if (!res.ok) throw await apiFailure(res);return absolutizeAttachment(await res.json());}@@ -2883,10 +2923,7 @@ export const api = {body: form,},);- if (!res.ok) {- const body = await res.json().catch(() => null);- throw new ApiError(res.status, body?.error ?? `${res.status} ${res.statusText}`);- }+ if (!res.ok) throw await apiFailure(res);return res.json();},updateSkillReferenceContent: (diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.tsindex 695c9a9e..89cfb833 100644--- a/apps/web/src/lib/auth-client.ts+++ b/apps/web/src/lib/auth-client.ts@@ -3,7 +3,7 @@ import { inferAdditionalFields } from 'better-auth/client/plugins';import { magicLinkClient, usernameClient } from 'better-auth/client/plugins';import { passkeyClient } from '@better-auth/passkey/client';import { apiKeyClient } from '@better-auth/api-key/client';-import { API_URL } from '@/lib/api';+import { API_URL, markSigningOut } from '@/lib/api';// The better-auth handler lives on the backend (Elysia), so baseURL is the API origin.// inferAdditionalFields declares the custom `role` column added in @repo/auth so the@@ -35,7 +35,6 @@ export const authClient = createAuthClient({export const {signIn,signUp,- signOut,useSession,getSession,passkey,@@ -53,4 +52,12 @@ export const {unlinkAccount,} = authClient;+// Sign out through this wrapper rather than through the client: it tells lib/api+// that the 401s the dropped session causes are expected, so they do not send the+// browser to the expired-session screen.+export async function signOut() {+ markSigningOut();+ return authClient.signOut();+}+export type SessionUser = typeof authClient.$Infer.Session.user;diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.tsindex f2437252..6c09aa98 100644--- a/apps/web/src/proxy.ts+++ b/apps/web/src/proxy.ts@@ -17,6 +17,9 @@ const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share'];// for the presence of the better-auth session cookie, not its validity — the API// does the real validation on every request. It keeps unauthenticated users out of// the planner UI and bounces signed-in users away from the auth pages.+// A cookie the API no longer accepts passes this check, so the client handles that+// case: `apiFailure` in `lib/api.ts` signs out on a 401 and lands on+// `/login?expired=1`.export function proxy(request: NextRequest) {const { pathname } = request.nextUrl;const hasSession = getSessionCookie(request) != null;