Skip to content

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

Go

MUL-7436 feat(auth): slide UI session expiry instead of forcing a re-login every 30 days (#8486)

Bohan Jiang1fcdff78d068
diff --git a/.env.example b/.env.example
index 68b891fe23..65211abc9e 100644
--- a/.env.example
+++ b/.env.example
@@ -383,6 +383,21 @@ COOKIE_DOMAIN=
# Default: 2592000 (30 days). Self-hosted deployments on trusted networks can
# set a longer value to reduce re-authentication frequency.
# Note: longer TTL = longer exposure window if a cookie is leaked.
+#
+# Sessions slide: once a session drops below HALF this value, the next
+# authenticated request re-issues it with a full TTL again, so an actively
+# used session is not logged out on the anniversary of its login. The bound
+# this puts on idleness is approximate and one-sided — a session last used
+# while it still had more than half its TTL left is NOT extended, so the
+# guaranteed survivable idle gap is TTL/2, not TTL. There is no absolute
+# cap: an account in continuous use stays signed in indefinitely.
+#
+# Minimum: 60 seconds. The renewal cadence is derived as TTL/10, and clients
+# floor what the server sends at 5 seconds; below a 60-second TTL that floor
+# would start deciding the cadence instead of the server, which is how a
+# client ends up checking less often than the session can survive. A value
+# below the minimum is clamped up to it with a warning at startup, rather
+# than silently logging active users out.
# AUTH_TOKEN_TTL=2592000
# Local file storage (fallback when S3_BUCKET is not set)
diff --git a/apps/docs/content/docs/auth-setup.ja.mdx b/apps/docs/content/docs/auth-setup.ja.mdx
index 87f423873b..97dfbea0c9 100644
--- a/apps/docs/content/docs/auth-setup.ja.mdx
+++ b/apps/docs/content/docs/auth-setup.ja.mdx
@@ -141,13 +141,19 @@ [email protected]
## セッション有効期間
-ブラウザのログインは、デフォルトで 30 日間保持されます。`AUTH_TOKEN_TTL` で調整でき、Go duration または正の整数秒を受け付けます:
+セッションはスライド更新されます。以下の値はサインインからのカウントダウンではなく、**アイドル**の上限です。残り有効期間が半分を下回ると、次のリクエストで完全な有効期間に再発行されるため、使い続けているアカウントが定期的にサインアウトされることはありません。絶対的な上限はありません。
+
+この上限は片側のみです。半分を下回ってからでないと再発行されないため、最後の利用時点で半分以上残っていたセッションは延長されません。常に耐えられるアイドル時間は、以下の値の半分です。
+
+`AUTH_TOKEN_TTL` で調整でき、Go duration または正の整数秒を受け付けます:
```dotenv
AUTH_TOKEN_TTL=720h
```
-変更後は API サービスの再起動が必要です。この値は、それ以降に発行されるログイン cookie と JWT にのみ影響し、発行済みのトークンを延長することはありません。
+最小値は `60s` です。これより短い値は `60s` に補正され、起動時に警告が記録されます。これを下回ると、サーバーが導出する更新チェック間隔がクライアント側の下限を割り込み、セッションが存続できる時間よりも低い頻度でしかチェックされなくなります。
+
+変更後は API サービスの再起動が必要です。この値は以降に発行・再発行されるセッションに適用されます。セッションはスライド更新されるため、既存のセッションも次の再発行時に新しい有効期間を受け取ります。
## 次のステップ
diff --git a/apps/docs/content/docs/auth-setup.ko.mdx b/apps/docs/content/docs/auth-setup.ko.mdx
index 79384e74d8..1f69c3250e 100644
--- a/apps/docs/content/docs/auth-setup.ko.mdx
+++ b/apps/docs/content/docs/auth-setup.ko.mdx
@@ -141,13 +141,19 @@ [email protected]
## 로그인 유효 기간
-브라우저 로그인은 기본적으로 30일 동안 유지됩니다. `AUTH_TOKEN_TTL`로 조정할 수 있으며 Go duration 또는 양의 정수 초를 지원합니다.
+세션은 슬라이딩 갱신됩니다. 아래 값은 로그인 시점부터의 카운트다운이 아니라 **유휴** 한도입니다. 남은 유효 기간이 절반 아래로 내려가면 다음 요청에서 전체 기간으로 다시 발급되므로, 계속 사용하는 계정이 주기적으로 로그아웃되지 않습니다. 절대 상한은 없습니다.
+
+이 한도는 한쪽 방향으로만 적용됩니다. 절반 아래로 내려간 뒤에야 다시 발급되므로, 마지막 사용 시점에 절반 이상 남아 있던 세션은 연장되지 않습니다. 항상 견딜 수 있는 유휴 시간은 아래 값의 절반입니다.
+
+`AUTH_TOKEN_TTL`로 조정할 수 있으며 Go duration 또는 양의 정수 초를 지원합니다.
```dotenv
AUTH_TOKEN_TTL=720h
```
-변경 후 API 서비스를 다시 시작해야 합니다. 이 값은 이후 발급되는 로그인 cookie와 JWT에만 적용되며 이미 발급된 token의 기간은 연장하지 않습니다.
+최솟값은 `60s`이며, 더 짧은 값은 `60s`로 조정되고 시작 시 경고가 기록됩니다. 이보다 짧으면 서버가 계산한 갱신 확인 주기가 클라이언트의 하한보다 낮아져, 세션이 유지될 수 있는 시간보다 드물게 확인하게 됩니다.
+
+변경 후 API 서비스를 다시 시작해야 합니다. 이 값은 이후 발급되거나 다시 발급되는 세션에 적용됩니다. 세션은 슬라이딩 갱신되므로 기존 세션도 다음 재발급 때 새 기간을 적용받습니다.
## 다음 단계
diff --git a/apps/docs/content/docs/auth-setup.mdx b/apps/docs/content/docs/auth-setup.mdx
index 8d7f24acb9..7bed76984f 100644
--- a/apps/docs/content/docs/auth-setup.mdx
+++ b/apps/docs/content/docs/auth-setup.mdx
@@ -141,13 +141,19 @@ To invite a new member on an instance with open signup disabled, add their email
## Session lifetime
-Browser sign-ins last 30 days by default. Adjust with `AUTH_TOKEN_TTL`, which accepts a Go duration or a positive integer of seconds:
+Sessions slide. The lifetime below is an **idle** bound, not a countdown from sign-in: once a session drops below half of it, the next request re-issues it with a full lifetime again, so an account in continuous use is never signed out on a schedule. There is no absolute cap.
+
+The bound is one-sided. A session is only re-issued once it is past the halfway point, so a session last used while it still had more than half its lifetime left is not extended — the idle gap that is always survivable is half the value below, not all of it.
+
+Adjust with `AUTH_TOKEN_TTL`, which accepts a Go duration or a positive integer of seconds:
```dotenv
AUTH_TOKEN_TTL=720h
```
-Restart the API service after changing it. The value only affects sign-in cookies and JWTs issued afterwards; it does not extend tokens that were already issued.
+The minimum is `60s`; anything shorter is clamped up to it and logs a warning at startup. Below that, the renewal cadence the server derives would fall under the floor clients apply to it, and clients would check for renewal less often than the session can survive.
+
+Restart the API service after changing it. The value applies to sessions issued or re-issued afterwards — because sessions slide, an existing session picks up the new lifetime the next time it is re-issued.
## Next steps
diff --git a/apps/docs/content/docs/auth-setup.zh.mdx b/apps/docs/content/docs/auth-setup.zh.mdx
index b781e85404..2efeb51a57 100644
--- a/apps/docs/content/docs/auth-setup.zh.mdx
+++ b/apps/docs/content/docs/auth-setup.zh.mdx
@@ -141,13 +141,19 @@ [email protected]
## 登录有效期
-浏览器登录默认保持 30 天。可以用 `AUTH_TOKEN_TTL` 调整,支持 Go duration 或正整数秒数:
+会话会滑动续期。下面这个值是**闲置**上限,不是从登录开始倒计时:会话剩余有效期低于一半时,下一个请求就会把它续到完整有效期,所以持续使用的账号不会被定时踢出。没有绝对上限。
+
+这个上限是单边的。只有掉到一半以下才会续期,因此最后一次使用时仍有超过一半有效期的会话不会被延长 —— 能保证活下来的闲置时长是下面这个值的一半,而不是全部。
+
+可以用 `AUTH_TOKEN_TTL` 调整,支持 Go duration 或正整数秒数:
```dotenv
AUTH_TOKEN_TTL=720h
```
-修改后需要重启 API 服务。这个值只影响之后签发的登录 cookie 和 JWT,不会延长已经签发的令牌。
+最小值是 `60s`,更小的取值会被上调到 `60s` 并在启动时打出警告。低于这个值时,服务端算出的续期检查间隔会低于客户端对它设置的下限,客户端的检查频率就会低于会话能存活的时长。
+
+修改后需要重启 API 服务。这个值对之后签发或续期的会话生效 —— 因为会话会滑动续期,已有会话会在下次续期时用上新的有效期。
## 接下来
diff --git a/apps/docs/content/docs/auth-tokens.ja.mdx b/apps/docs/content/docs/auth-tokens.ja.mdx
index 0199a7cad9..0ad4f815f3 100644
--- a/apps/docs/content/docs/auth-tokens.ja.mdx
+++ b/apps/docs/content/docs/auth-tokens.ja.mdx
@@ -11,7 +11,7 @@ Multica の日常的な利用で主に扱う認証情報は 2 種類です: ブ
メールの確認コードまたは Google でサインインすると、Multica は `multica_auth` という名前の HttpOnly cookie に JWT を保存します。ブラウザが自動的に送信し、JavaScript から直接読み取ることはできません。
-セッションはデフォルトで 30 日間有効です。セルフホストの管理者は、`AUTH_TOKEN_TTL` で以後発行されるセッションの有効期間を調整できます。[サインインとサインアップ](/auth-setup#セッション有効期間)を参照してください。サインアウトすると、現在のブラウザの認証 cookie と CSRF cookie が削除されます。
+セッションはデフォルトで 30 日間有効ですが、これはサインインからのカウントダウンではありません。使い続けているセッションは失効前に再発行されるため、定期的にサインインし直す必要はありません。再発行されるのは有効期間の半分を過ぎてからなので、使われなくなったセッションは最後の利用から 30 日を待たずに失効することがあります。セルフホストの管理者は、`AUTH_TOKEN_TTL` で有効期間を調整できます。[サインインとサインアップ](/auth-setup#セッション有効期間)を参照してください。サインアウトすると、現在のブラウザの認証 cookie と CSRF cookie が削除されます。
ブラウザの cookie をスクリプトや CLI にコピーするのは適切ではありません。ターミナルから Multica にアクセスするには個人アクセストークンを使います。
diff --git a/apps/docs/content/docs/auth-tokens.ko.mdx b/apps/docs/content/docs/auth-tokens.ko.mdx
index a402315bf3..18353ec486 100644
--- a/apps/docs/content/docs/auth-tokens.ko.mdx
+++ b/apps/docs/content/docs/auth-tokens.ko.mdx
@@ -11,7 +11,7 @@ Multica를 일상적으로 사용할 때 주로 접하는 자격 증명은 브
이메일 인증 코드 또는 Google로 로그인하면 Multica가 JWT를 `multica_auth`라는 HttpOnly cookie에 저장합니다. 브라우저가 자동으로 함께 보내며 JavaScript에서는 직접 읽을 수 없습니다.
-세션은 기본적으로 30일 동안 유효합니다. 자체 호스팅 관리자는 `AUTH_TOKEN_TTL`로 이후 발급되는 세션의 유효 기간을 조정할 수 있습니다. [로그인과 가입](/auth-setup#로그인-유효-기간)을 참고하세요. 로그아웃하면 현재 브라우저의 인증 및 CSRF cookie가 삭제됩니다.
+세션은 기본적으로 30일 동안 유효하지만 로그인 시점부터의 카운트다운은 아닙니다. 계속 사용하는 세션은 만료 전에 다시 발급되므로 주기적으로 다시 로그인할 필요가 없습니다. 다시 발급은 유효 기간의 절반이 지난 뒤에만 일어나므로, 사용하지 않는 세션은 마지막 사용 후 30일이 되기 전에 만료될 수 있습니다. 자체 호스팅 관리자는 `AUTH_TOKEN_TTL`로 유효 기간을 조정할 수 있습니다. [로그인과 가입](/auth-setup#로그인-유효-기간)을 참고하세요. 로그아웃하면 현재 브라우저의 인증 및 CSRF cookie가 삭제됩니다.
브라우저 cookie는 스크립트나 CLI에 복사하기에 적합하지 않습니다. 터미널에서 Multica에 접근할 때는 개인 액세스 토큰을 사용하세요.
diff --git a/apps/docs/content/docs/auth-tokens.mdx b/apps/docs/content/docs/auth-tokens.mdx
index 4c176440ec..b61fb658d9 100644
--- a/apps/docs/content/docs/auth-tokens.mdx
+++ b/apps/docs/content/docs/auth-tokens.mdx
@@ -11,7 +11,7 @@ In day-to-day use of Multica you mainly deal with two kinds of credentials: brow
After signing in with an email verification code or Google, Multica stores a JWT in an HttpOnly cookie named `multica_auth`. The browser sends it automatically; JavaScript cannot read it directly.
-Sessions last 30 days by default. Self-hosting admins can adjust the lifetime of sessions issued from then on with `AUTH_TOKEN_TTL`; see [Sign-in and signup configuration](/auth-setup#session-lifetime). Logging out clears the auth and CSRF cookies in the current browser.
+By default a session lasts 30 days, but that is not a countdown from sign-in: a session in continuous use is re-issued before it expires, so staying signed in does not require signing in again on a schedule. It is only re-issued once it is past the halfway point of its lifetime, so a session left unused can end sooner than 30 days after its last use. Self-hosting admins can adjust the lifetime with `AUTH_TOKEN_TTL`; see [Sign-in and signup configuration](/auth-setup#session-lifetime). Logging out clears the auth and CSRF cookies in the current browser.
Browser cookies are not meant to be copied into scripts or the CLI; use a personal access token to access Multica from a terminal.
diff --git a/apps/docs/content/docs/auth-tokens.zh.mdx b/apps/docs/content/docs/auth-tokens.zh.mdx
index 238402b9e8..d7c6160ed4 100644
--- a/apps/docs/content/docs/auth-tokens.zh.mdx
+++ b/apps/docs/content/docs/auth-tokens.zh.mdx
@@ -11,7 +11,7 @@ import { Callout } from "fumadocs-ui/components/callout";
通过邮箱验证码或 Google 登录后,Multica 会把 JWT 保存到名为 `multica_auth` 的 HttpOnly cookie 中。浏览器自动携带它,JavaScript 无法直接读取。
-会话默认有效 30 天。自托管管理员可以通过 `AUTH_TOKEN_TTL` 调整之后签发的会话有效期,见[登录与注册](/auth-setup#登录有效期)。退出登录会清除当前浏览器的认证与 CSRF cookie。
+会话默认有效 30 天,但这不是从登录起算的倒计时:持续使用的会话会在到期前自动续期,所以不需要每隔一段时间重新登录一次。续期只在剩余有效期过半之后才发生,因此闲置的会话可能在最后一次使用后不到 30 天就失效。自托管管理员可以通过 `AUTH_TOKEN_TTL` 调整有效期,见[登录与注册](/auth-setup#登录有效期)。退出登录会清除当前浏览器的认证与 CSRF cookie。
浏览器 cookie 不适合复制到脚本或 CLI;从终端访问 Multica 使用个人访问令牌。
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 5b60481c0b..22396c8de1 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -42,7 +42,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `PORT` | `8080` | API のリッスンポート |
| `JWT_SECRET` | 本番環境で必須 | ログイン JWT と一部の署名フローに使うシークレット。本番では空または既知のプレースホルダーだと起動を拒否 |
| `APP_ENV` | 空 | プロダクションでは `production` を設定 |
-| `AUTH_TOKEN_TTL` | `720h`(30 日) | ブラウザ JWT と cookie の有効期間。Go duration または正の整数秒を受け付けます |
+| `AUTH_TOKEN_TTL` | `720h`(30 日) | ブラウザ JWT と cookie の有効期間。Go duration または正の整数秒を受け付けます。セッションは有効期間の半分を過ぎるとスライド更新され、使い続けている限り失効しません。`60s` 未満は `60s` に補正されます |
| `LOG_LEVEL` | アプリのデフォルト | ログレベル |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 終了シグナル受信後、グレースフルシャットダウンを開始するまでの待機時間 |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | オフラインのランタイムが処理中の作業を失敗させずに再接続できる猶予時間。`150s` 未満は `150s` に補正されます |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 4ebab7e3aa..a4ea346498 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -42,7 +42,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `PORT` | `8080` | API listen port |
| `JWT_SECRET` | 프로덕션에서 필수 | 로그인 JWT와 일부 서명 절차에서 사용하는 키. 프로덕션에서는 비어 있거나 알려진 자리표시자 값으로 부팅 거부 |
| `APP_ENV` | 비어 있음 | 프로덕션 환경에서는 `production`으로 설정 |
-| `AUTH_TOKEN_TTL` | `720h`(30일) | 브라우저 JWT와 cookie 유효 기간. Go duration 또는 양의 정수 초 허용 |
+| `AUTH_TOKEN_TTL` | `720h`(30일) | 브라우저 JWT와 cookie 유효 기간. Go duration 또는 양의 정수 초 허용. 세션은 유효 기간의 절반이 지나면 슬라이딩 갱신되어, 계속 사용하는 동안에는 만료되지 않습니다. `60s` 미만은 `60s`로 조정됩니다 |
| `LOG_LEVEL` | 앱 기본값 | 로그 수준 |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 종료 신호를 받은 뒤 graceful shutdown을 시작하기 전 대기 시간 |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | 오프라인 런타임이 진행 중인 실행을 실패시키지 않고 재연결할 수 있는 유예 시간. `150s` 미만은 `150s`로 조정됨 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 6c83771ff1..6b8af5e1ee 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -42,7 +42,7 @@ You also need to pick an email service, otherwise verification codes and invitat
| `PORT` | `8080` | API listen port |
| `JWT_SECRET` | required in production | Secret for sign-in JWTs and some signing flows; production refuses to boot on empty or known placeholders |
| `APP_ENV` | empty | Set to `production` in production |
-| `AUTH_TOKEN_TTL` | `720h` (30 days) | Lifetime of browser JWTs and cookies; accepts a Go duration or a positive integer of seconds |
+| `AUTH_TOKEN_TTL` | `720h` (30 days) | Lifetime of browser JWTs and cookies; accepts a Go duration or a positive integer of seconds. Sessions slide: one in continuous use is re-issued rather than expiring, from the halfway point of its lifetime onward. Values below `60s` are clamped to `60s` |
| `LOG_LEVEL` | application default | Log level |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | How long to wait after a termination signal before graceful shutdown begins |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | How long an offline runtime may reconnect before its in-flight runs fail; values below `150s` are clamped |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index df0b01a241..c9fc4e0b0d 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -42,7 +42,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `PORT` | `8080` | API 监听端口 |
| `JWT_SECRET` | 生产环境必填 | 登录 JWT、部分签名流程使用的密钥;生产环境对空值或已知占位值拒绝启动 |
| `APP_ENV` | 空 | 生产环境设为 `production` |
-| `AUTH_TOKEN_TTL` | `720h`(30 天) | 浏览器 JWT 与 cookie 有效期;接受 Go duration 或正整数秒数 |
+| `AUTH_TOKEN_TTL` | `720h`(30 天) | 浏览器 JWT 与 cookie 有效期;接受 Go duration 或正整数秒数。会话会滑动续期:剩余有效期过半后,持续使用的会话会被续期而不是到期。低于 `60s` 的取值会按 `60s` 处理 |
| `LOG_LEVEL` | 应用默认 | 日志级别 |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 收到终止信号后,开始优雅退出前等待多久 |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | 运行时离线后可重新连接且不终止在途运行的宽限时间;低于 `150s` 时按 `150s` 处理 |
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index c5d8d9e8d6..0277ffc70f 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -1,6 +1,7 @@
import "../global.css";
import { useEffect, useRef } from "react";
+import { AppState, type AppStateStatus } from "react-native";
import { Stack, router } from "expo-router";
import { StatusBar } from "expo-status-bar";
import { GestureHandlerRootView } from "react-native-gesture-handler";
@@ -10,9 +11,11 @@ import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { ThemeProvider } from "@react-navigation/native";
import { PortalHost } from "@rn-primitives/portal";
import { api } from "@/data/api";
+import { maybeRenewSession } from "@/data/session-renewal";
import { queryClient } from "@/data/query-client";
import { useAuthStore } from "@/data/auth-store";
import { useWorkspaceStore } from "@/data/workspace-store";
+import { SessionActivityBoundary } from "@/components/auth/session-activity-boundary";
import { LightboxProvider, prewarmHighlighter } from "@/lib/markdown";
import { NAV_THEME } from "@/lib/theme";
import { useColorScheme } from "@/lib/use-color-scheme";
@@ -51,9 +54,24 @@ function AuthInitializer({ children }: { children: React.ReactNode }) {
})();
},
});
- initialize();
+ // Launch check for the sliding session (MUL-7436). Runs after the token
+ // is restored and the identity probe has settled, so it never races the
+ // first getMe(); a no-op when there is no session to extend.
+ void initialize().then(() => maybeRenewSession());
}, [initialize, qc]);
+ // Foreground transitions are one of the two "someone is using this" signals;
+ // SessionActivityBoundary below supplies the other, so an app that stays
+ // foregrounded for longer than the check interval still renews. Deliberately
+ // not a timer: a backgrounded or untouched app must not keep the session of
+ // someone who stopped using it alive.
+ useEffect(() => {
+ const sub = AppState.addEventListener("change", (status: AppStateStatus) => {
+ if (status === "active") maybeRenewSession();
+ });
+ return () => sub.remove();
+ }, []);
+
return <>{children}</>;
}
@@ -66,6 +84,7 @@ export default function RootLayout() {
<QueryClientProvider client={queryClient}>
<ThemeProvider value={NAV_THEME[colorScheme]}>
<AuthInitializer>
+ <SessionActivityBoundary>
<LightboxProvider>
<StatusBar style={isDarkColorScheme ? "light" : "dark"} />
<Stack screenOptions={{ headerShown: false }}>
@@ -75,6 +94,7 @@ export default function RootLayout() {
</Stack>
<PortalHost />
</LightboxProvider>
+ </SessionActivityBoundary>
</AuthInitializer>
</ThemeProvider>
</QueryClientProvider>
diff --git a/apps/mobile/components/auth/session-activity-boundary.tsx b/apps/mobile/components/auth/session-activity-boundary.tsx
new file mode 100644
index 0000000000..f4b8720b11
--- /dev/null
+++ b/apps/mobile/components/auth/session-activity-boundary.tsx
@@ -0,0 +1,36 @@
+import type { ReactNode } from "react";
+import { useMemo } from "react";
+import { PanResponder, View } from "react-native";
+
+import { sessionActivityResponderConfig } from "@/data/session-activity";
+
+/**
+ * Notices that someone is actually using the app, so the sliding session can
+ * follow use rather than a clock (MUL-7436).
+ *
+ * Launch and foreground transitions alone are not enough: an app opened once
+ * and then used continuously in the foreground for longer than the renewal
+ * cadence would never check again, and could expire under the user's hands.
+ * Every touch that starts anywhere in the tree passes through here first.
+ *
+ * The responder config declines the gesture it observes — see
+ * `sessionActivityResponderConfig` — so taps, scrolls and swipes behave
+ * exactly as they would without this wrapper. `maybeRenewSession` is a
+ * timestamp comparison on all but one call per interval, so it is cheap enough
+ * to sit on that path.
+ *
+ * There is deliberately no timer: a phone in a pocket with the app foregrounded
+ * must not keep renewing a session nobody is using.
+ */
+export function SessionActivityBoundary({ children }: { children: ReactNode }) {
+ const responder = useMemo(
+ () => PanResponder.create(sessionActivityResponderConfig),
+ [],
+ );
+
+ return (
+ <View style={{ flex: 1 }} {...responder.panHandlers}>
+ {children}
+ </View>
+ );
+}
diff --git a/apps/mobile/data/api.ts b/apps/mobile/data/api.ts
index cc49784332..c8628a5283 100644
--- a/apps/mobile/data/api.ts
+++ b/apps/mobile/data/api.ts
@@ -63,6 +63,8 @@ import type {
import {
AppConfigSchema,
EMPTY_APP_CONFIG,
+ EMPTY_REFRESH_SESSION_RESPONSE,
+ RefreshSessionResponseSchema,
EMPTY_LIST_ISSUE_STATUSES_RESPONSE,
EMPTY_LIST_ISSUES_RESPONSE,
EMPTY_TIMELINE_ENTRIES,
@@ -72,7 +74,10 @@ import {
TimelineEntriesSchema,
WorkspaceSubscriptionSummarySchema,
} from "@multica/core/api/schemas";
-import type { AppConfigResponse } from "@multica/core/api/schemas";
+import type {
+ AppConfigResponse,
+ RefreshSessionResponse,
+} from "@multica/core/api/schemas";
import {
ActiveTasksResponseSchema,
AgentListSchema,
@@ -197,6 +202,13 @@ class ApiClient {
this.token = token;
}
+ /** The bearer token in use, or null when signed out. Session renewal reads
+ * it to confirm the session it started from is still the live one, and the
+ * WS client reads it so a reconnect uses the current credential. */
+ getToken(): string | null {
+ return this.token;
+ }
+
setOptions(options: ApiClientOptions) {
this.options = { ...this.options, ...options };
}
@@ -388,6 +400,21 @@ class ApiClient {
});
}
+ /**
+ * Ask the server to extend this session if it has entered its renewal
+ * window (MUL-7436). The server owns that decision — the app never reads
+ * `exp`, so a device with a skewed clock behaves exactly like one without.
+ */
+ async refreshSession(): Promise<RefreshSessionResponse> {
+ return this.fetchValidatedWith(
+ "/api/auth/refresh",
+ RefreshSessionResponseSchema,
+ EMPTY_REFRESH_SESSION_RESPONSE,
+ { method: "POST" },
+ { endpoint: "refreshSession" },
+ );
+ }
+
async getMe(opts?: { signal?: AbortSignal }): Promise<User> {
return this.fetchValidated(
"/api/me",
diff --git a/apps/mobile/data/auth-store.ts b/apps/mobile/data/auth-store.ts
index 8435eb3e3a..0222a1eeae 100644
--- a/apps/mobile/data/auth-store.ts
+++ b/apps/mobile/data/auth-store.ts
@@ -13,6 +13,7 @@ import { create } from "zustand";
import type { User } from "@multica/core/types";
import { api, ApiError } from "./api";
import { clearToken, getToken, setToken } from "./secure-storage";
+import { invalidateSessionEpoch } from "./session-epoch";
import { useWorkspaceStore } from "./workspace-store";
interface AuthState {
@@ -50,6 +51,10 @@ export const useAuthStore = create<AuthState>((set) => ({
// Only clear token on a genuine 401. Network blips / 5xx keep the
// token so the next launch (or a manual refresh) can retry.
if (err instanceof ApiError && err.status === 401) {
+ // Synchronous first, before the awaited delete: anything already
+ // in flight has to learn the credential is dead now, not once the
+ // Keychain write lands.
+ invalidateSessionEpoch();
await clearToken();
api.setToken(null);
}
@@ -63,6 +68,10 @@ export const useAuthStore = create<AuthState>((set) => ({
verifyCode: async (email, code) => {
const { token, user } = await api.verifyCode(email, code);
+ // Signing in replaces the credential just as decisively as signing out:
+ // a renewal still in flight for the previous account must not write its
+ // result over this one.
+ invalidateSessionEpoch();
await setToken(token);
api.setToken(token);
set({ user });
@@ -70,6 +79,10 @@ export const useAuthStore = create<AuthState>((set) => ({
},
logout: async () => {
+ // First statement in the function, before any await. The Keychain delete
+ // below is async, so until it lands a concurrent read still returns the
+ // token being removed — the epoch is what makes this instant.
+ invalidateSessionEpoch();
await clearToken();
api.setToken(null);
set({ user: null });
diff --git a/apps/mobile/data/realtime/realtime-provider.tsx b/apps/mobile/data/realtime/realtime-provider.tsx
index 969a0083e3..70aa71451b 100644
--- a/apps/mobile/data/realtime/realtime-provider.tsx
+++ b/apps/mobile/data/realtime/realtime-provider.tsx
@@ -39,6 +39,7 @@ import NetInfo from "@react-native-community/netinfo";
import { useAuthStore } from "@/data/auth-store";
import { useWorkspaceStore } from "@/data/workspace-store";
import { getToken } from "@/data/secure-storage";
+import { api } from "@/data/api";
import { WSClient } from "./ws-client";
const API_URL = process.env.EXPO_PUBLIC_API_URL;
@@ -89,6 +90,10 @@ export function RealtimeProvider({ children }: { children: React.ReactNode }) {
ws = new WSClient({
url: WS_URL,
token,
+ // Re-read per connection rather than reusing the token captured
+ // above: a session renewed since this effect ran would otherwise keep
+ // reconnecting with a credential on its way to expiring.
+ getToken: () => api.getToken(),
workspaceSlug: wsSlug,
clientVersion: "0.1.0",
logger: console,
diff --git a/apps/mobile/data/realtime/ws-client.test.ts b/apps/mobile/data/realtime/ws-client.test.ts
index 4099f9f7a0..73ac99a918 100644
--- a/apps/mobile/data/realtime/ws-client.test.ts
+++ b/apps/mobile/data/realtime/ws-client.test.ts
@@ -91,3 +91,61 @@ describe("WSClient application heartbeat", () => {
client.disconnect();
});
});
+
+// A phone reconnects constantly — after every backgrounding, every network
+// switch. By the time it does, a sliding session may have been renewed, and
+// the token captured when this client was built is on its way out (MUL-7436).
+describe("WSClient session renewal", () => {
+ beforeEach(() => {
+ vi.stubGlobal("WebSocket", MockWebSocket);
+ MockWebSocket.instances = [];
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("authenticates each connection with the current token", () => {
+ let current = "token-v1";
+ const client = new WSClient({
+ url: "wss://example.test/ws",
+ token: "token-v1",
+ workspaceSlug: "workspace",
+ getToken: () => current,
+ });
+
+ client.connect();
+ MockWebSocket.instances[0].open();
+ expect(JSON.parse(MockWebSocket.instances[0].sent[0])).toEqual({
+ type: "auth",
+ payload: { token: "token-v1" },
+ });
+
+ current = "token-v2";
+ client.forceReconnect();
+ const reconnected = MockWebSocket.instances[MockWebSocket.instances.length - 1];
+ reconnected.open();
+
+ expect(JSON.parse(reconnected.sent[0])).toEqual({
+ type: "auth",
+ payload: { token: "token-v2" },
+ });
+ });
+
+ it("falls back to the constructor token when no reader is supplied", () => {
+ const client = new WSClient({
+ url: "wss://example.test/ws",
+ token: "token-only",
+ workspaceSlug: "workspace",
+ });
+
+ client.connect();
+ MockWebSocket.instances[0].open();
+
+ expect(JSON.parse(MockWebSocket.instances[0].sent[0])).toEqual({
+ type: "auth",
+ payload: { token: "token-only" },
+ });
+ });
+});
diff --git a/apps/mobile/data/realtime/ws-client.ts b/apps/mobile/data/realtime/ws-client.ts
index 5f04f069cd..58386eaed1 100644
--- a/apps/mobile/data/realtime/ws-client.ts
+++ b/apps/mobile/data/realtime/ws-client.ts
@@ -52,6 +52,11 @@ export interface WSClientOptions {
url: string;
/** Bearer token sent as the first frame. */
token: string;
+ /** Reads the CURRENT token at auth-frame time. A reconnect can happen long
+ * after this client was built — long enough for a sliding session to have
+ * been renewed in between — so `token` above is only the value to fall
+ * back on when no reader is supplied (MUL-7436). */
+ getToken?: () => string | null;
/** Workspace slug — server resolves to UUID and gates membership. */
workspaceSlug: string;
/** Mobile app version, surfaced to server logs for debuggability. */
@@ -211,7 +216,10 @@ export class WSClient {
ws.onopen = () => {
this.logger.info("[ws] socket open, sending auth frame");
ws.send(
- JSON.stringify({ type: "auth", payload: { token: this.opts.token } }),
+ JSON.stringify({
+ type: "auth",
+ payload: { token: this.opts.getToken?.() ?? this.opts.token },
+ }),
);
};
diff --git a/apps/mobile/data/secure-storage.ts b/apps/mobile/data/secure-storage.ts
index f8526eb460..eaee77b0da 100644
--- a/apps/mobile/data/secure-storage.ts
+++ b/apps/mobile/data/secure-storage.ts
@@ -1,20 +1,71 @@
/**
- * Thin wrapper around expo-secure-store for the auth token.
+ * The app's single writer for the auth token.
+ *
* Keyed identically to web/desktop ("multica_token") so logic stays aligned
* with packages/core/auth/store.ts even though storage backends differ.
+ *
+ * Every Keychain operation is async, and several things race to write this one
+ * value: logout, a 401 teardown, a new sign-in, and a background session
+ * renewal that started before any of them. Interleaved, they produce states no
+ * single path intends — most sharply, a renewal writing its result on top of a
+ * sign-in that finished while it was suspended, leaving the app logged in as
+ * one account and persisted as another.
+ *
+ * So writes are SERIALIZED here, and a conditional write can be decided inside
+ * that serialization (see commitRenewedToken). That is what makes a stale
+ * write refusable instead of something to undo afterwards — undoing it means
+ * deleting whatever is there now, which may belong to a session that started
+ * after the stale one and has every right to exist.
*/
import * as SecureStore from "expo-secure-store";
+import { sessionEpochChanged } from "./session-epoch";
+
const TOKEN_KEY = "multica_token";
+// Tail of the write queue. Each operation chains onto the previous one so no
+// two can be in flight at once; failures do not stall the queue.
+let writes: Promise<unknown> = Promise.resolve();
+
+function serialize<T>(operation: () => Promise<T>): Promise<T> {
+ const result = writes.then(operation, operation);
+ writes = result.catch(() => undefined);
+ return result;
+}
+
export async function getToken(): Promise<string | null> {
return SecureStore.getItemAsync(TOKEN_KEY);
}
export async function setToken(token: string): Promise<void> {
- await SecureStore.setItemAsync(TOKEN_KEY, token);
+ await serialize(() => SecureStore.setItemAsync(TOKEN_KEY, token));
}
export async function clearToken(): Promise<void> {
- await SecureStore.deleteItemAsync(TOKEN_KEY);
+ await serialize(() => SecureStore.deleteItemAsync(TOKEN_KEY));
+}
+
+/**
+ * Persist a renewed token, but only if the session it renews is still the one
+ * the app is using. Returns whether the write happened.
+ *
+ * The check and the write are one serialized unit, which is the whole point: a
+ * logout or a sign-in cannot land between them, so "is this still current?"
+ * cannot go stale between being asked and being acted on. Both conditions are
+ * needed and neither implies the other — the epoch catches a teardown that has
+ * STARTED but not finished (its Keychain delete is still in flight, so a read
+ * would still return the old token), and the value comparison catches a
+ * credential replaced by any path that did not move the epoch.
+ */
+export async function commitRenewedToken(
+ token: string,
+ expected: { epoch: number; previousToken: string },
+): Promise<boolean> {
+ return serialize(async () => {
+ if (sessionEpochChanged(expected.epoch)) return false;
+ const current = await SecureStore.getItemAsync(TOKEN_KEY);
+ if (current !== expected.previousToken) return false;
+ await SecureStore.setItemAsync(TOKEN_KEY, token);
+ return true;
+ });
}
diff --git a/apps/mobile/data/session-activity.ts b/apps/mobile/data/session-activity.ts
new file mode 100644
index 0000000000..f026c4afa2
--- /dev/null
+++ b/apps/mobile/data/session-activity.ts
@@ -0,0 +1,22 @@
+import { maybeRenewSession } from "./session-renewal";
+
+/**
+ * The touch-observer half of activity-driven session renewal (MUL-7436).
+ *
+ * Kept out of the component so it can be tested where mobile's test setup
+ * lives — the data layer — rather than requiring a React Native renderer for
+ * what is really one decision: notice the touch, decline the gesture.
+ *
+ * `onStartShouldSetPanResponderCapture` runs in the capture phase, before any
+ * child can claim the gesture, and returning false declines to become the
+ * responder. That combination is what lets this sit on the path of every touch
+ * in the app without changing how a single one behaves.
+ */
+export const sessionActivityResponderConfig = {
+ onStartShouldSetPanResponderCapture: (): boolean => {
+ maybeRenewSession();
+ // Never true. Returning true here would make this wrapper the responder
+ // and swallow every tap, scroll and swipe in the app.
+ return false;
+ },
+};
diff --git a/apps/mobile/data/session-epoch.ts b/apps/mobile/data/session-epoch.ts
new file mode 100644
index 0000000000..d5f3572c10
--- /dev/null
+++ b/apps/mobile/data/session-epoch.ts
@@ -0,0 +1,42 @@
+/**
+ * A synchronous marker for "the credential this app is holding has changed".
+ *
+ * Mobile stores the token in the Keychain, and every Keychain operation is
+ * async. That makes "is the session I started from still the live one?"
+ * unanswerable by reading storage: logout does `await clearToken()`, so
+ * between the moment logout begins and the moment the delete lands, a read
+ * still returns the old token. A background session renewal that sampled
+ * storage in that window would see a token that is on its way out, then write
+ * its replacement back — resurrecting a session the user just ended, on the
+ * device they ended it from.
+ *
+ * The epoch closes that window because incrementing it is synchronous and
+ * happens FIRST, before any await in the path that invalidates the session.
+ * Anything long-running captures the epoch before its first await and refuses
+ * to apply a result if the value moved.
+ *
+ * Deliberately module state and not a store: it has to be readable and
+ * writable without React, without awaiting, and from both the auth store and
+ * the API client's 401 handler.
+ */
+let epoch = 0;
+
+/** Read the current epoch. Capture this BEFORE the first await. */
+export function currentSessionEpoch(): number {
+ return epoch;
+}
+
+/**
+ * Mark every credential captured so far as stale. Call synchronously at the
+ * START of anything that ends or replaces the session — logout, a 401
+ * teardown, signing in as someone else — before awaiting the storage writes
+ * that carry it out.
+ */
+export function invalidateSessionEpoch(): void {
+ epoch++;
+}
+
+/** True when the session has been invalidated or replaced since `at`. */
+export function sessionEpochChanged(at: number): boolean {
+ return epoch !== at;
+}
diff --git a/apps/mobile/data/session-renewal.test.ts b/apps/mobile/data/session-renewal.test.ts
new file mode 100644
index 0000000000..cf48d2bc9e
--- /dev/null
+++ b/apps/mobile/data/session-renewal.test.ts
@@ -0,0 +1,401 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// The Keychain is async, and that is the whole point of these tests: `defer`
+// lets one operation be started and finished at a chosen moment, so a logout
+// and a renewal can be interleaved in either order.
+const keychain = vi.hoisted(() => ({
+ value: null as string | null,
+ // When held, the operation suspends on entry and stays there until the test
+ // releases it. `onSetEnter` fires at that moment, so a test can await the
+ // exact instant a write is in flight instead of guessing at microtask
+ // counts — the difference between pinning an interleaving and hoping for one.
+ holdSet: false,
+ releaseSet: null as null | (() => void),
+ onSetEnter: null as null | (() => void),
+ holdClear: false,
+ releaseClear: null as null | (() => void),
+}));
+
+// The real module is used, not a hand-written stand-in: its serialization is
+// the mechanism under test here, so replacing it would test nothing. Only
+// expo-secure-store underneath is faked, with hold/release so a test can pin
+// an interleaving instead of guessing at microtask counts.
+vi.mock("expo-secure-store", () => ({
+ getItemAsync: vi.fn(async () => keychain.value),
+ setItemAsync: vi.fn(async (_key: string, token: string) => {
+ if (keychain.holdSet) {
+ await new Promise<void>((resolve) => {
+ keychain.releaseSet = resolve;
+ keychain.onSetEnter?.();
+ });
+ }
+ keychain.value = token;
+ }),
+ deleteItemAsync: vi.fn(async () => {
+ if (keychain.holdClear) {
+ await new Promise<void>((resolve) => {
+ keychain.releaseClear = resolve;
+ });
+ }
+ keychain.value = null;
+ }),
+}));
+
+function resetKeychain() {
+ keychain.value = "token-v1";
+ keychain.holdSet = false;
+ keychain.releaseSet = null;
+ keychain.onSetEnter = null;
+ keychain.holdClear = false;
+ keychain.releaseClear = null;
+}
+
+const apiMock = vi.hoisted(() => ({
+ refreshSession: vi.fn(),
+ setToken: vi.fn(),
+}));
+
+vi.mock("./api", async () => {
+ class ApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ this.name = "ApiError";
+ }
+ }
+ return { api: apiMock, ApiError };
+});
+
+import { ApiError } from "./api";
+import {
+ maybeRenewSession,
+ renewSessionNow,
+ resetSessionRenewalForTest,
+} from "./session-renewal";
+import { invalidateSessionEpoch } from "./session-epoch";
+import { sessionActivityResponderConfig } from "./session-activity";
+import * as SecureStore from "expo-secure-store";
+import { clearToken, getToken, setToken } from "./secure-storage";
+
+function renewed(token: string, checkAgainInSeconds = 3600) {
+ return {
+ token,
+ expires_at: "2026-10-16T00:00:00Z",
+ renewed: true,
+ check_again_in_seconds: checkAgainInSeconds,
+ };
+}
+
+function notYet(checkAgainInSeconds = 3600) {
+ return {
+ expires_at: "2026-10-16T00:00:00Z",
+ renewed: false,
+ check_again_in_seconds: checkAgainInSeconds,
+ };
+}
+
+describe("mobile session renewal", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetKeychain();
+ resetSessionRenewalForTest();
+ });
+
+ it("writes a renewed token to the Keychain and the API client", async () => {
+ apiMock.refreshSession.mockResolvedValue(renewed("token-v2"));
+
+ await renewSessionNow();
+
+ expect(await getToken()).toBe("token-v2");
+ expect(apiMock.setToken).toHaveBeenCalledWith("token-v2");
+ });
+
+ it("leaves the session alone when the server says it is not time yet", async () => {
+ apiMock.refreshSession.mockResolvedValue(notYet());
+
+ await renewSessionNow();
+
+ expect(await getToken()).toBe("token-v1");
+ expect(vi.mocked(SecureStore.setItemAsync)).not.toHaveBeenCalled();
+ });
+
+ // Launch and a foreground transition land together all the time on iOS.
+ it("coalesces concurrent renewals into one request", async () => {
+ let resolve!: (value: unknown) => void;
+ apiMock.refreshSession.mockReturnValue(
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+
+ const first = renewSessionNow();
+ const second = renewSessionNow();
+ resolve(renewed("token-v2"));
+ await Promise.all([first, second]);
+
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1);
+ });
+
+ // Phones background constantly. A timer would keep the session of someone
+ // who stopped opening the app alive forever; the interval gate is what
+ // makes foreground checks safe to fire on every activation.
+ it("declines a repeat check until the server-supplied interval elapses", async () => {
+ apiMock.refreshSession.mockResolvedValue(notYet(3600));
+
+ await renewSessionNow();
+ for (let i = 0; i < 20; i++) maybeRenewSession();
+ await Promise.resolve();
+
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ["offline", new TypeError("Network request failed")],
+ ["server error", new ApiError("boom", 500)],
+ ])("keeps the current session when renewal fails (%s)", async (_name, err) => {
+ apiMock.refreshSession.mockRejectedValue(err);
+
+ await renewSessionNow();
+
+ expect(await getToken()).toBe("token-v1");
+ expect(apiMock.setToken).not.toHaveBeenCalled();
+ });
+
+ // A failure must not consume the normal cadence. With the 30-day default
+ // that cadence is three days, so a single 503 near the end of a session
+ // would otherwise push the next attempt past the expiry it was trying to
+ // prevent.
+ it("retries within seconds after a failure, not after the server cadence", async () => {
+ apiMock.refreshSession.mockResolvedValue(notYet(3 * 24 * 60 * 60));
+ await renewSessionNow();
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1);
+
+ apiMock.refreshSession.mockRejectedValue(new TypeError("Network request failed"));
+ const start = Date.now();
+ vi.spyOn(Date, "now").mockReturnValue(start + 3 * 24 * 60 * 60 * 1000);
+ await renewSessionNow();
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(2);
+
+ // Connectivity returns a second later and the user is still working.
+ apiMock.refreshSession.mockResolvedValue(notYet(3 * 24 * 60 * 60));
+ vi.mocked(Date.now).mockReturnValue(start + 3 * 24 * 60 * 60 * 1000 + 1_500);
+ maybeRenewSession();
+ await vi.waitFor(() =>
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(3),
+ );
+ vi.mocked(Date.now).mockRestore();
+ });
+
+ // A 200 whose body failed schema validation comes back as zeroes rather
+ // than as a throw; without treating it as a failure the deadline never
+ // moves and every touch fires another request.
+ it("backs off on a response that carries no cadence", async () => {
+ apiMock.refreshSession.mockResolvedValue({
+ expires_at: "",
+ renewed: false,
+ check_again_in_seconds: 0,
+ });
+
+ const start = Date.now();
+ vi.spyOn(Date, "now").mockReturnValue(start);
+ await renewSessionNow();
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1);
+
+ for (let i = 0; i < 20; i++) maybeRenewSession();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1);
+
+ vi.mocked(Date.now).mockReturnValue(start + 1_100);
+ maybeRenewSession();
+ await vi.waitFor(() =>
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(2),
+ );
+ vi.mocked(Date.now).mockRestore();
+ });
+
+ it("discards a response that arrives after sign-out", async () => {
+ let resolve!: (value: unknown) => void;
+ apiMock.refreshSession.mockReturnValue(
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+
+ const pending = renewSessionNow();
+ keychain.value = null; // logout cleared the Keychain mid-flight
+
+ resolve(renewed("token-v2"));
+ await pending;
+
+ expect(await getToken()).toBeNull();
+ expect(apiMock.setToken).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when there is no session to extend", async () => {
+ keychain.value = null;
+
+ await renewSessionNow();
+
+ expect(apiMock.refreshSession).not.toHaveBeenCalled();
+ });
+});
+
+// Logging out is not instantaneous on mobile: `clearToken` is a Keychain
+// write, so between "the user tapped Sign out" and "the token is gone" there
+// is a window where a read still returns it. A renewal that sampled storage in
+// that window would write its replacement back and sign the user straight
+// in again, on the device they just signed out of.
+//
+// Both completion orders are covered, because the two guards catch different
+// halves: the epoch is true the instant logout starts, the token comparison
+// only once the delete lands.
+/**
+ * Starts a renewal and returns once its request is genuinely in flight — i.e.
+ * once the early "is this session still current?" checks have already passed.
+ *
+ * Without waiting for that, a test that logs out immediately is caught by
+ * those early checks and never reaches the commit, so it would pass whether
+ * or not the commit guards the write at all.
+ */
+async function renewalInFlight(): Promise<{
+ pending: Promise<void>;
+ respond: (value: unknown) => void;
+}> {
+ let respond!: (value: unknown) => void;
+ let requestStarted!: () => void;
+ const started = new Promise<void>((resolve) => {
+ requestStarted = resolve;
+ });
+ apiMock.refreshSession.mockImplementation(() => {
+ requestStarted();
+ return new Promise((resolve) => {
+ respond = resolve;
+ });
+ });
+
+ const pending = renewSessionNow();
+ await started;
+ return { pending, respond };
+}
+
+describe("mobile session renewal — logout races", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetKeychain();
+ resetSessionRenewalForTest();
+ });
+
+ it("refuses the result when logout has STARTED but its delete has not landed", async () => {
+ const { pending, respond } = await renewalInFlight();
+
+ // Logout begins: the epoch moves synchronously and the Keychain delete is
+ // left in flight, so a plain read would still return the old token.
+ keychain.holdClear = true;
+ invalidateSessionEpoch();
+ const logout = clearToken();
+
+ respond(renewed("token-v2"));
+
+ // The renewal's commit queues behind the in-flight delete — that is the
+ // serialization doing its job. Release the delete so both can finish.
+ keychain.holdClear = false;
+ keychain.releaseClear?.();
+ await Promise.all([logout, pending]);
+
+ expect(await getToken()).toBeNull();
+ expect(apiMock.setToken).not.toHaveBeenCalledWith("token-v2");
+ });
+
+ // The three-party case: a stale renewal must not disturb a session that
+ // started AFTER it. Refusing has to mean "write nothing" — deleting instead
+ // would wipe the new account's credential and leave the app logged in in
+ // memory but signed out on the next launch.
+ it("leaves a newer sign-in untouched when a stale renewal lands last", async () => {
+ const { pending, respond } = await renewalInFlight();
+
+ // Logout, then a fresh sign-in as someone else — both complete while the
+ // renewal is still waiting on its response.
+ invalidateSessionEpoch();
+ await clearToken();
+ invalidateSessionEpoch();
+ await setToken("new-account-token");
+
+ respond(renewed("stale-token-v2"));
+ await pending;
+
+ expect(await getToken()).toBe("new-account-token");
+ expect(apiMock.setToken).not.toHaveBeenCalledWith("stale-token-v2");
+ });
+
+ // Same shape, but the stale renewal's own write is the one still pending
+ // when the newer session arrives. Serialization means it cannot land in the
+ // middle of the sign-in; it is simply refused when its turn comes.
+ it("refuses a stale renewal even when its write is the last to be queued", async () => {
+ const { pending, respond } = await renewalInFlight();
+
+ invalidateSessionEpoch();
+ const logout = clearToken();
+ const login = setToken("new-account-token");
+ respond(renewed("stale-token-v2"));
+
+ await Promise.all([logout, login, pending]);
+
+ expect(await getToken()).toBe("new-account-token");
+ expect(apiMock.setToken).not.toHaveBeenCalledWith("stale-token-v2");
+ });
+
+ it("still applies the renewal when no logout happened", async () => {
+ apiMock.refreshSession.mockResolvedValue(renewed("token-v2"));
+
+ await renewSessionNow();
+
+ expect(await getToken()).toBe("token-v2");
+ expect(apiMock.setToken).toHaveBeenCalledWith("token-v2");
+ });
+});
+
+// Launch and foreground alone leave a gap: an app opened once and then used
+// continuously in the foreground for longer than the check interval would
+// never check again and could expire while the user was mid-sentence.
+describe("session activity responder", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetKeychain();
+ resetSessionRenewalForTest();
+ });
+
+ it("checks on a touch and never claims the gesture", async () => {
+ apiMock.refreshSession.mockResolvedValue(notYet(3600));
+
+ const claimed =
+ sessionActivityResponderConfig.onStartShouldSetPanResponderCapture();
+
+ // Returning true would make the wrapper the responder and swallow every
+ // tap, scroll and swipe in the app.
+ expect(claimed).toBe(false);
+ await vi.waitFor(() =>
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1),
+ );
+ });
+
+ it("throttles to the server-supplied cadence, so touches are not requests", async () => {
+ apiMock.refreshSession.mockResolvedValue(notYet(3600));
+
+ sessionActivityResponderConfig.onStartShouldSetPanResponderCapture();
+ await vi.waitFor(() =>
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1),
+ );
+
+ for (let i = 0; i < 100; i++) {
+ expect(
+ sessionActivityResponderConfig.onStartShouldSetPanResponderCapture(),
+ ).toBe(false);
+ }
+ await Promise.resolve();
+
+ expect(apiMock.refreshSession).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/data/session-renewal.ts b/apps/mobile/data/session-renewal.ts
new file mode 100644
index 0000000000..e53c28fb25
--- /dev/null
+++ b/apps/mobile/data/session-renewal.ts
@@ -0,0 +1,159 @@
+/**
+ * Sliding session renewal (MUL-7436).
+ *
+ * Mirrors packages/core/platform/session-renewal.ts in contract, not in code:
+ * mobile owns its own API client and stores the token in the Keychain behind
+ * an async API, so this is a mobile-local implementation of the same two
+ * rules.
+ *
+ * Renewal follows USE, not time. There is no interval timer — a check runs at
+ * launch and whenever the app returns to the foreground. A backgrounded phone
+ * is the normal state of a phone, and a timer there would keep a session
+ * alive for a user who stopped using the app months ago.
+ *
+ * Renewal is not a session event. It swaps a credential in place and must
+ * never look like a login or a logout. Offline, 5xx and a malformed response
+ * all leave the current session untouched — but leaving it alone is not the
+ * same as waiting: a failure happens INSIDE the renewal window, where the
+ * remaining lifetime is under half a TTL and shrinking, so the retry has to
+ * come back quickly instead of consuming the normal cadence. Only a real 401
+ * ends a session, and `onUnauthorized` in app/_layout.tsx already owns that.
+ */
+import { api, ApiError } from "./api";
+import { commitRenewedToken, getToken } from "./secure-storage";
+import { currentSessionEpoch, sessionEpochChanged } from "./session-epoch";
+
+/**
+ * How long to wait after a FAILED check before another is allowed, by
+ * consecutive failure — deliberately not the normal cadence.
+ *
+ * The normal cadence comes from the token's lifetime and can be days. A
+ * failure that consumed it would be fatal in the ordinary case, not only at
+ * short TTLs: a client told "check again in 3 days" on day 12, returning on
+ * day 29 with one day left and hitting a single 503, would not be allowed to
+ * retry until day 32 — two days after the session expired. A failure buys a
+ * short backoff instead, reset by the next success. Mirrors
+ * RETRY_DELAYS_MS in packages/core/platform/session-renewal.ts.
+ */
+const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000] as const;
+
+/**
+ * Anti-busy-loop floor, not a policy. It matches the server's own floor, so it
+ * never overrides a cadence the server actually chose — a floor above the
+ * server's smallest value would silently let an active session expire. See
+ * minSessionRenewCheckInterval in server/internal/auth/session.go.
+ */
+const MIN_CHECK_INTERVAL_MS = 5 * 1000;
+
+// The earliest a check may run. Zero at start, so the launch check fires on
+// the first trigger; a success pushes it out by the server's cadence and a
+// failure by a short backoff. Tracking the deadline rather than the last
+// attempt is what keeps those two from sharing one number.
+let nextCheckAt = 0;
+let consecutiveFailures = 0;
+
+/** Push the next allowed check out by the current backoff step. */
+function scheduleRetryAfterFailure(): void {
+ const delay =
+ RETRY_DELAYS_MS[Math.min(consecutiveFailures, RETRY_DELAYS_MS.length - 1)]!;
+ consecutiveFailures += 1;
+ nextCheckAt = Date.now() + delay;
+}
+// Collapses concurrent triggers: launch and a foreground transition can land
+// together, and two renewals would leave two valid tokens racing to be the
+// one written to the Keychain.
+let inFlight: Promise<void> | null = null;
+
+/**
+ * Run a renewal check now, regardless of how recently one ran. Use at launch;
+ * everywhere else prefer `maybeRenewSession`.
+ */
+export async function renewSessionNow(): Promise<void> {
+ if (inFlight) return inFlight;
+
+ // Captured before anything awaits. Comparing tokens alone is not enough on
+ // mobile: logout's Keychain delete is async, so a read taken after logout
+ // began but before the delete landed still returns the old token, and this
+ // attempt would then write its replacement back over a session the user
+ // just ended. The epoch moves synchronously at the start of logout, a 401
+ // teardown and a new sign-in, so it is already stale by the time we check.
+ const epochAtStart = currentSessionEpoch();
+
+ // Assigned before the first await, so two callers in the same tick cannot
+ // both get past the guard above. Reading the Keychain is itself async, so
+ // doing that first — outside the promise — would reopen the window this
+ // guard exists to close.
+ inFlight = (async () => {
+ try {
+ // The session this attempt is for. Anything applied below is checked
+ // against it, so an attempt that outlives its own session writes
+ // nothing.
+ const startedFrom = await getToken();
+ if (!startedFrom || sessionEpochChanged(epochAtStart)) return;
+
+ const result = await api.refreshSession();
+ // A response that carries no cadence is not a usable answer. The schema
+ // fallback produces exactly this shape — `parseWithFallback` returns
+ // zeroes for a body that failed validation instead of throwing — and a
+ // real server always sends a positive interval. Left untreated it would
+ // reset the failure count without moving the deadline, so every
+ // subsequent interaction fires another request. Back off as for a
+ // failure.
+ if (result.check_again_in_seconds <= 0) {
+ scheduleRetryAfterFailure();
+ } else {
+ consecutiveFailures = 0;
+ nextCheckAt =
+ Date.now() +
+ Math.max(MIN_CHECK_INTERVAL_MS, result.check_again_in_seconds * 1000);
+ }
+ // A token that did arrive is still worth applying, whatever the cadence
+ // field said.
+ if (!result.renewed || !result.token) return;
+
+ // The decision to keep this result and the write that acts on it happen
+ // together, inside the credential writer's serialization — so a logout
+ // or a sign-in cannot slip between them. A refusal is just a no-op:
+ // nothing is deleted, because by the time a renewal is stale whatever is
+ // stored may belong to a session that started after it.
+ const applied = await commitRenewedToken(result.token, {
+ epoch: epochAtStart,
+ previousToken: startedFrom,
+ });
+ if (!applied) return;
+
+ // The write is committed; publishing it in memory is the last step. A
+ // teardown that lands in this gap has already cleared storage and will
+ // clear the in-memory token too, so stay out of its way.
+ if (sessionEpochChanged(epochAtStart)) return;
+ api.setToken(result.token);
+ } catch (err) {
+ // A 401 has already been routed to the sign-out path by the client's
+ // onUnauthorized hook. Everything else — airplane mode, a captive
+ // portal, a 5xx — says nothing about the session, which just
+ // authenticated this request. Keep it, and come back soon: the window
+ // this failed inside is still closing.
+ scheduleRetryAfterFailure();
+ if (!(err instanceof ApiError) || err.status !== 401) {
+ console.log("[auth] session renewal deferred", err);
+ }
+ } finally {
+ inFlight = null;
+ }
+ })();
+
+ return inFlight;
+}
+
+/** Run a check unless one is not due yet. */
+export function maybeRenewSession(): void {
+ if (Date.now() < nextCheckAt) return;
+ void renewSessionNow();
+}
+
+/** Test seam: forget the cadence and the last-attempt timestamp. */
+export function resetSessionRenewalForTest(): void {
+ nextCheckAt = 0;
+ consecutiveFailures = 0;
+ inFlight = null;
+}
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 7392b524d6..bdf3bb3f0e 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -2736,3 +2736,321 @@ describe("ApiClient session expiry", () => {
expect(storage.getItem("multica_token")).toBeNull();
});
});
+
+describe("ApiClient sliding session renewal", () => {
+ function jsonResponse(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ it("validates the refresh response and falls back to 'not renewed'", async () => {
+ // A malformed body must never be read as a renewal: acting on it would
+ // hand `undefined` to the code that persists the token.
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ renewed: "yes" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const result = await new ApiClient("https://api.example.test").refreshSession();
+
+ expect(result.renewed).toBe(false);
+ expect(result.token).toBeUndefined();
+ expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/auth/refresh");
+ expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
+ });
+
+ it("returns the renewed token for a bearer client", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ jsonResponse({
+ token: "token-v2",
+ expires_at: "2026-10-16T00:00:00Z",
+ renewed: true,
+ check_again_in_seconds: 259200,
+ }),
+ ),
+ );
+
+ const result = await new ApiClient("https://api.example.test").refreshSession();
+
+ expect(result).toMatchObject({
+ token: "token-v2",
+ renewed: true,
+ check_again_in_seconds: 259200,
+ });
+ });
+
+ // The one case where a session renewal can invalidate a CSRF token another
+ // tab is already holding: the first renewal of a session that predates the
+ // session-bound binding. The cookie has already been replaced by then, so
+ // re-reading it and sending again is enough (MUL-7436).
+ it("retries once when a CSRF token turns out to be stale", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ error: "CSRF validation failed" }, 403))
+ .mockResolvedValueOnce(jsonResponse({ ok: true }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.markOnboardingComplete()).resolves.toBeDefined();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not retry a 403 that is a real authorization failure", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(jsonResponse({ error: "forbidden" }, 403));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.markOnboardingComplete()).rejects.toBeInstanceOf(ApiError);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("gives up after one retry rather than looping", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(jsonResponse({ error: "CSRF validation failed" }, 403));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.markOnboardingComplete()).rejects.toBeInstanceOf(ApiError);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+});
+
+// This file runs in the node environment, so `document` is stubbed rather
+// than relying on jsdom — readCookie only ever reads `document.cookie`, and a
+// stub keeps these tests next to the rest of the client's coverage.
+// This file runs in the node environment, so `document` is stubbed rather
+// than relying on jsdom — readCookie only ever reads `document.cookie`, and a
+// stub keeps these tests next to the rest of the client's coverage.
+describe("ApiClient CSRF headers", () => {
+ function stubCookies(cookie: string) {
+ vi.stubGlobal("document", { cookie });
+ }
+
+ function jsonResponse(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ function capturedHeaders(fetchMock: ReturnType<typeof vi.fn>, call = 0) {
+ return (fetchMock.mock.calls[call]?.[1]?.headers ?? {}) as Record<string, string>;
+ }
+
+ // One header name, deliberately. A second one would have to be in the
+ // server's CORS allowlist, and a rolled-back server allowlists only the
+ // names it shipped with — the preflight would fail and no retry could help.
+ it("sends exactly one CSRF header, preferring the session-bound value", async () => {
+ stubCookies("multica_csrf=token-bound; multica_csrf_session=session-bound");
+ const fetchMock = vi.fn().mockImplementation(async () => jsonResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").markOnboardingComplete();
+
+ const headers = capturedHeaders(fetchMock);
+ expect(headers["X-CSRF-Token"]).toBe("session-bound");
+ expect(headers["X-CSRF-Session"]).toBeUndefined();
+ });
+
+ // A session that predates the session-bound cookie, and every request after
+ // a rollback, has only the token-bound value to offer.
+ it("falls back to the token-bound value when no session cookie exists", async () => {
+ stubCookies("multica_csrf=token-bound");
+ const fetchMock = vi.fn().mockImplementation(async () => jsonResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").markOnboardingComplete();
+
+ expect(capturedHeaders(fetchMock)["X-CSRF-Token"]).toBe("token-bound");
+ });
+
+ it("sends no CSRF header when there is no cookie to echo", async () => {
+ stubCookies("");
+ const fetchMock = vi.fn().mockImplementation(async () => jsonResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").markOnboardingComplete();
+
+ expect(capturedHeaders(fetchMock)["X-CSRF-Token"]).toBeUndefined();
+ });
+
+ // The rollback path end to end: a server running the previous release
+ // cannot verify the session-bound value, and the client has to discover that
+ // and switch — otherwise the user is authenticated for reads and rejected
+ // for every write.
+ it("retries with the token-bound value when the server rejects the session-bound one", async () => {
+ stubCookies("multica_csrf=token-bound; multica_csrf_session=session-bound");
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ error: "CSRF validation failed" }, 403))
+ // A factory, not a fixed value: a Response body can only be read once,
+ // so a shared instance breaks on the second call.
+ .mockImplementation(async () => jsonResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await client.markOnboardingComplete();
+
+ expect(capturedHeaders(fetchMock, 0)["X-CSRF-Token"]).toBe("session-bound");
+ expect(capturedHeaders(fetchMock, 1)["X-CSRF-Token"]).toBe("token-bound");
+ });
+
+ // ...and it stays switched, so a rolled-back server does not cost two
+ // requests per write for the rest of the session.
+ it("keeps using the token-bound value while the rejected cookie is current", async () => {
+ stubCookies("multica_csrf=token-bound; multica_csrf_session=session-bound");
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ error: "CSRF validation failed" }, 403))
+ // A factory, not a fixed value: a Response body can only be read once,
+ // so a shared instance breaks on the second call.
+ .mockImplementation(async () => jsonResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await client.markOnboardingComplete();
+ await client.markOnboardingComplete();
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(capturedHeaders(fetchMock, 2)["X-CSRF-Token"]).toBe("token-bound");
+ });
+
+ // But only while it is current. A renewal or a new login replaces the
+ // session cookie, and the preferred binding is worth trying again — keying
+ // on the value rather than a boolean is what stops this oscillating once
+ // per renewal against a server that understands it perfectly well.
+ it("prefers the session-bound value again once the cookie changes", async () => {
+ stubCookies("multica_csrf=token-bound; multica_csrf_session=session-bound");
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ error: "CSRF validation failed" }, 403))
+ // A factory, not a fixed value: a Response body can only be read once,
+ // so a shared instance breaks on the second call.
+ .mockImplementation(async () => jsonResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await client.markOnboardingComplete();
+
+ stubCookies("multica_csrf=token-bound-2; multica_csrf_session=session-bound-2");
+ await client.markOnboardingComplete();
+
+ expect(capturedHeaders(fetchMock, 2)["X-CSRF-Token"]).toBe("session-bound-2");
+ });
+});
+
+// Desktop runs one ApiClient per window over one shared localStorage. Before
+// MUL-7436 each instance cached the bearer token, so a session renewed in one
+// window left every other window sending the credential it happened to be
+// holding — until that one expired and took the whole session down with it,
+// clearing tabs and drafts on the way (MUL-7028).
+describe("ApiClient shared credential across windows", () => {
+ function sharedStorage(initial: string | null) {
+ let token = initial;
+ return {
+ read: () => token,
+ write: (next: string | null) => {
+ token = next;
+ },
+ };
+ }
+
+ function jsonResponse(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+
+ function authHeaderOf(fetchMock: ReturnType<typeof vi.fn>, call: number) {
+ const headers = (fetchMock.mock.calls[call]?.[1]?.headers ?? {}) as Record<string, string>;
+ return headers["Authorization"];
+ }
+
+ it("reads the current token per request, so a renewal in one window reaches the others", async () => {
+ const storage = sharedStorage("token-v1");
+ const windowA = new ApiClient("https://api.example.test", { getToken: storage.read });
+ const windowB = new ApiClient("https://api.example.test", { getToken: storage.read });
+
+ const fetchMock = vi.fn().mockImplementation(async () => jsonResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await windowB.markOnboardingComplete();
+ expect(authHeaderOf(fetchMock, 0)).toBe("Bearer token-v1");
+
+ // Window A renews; only shared storage is updated, exactly as the renewal
+ // controller does it.
+ storage.write("token-v2");
+ windowA.setToken("token-v2");
+
+ await windowB.markOnboardingComplete();
+ expect(authHeaderOf(fetchMock, 1)).toBe("Bearer token-v2");
+ });
+
+ // The other half: a request that went out with the previous credential can
+ // 401 AFTER the renewal landed. Ending the session on that would tear down
+ // one that is demonstrably alive.
+ it("ignores a 401 for a credential that has since been replaced", async () => {
+ const storage = sharedStorage("token-v1");
+ const onUnauthorized = vi.fn();
+ const client = new ApiClient("https://api.example.test", {
+ getToken: storage.read,
+ onUnauthorized,
+ });
+
+ const fetchMock = vi.fn().mockImplementation(async () => {
+ // The renewal lands while this request is in flight.
+ storage.write("token-v2");
+ return jsonResponse({ error: "invalid token" }, 401);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(client.markOnboardingComplete()).rejects.toBeInstanceOf(ApiError);
+
+ expect(onUnauthorized).not.toHaveBeenCalled();
+ });
+
+ // ...but a genuine expiry still ends the session: nothing replaced the
+ // credential, so the 401 is about the one still in use.
+ it("still ends the session on a 401 for the credential in use", async () => {
+ const storage = sharedStorage("token-v1");
+ const onUnauthorized = vi.fn();
+ const client = new ApiClient("https://api.example.test", {
+ getToken: storage.read,
+ onUnauthorized,
+ });
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async () => jsonResponse({ error: "invalid token" }, 401)),
+ );
+
+ await expect(client.markOnboardingComplete()).rejects.toBeInstanceOf(ApiError);
+
+ expect(onUnauthorized).toHaveBeenCalledTimes(1);
+ });
+
+ // Cookie mode has no bearer token to compare, so the guard must not swallow
+ // its expiries.
+ it("ends the session on a 401 in cookie mode", async () => {
+ const onUnauthorized = vi.fn();
+ const client = new ApiClient("https://api.example.test", { onUnauthorized });
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async () => jsonResponse({ error: "invalid token" }, 401)),
+ );
+
+ await expect(client.markOnboardingComplete()).rejects.toBeInstanceOf(ApiError);
+
+ expect(onUnauthorized).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index f257ad9827..edbba008c8 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -297,6 +297,9 @@ import {
EMPTY_WEBHOOK_DELIVERY,
AppConfigSchema,
type AppConfigResponse,
+ type RefreshSessionResponse,
+ RefreshSessionResponseSchema,
+ EMPTY_REFRESH_SESSION_RESPONSE,
GroupedIssuesResponseSchema,
IssueTableFacetsResponseSchema,
IssueTableGroupsResponseSchema,
@@ -477,6 +480,18 @@ export interface ApiClientOptions {
onUnauthorized?: () => void;
/** Identifies the client to the server. Sent as X-Client-* headers. */
identity?: ApiClientIdentity;
+ /**
+ * Reads the bearer token from shared storage at request time (token mode
+ * only; omit in cookie mode).
+ *
+ * Without it the token is per-instance, and Desktop runs one ApiClient per
+ * window over one shared localStorage: a session renewed in window A would
+ * leave every other window still sending the token it happened to be
+ * holding, until that one expired and took the whole session down with it
+ * (MUL-7436). Reading through means there is one current credential, not one
+ * per window.
+ */
+ getToken?: () => string | null;
}
export interface ClientRuntimeSnapshot {
@@ -669,6 +684,31 @@ function dingTalkGroupSearch(params: ListDingTalkGroupsParams): string {
return encoded ? `?${encoded}` : "";
}
+// The server's exact wording for a rejected CSRF token
+// (server/internal/middleware/auth.go). Matched rather than inferred from the
+// status, because 403 also covers real authorization failures that must not
+// be retried.
+const CSRF_REJECTED_ERROR = "CSRF validation failed";
+
+// One header, two possible values — see ApiClient.readCsrfValue.
+const CSRF_HEADER = "X-CSRF-Token";
+const CSRF_COOKIE = "multica_csrf";
+const SESSION_CSRF_COOKIE = "multica_csrf_session";
+
+/**
+ * Whether a request body can be sent a second time. Strings and multipart
+ * forms can; a stream cannot, and silently replaying a half-consumed one
+ * would send a truncated request.
+ */
+function isReplayableBody(body: BodyInit | null | undefined): boolean {
+ if (body === undefined || body === null) return true;
+ if (typeof body === "string") return true;
+ if (typeof FormData !== "undefined" && body instanceof FormData) return true;
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams)
+ return true;
+ return false;
+}
+
export class ApiClient {
private baseUrl: string;
private token: string | null = null;
@@ -689,21 +729,62 @@ export class ApiClient {
this.token = token;
}
- private readCsrfToken(): string | null {
+ /**
+ * The bearer token this client is currently using, or null in cookie mode.
+ *
+ * Prefers the shared-storage reader when one is configured, so every window
+ * agrees on the current credential rather than each trusting its own copy.
+ */
+ getToken(): string | null {
+ const shared = this.options.getToken?.();
+ if (shared !== undefined) return shared;
+ return this.token;
+ }
+
+ /**
+ * Which of the two CSRF cookies to echo (MUL-7436).
+ *
+ * The session-bound value is preferred: it survives a sliding renewal, so a
+ * request another tab built before a renewal still validates after it. The
+ * token-bound value is the fallback, and it is what a server running the
+ * PREVIOUS release can verify — after a rollback the session-bound value is
+ * meaningless to it.
+ *
+ * Both travel in the same header. A second header name would have to be in
+ * that server's CORS allowlist, and a rolled-back server allowlists only the
+ * names it shipped with: the preflight would fail and no retry could help.
+ *
+ * `csrfSessionValueRejected` records the exact session-bound value a server
+ * refused, so the fallback is used for as long as that value is current and
+ * no longer — a renewal or a new login replaces the cookie and the preferred
+ * binding is tried again. Keying on the value rather than a boolean is what
+ * stops this from oscillating once per renewal against a current server.
+ */
+ private csrfSessionValueRejected: string | null = null;
+
+ private readCsrfValue(): string | null {
+ const sessionBound = this.readCookie(SESSION_CSRF_COOKIE);
+ if (sessionBound && sessionBound !== this.csrfSessionValueRejected) {
+ return sessionBound;
+ }
+ return this.readCookie(CSRF_COOKIE) ?? sessionBound;
+ }
+
+ private readCookie(name: string): string | null {
if (typeof document === "undefined") return null;
- const match = document.cookie
- .split("; ")
- .find((c) => c.startsWith("multica_csrf="));
- return match ? match.split("=")[1] ?? null : null;
+ const prefix = `${name}=`;
+ const match = document.cookie.split("; ").find((c) => c.startsWith(prefix));
+ return match ? match.slice(prefix.length) || null : null;
}
private authHeaders(): Record<string, string> {
const headers: Record<string, string> = {};
- if (this.token) headers["Authorization"] = `Bearer ${this.token}`;
+ const token = this.getToken();
+ if (token) headers["Authorization"] = `Bearer ${token}`;
const slug = getCurrentSlug();
if (slug) headers["X-Workspace-Slug"] = slug;
- const csrf = this.readCsrfToken();
- if (csrf) headers["X-CSRF-Token"] = csrf;
+ const csrf = this.readCsrfValue();
+ if (csrf) headers[CSRF_HEADER] = csrf;
const id = this.options.identity;
if (id?.platform) headers["X-Client-Platform"] = id.platform;
if (id?.version) headers["X-Client-Version"] = id.version;
@@ -711,7 +792,23 @@ export class ApiClient {
return headers;
}
- private handleUnauthorized() {
+ /**
+ * A 401 ends the session — unless the credential it answered has already
+ * been replaced.
+ *
+ * A request that went out just before a renewal (or from another window
+ * still finishing one) carries the previous token, and its 401 arrives
+ * AFTER the new one is in storage. Treating that as expiry would tear down
+ * a session that is demonstrably alive, clearing drafts and tabs with it
+ * (MUL-7028). Comparing against the credential in use now is what tells the
+ * two apart: a genuinely expired session still has the same token stored,
+ * so the real case is unaffected.
+ */
+ private handleUnauthorized(credentialUsed: string | null) {
+ if (credentialUsed !== null && this.getToken() !== credentialUsed) {
+ this.logger.info("ignoring 401 for a credential that has since been replaced");
+ return;
+ }
this.token = null;
// Workspace id is owned by the URL-driven workspace-storage singleton
// (set by [workspaceSlug]/layout.tsx). On 401, the auth flow navigates
@@ -756,23 +853,55 @@ export class ApiClient {
const start = Date.now();
const method = init?.method ?? "GET";
- const headers: Record<string, string> = {
+ // Rebuilt per attempt rather than captured once: authHeaders() reads the
+ // CSRF cookie at call time, and the retry below exists precisely because
+ // that cookie may have just been replaced.
+ const buildHeaders = (): Record<string, string> => ({
"X-Request-ID": rid,
...this.authHeaders(),
...(init?.extraHeaders ?? {}),
...((init?.headers as Record<string, string>) ?? {}),
- };
+ });
+
+ // Captured before the request so a late 401 can be matched against the
+ // credential it actually used, not whatever is current when it lands.
+ const credentialUsed = this.getToken();
this.logger.info(`→ ${method} ${path}`, { rid });
- const res = await fetch(`${this.baseUrl}${path}`, {
- ...init,
- headers,
- credentials: "include",
- });
+ const send = () =>
+ fetch(`${this.baseUrl}${path}`, {
+ ...init,
+ headers: buildHeaders(),
+ credentials: "include",
+ });
+
+ let res = await send();
+
+ // Two things can make a CSRF value the server refuses, and one retry
+ // covers both (MUL-7436):
+ //
+ // - It went stale. The first renewal of a session that predates the
+ // session-bound binding rotates the cookie the old value was keyed to,
+ // and a request another tab had already built carries the previous
+ // one. Rebuilding the headers re-reads the cookie.
+ // - The server does not understand it. After a rollback, the previous
+ // release can only verify the token-bound binding. Recording the
+ // rejected value switches this client to that binding until the cookie
+ // changes again.
+ //
+ // Neither is an attack, and neither should surface as a failed write.
+ if (res.status === 403 && isReplayableBody(init?.body)) {
+ const { message } = await this.parseErrorBody(res.clone(), "");
+ if (message === CSRF_REJECTED_ERROR) {
+ this.csrfSessionValueRejected = this.readCookie(SESSION_CSRF_COOKIE);
+ this.logger.info(`↻ ${method} ${path} (CSRF token rejected, retrying once)`, { rid });
+ res = await send();
+ }
+ }
if (!res.ok) {
- if (res.status === 401) this.handleUnauthorized();
+ if (res.status === 401) this.handleUnauthorized(credentialUsed);
const { message, body } = await this.parseErrorBody(res, `API error: ${res.status} ${res.statusText}`);
const logLevel = res.status === 404 ? "warn" : "error";
this.logger[logLevel](`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms`, error: message });
@@ -825,6 +954,27 @@ export class ApiClient {
return this.fetch("/api/cli-token", { method: "POST" });
}
+ /**
+ * Ask the server to extend this session if it has entered its renewal
+ * window. The server owns that decision — no client reads `exp` or
+ * compares it against a local clock, which is what keeps clock skew out of
+ * the picture entirely.
+ *
+ * Cookie-mode callers never need this: middleware.Auth re-issues their
+ * cookie inline on any authenticated safe request.
+ */
+ async refreshSession(): Promise<RefreshSessionResponse> {
+ const raw = await this.fetch<unknown>("/api/auth/refresh", {
+ method: "POST",
+ });
+ return parseWithFallback<RefreshSessionResponse>(
+ raw,
+ RefreshSessionResponseSchema,
+ EMPTY_REFRESH_SESSION_RESPONSE,
+ { endpoint: "POST /api/auth/refresh" },
+ );
+ }
+
async getMe(): Promise<User> {
const raw = await this.fetch<unknown>("/api/me");
return parseWithFallback(raw, UserSchema, EMPTY_USER, {
@@ -2768,6 +2918,7 @@ export class ApiClient {
const formData = new FormData();
formData.append("bundle", bundle);
+ const credentialUsed = this.getToken();
const res = await fetch(`${this.baseUrl}/api/workspaces/${workspaceId}/plugins/packages`, {
method: "POST",
headers: this.authHeaders(),
@@ -2775,7 +2926,7 @@ export class ApiClient {
credentials: "include",
});
if (!res.ok) {
- if (res.status === 401) this.handleUnauthorized();
+ if (res.status === 401) this.handleUnauthorized(credentialUsed);
throw new Error(await this.parseErrorMessage(res, `Publishing failed: ${res.status}`));
}
const raw = (await res.json()) as unknown;
@@ -3239,6 +3390,7 @@ export class ApiClient {
const start = Date.now();
this.logger.info("→ POST /api/upload-file", { rid });
+ const credentialUsed = this.getToken();
const res = await fetch(`${this.baseUrl}/api/upload-file`, {
method: "POST",
headers: this.authHeaders(),
@@ -3248,7 +3400,7 @@ export class ApiClient {
});
if (!res.ok) {
- if (res.status === 401) this.handleUnauthorized();
+ if (res.status === 401) this.handleUnauthorized(credentialUsed);
const message = await this.parseErrorMessage(res, `Upload failed: ${res.status}`);
this.logger.error(`← ${res.status} /api/upload-file`, { rid, duration: `${Date.now() - start}ms`, error: message });
throw new Error(message);
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index ea01fbd2db..45ed09157a 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -947,6 +947,42 @@ const FeatureFlagsSchema = z.preprocess(
z.record(z.string(), BooleanWithDefaultSchema(false)).default({}),
);
+/**
+ * POST /api/auth/refresh — sliding session renewal (MUL-7436).
+ *
+ * `token` is present only for clients that carry the session as a string
+ * (Desktop, mobile). A cookie-authenticated browser gets the renewed session
+ * as a Set-Cookie and must never be handed a readable JWT, so the field is
+ * absent there rather than empty.
+ *
+ * `renewed: false` is the normal answer to asking early, not an error —
+ * clients poll on a cadence and most calls land outside the renewal window.
+ * `check_again_in_seconds` is that cadence: the server derives it from the
+ * deployment's configured TTL, so no client hardcodes one.
+ */
+export interface RefreshSessionResponse {
+ token?: string;
+ expires_at: string;
+ renewed: boolean;
+ check_again_in_seconds: number;
+}
+
+export const RefreshSessionResponseSchema = z.object({
+ token: OptionalStringSchema,
+ expires_at: OptionalStringSchema,
+ renewed: BooleanWithDefaultSchema(false),
+ check_again_in_seconds: z.number().int().nonnegative().default(0),
+}).loose();
+
+// Fail closed: an unreadable response means "nothing was renewed", so the
+// client keeps the session it already has and retries later. A fallback that
+// claimed renewal would drop a working session on the floor.
+export const EMPTY_REFRESH_SESSION_RESPONSE: RefreshSessionResponse = {
+ expires_at: "",
+ renewed: false,
+ check_again_in_seconds: 0,
+};
+
export const AppConfigSchema = z.object({
cdn_domain: z.string().default(""),
cdn_signed: BooleanWithDefaultSchema(false),
diff --git a/packages/core/api/ws-client.test.ts b/packages/core/api/ws-client.test.ts
index 91dbac0f46..251e955c58 100644
--- a/packages/core/api/ws-client.test.ts
+++ b/packages/core/api/ws-client.test.ts
@@ -19,7 +19,10 @@ class FakeWebSocket {
FakeWebSocket.lastInstance = this;
}
close() {}
- send() {}
+ sent: string[] = [];
+ send(frame: string) {
+ this.sent.push(frame);
+ }
}
describe("WSClient", () => {
@@ -474,3 +477,57 @@ describe("WSClient", () => {
});
});
});
+
+// A socket can be reconnecting hours after the provider built this client —
+// long enough for a sliding session to have been renewed. Sending the token
+// captured at construction would authenticate the new connection with a
+// credential on its way out (MUL-7436).
+describe("WSClient session renewal", () => {
+ beforeEach(() => {
+ FakeWebSocket.lastUrl = null;
+ FakeWebSocket.lastInstance = null;
+ vi.stubGlobal("WebSocket", FakeWebSocket as unknown as typeof WebSocket);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("reads the current token on every connect", () => {
+ let current = "token-v1";
+ const ws = new WSClient("ws://example.test/ws", {
+ getToken: () => current,
+ });
+ ws.setAuth("token-v1", "acme");
+
+ ws.connect();
+ FakeWebSocket.lastInstance!.onopen!();
+ expect(JSON.parse(FakeWebSocket.lastInstance!.sent[0]!)).toEqual({
+ type: "auth",
+ payload: { token: "token-v1" },
+ });
+
+ // Session renewed between connections.
+ current = "token-v2";
+
+ ws.connect();
+ FakeWebSocket.lastInstance!.onopen!();
+ expect(JSON.parse(FakeWebSocket.lastInstance!.sent[0]!)).toEqual({
+ type: "auth",
+ payload: { token: "token-v2" },
+ });
+ });
+
+ it("sends no auth frame in cookie mode, where the cookie rides the upgrade", () => {
+ const ws = new WSClient("ws://example.test/ws", {
+ cookieAuth: true,
+ getToken: () => "should-not-be-used",
+ });
+ ws.setAuth(null, "acme");
+
+ ws.connect();
+ FakeWebSocket.lastInstance!.onopen!();
+
+ expect(FakeWebSocket.lastInstance!.sent).toEqual([]);
+ });
+});
diff --git a/packages/core/api/ws-client.ts b/packages/core/api/ws-client.ts
index 6d47b957b2..1e764ac526 100644
--- a/packages/core/api/ws-client.ts
+++ b/packages/core/api/ws-client.ts
@@ -51,18 +51,28 @@ export class WSClient {
private anyHandlers = new Set<(msg: WSMessage) => void>();
private logger: Logger;
+ /**
+ * Reads the current token at connect time. A reconnect can happen long
+ * after this client was built — long enough for a sliding session to have
+ * been renewed in between — so the token the auth frame carries has to be
+ * looked up now, not captured once (MUL-7436).
+ */
+ private getToken: (() => string | null) | undefined;
+
constructor(
url: string,
options?: {
logger?: Logger;
cookieAuth?: boolean;
identity?: WSClientIdentity;
+ getToken?: () => string | null;
},
) {
this.baseUrl = url;
this.logger = options?.logger ?? noopLogger;
this.cookieAuth = options?.cookieAuth ?? false;
this.identity = options?.identity;
+ this.getToken = options?.getToken;
}
setAuth(token: string | null, workspaceSlug: string) {
@@ -89,9 +99,10 @@ export class WSClient {
this.ws = new WebSocket(url.toString());
this.ws.onopen = () => {
- if (!this.cookieAuth && this.token) {
+ const token = this.getToken?.() ?? this.token;
+ if (!this.cookieAuth && token) {
this.ws!.send(
- JSON.stringify({ type: "auth", payload: { token: this.token } }),
+ JSON.stringify({ type: "auth", payload: { token } }),
);
return;
}
diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsx
index b7b80f1419..92dd9b5747 100644
--- a/packages/core/platform/core-provider.tsx
+++ b/packages/core/platform/core-provider.tsx
@@ -16,6 +16,11 @@ import { QueryProvider } from "../provider";
import { createLogger } from "../logger";
import { defaultStorage } from "./storage";
import { AuthInitializer } from "./auth-initializer";
+import {
+ createSessionRenewal,
+ watchSessionActivity,
+ type SessionRenewal,
+} from "./session-renewal";
import type { CoreProviderProps, ClientIdentity } from "./types";
import type { StorageAdapter } from "../types/storage";
import { ClientUsageReporter } from "../client-usage";
@@ -29,6 +34,10 @@ import {
let initialized = false;
let authStore: ReturnType<typeof createAuthStore>;
let chatStore: ReturnType<typeof createChatStore>;
+// Token mode only. Cookie-mode browsers have their session re-issued by the
+// server on any authenticated request, so there is nothing for a client-side
+// renewer to do there (MUL-7436).
+let sessionRenewal: SessionRenewal | null = null;
// Named rather than positional: onLogin / onLogout / onSessionExpired are
// three adjacent `() => void`, and nothing but the argument order would tell
// them apart at the call site.
@@ -81,6 +90,13 @@ function initCore({
onUnauthorized: () => {
authStore.getState().sessionExpired();
},
+ // Token mode only. Desktop runs one ApiClient per window over one shared
+ // localStorage, so the credential has to be read through to storage rather
+ // than cached per instance — otherwise a session renewed in one window
+ // leaves the others sending a token that is on its way out (MUL-7436).
+ getToken: cookieAuth
+ ? undefined
+ : () => storage.getItem("multica_token"),
identity,
});
setApiInstance(api);
@@ -109,6 +125,15 @@ function initCore({
chatStore = createChatStore({ storage });
registerChatStore(chatStore);
+ if (!cookieAuth) {
+ sessionRenewal = createSessionRenewal({
+ api,
+ storage,
+ isAuthenticated: () => authStore.getState().status === "authenticated",
+ logger: createLogger("auth"),
+ });
+ }
+
initialized = true;
}
@@ -150,6 +175,23 @@ export function CoreProvider({
installFreezeWatchdog();
}, []);
+ // Sliding session renewal, driven by use rather than by a clock. The store
+ // subscription covers the launch check: at mount the boot identity probe is
+ // still running, so the first attempt that finds a live session is the one
+ // that fires — and `maybeRenew` declines cheaply for every store update
+ // after that until the server-supplied interval has elapsed.
+ useEffect(() => {
+ const renewal = sessionRenewal;
+ if (!renewal) return;
+ const unsubscribe = authStore.subscribe(() => renewal.maybeRenew());
+ const stopWatching = watchSessionActivity(renewal);
+ renewal.maybeRenew();
+ return () => {
+ unsubscribe();
+ stopWatching();
+ };
+ }, []);
+
// I18nProvider wraps everything else: server and client must use the same
// (locale, resources) to avoid hydration mismatch. Language switching goes
// through window.location.reload(), never client-side changeLanguage.
diff --git a/packages/core/platform/session-renewal.test.ts b/packages/core/platform/session-renewal.test.ts
new file mode 100644
index 0000000000..a02f9472a2
--- /dev/null
+++ b/packages/core/platform/session-renewal.test.ts
@@ -0,0 +1,453 @@
+/**
+ * @vitest-environment jsdom
+ */
+// jsdom rather than node: watchSessionActivity binds to window/document, and
+// under node it would take the `typeof window === "undefined"` branch and
+// "pass" without ever touching the listeners this file is about.
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError, type ApiClient } from "../api/client";
+import type { StorageAdapter } from "../types/storage";
+import type { RefreshSessionResponse } from "../api/schemas";
+import { createSessionRenewal, watchSessionActivity } from "./session-renewal";
+
+const TOKEN_KEY = "multica_token";
+
+function makeStorage(
+ initial: Record<string, string> = {},
+): StorageAdapter & { snapshot: () => Record<string, string> } {
+ const values = { ...initial };
+ return {
+ getItem: (key) => values[key] ?? null,
+ setItem: (key, value) => {
+ values[key] = value;
+ },
+ removeItem: (key) => {
+ delete values[key];
+ },
+ snapshot: () => ({ ...values }),
+ };
+}
+
+function renewedResponse(
+ token: string,
+ checkAgainInSeconds = 3600,
+): RefreshSessionResponse {
+ return {
+ token,
+ expires_at: "2026-10-16T00:00:00Z",
+ renewed: true,
+ check_again_in_seconds: checkAgainInSeconds,
+ };
+}
+
+function notYetResponse(checkAgainInSeconds = 3600): RefreshSessionResponse {
+ return {
+ expires_at: "2026-10-16T00:00:00Z",
+ renewed: false,
+ check_again_in_seconds: checkAgainInSeconds,
+ };
+}
+
+interface Harness {
+ api: { refreshSession: ReturnType<typeof vi.fn>; setToken: ReturnType<typeof vi.fn> };
+ storage: ReturnType<typeof makeStorage>;
+ authenticated: { value: boolean };
+}
+
+function makeHarness(initialToken: string | null = "token-v1"): Harness {
+ return {
+ api: { refreshSession: vi.fn(), setToken: vi.fn() },
+ storage: makeStorage(initialToken ? { [TOKEN_KEY]: initialToken } : {}),
+ authenticated: { value: true },
+ };
+}
+
+function renewalFor(h: Harness) {
+ return createSessionRenewal({
+ api: h.api as unknown as ApiClient,
+ storage: h.storage,
+ isAuthenticated: () => h.authenticated.value,
+ });
+}
+
+describe("createSessionRenewal", () => {
+ beforeEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("persists a renewed token to storage and to the API client", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockResolvedValue(renewedResponse("token-v2"));
+
+ await renewalFor(h).renewNow();
+
+ expect(h.storage.snapshot()[TOKEN_KEY]).toBe("token-v2");
+ expect(h.api.setToken).toHaveBeenCalledWith("token-v2");
+ });
+
+ // The common answer. Asking before the window opens must change nothing —
+ // in particular it must not clear or rewrite the token in play.
+ it("leaves the session alone when the server says it is not time yet", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockResolvedValue(notYetResponse());
+
+ await renewalFor(h).renewNow();
+
+ expect(h.storage.snapshot()[TOKEN_KEY]).toBe("token-v1");
+ expect(h.api.setToken).not.toHaveBeenCalled();
+ });
+
+ // A foreground event and a click can land in the same tick. Two renewals
+ // would produce two valid tokens racing to be the one stored.
+ it("coalesces concurrent renewals into one request", async () => {
+ const h = makeHarness();
+ let resolve!: (value: RefreshSessionResponse) => void;
+ h.api.refreshSession.mockReturnValue(
+ new Promise<RefreshSessionResponse>((r) => {
+ resolve = r;
+ }),
+ );
+
+ const renewal = renewalFor(h);
+ const first = renewal.renewNow();
+ const second = renewal.renewNow();
+ renewal.maybeRenew();
+
+ resolve(renewedResponse("token-v2"));
+ await Promise.all([first, second]);
+
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+ expect(h.storage.snapshot()[TOKEN_KEY]).toBe("token-v2");
+ });
+
+ // The whole point of the design: an app nobody is touching does not keep
+ // its own session alive. maybeRenew is wired to activity, so it has to
+ // decline until the server-supplied interval has actually elapsed.
+ it("declines a repeat check until the server-supplied interval elapses", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockResolvedValue(notYetResponse(3600));
+
+ const renewal = renewalFor(h);
+ await renewal.renewNow();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+
+ // Simulate a busy user: many activity events, well inside the interval.
+ for (let i = 0; i < 50; i++) renewal.maybeRenew();
+ await Promise.resolve();
+
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+ });
+
+ // A failure must not consume the normal cadence. This is the ordinary-case
+ // version of the bug, not a short-TTL curiosity: a client told "check again
+ // in 3 days", returning with one day of session left and hitting a single
+ // 503, would otherwise not be allowed to retry until two days after the
+ // session it was trying to save had expired.
+ it("retries within seconds after a failure, not after the server cadence", async () => {
+ const h = makeHarness();
+ // Establish a long cadence the way a real client would: one good check.
+ h.api.refreshSession.mockResolvedValue(notYetResponse(3 * 24 * 60 * 60));
+ const renewal = renewalFor(h);
+ await renewal.renewNow();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+
+ // Now the network blips.
+ h.api.refreshSession.mockRejectedValue(new TypeError("Failed to fetch"));
+ const now = Date.now();
+ vi.spyOn(Date, "now").mockReturnValue(now + 3 * 24 * 60 * 60 * 1000);
+ await renewal.renewNow();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(2);
+
+ // It recovers a second later and the user is still working. The next
+ // attempt must go out now, not in another three days.
+ h.api.refreshSession.mockResolvedValue(notYetResponse(3 * 24 * 60 * 60));
+ vi.mocked(Date.now).mockReturnValue(now + 3 * 24 * 60 * 60 * 1000 + 1_500);
+ renewal.maybeRenew();
+ await vi.waitFor(() =>
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(3),
+ );
+ vi.mocked(Date.now).mockRestore();
+ });
+
+ // A 200 whose body failed schema validation comes back through
+ // parseWithFallback as zeroes rather than as a throw. Without treating that
+ // as a failure the deadline never moves, and every click fires another
+ // request at a server that is already answering badly.
+ it("backs off on a response that carries no cadence", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockResolvedValue({
+ expires_at: "",
+ renewed: false,
+ check_again_in_seconds: 0,
+ } satisfies RefreshSessionResponse);
+
+ const renewal = renewalFor(h);
+ const start = Date.now();
+ vi.spyOn(Date, "now").mockReturnValue(start);
+ await renewal.renewNow();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+
+ // Busy user, well inside the backoff: no further requests.
+ for (let i = 0; i < 20; i++) renewal.maybeRenew();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+
+ // And it does come back, on the backoff rather than never.
+ vi.mocked(Date.now).mockReturnValue(start + 1_100);
+ renewal.maybeRenew();
+ await vi.waitFor(() =>
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(2),
+ );
+ vi.mocked(Date.now).mockRestore();
+ });
+
+ // Recovering fast must not mean hammering a server that is genuinely down.
+ it("backs off across consecutive failures and resets on success", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockRejectedValue(new TypeError("Failed to fetch"));
+ const renewal = renewalFor(h);
+
+ const start = Date.now();
+ const at = (ms: number) => vi.mocked(Date.now).mockReturnValue(start + ms);
+ // Let the promise chain — including the finally that clears `inFlight` —
+ // settle, so the next step is not blocked by the previous one.
+ const settle = async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ };
+ vi.spyOn(Date, "now").mockReturnValue(start);
+
+ at(0);
+ await renewal.renewNow(); // failure 1 → retry allowed 1s later
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+
+ at(999);
+ renewal.maybeRenew();
+ await settle();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1);
+
+ at(1_000);
+ await renewal.renewNow(); // failure 2 → the delay has doubled to 2s
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(2);
+
+ at(2_999);
+ renewal.maybeRenew();
+ await settle();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(2);
+
+ at(3_000);
+ renewal.maybeRenew();
+ await settle();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(3);
+
+ // A success clears the streak and installs the server's cadence...
+ h.api.refreshSession.mockResolvedValue(notYetResponse(3600));
+ at(10_000);
+ await renewal.renewNow();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(4);
+
+ // ...so the next failure starts from one second again, not from where the
+ // earlier streak left off.
+ h.api.refreshSession.mockRejectedValue(new TypeError("Failed to fetch"));
+ at(4_000_000);
+ await renewal.renewNow();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(5);
+
+ at(4_000_999);
+ renewal.maybeRenew();
+ await settle();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(5);
+
+ at(4_001_000);
+ renewal.maybeRenew();
+ await settle();
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(6);
+
+ vi.mocked(Date.now).mockRestore();
+ });
+
+ // The server computes a cadence that fits inside the renewal window, which
+ // for a short AUTH_TOKEN_TTL can be seconds. A client-side floor above that
+ // value would silently override the server and let an actively used session
+ // expire, so the floor has to stay below anything the server can send.
+ it("honours a short server-supplied cadence instead of flooring it", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockResolvedValue(notYetResponse(10));
+
+ const renewal = renewalFor(h);
+ await renewal.renewNow();
+
+ const now = Date.now();
+ vi.spyOn(Date, "now").mockReturnValue(now + 11_000);
+ renewal.maybeRenew();
+ await vi.waitFor(() =>
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(2),
+ );
+ vi.mocked(Date.now).mockRestore();
+ });
+
+ it("checks again once the interval has passed", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockResolvedValue(notYetResponse(60));
+
+ const renewal = renewalFor(h);
+ await renewal.renewNow();
+
+ const now = Date.now();
+ vi.spyOn(Date, "now").mockReturnValue(now + 61_000);
+ renewal.maybeRenew();
+ await vi.waitFor(() =>
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(2),
+ );
+ vi.mocked(Date.now).mockRestore();
+ });
+
+ // MUL-7028 made session teardown clear every client-side store — drafts,
+ // tab layout, the Query cache. A renewal that treats a network blip as the
+ // end of the session would fire all of that on a flaky connection.
+ it.each([
+ ["offline", new TypeError("Failed to fetch")],
+ ["server error", new ApiError("boom", 500, "Internal Server Error")],
+ ["gateway error", new ApiError("bad gateway", 502, "Bad Gateway")],
+ ])("keeps the current session when renewal fails (%s)", async (_name, err) => {
+ const h = makeHarness();
+ h.api.refreshSession.mockRejectedValue(err);
+
+ await renewalFor(h).renewNow();
+
+ expect(h.storage.snapshot()[TOKEN_KEY]).toBe("token-v1");
+ expect(h.api.setToken).not.toHaveBeenCalled();
+ });
+
+ // A 401 IS handled — by ApiClient, before this code sees the rejection.
+ // What matters here is that the renewal path does not additionally clear
+ // anything, which would race the teardown already under way.
+ it("does not tear anything down itself on a 401", async () => {
+ const h = makeHarness();
+ h.api.refreshSession.mockRejectedValue(
+ new ApiError("invalid token", 401, "Unauthorized"),
+ );
+
+ await renewalFor(h).renewNow();
+
+ expect(h.api.setToken).not.toHaveBeenCalled();
+ // Storage is the auth store's to clear, and it already did.
+ expect(h.storage.snapshot()[TOKEN_KEY]).toBe("token-v1");
+ });
+
+ // Log out while a renewal is in flight and the response lands afterwards.
+ // Writing the token back would resurrect a session the app has torn down.
+ it("discards a response that arrives after logout", async () => {
+ const h = makeHarness();
+ let resolve!: (value: RefreshSessionResponse) => void;
+ h.api.refreshSession.mockReturnValue(
+ new Promise<RefreshSessionResponse>((r) => {
+ resolve = r;
+ }),
+ );
+
+ const pending = renewalFor(h).renewNow();
+
+ // Logout, exactly as the auth store does it.
+ h.storage.removeItem(TOKEN_KEY);
+ h.authenticated.value = false;
+
+ resolve(renewedResponse("token-v2"));
+ await pending;
+
+ expect(h.storage.snapshot()[TOKEN_KEY]).toBeUndefined();
+ expect(h.api.setToken).not.toHaveBeenCalled();
+ });
+
+ // Same shape, different cause: a second account signed in during the round
+ // trip. The late token belongs to the previous user.
+ it("discards a response that arrives after an account switch", async () => {
+ const h = makeHarness();
+ let resolve!: (value: RefreshSessionResponse) => void;
+ h.api.refreshSession.mockReturnValue(
+ new Promise<RefreshSessionResponse>((r) => {
+ resolve = r;
+ }),
+ );
+
+ const pending = renewalFor(h).renewNow();
+ h.storage.setItem(TOKEN_KEY, "someone-elses-token");
+
+ resolve(renewedResponse("token-v2"));
+ await pending;
+
+ expect(h.storage.snapshot()[TOKEN_KEY]).toBe("someone-elses-token");
+ expect(h.api.setToken).not.toHaveBeenCalled();
+ });
+
+ it("does nothing while signed out or still booting", async () => {
+ const h = makeHarness();
+ h.authenticated.value = false;
+
+ await renewalFor(h).renewNow();
+
+ expect(h.api.refreshSession).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when there is no stored session", async () => {
+ const h = makeHarness(null);
+
+ await renewalFor(h).renewNow();
+
+ expect(h.api.refreshSession).not.toHaveBeenCalled();
+ });
+
+ // A skipped attempt must not consume the interval, or a check that landed
+ // one tick before the boot probe finished would postpone the real one.
+ it("does not consume the interval when it declines to run", async () => {
+ const h = makeHarness();
+ h.authenticated.value = false;
+ h.api.refreshSession.mockResolvedValue(notYetResponse());
+
+ const renewal = renewalFor(h);
+ renewal.maybeRenew();
+ expect(h.api.refreshSession).not.toHaveBeenCalled();
+
+ h.authenticated.value = true;
+ renewal.maybeRenew();
+ await vi.waitFor(() =>
+ expect(h.api.refreshSession).toHaveBeenCalledTimes(1),
+ );
+ });
+});
+
+describe("watchSessionActivity", () => {
+ it("checks on foreground and on interaction, never on a timer", async () => {
+ vi.useFakeTimers();
+ const renewal = {
+ maybeRenew: vi.fn(),
+ renewNow: vi.fn().mockResolvedValue(undefined),
+ reset: vi.fn(),
+ };
+
+ const stop = watchSessionActivity(renewal);
+
+ // No timer anywhere: an untouched app must not renew itself, however
+ // long it is left open.
+ vi.advanceTimersByTime(7 * 24 * 60 * 60 * 1000);
+ expect(renewal.maybeRenew).not.toHaveBeenCalled();
+
+ window.dispatchEvent(new Event("focus"));
+ expect(renewal.maybeRenew).toHaveBeenCalledTimes(1);
+
+ window.dispatchEvent(new Event("pointerdown"));
+ expect(renewal.maybeRenew).toHaveBeenCalledTimes(2);
+
+ window.dispatchEvent(new Event("keydown"));
+ expect(renewal.maybeRenew).toHaveBeenCalledTimes(3);
+
+ document.dispatchEvent(new Event("visibilitychange"));
+ expect(renewal.maybeRenew).toHaveBeenCalledTimes(4);
+
+ stop();
+ window.dispatchEvent(new Event("focus"));
+ window.dispatchEvent(new Event("pointerdown"));
+ expect(renewal.maybeRenew).toHaveBeenCalledTimes(4);
+
+ vi.useRealTimers();
+ });
+});
diff --git a/packages/core/platform/session-renewal.ts b/packages/core/platform/session-renewal.ts
new file mode 100644
index 0000000000..a4f0c55424
--- /dev/null
+++ b/packages/core/platform/session-renewal.ts
@@ -0,0 +1,232 @@
+import type { ApiClient } from "../api/client";
+import type { StorageAdapter } from "../types/storage";
+import type { Logger } from "../logger";
+
+/**
+ * Sliding session renewal for clients that hold the session as a string
+ * (Desktop; web only while a legacy localStorage token is still in play).
+ * Cookie-mode browsers are renewed by the server inline on any authenticated
+ * request and never come through here — see middleware.Auth (MUL-7436).
+ *
+ * Two properties shape everything below.
+ *
+ * Renewal follows USE, not time. There is no interval timer: a check runs at
+ * launch, when the app comes back to the foreground, and when the user
+ * actually interacts with it. A timer would keep an abandoned but still-open
+ * window's session alive indefinitely, which is the one thing a session
+ * lifetime is for.
+ *
+ * Renewal is not a session event. It replaces a credential in place; it must
+ * never look like a login or a logout to anything downstream. Offline, 5xx and
+ * a malformed response all leave everything exactly as it was — but "leave it
+ * alone" is not the same as "wait": a failure happens INSIDE the renewal
+ * window, where the remaining lifetime is by definition under half a TTL and
+ * shrinking, so the retry has to come back quickly rather than consume the
+ * normal cadence. Only the server actually rejecting the credential ends a
+ * session, and that path already exists (ApiClient's 401 handling).
+ */
+
+const TOKEN_STORAGE_KEY = "multica_token";
+
+/**
+ * How long to wait after a FAILED check before another is allowed, by
+ * consecutive failure. This is deliberately not the normal cadence.
+ *
+ * The normal cadence is derived from the token's lifetime and can be days. A
+ * failure that consumed it would be fatal in the ordinary case, not just at
+ * short TTLs: a client that learned "check again in 3 days" on day 12, comes
+ * back on day 29 with one day left, and hits a single 503 would not be allowed
+ * to try again until day 32 — two days after the session it was trying to save
+ * had already expired.
+ *
+ * So a failure buys a short, backing-off delay instead, reset by the next
+ * success. The shape mirrors the identity-probe recovery in auth-initializer,
+ * for the same reason: recover in seconds when the blip was brief, and stop
+ * hammering a server that is genuinely down.
+ */
+const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000] as const;
+
+/**
+ * Anti-busy-loop floor, not a policy. The server owns the cadence and
+ * guarantees its value fits inside the renewal window; this only stops a
+ * nonsense `check_again_in_seconds` from turning activity into a request per
+ * event. It matches the server's own floor, so it never overrides a value the
+ * server actually chose — a floor above that would silently let an active
+ * session expire. See minSessionRenewCheckInterval in
+ * server/internal/auth/session.go.
+ */
+const MIN_CHECK_INTERVAL_MS = 5 * 1000;
+
+export interface SessionRenewalOptions {
+ api: ApiClient;
+ storage: StorageAdapter;
+ /**
+ * Whether a session is live right now. Renewal is skipped while logged out
+ * or still booting — there is nothing to extend, and a request fired during
+ * the identity probe would race it.
+ */
+ isAuthenticated: () => boolean;
+ logger?: Logger;
+}
+
+export interface SessionRenewal {
+ /**
+ * Run a check unless one ran recently. Safe to call on every user
+ * interaction — the interval check makes all but the first a no-op.
+ */
+ maybeRenew: () => void;
+ /** Run a check now, ignoring the interval. Used at app start. */
+ renewNow: () => Promise<void>;
+ /** Test seam: forget the last-attempt timestamp and cadence. */
+ reset: () => void;
+}
+
+export function createSessionRenewal({
+ api,
+ storage,
+ isAuthenticated,
+ logger,
+}: SessionRenewalOptions): SessionRenewal {
+ // The earliest a check may run. Zero at start, so the launch check fires on
+ // the first trigger; a success pushes it out by the server's cadence and a
+ // failure by a short backoff. Tracking the deadline rather than the last
+ // attempt is what keeps those two from sharing one number.
+ let nextCheckAt = 0;
+ let consecutiveFailures = 0;
+
+ /** Push the next allowed check out by the current backoff step. */
+ function scheduleRetryAfterFailure(): number {
+ const delay =
+ RETRY_DELAYS_MS[Math.min(consecutiveFailures, RETRY_DELAYS_MS.length - 1)]!;
+ consecutiveFailures += 1;
+ nextCheckAt = Date.now() + delay;
+ return delay;
+ }
+ // Collapses concurrent triggers — a foreground event and a click in the
+ // same moment must not produce two renewals, which would leave two valid
+ // tokens racing to be the one written to storage.
+ let inFlight: Promise<void> | null = null;
+
+ async function renewNow(): Promise<void> {
+ if (inFlight) return inFlight;
+ if (!isAuthenticated()) return;
+
+ // The session this attempt is FOR. Everything applied at the end is
+ // checked against it: an attempt that outlives its own session must not
+ // write anything back.
+ const startedFrom = storage.getItem(TOKEN_STORAGE_KEY);
+ if (!startedFrom) return;
+
+ inFlight = api
+ .refreshSession()
+ .then((result) => {
+ // A response that carries no cadence is not a usable answer. The
+ // schema fallback produces exactly this shape — `parseWithFallback`
+ // returns zeroes for a body that failed validation instead of
+ // throwing — and a real server always sends a positive interval. Left
+ // untreated it would reset the failure count without moving the
+ // deadline, so every subsequent interaction fires another request.
+ // Back off exactly as for a failure.
+ if (result.check_again_in_seconds <= 0) {
+ scheduleRetryAfterFailure();
+ } else {
+ consecutiveFailures = 0;
+ nextCheckAt =
+ Date.now() +
+ Math.max(MIN_CHECK_INTERVAL_MS, result.check_again_in_seconds * 1000);
+ }
+ // A token that did arrive is still worth applying, whatever the
+ // cadence field said.
+ if (!result.renewed || !result.token) return;
+
+ // Late-result guard. Between the request and this line the user may
+ // have logged out, switched accounts, or had the session expire — all
+ // of which replace or clear the stored token. Writing our token back
+ // over any of those would resurrect a session the app has already
+ // torn down.
+ if (!isAuthenticated()) return;
+ if (storage.getItem(TOKEN_STORAGE_KEY) !== startedFrom) return;
+
+ // Order matters: persist before the in-memory client, so a crash
+ // between the two lines leaves the newer credential on disk rather
+ // than an older one that requests have already stopped using.
+ storage.setItem(TOKEN_STORAGE_KEY, result.token);
+ api.setToken(result.token);
+ logger?.info("session renewed", { expiresAt: result.expires_at });
+ })
+ .catch((err: unknown) => {
+ // Offline, 5xx, a server-side signing failure, a response that failed
+ // its schema — none of these say anything about whether the session
+ // is still good, and it demonstrably is: it authenticated this very
+ // request path moments ago. Keep it, and come back SOON — this failure
+ // happened inside the renewal window, so the session it was trying to
+ // extend is running out while we wait.
+ //
+ // A genuine 401 is not handled here either, but for the opposite
+ // reason: ApiClient already routed it to the session-expiry path
+ // before this catch ran.
+ const delay = scheduleRetryAfterFailure();
+ logger?.debug("session renewal did not complete; keeping the current session", {
+ error: err instanceof Error ? err.message : String(err),
+ retryInMs: delay,
+ });
+ })
+ .finally(() => {
+ inFlight = null;
+ });
+
+ return inFlight;
+ }
+
+ function maybeRenew(): void {
+ if (Date.now() < nextCheckAt) return;
+ void renewNow();
+ }
+
+ return {
+ maybeRenew,
+ renewNow,
+ reset: () => {
+ nextCheckAt = 0;
+ consecutiveFailures = 0;
+ inFlight = null;
+ },
+ };
+}
+
+/**
+ * Wire a renewal controller to the signals that mean "someone is using this
+ * app": returning to the foreground, and interacting with it. Returns a
+ * teardown.
+ *
+ * Deliberately no interval timer. `maybeRenew` is cheap when it declines, and
+ * a token-mode app nobody is touching should not be renewing anything.
+ *
+ * Note this is only true of token mode. A cookie-mode browser is renewed by
+ * the server on any authenticated request, so an open tab that polls in the
+ * background keeps its session alive without anyone touching it.
+ */
+export function watchSessionActivity(renewal: SessionRenewal): () => void {
+ if (typeof window === "undefined" || typeof document === "undefined") {
+ return () => {};
+ }
+
+ const onVisible = () => {
+ if (document.visibilityState === "visible") renewal.maybeRenew();
+ };
+ const onActivity = () => renewal.maybeRenew();
+
+ document.addEventListener("visibilitychange", onVisible);
+ window.addEventListener("focus", onActivity);
+ // Passive so the listeners never delay scrolling or input handling; they do
+ // nothing but read a timestamp on all but one call in every check interval.
+ window.addEventListener("pointerdown", onActivity, { passive: true });
+ window.addEventListener("keydown", onActivity, { passive: true });
+
+ return () => {
+ document.removeEventListener("visibilitychange", onVisible);
+ window.removeEventListener("focus", onActivity);
+ window.removeEventListener("pointerdown", onActivity);
+ window.removeEventListener("keydown", onActivity);
+ };
+}
diff --git a/packages/core/realtime/provider.tsx b/packages/core/realtime/provider.tsx
index 2cc9265125..39b65b09d6 100644
--- a/packages/core/realtime/provider.tsx
+++ b/packages/core/realtime/provider.tsx
@@ -87,6 +87,10 @@ export function WSProvider({
const ws = new WSClient(wsUrl, {
logger: createLogger("ws"),
cookieAuth,
+ // Re-read on every (re)connect instead of pinning the token captured
+ // below: a session renewed since this effect ran would otherwise keep
+ // reconnecting with a credential that is on its way to expiring.
+ getToken: cookieAuth ? undefined : () => storage.getItem("multica_token"),
identity:
identityPlatform || identityVersion || identityOS
? {
diff --git a/server/cmd/server/cors_headers_test.go b/server/cmd/server/cors_headers_test.go
index bfb75b3123..22e4676da4 100644
--- a/server/cmd/server/cors_headers_test.go
+++ b/server/cmd/server/cors_headers_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -63,3 +64,49 @@ func headerListContains(header, want string) bool {
}
return false
}
+
+// Every header the browser clients send has to be preflight-allowed, and the
+// CSRF header is the one where getting this wrong is invisible in same-origin
+// development and fatal in a split app/API deployment: the preflight fails, so
+// the request never reaches a handler and the failure looks nothing like a
+// rejected CSRF token.
+//
+// It is also the header whose name must not change casually. A rolled-back
+// server allowlists only the names it shipped with, so a client that starts
+// sending a NEW header can be blocked by a version of the server that predates
+// it — which is why MUL-7436 carries two CSRF cookie values through this one
+// header name rather than adding a second.
+func TestRouterCORSAllowsTheCSRFHeader(t *testing.T) {
+ const origin = "https://cors-client.example"
+ t.Setenv("CORS_ALLOWED_ORIGINS", origin)
+ router := NewRouter(nil, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil)
+
+ req := httptest.NewRequest(http.MethodOptions, "/api/config", nil)
+ req.Header.Set("Origin", origin)
+ req.Header.Set("Access-Control-Request-Method", http.MethodPost)
+ req.Header.Set("Access-Control-Request-Headers", auth.CSRFHeaderName)
+ rec := httptest.NewRecorder()
+
+ router.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("preflight status = %d, want %d", rec.Code, http.StatusOK)
+ }
+ allowed := rec.Header().Get("Access-Control-Allow-Headers")
+ if !headerListContains(allowed, auth.CSRFHeaderName) {
+ t.Errorf("Access-Control-Allow-Headers = %q, missing %q", allowed, auth.CSRFHeaderName)
+ }
+}
+
+// Pins the invariant rather than one name: whatever header the auth package
+// tells clients to send, the router must allow. If someone introduces a second
+// CSRF header without touching corsAllowedHeaders, this fails here instead of
+// in a production split-origin deployment.
+func TestCSRFHeaderIsInTheCORSAllowlist(t *testing.T) {
+ for _, h := range corsAllowedHeaders {
+ if strings.EqualFold(h, auth.CSRFHeaderName) {
+ return
+ }
+ }
+ t.Fatalf("auth.CSRFHeaderName (%q) is not in corsAllowedHeaders; browsers would fail the preflight", auth.CSRFHeaderName)
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 309776bca5..cdb844560d 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1521,7 +1521,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// signed-in user's session and the installation header. Keeping it outside
// /v1 prevents the Public API from accepting session cookies.
r.Group(func(r chi.Router) {
- r.Use(middleware.Auth(queries, patCache, cloudPATVerifier))
+ r.Use(middleware.Auth(queries, patCache, cloudPATVerifier, cfSigner))
r.Route(pluginBridgePrefix, func(r chi.Router) {
registerPluginActionRoutes(r, h)
// ui / manual only. `event` is dispatched by the host off the event
@@ -1531,7 +1531,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
})
r.Group(func(r chi.Router) {
- r.Use(middleware.Auth(queries, patCache, cloudPATVerifier))
+ r.Use(middleware.Auth(queries, patCache, cloudPATVerifier, cfSigner))
r.Use(middleware.RefreshCloudFrontCookies(cfSigner))
// Plugin Action API. Called by the HOST PAGE on the signed-in user's
@@ -1557,6 +1557,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/api/me/onboarding/runtime-bootstrap", h.BootstrapOnboardingRuntime)
r.Post("/api/me/onboarding/no-runtime-bootstrap", h.BootstrapOnboardingNoRuntime)
r.Post("/api/cli-token", h.IssueCliToken)
+ // Sliding session renewal for clients that hold the session as a
+ // string (Desktop, mobile). Browsers get theirs re-issued inline by
+ // middleware.Auth and never call this (MUL-7436).
+ r.Post("/api/auth/refresh", h.RefreshSession)
r.Post("/api/upload-file", h.UploadFile)
r.Post("/api/feedback", h.CreateFeedback)
r.With(handler.RequireHumanActor).Post("/api/client-usage", h.UpsertClientUsage)
diff --git a/server/internal/auth/cookie.go b/server/internal/auth/cookie.go
index 8634e0cd84..9511c1bdec 100644
--- a/server/internal/auth/cookie.go
+++ b/server/internal/auth/cookie.go
@@ -18,9 +18,54 @@ import (
)
const (
- AuthCookieName = "multica_auth"
- CSRFCookieName = "multica_csrf"
+ AuthCookieName = "multica_auth"
+ // CSRFCookieName carries the token-bound CSRF value, and keeps carrying
+ // it: every server that has ever run this code understands this cookie,
+ // which is what makes rolling BACK past MUL-7436 safe. See
+ // SessionCSRFCookieName.
+ CSRFCookieName = "multica_csrf"
+ // SessionCSRFCookieName carries the session-bound CSRF value added by
+ // MUL-7436. It is the one the server prefers, because it survives a
+ // sliding renewal; the token-bound cookie above cannot, since renewal
+ // replaces the very token it is keyed to.
+ SessionCSRFCookieName = "multica_csrf_session"
+
+ // CSRFHeaderName is where clients echo ONE of the two cookies back, and
+ // there is deliberately only one header name.
+ //
+ // A second header would have to be added to corsAllowedHeaders, and that
+ // list is version-specific: a browser holding a cookie issued by this
+ // release, talking to a rolled-back server, would send a header that
+ // server does not allowlist. The preflight fails, the request never
+ // reaches a handler, and no amount of client retrying helps — which is
+ // exactly the half-logged-in state the second cookie exists to prevent.
+ // Keeping one header name means the rollback path has no preflight
+ // dependency at all; the server simply tries both bindings against
+ // whatever value arrives.
+ CSRFHeaderName = "X-CSRF-Token"
+
defaultAuthTokenTTL = 30 * 24 * time.Hour // 30 days
+
+ // MinAuthTokenTTL is the shortest session lifetime this system can serve
+ // correctly, and what sets it is the CLIENT FLOOR, not the wire format.
+ //
+ // The renewal cadence is TTL/10, and every client floors what the server
+ // sends at five seconds so a nonsense value cannot turn activity into a
+ // request per event. Once TTL/10 drops below that floor the floor wins,
+ // and the client is checking on a schedule the server did not choose —
+ // which is exactly how a cadence ends up longer than the window it has to
+ // land in. TTL/10 >= 5s means TTL >= 50 seconds; one minute is that bound
+ // rounded to something an operator would actually write, and it leaves
+ // the cadence (six seconds) comfortably above the floor.
+ //
+ // Whole-second serialisation (RefreshSessionResponse.CheckAgainInSeconds)
+ // is a second, looser constraint: it only bites below about four seconds
+ // of cadence, i.e. a TTL under 40 seconds, so the client floor is the one
+ // that actually decides this number.
+ //
+ // Anything shorter is clamped up rather than honoured, because honouring
+ // it would mean silently logging active users out.
+ MinAuthTokenTTL = time.Minute
)
var (
@@ -75,6 +120,16 @@ func AuthTokenTTL() time.Duration {
authTokenTTLOnce.Do(func() {
raw := os.Getenv("AUTH_TOKEN_TTL")
if ttl, ok := parseAuthTokenTTL(raw); ok {
+ if ttl < MinAuthTokenTTL {
+ // Clamping up, not falling back to the default: someone who
+ // asked for 30 seconds is far better served by 1 minute than
+ // by the 30-day default they did not ask for, and the warning
+ // says exactly what happened.
+ slog.Warn("AUTH_TOKEN_TTL is below the shortest supported session lifetime; using the minimum",
+ "value", raw, "minimum_seconds", int(MinAuthTokenTTL.Seconds()),
+ "reason", "a shorter TTL derives a renewal cadence below the floor every client applies, so clients would check on a schedule this server did not choose")
+ ttl = MinAuthTokenTTL
+ }
authTokenTTLCached = ttl
slog.Info("auth token TTL configured", "seconds", int(ttl.Seconds()))
return
@@ -127,31 +182,91 @@ func isSecureCookie() bool {
return strings.EqualFold(u.Scheme, "https")
}
-// generateCSRFToken creates a CSRF token bound to the auth token via HMAC.
-// Format: hex(nonce) + "." + hex(HMAC-SHA256(nonce, authToken)).
-// This ensures an attacker who can write cookies on a subdomain cannot forge
-// a valid CSRF token without knowing the auth token.
-func generateCSRFToken(authToken string) (string, error) {
+// Two CSRF bindings exist side by side, and the pair is deliberate.
+//
+// - Session-bound: HMAC-SHA256 keyed by the server's JWT secret over
+// (sessionID, nonce). `sid` survives renewal, so re-signing the auth
+// cookie leaves every CSRF token already issued for that session valid —
+// which is what keeps sliding renewal from racing other tabs (MUL-7436).
+// This is the HMAC-based Token Pattern OWASP recommends.
+// - Token-bound: HMAC-SHA256 keyed by the auth token itself over the nonce.
+// This is the original scheme, and it is still ISSUED, not merely still
+// accepted. A server running the previous release can verify only this
+// one, so dropping it would make a rollback strand every signed-in user
+// able to read but unable to write: their session would authenticate on
+// GET and 403 on every POST, with no client-side retry able to help. It
+// is the only binding either version can agree on, so both are written.
+//
+// Both defend the same thing: an attacker who can write cookies on a sibling
+// subdomain cannot produce a CSRF value matching the auth cookie without
+// already holding the session it belongs to.
+//
+// The token-bound cookie becomes removable one release after this ships, when
+// no deployable version still needs it.
+func sessionCSRFSignature(sessionID string, nonce []byte) []byte {
+ mac := hmac.New(sha256.New, JWTSecret())
+ mac.Write([]byte(sessionID))
+ // Domain separator: without it a (sessionID, nonce) pair could be
+ // re-split, letting one session's token be read as another's.
+ mac.Write([]byte{0})
+ mac.Write(nonce)
+ return mac.Sum(nil)
+}
+
+func tokenCSRFSignature(authToken string, nonce []byte) []byte {
+ mac := hmac.New(sha256.New, []byte(authToken))
+ mac.Write(nonce)
+ return mac.Sum(nil)
+}
+
+// csrfToken formats a CSRF value as hex(nonce) + "." + hex(signature).
+func csrfToken(sign func(nonce []byte) []byte) (string, error) {
nonce := make([]byte, 16)
if _, err := rand.Read(nonce); err != nil {
return "", err
}
- nonceHex := hex.EncodeToString(nonce)
-
- mac := hmac.New(sha256.New, []byte(authToken))
- mac.Write(nonce)
- sig := hex.EncodeToString(mac.Sum(nil))
+ return hex.EncodeToString(nonce) + "." + hex.EncodeToString(sign(nonce)), nil
+}
- return nonceHex + "." + sig, nil
+// verifyCSRFToken checks a presented "nonce.signature" value against sign.
+func verifyCSRFToken(presented string, sign func(nonce []byte) []byte) bool {
+ parts := strings.SplitN(presented, ".", 2)
+ if len(parts) != 2 {
+ return false
+ }
+ nonce, err := hex.DecodeString(parts[0])
+ if err != nil {
+ return false
+ }
+ sig, err := hex.DecodeString(parts[1])
+ if err != nil {
+ return false
+ }
+ return hmac.Equal(sign(nonce), sig)
}
-// SetAuthCookies sets the HttpOnly auth cookie and the readable CSRF cookie on the response.
+// SetAuthCookies sets the HttpOnly auth cookie and both readable CSRF cookies
+// on the response.
func SetAuthCookies(w http.ResponseWriter, token string) error {
secure := isSecureCookie()
domain := cookieDomain()
ttl := AuthTokenTTL()
now := time.Now()
+ readable := func(name, value string) {
+ http.SetCookie(w, &http.Cookie{
+ Name: name,
+ Value: value,
+ Path: "/",
+ Domain: domain,
+ MaxAge: int(ttl.Seconds()),
+ Expires: now.Add(ttl),
+ HttpOnly: false,
+ Secure: secure,
+ SameSite: http.SameSiteStrictMode,
+ })
+ }
+
http.SetCookie(w, &http.Cookie{
Name: AuthCookieName,
Value: token,
@@ -164,68 +279,93 @@ func SetAuthCookies(w http.ResponseWriter, token string) error {
SameSite: http.SameSiteStrictMode,
})
- csrfToken, err := generateCSRFToken(token)
+ tokenBound, err := csrfToken(func(nonce []byte) []byte {
+ return tokenCSRFSignature(token, nonce)
+ })
if err != nil {
return err
}
+ readable(CSRFCookieName, tokenBound)
- http.SetCookie(w, &http.Cookie{
- Name: CSRFCookieName,
- Value: csrfToken,
- Path: "/",
- Domain: domain,
- MaxAge: int(ttl.Seconds()),
- Expires: now.Add(ttl),
- HttpOnly: false,
- Secure: secure,
- SameSite: http.SameSiteStrictMode,
- })
+ // Only a token carrying `sid` can have a session-bound value. A token
+ // minted before MUL-7436 has none until it renews, and until then the
+ // token-bound cookie above is the only one it can use.
+ if sid := SessionIDFromToken(token); sid != "" {
+ sessionBound, err := csrfToken(func(nonce []byte) []byte {
+ return sessionCSRFSignature(sid, nonce)
+ })
+ if err != nil {
+ return err
+ }
+ readable(SessionCSRFCookieName, sessionBound)
+ }
return nil
}
-// ClearAuthCookies removes the auth and CSRF cookies.
+// ClearAuthCookies removes the auth cookie and both CSRF cookies.
func ClearAuthCookies(w http.ResponseWriter) {
domain := cookieDomain()
secure := isSecureCookie()
- http.SetCookie(w, &http.Cookie{
- Name: AuthCookieName,
- Value: "",
- Path: "/",
- Domain: domain,
- MaxAge: -1,
- Expires: time.Unix(0, 0),
- HttpOnly: true,
- Secure: secure,
- SameSite: http.SameSiteStrictMode,
- })
+ expire := func(name string, httpOnly bool) {
+ http.SetCookie(w, &http.Cookie{
+ Name: name,
+ Value: "",
+ Path: "/",
+ Domain: domain,
+ MaxAge: -1,
+ Expires: time.Unix(0, 0),
+ HttpOnly: httpOnly,
+ Secure: secure,
+ SameSite: http.SameSiteStrictMode,
+ })
+ }
- http.SetCookie(w, &http.Cookie{
- Name: CSRFCookieName,
- Value: "",
- Path: "/",
- Domain: domain,
- MaxAge: -1,
- Expires: time.Unix(0, 0),
- HttpOnly: false,
- Secure: secure,
- SameSite: http.SameSiteStrictMode,
- })
+ expire(AuthCookieName, true)
+ expire(CSRFCookieName, false)
+ // Logout must clear BOTH, or a stale session-bound value survives the
+ // logout and is presented alongside the next login's cookies.
+ expire(SessionCSRFCookieName, false)
}
-// ValidateCSRF checks the X-CSRF-Token header against the auth cookie.
-// The CSRF token is HMAC-signed with the auth token, so the server verifies
-// the signature rather than simply comparing cookie == header.
+// IsSafeMethod reports whether a method is read-only under RFC 9110, i.e. one
+// that carries no CSRF requirement. Exported because the session-renewal
+// middleware reuses it: re-issuing the auth cookie is itself a write to the
+// client's cookie jar, and doing it only on safe requests keeps a rotation
+// from ever racing the CSRF token of the request that triggered it.
+func IsSafeMethod(method string) bool {
+ switch method {
+ case http.MethodGet, http.MethodHead, http.MethodOptions:
+ return true
+ }
+ return false
+}
+
+// ValidateCSRF checks the CSRF header against the auth cookie. The value is
+// HMAC-signed, so the server verifies a signature rather than comparing
+// cookie == header.
// Returns true if validation passes (including for safe methods that don't need CSRF).
+//
+// One header, two acceptable bindings. Clients prefer the session-bound
+// cookie, which survives a sliding renewal; a client that has not picked up
+// that cookie, or is talking to us right after a rollback, sends the
+// token-bound one. Trying both here is what lets a single header name serve
+// every combination of client and server version — see CSRFHeaderName.
+//
+// The `sid` is read from the cookie WITHOUT enforcing expiry
+// (SessionIDFromToken). That is what keeps an expired session from failing
+// here: this function must not be the thing that answers a user whose session
+// just ended, because a 403 leaves the client retrying a write instead of
+// returning them to the login page. Authentication — and the 401 — happens
+// immediately after, in the auth middleware.
func ValidateCSRF(r *http.Request) bool {
- switch r.Method {
- case http.MethodGet, http.MethodHead, http.MethodOptions:
+ if IsSafeMethod(r.Method) {
return true
}
- csrfHeader := r.Header.Get("X-CSRF-Token")
- if csrfHeader == "" {
+ presented := r.Header.Get(CSRFHeaderName)
+ if presented == "" {
return false
}
@@ -234,22 +374,15 @@ func ValidateCSRF(r *http.Request) bool {
return false
}
- parts := strings.SplitN(csrfHeader, ".", 2)
- if len(parts) != 2 {
- return false
- }
-
- nonce, err := hex.DecodeString(parts[0])
- if err != nil {
- return false
- }
-
- expectedSig, err := hex.DecodeString(parts[1])
- if err != nil {
- return false
+ if sid := SessionIDFromToken(authCookie.Value); sid != "" {
+ if verifyCSRFToken(presented, func(nonce []byte) []byte {
+ return sessionCSRFSignature(sid, nonce)
+ }) {
+ return true
+ }
}
- mac := hmac.New(sha256.New, []byte(authCookie.Value))
- mac.Write(nonce)
- return hmac.Equal(mac.Sum(nil), expectedSig)
+ return verifyCSRFToken(presented, func(nonce []byte) []byte {
+ return tokenCSRFSignature(authCookie.Value, nonce)
+ })
}
diff --git a/server/internal/auth/cookie_test.go b/server/internal/auth/cookie_test.go
index 775eeb362b..c1c1d19708 100644
--- a/server/internal/auth/cookie_test.go
+++ b/server/internal/auth/cookie_test.go
@@ -1,6 +1,7 @@
package auth
import (
+ "net/http"
"net/http/httptest"
"testing"
"time"
@@ -131,3 +132,258 @@ func TestSetAuthCookies_HTTPSProduction(t *testing.T) {
}
}
}
+
+// csrfHeaderFor builds the request a browser would send: the auth cookie the
+// server set, plus the CSRF cookie's value echoed in the header.
+// csrfRequest presents authToken as the auth cookie and echoes csrfValue in
+// the single CSRF header. Which of the two cookie values a client puts there
+// is the client's choice; the server tries both bindings either way.
+func csrfRequest(t *testing.T, authToken, csrfValue string) *http.Request {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/api/issues", nil)
+ req.AddCookie(&http.Cookie{Name: AuthCookieName, Value: authToken})
+ req.Header.Set(CSRFHeaderName, csrfValue)
+ return req
+}
+
+// legacyCSRFRequest is the same request; the name records that the value came
+// from the token-bound cookie — what a client that has not picked up the new
+// cookie sends, and what a rolled-back server would be verifying.
+func legacyCSRFRequest(t *testing.T, authToken, csrfValue string) *http.Request {
+ t.Helper()
+ return csrfRequest(t, authToken, csrfValue)
+}
+
+// cookieValues runs the real cookie-setting path and returns the readable
+// cookies by name.
+func cookieValues(t *testing.T, authToken string) map[string]string {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ if err := SetAuthCookies(rec, authToken); err != nil {
+ t.Fatalf("SetAuthCookies: %v", err)
+ }
+ out := map[string]string{}
+ for _, c := range rec.Result().Cookies() {
+ out[c.Name] = c.Value
+ }
+ return out
+}
+
+// setAuthCookiesFor runs the real cookie-setting path and returns the CSRF
+// token it minted, so tests exercise the same code the login and renewal
+// paths use rather than reimplementing the token format.
+func setAuthCookiesFor(t *testing.T, authToken string) string {
+ t.Helper()
+ values := cookieValues(t, authToken)
+ if v := values[SessionCSRFCookieName]; v != "" {
+ return v
+ }
+ t.Fatal("no session-bound CSRF cookie was set")
+ return ""
+}
+
+// The point of binding CSRF to `sid` instead of to the token string: sliding
+// renewal re-issues the auth cookie mid-session, and a CSRF token another tab
+// read before that must keep working afterwards (MUL-7436).
+func TestValidateCSRF_SurvivesSessionRenewal(t *testing.T) {
+ sid, err := NewSessionID()
+ if err != nil {
+ t.Fatalf("NewSessionID: %v", err)
+ }
+ claims := sessionClaims(t, time.Now().Add(20*24*time.Hour), sid)
+ original := signSession(t, claims)
+
+ // A tab reads the CSRF cookie...
+ csrfToken := setAuthCookiesFor(t, original)
+
+ // ...the session is renewed on another tab's GET, producing a different
+ // auth token for the same session...
+ renewed, _, err := RenewSessionToken(claims)
+ if err != nil {
+ t.Fatalf("RenewSessionToken: %v", err)
+ }
+ if renewed == original {
+ t.Fatal("renewal must produce a different token")
+ }
+
+ // ...and the first tab's POST still validates against the new cookie.
+ if !ValidateCSRF(csrfRequest(t, renewed, csrfToken)) {
+ t.Error("CSRF token issued before renewal must stay valid after it")
+ }
+
+ // The reverse also holds: a token minted after renewal works, so both
+ // tabs converge without either having to reload.
+ if !ValidateCSRF(csrfRequest(t, renewed, setAuthCookiesFor(t, renewed))) {
+ t.Error("CSRF token issued after renewal must validate")
+ }
+}
+
+// Binding to the session must not become a way to use one session's CSRF
+// token against another's cookie.
+func TestValidateCSRF_RejectsTokenFromAnotherSession(t *testing.T) {
+ sidA, _ := NewSessionID()
+ sidB, _ := NewSessionID()
+ tokenA := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sidA))
+ tokenB := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sidB))
+
+ csrfA := setAuthCookiesFor(t, tokenA)
+ if ValidateCSRF(csrfRequest(t, tokenB, csrfA)) {
+ t.Error("a CSRF token from another session must not validate")
+ }
+}
+
+// Everyone signed in when this ships holds a cookie pair minted under the old
+// binding. Those must keep working until that session renews, or the deploy
+// logs the whole userbase out of every state-changing action.
+func TestValidateCSRF_AcceptsTokenBinding(t *testing.T) {
+ legacy := signSession(t, sessionClaims(t, time.Now().Add(20*24*time.Hour), ""))
+
+ values := cookieValues(t, legacy)
+ if values[SessionCSRFCookieName] != "" {
+ t.Error("a token without `sid` has no session to bind to; no session cookie should be set")
+ }
+ if !ValidateCSRF(legacyCSRFRequest(t, legacy, values[CSRFCookieName])) {
+ t.Error("a pre-MUL-7436 cookie pair must still validate")
+ }
+
+ // And the token binding stays bound: it is keyed by the token itself, so
+ // it must not validate against a different one.
+ other := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), ""))
+ if ValidateCSRF(legacyCSRFRequest(t, other, values[CSRFCookieName])) {
+ t.Error("a token-bound CSRF value must not validate against a different auth token")
+ }
+}
+
+// Rolling BACK past MUL-7436 must not strand signed-in users able to read and
+// unable to write. A previous release verifies only the token binding, so
+// every cookie set here has to include one — that is the sole reason it is
+// still issued alongside the session binding.
+func TestSetAuthCookies_KeepsTokenBindingForRollback(t *testing.T) {
+ sid, _ := NewSessionID()
+ token := signSession(t, sessionClaims(t, time.Now().Add(20*24*time.Hour), sid))
+
+ values := cookieValues(t, token)
+ if values[CSRFCookieName] == "" {
+ t.Fatal("the token-bound cookie must still be issued; without it a rollback cannot verify any write")
+ }
+ if values[SessionCSRFCookieName] == "" {
+ t.Fatal("the session-bound cookie must be issued")
+ }
+ if values[CSRFCookieName] == values[SessionCSRFCookieName] {
+ t.Error("the two cookies must carry different bindings")
+ }
+
+ // Exactly what a rolled-back server does: verify the token-bound value
+ // against the auth cookie, knowing nothing about `sid`.
+ if !verifyCSRFToken(values[CSRFCookieName], func(nonce []byte) []byte {
+ return tokenCSRFSignature(token, nonce)
+ }) {
+ t.Error("the token-bound cookie must verify under the pre-MUL-7436 scheme")
+ }
+
+ // And a current server accepts it too, so a client that only ever sends
+ // the token-bound header keeps working.
+ if !ValidateCSRF(legacyCSRFRequest(t, token, values[CSRFCookieName])) {
+ t.Error("a current server must still accept the token-bound header")
+ }
+}
+
+// After a renewal the token-bound cookie is re-minted for the NEW token, so a
+// rollback taken at any point still finds a usable pair — that is what makes
+// the rollback path complete rather than only true at login.
+func TestSetAuthCookies_TokenBindingTracksRenewal(t *testing.T) {
+ sid, _ := NewSessionID()
+ claims := sessionClaims(t, time.Now().Add(20*24*time.Hour), sid)
+ renewed, _, err := RenewSessionToken(claims)
+ if err != nil {
+ t.Fatalf("RenewSessionToken: %v", err)
+ }
+
+ values := cookieValues(t, renewed)
+ if !verifyCSRFToken(values[CSRFCookieName], func(nonce []byte) []byte {
+ return tokenCSRFSignature(renewed, nonce)
+ }) {
+ t.Error("the renewed token-bound cookie must be keyed to the renewed token")
+ }
+}
+
+// One header, two acceptable bindings: whichever cookie value a client
+// chooses to echo, the server has to recognise it. This is what lets the
+// single header name serve every client/server version combination without a
+// CORS change — see CSRFHeaderName.
+func TestValidateCSRF_AcceptsEitherCookieValueInTheOneHeader(t *testing.T) {
+ sid, _ := NewSessionID()
+ token := signSession(t, sessionClaims(t, time.Now().Add(20*24*time.Hour), sid))
+ values := cookieValues(t, token)
+
+ if !ValidateCSRF(csrfRequest(t, token, values[SessionCSRFCookieName])) {
+ t.Error("the session-bound value must validate")
+ }
+ if !ValidateCSRF(csrfRequest(t, token, values[CSRFCookieName])) {
+ t.Error("the token-bound value must validate")
+ }
+
+ // After a renewal the token-bound value from BEFORE it is stale, and the
+ // session-bound one is not — which is the whole reason clients prefer it.
+ renewed, _, err := RenewSessionToken(sessionClaims(t, time.Now().Add(20*24*time.Hour), sid))
+ if err != nil {
+ t.Fatalf("RenewSessionToken: %v", err)
+ }
+ if !ValidateCSRF(csrfRequest(t, renewed, values[SessionCSRFCookieName])) {
+ t.Error("a session-bound value must survive renewal")
+ }
+ if ValidateCSRF(csrfRequest(t, renewed, values[CSRFCookieName])) {
+ t.Error("a pre-renewal token-bound value must NOT still validate; clients fall back to the re-minted one")
+ }
+}
+
+// Expiry is not this gate's business. SessionIDFromToken reads `sid` without
+// enforcing it, so an expired-but-genuine cookie still validates here and the
+// auth middleware answers with the 401 that ends the session.
+func TestValidateCSRF_IgnoresExpirySoAuthCanAnswer(t *testing.T) {
+ sid, _ := NewSessionID()
+ live := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sid))
+ expired := signSession(t, sessionClaims(t, time.Now().Add(-time.Hour), sid))
+
+ csrf := setAuthCookiesFor(t, live)
+ if !ValidateCSRF(csrfRequest(t, expired, csrf)) {
+ t.Error("an expired session must fail authentication, not CSRF — a 403 here never reaches the session-expiry path")
+ }
+}
+
+func TestValidateCSRF_RejectsMalformedAndMissing(t *testing.T) {
+ sid, _ := NewSessionID()
+ token := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), sid))
+
+ cases := map[string]string{
+ "empty": "",
+ "no separator": "abcdef",
+ "bad nonce hex": "zz.00",
+ "bad sig hex": "00.zz",
+ "wrong sig": "0011223344556677889900112233445566.00",
+ "extra segments": "00.11.22",
+ }
+ for name, csrf := range cases {
+ t.Run(name, func(t *testing.T) {
+ if ValidateCSRF(csrfRequest(t, token, csrf)) {
+ t.Errorf("malformed CSRF token %q must not validate", csrf)
+ }
+ })
+ }
+
+ // No auth cookie at all: nothing to bind to, so nothing validates.
+ req := httptest.NewRequest(http.MethodPost, "/api/issues", nil)
+ req.Header.Set("X-CSRF-Token", setAuthCookiesFor(t, token))
+ if ValidateCSRF(req) {
+ t.Error("CSRF must not validate without an auth cookie")
+ }
+}
+
+func TestValidateCSRF_SafeMethodsSkipTheCheck(t *testing.T) {
+ for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodOptions} {
+ req := httptest.NewRequest(method, "/api/issues", nil)
+ if !ValidateCSRF(req) {
+ t.Errorf("%s must not require a CSRF token", method)
+ }
+ }
+}
diff --git a/server/internal/auth/session.go b/server/internal/auth/session.go
new file mode 100644
index 0000000000..2085da1e9c
--- /dev/null
+++ b/server/internal/auth/session.go
@@ -0,0 +1,255 @@
+package auth
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+)
+
+// Sliding session renewal (MUL-7436).
+//
+// A UI session token used to have its lifetime fixed at login: `exp` was
+// stamped once and never moved, so every continuously active user was logged
+// out on a schedule — 30 days after login, always while they were mid-task.
+// Renewal turns that into an IDLE bound instead: a token inside its renewal
+// window is re-signed with a fresh `exp` on the next authenticated request.
+//
+// The model is deliberately stateless. Renewal copies the identity claims of
+// a token we ourselves signed and moves `exp`; there is no session row, no
+// refresh token, and no DB read on the hot path. What that buys in
+// simplicity it gives up in revocation — which the JWT path never had
+// anyway (logout clears the cookie; the token itself stays valid until
+// `exp`). Real revocation needs server-side session records and is tracked
+// separately.
+//
+// The idle bound is approximate, and the approximation is one-sided: a
+// session is renewed only once it drops below half its TTL, so the guarantee
+// is "at least TTL/2 of idleness is survivable", not "exactly TTL after the
+// last request". A token signed on day 0 and last used on day 14 was not yet
+// eligible, so it still expires on day 30 — 16 idle days, not 30. Sessions
+// used at any point inside the second half of their lifetime get the full
+// TTL from that moment.
+
+const (
+ // sessionIDClaim carries a per-login identifier that is STABLE across
+ // renewals and changes only when the user authenticates again. It is
+ // what the CSRF token is bound to, so re-signing the auth cookie does
+ // not invalidate CSRF tokens other tabs are already holding.
+ sessionIDClaim = "sid"
+
+ // sessionRenewCheckDivisor derives the client-side re-check cadence
+ // from the configured TTL: a client that checks every TTL/10 gets
+ // roughly five attempts inside the renewal window, so several
+ // consecutive failures still leave the session recoverable. At the
+ // default 30-day TTL this is 3 days, matching the daemon's PAT
+ // renewal cadence (DefaultTokenRenewalInterval).
+ sessionRenewCheckDivisor = 10
+
+ // minSessionRenewCheckInterval is a pure anti-busy-loop floor, not a
+ // policy. With MinAuthTokenTTL enforced the smallest cadence this can
+ // ever produce is six seconds, so this floor never actually binds; it
+ // stays as a backstop, and the window cap below outranks it either way,
+ // because an interval that cannot fit inside the renewal window is not a
+ // cadence, it is a guaranteed logout.
+ //
+ // Every client floor must be at or below this value, or the client would
+ // silently override a cadence the server chose for correctness. See
+ // packages/core/platform/session-renewal.ts and
+ // apps/mobile/data/session-renewal.ts.
+ minSessionRenewCheckInterval = 5 * time.Second
+
+ // maxSessionRenewCheckInterval bounds the other end: a client that has
+ // not asked in a week is far enough from its own state that checking is
+ // cheap insurance, whatever the TTL says.
+ maxSessionRenewCheckInterval = 7 * 24 * time.Hour
+)
+
+// ErrNotSessionToken is returned by RenewSessionToken when handed something
+// that is not one of our own UI session JWTs. PATs (mul_), agent task tokens
+// (mat_) and cloud-node PATs (mcn_) authenticate fine at the middleware but
+// must never be exchanged for an interactive session.
+var ErrNotSessionToken = errors.New("not an interactive session token")
+
+// AuthRenewThreshold is the remaining lifetime at or below which a session
+// token becomes eligible for renewal. Half the TTL is the largest threshold
+// that still leaves renewal rare (one re-sign per TTL/2 of continuous use)
+// while giving an intermittently used client a window measured in days
+// rather than minutes to land a successful renewal.
+func AuthRenewThreshold() time.Duration { return AuthTokenTTL() / 2 }
+
+// SessionRenewCheckInterval is how long a token-mode client should wait
+// before asking whether its session is renewable again. Derived from the
+// configured TTL so a deployment that shortens AUTH_TOKEN_TTL automatically
+// gets proportionally more frequent checks — clients must never hardcode a
+// cadence tuned for the 30-day default.
+//
+// The cadence has one hard requirement: it must fit inside the renewal
+// window, or a client that follows it can miss the window entirely and be
+// logged out while actively using the app. Capping at half the threshold
+// guarantees at least two attempts inside it, so a single failed check is
+// never fatal. That cap is applied last, after both clamps, because it is
+// the correctness constraint and they are only guard rails.
+func SessionRenewCheckInterval() time.Duration {
+ interval := AuthTokenTTL() / sessionRenewCheckDivisor
+ if interval < minSessionRenewCheckInterval {
+ interval = minSessionRenewCheckInterval
+ }
+ if interval > maxSessionRenewCheckInterval {
+ interval = maxSessionRenewCheckInterval
+ }
+ if cap := AuthRenewThreshold() / 2; interval > cap {
+ interval = cap
+ }
+ return interval
+}
+
+// ShouldRenewSession reports whether a token expiring at expiresAt is inside
+// the renewal window at now.
+//
+// An already-expired token is never renewable: `exp` in the past means the
+// credential is dead, and renewal must not be a way to resurrect one. The
+// middleware rejects those before this is ever reached; this is the second
+// lock on the same door.
+func ShouldRenewSession(now, expiresAt time.Time) bool {
+ if expiresAt.IsZero() {
+ return false
+ }
+ remaining := expiresAt.Sub(now)
+ if remaining <= 0 {
+ return false
+ }
+ return remaining <= AuthRenewThreshold()
+}
+
+// NewSessionID mints the per-login identifier stamped into the `sid` claim.
+func NewSessionID() (string, error) {
+ b := make([]byte, 16)
+ if _, err := rand.Read(b); err != nil {
+ return "", fmt.Errorf("generate session id: %w", err)
+ }
+ return hex.EncodeToString(b), nil
+}
+
+// SessionExpiry reads the `exp` claim as a time. Zero when absent or
+// malformed — callers treat that as "not renewable" rather than "never
+// expires", because a session token we signed always has one.
+func SessionExpiry(claims jwt.MapClaims) time.Time {
+ exp, err := claims.GetExpirationTime()
+ if err != nil || exp == nil {
+ return time.Time{}
+ }
+ return exp.Time
+}
+
+func parseSignedToken(tokenString string, opts ...jwt.ParserOption) (jwt.MapClaims, error) {
+ token, err := jwt.Parse(tokenString, func(t *jwt.Token) (any, error) {
+ if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
+ return nil, jwt.ErrSignatureInvalid
+ }
+ return JWTSecret(), nil
+ }, opts...)
+ if err != nil || !token.Valid {
+ return nil, ErrNotSessionToken
+ }
+ claims, ok := token.Claims.(jwt.MapClaims)
+ if !ok {
+ return nil, ErrNotSessionToken
+ }
+ return claims, nil
+}
+
+// ParseSessionToken verifies a raw token string as one of our UI session
+// JWTs and returns its claims. Anything that is not a validly signed,
+// unexpired HS256 JWT — including every opaque token prefix — comes back as
+// ErrNotSessionToken.
+//
+// This is the AUTHENTICATION parser: use it wherever the answer decides
+// whether the caller is logged in or whether a session may be extended.
+func ParseSessionToken(tokenString string) (jwt.MapClaims, error) {
+ return parseSignedToken(tokenString)
+}
+
+// SessionIDFromToken returns the `sid` claim of a token we signed, or "" for
+// anything else — an opaque PAT, a forged string, or one of the pre-MUL-7436
+// JWTs minted before the claim existed. "" is the signal to fall back to the
+// legacy CSRF binding; see ValidateCSRF.
+//
+// Expiry is deliberately NOT enforced here, and that distinction is
+// load-bearing. This function answers "which session does this cookie
+// belong to", not "may this cookie authenticate" — the signature alone
+// settles the first question, and the auth middleware settles the second a
+// few lines later. Enforcing expiry here instead meant an EXPIRED cookie
+// lost its `sid`, so its perfectly valid CSRF token failed to verify and the
+// user's first action after expiry was answered with 403 "CSRF validation
+// failed" rather than the 401 that ends the session and sends them to the
+// login page. A rejected CSRF token must never be how a user learns their
+// session ended.
+func SessionIDFromToken(tokenString string) string {
+ claims, err := parseSignedToken(tokenString, jwt.WithoutClaimsValidation())
+ if err != nil {
+ return ""
+ }
+ sid, _ := claims[sessionIDClaim].(string)
+ return sid
+}
+
+// RenewSessionToken re-signs the identity carried by claims with a fresh
+// lifetime, returning the new token and its expiry.
+//
+// Only `exp` and `iat` move. `sub`, `email`, `name` and `sid` are copied
+// forward verbatim, which is what makes renewal free of any database read:
+// the claims were signed by this server, so they are already authoritative
+// for exactly the fields the auth middleware reads back out.
+//
+// A pre-MUL-7436 token carries no `sid`. Renewal mints one, which is the
+// migration path for sessions that predate this code — and the one moment
+// where a CSRF token already read by another tab stops matching. It happens
+// once per legacy session, on a safe-method request; clients retry a CSRF
+// rejection once (packages/core/api/client.ts).
+func RenewSessionToken(claims jwt.MapClaims) (string, time.Time, error) {
+ sub, _ := claims["sub"].(string)
+ if sub == "" {
+ return "", time.Time{}, ErrNotSessionToken
+ }
+ email, _ := claims["email"].(string)
+
+ // A user disabled since their token was signed must not have that token
+ // extended — renewal is the one place a live session's lifetime is
+ // decided after login, so the check belongs here as much as at issuance.
+ if IsTemporarilyDisabledUser(sub, email) {
+ return "", time.Time{}, ErrTemporarilyDisabledUser
+ }
+
+ sid, _ := claims[sessionIDClaim].(string)
+ if sid == "" {
+ var err error
+ if sid, err = NewSessionID(); err != nil {
+ return "", time.Time{}, err
+ }
+ }
+
+ now := time.Now()
+ expiresAt := now.Add(AuthTokenTTL())
+ next := jwt.MapClaims{
+ "sub": sub,
+ "exp": expiresAt.Unix(),
+ "iat": now.Unix(),
+ sessionIDClaim: sid,
+ }
+ if email != "" {
+ next["email"] = email
+ }
+ if name, ok := claims["name"].(string); ok && name != "" {
+ next["name"] = name
+ }
+
+ signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, next).SignedString(JWTSecret())
+ if err != nil {
+ return "", time.Time{}, err
+ }
+ return signed, expiresAt, nil
+}
diff --git a/server/internal/auth/session_test.go b/server/internal/auth/session_test.go
new file mode 100644
index 0000000000..1929bcb8ad
--- /dev/null
+++ b/server/internal/auth/session_test.go
@@ -0,0 +1,419 @@
+package auth
+
+import (
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+)
+
+// resetAuthTokenTTLForTest makes AuthTokenTTL() re-read the environment.
+// The production path caches it behind a sync.Once on purpose — the TTL is
+// deployment configuration, not per-request state — so a test that wants a
+// specific TTL has to clear the cache on both sides of itself.
+func resetAuthTokenTTLForTest(t *testing.T) {
+ t.Helper()
+ clear := func() {
+ authTokenTTLOnce = sync.Once{}
+ authTokenTTLCached = 0
+ }
+ clear()
+ t.Cleanup(clear)
+}
+
+func sessionClaims(t *testing.T, exp time.Time, sid string) jwt.MapClaims {
+ t.Helper()
+ // float64, not int64: every claims map the production code sees comes out
+ // of jwt.Parse, which JSON-decodes numeric dates into float64. An int64
+ // here would make MapClaims.GetExpirationTime fail in a way it never does
+ // at runtime, and the test would be asserting against a shape that does
+ // not exist.
+ claims := jwt.MapClaims{
+ "sub": "user-1",
+ "email": "[email protected]",
+ "name": "User One",
+ "exp": float64(exp.Unix()),
+ "iat": float64(time.Now().Add(-time.Hour).Unix()),
+ }
+ if sid != "" {
+ claims["sid"] = sid
+ }
+ return claims
+}
+
+func signSession(t *testing.T, claims jwt.MapClaims) string {
+ t.Helper()
+ signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(JWTSecret())
+ if err != nil {
+ t.Fatalf("sign session token: %v", err)
+ }
+ return signed
+}
+
+// The renewal window is the defining behaviour of a sliding session: too
+// eager and every response carries a Set-Cookie, too lazy and an active user
+// still gets logged out. Half the TTL is the contract Bohan approved on
+// MUL-7436, so pin both sides of the boundary.
+func TestShouldRenewSession_HalfTTLBoundary(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", "720h") // 30 days
+ resetAuthTokenTTLForTest(t)
+
+ now := time.Now()
+ ttl := AuthTokenTTL()
+
+ cases := []struct {
+ name string
+ remaining time.Duration
+ want bool
+ }{
+ {"freshly issued", ttl, false},
+ {"just above half", ttl/2 + time.Minute, false},
+ {"exactly half", ttl / 2, true},
+ {"just below half", ttl/2 - time.Minute, true},
+ {"nearly expired", time.Minute, true},
+ // An expired session is dead, not stale. Renewal extends a live
+ // session; it must never be a way to resurrect one.
+ {"expired a second ago", -time.Second, false},
+ {"long expired", -30 * 24 * time.Hour, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := ShouldRenewSession(now, now.Add(tc.remaining)); got != tc.want {
+ t.Errorf("ShouldRenewSession(remaining=%s) = %v, want %v", tc.remaining, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestShouldRenewSession_NoExpiryIsNotRenewable(t *testing.T) {
+ if ShouldRenewSession(time.Now(), time.Time{}) {
+ t.Error("a token with no exp must not be renewable")
+ }
+}
+
+// Clients must never hardcode a cadence: a deployment that shortens the TTL
+// has to get proportionally more frequent checks, or its sessions die between
+// two of them.
+func TestSessionRenewCheckInterval_TracksTTL(t *testing.T) {
+ cases := []struct {
+ ttl string
+ want time.Duration
+ why string
+ }{
+ {"720h", 72 * time.Hour, "30d default → TTL/10 = 3d, same as the daemon's PAT cadence"},
+ {"24h", 144 * time.Minute, "short TTL → proportionally short cadence"},
+ {"30m", 3 * time.Minute, "TTL/10, comfortably inside the 15m window"},
+ {"10m", time.Minute, "the TTL the PR's manual test plan uses"},
+ {"1m", 6 * time.Second, "the shortest supported TTL; 6s is expressible in whole seconds"},
+ {"20s", 6 * time.Second, "below MinAuthTokenTTL, so the TTL itself is clamped up to 1m first"},
+ {"87600h", 7 * 24 * time.Hour, "10y → clamped at the ceiling"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.ttl, func(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", tc.ttl)
+ resetAuthTokenTTLForTest(t)
+ if got := SessionRenewCheckInterval(); got != tc.want {
+ t.Errorf("SessionRenewCheckInterval() = %s, want %s (TTL=%s: %s)", got, tc.want, tc.ttl, tc.why)
+ }
+ })
+ }
+}
+
+// The cadence has exactly one property that must hold for every configurable
+// TTL: a client that follows it gets at least two chances inside the renewal
+// window. Without that a short TTL produces an interval LONGER than the window
+// — and a client doing everything right is logged out while actively using the
+// app. A flat five-minute floor did that for any TTL under ten minutes.
+//
+// The assertion is made against the value that actually reaches a client —
+// whole seconds, as it is serialised — not the internal time.Duration. Those
+// differ, and only the serialised one governs client behaviour.
+func TestSessionRenewCheckInterval_WireValueFitsInsideTheRenewalWindow(t *testing.T) {
+ for _, ttl := range []string{"1s", "10s", "1m", "5m", "10m", "30m", "1h", "24h", "720h", "8760h", "87600h"} {
+ t.Run(ttl, func(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", ttl)
+ resetAuthTokenTTLForTest(t)
+
+ // Exactly what handler.RefreshSession puts on the wire.
+ wireSeconds := int(SessionRenewCheckInterval().Seconds())
+ if wireSeconds < 1 {
+ t.Fatalf("cadence serialises to %ds — a client is told to check immediately, forever (TTL=%s)", wireSeconds, ttl)
+ }
+
+ asClientSeesIt := time.Duration(wireSeconds) * time.Second
+ threshold := AuthRenewThreshold()
+ if asClientSeesIt > threshold/2 {
+ t.Errorf("client-visible cadence %s leaves fewer than two attempts inside a %s window (TTL=%s)",
+ asClientSeesIt, threshold, ttl)
+ }
+ })
+ }
+}
+
+// Clients floor the server's cadence to protect themselves from a nonsense
+// value. That floor must never be the thing that decides the cadence, so the
+// server's own smallest possible value has to sit above it.
+func TestSessionRenewCheckInterval_StaysAboveTheClientFloors(t *testing.T) {
+ // packages/core/platform/session-renewal.ts and
+ // apps/mobile/data/session-renewal.ts both floor at 5 seconds.
+ const clientFloor = 5 * time.Second
+
+ for _, ttl := range []string{"1s", "30s", "1m", "10m", "720h"} {
+ t.Run(ttl, func(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", ttl)
+ resetAuthTokenTTLForTest(t)
+
+ asClientSeesIt := time.Duration(int(SessionRenewCheckInterval().Seconds())) * time.Second
+ if asClientSeesIt < clientFloor {
+ t.Errorf("server cadence %s is below the %s client floor, so clients would silently override it (TTL=%s)",
+ asClientSeesIt, clientFloor, ttl)
+ }
+ })
+ }
+}
+
+// A TTL too short to serve correctly is clamped up rather than honoured or
+// replaced by the default. Honouring it would mean telling clients to check
+// on a cadence the wire cannot carry; falling back to 30 days would be a far
+// bigger surprise than the one-minute floor.
+func TestAuthTokenTTL_ClampsBelowTheSupportedMinimum(t *testing.T) {
+ cases := map[string]time.Duration{
+ "1s": MinAuthTokenTTL,
+ "30s": MinAuthTokenTTL,
+ "59s": MinAuthTokenTTL,
+ "1m": time.Minute,
+ "10m": 10 * time.Minute,
+ }
+ for raw, want := range cases {
+ t.Run(raw, func(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", raw)
+ resetAuthTokenTTLForTest(t)
+ if got := AuthTokenTTL(); got != want {
+ t.Errorf("AuthTokenTTL() = %s, want %s (AUTH_TOKEN_TTL=%s)", got, want, raw)
+ }
+ })
+ }
+}
+
+// Renewal reads no database, so the claims it copies forward ARE the identity
+// the next request authenticates as. Dropping one would silently downgrade
+// the session.
+func TestRenewSessionToken_CarriesIdentityForward(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", "720h")
+ resetAuthTokenTTLForTest(t)
+
+ old := sessionClaims(t, time.Now().Add(24*time.Hour), "session-abc")
+ token, expiresAt, err := RenewSessionToken(old)
+ if err != nil {
+ t.Fatalf("RenewSessionToken: %v", err)
+ }
+
+ next, err := ParseSessionToken(token)
+ if err != nil {
+ t.Fatalf("renewed token does not parse: %v", err)
+ }
+ for _, claim := range []string{"sub", "email", "name", "sid"} {
+ if next[claim] != old[claim] {
+ t.Errorf("claim %q = %v, want %v", claim, next[claim], old[claim])
+ }
+ }
+
+ // exp moved to a full TTL from now, not from the old expiry.
+ want := time.Now().Add(AuthTokenTTL())
+ if delta := expiresAt.Sub(want); delta > time.Minute || delta < -time.Minute {
+ t.Errorf("new expiry %s is not ~now+TTL (%s)", expiresAt, want)
+ }
+ if got := SessionExpiry(next); got.Unix() != expiresAt.Unix() {
+ t.Errorf("exp claim %s does not match returned expiry %s", got, expiresAt)
+ }
+}
+
+// Sessions that predate MUL-7436 carry no `sid`. They must still renew — this
+// is the migration path for everyone logged in when this ships — and the
+// renewed token has to acquire one so its CSRF binding becomes stable.
+func TestRenewSessionToken_MintsSessionIDForLegacyToken(t *testing.T) {
+ legacy := sessionClaims(t, time.Now().Add(24*time.Hour), "")
+
+ token, _, err := RenewSessionToken(legacy)
+ if err != nil {
+ t.Fatalf("RenewSessionToken: %v", err)
+ }
+ if sid := SessionIDFromToken(token); sid == "" {
+ t.Error("renewed legacy token must carry a session id")
+ }
+}
+
+// Renewal is the one place a live session's lifetime is decided after login,
+// so the disabled-user check has to live there too — otherwise disabling an
+// abusive account leaves their session renewing itself forever.
+func TestRenewSessionToken_RejectsDisabledUser(t *testing.T) {
+ // One of the ids on the standing emergency denylist.
+ var disabledID string
+ for id := range temporarilyDisabledUserIDs {
+ disabledID = id
+ break
+ }
+ claims := sessionClaims(t, time.Now().Add(time.Hour), "sid-1")
+ claims["sub"] = disabledID
+
+ _, _, err := RenewSessionToken(claims)
+ if err != ErrTemporarilyDisabledUser {
+ t.Fatalf("err = %v, want ErrTemporarilyDisabledUser", err)
+ }
+}
+
+func TestRenewSessionToken_RejectsClaimsWithoutSubject(t *testing.T) {
+ _, _, err := RenewSessionToken(jwt.MapClaims{"email": "[email protected]"})
+ if err != ErrNotSessionToken {
+ t.Fatalf("err = %v, want ErrNotSessionToken", err)
+ }
+}
+
+// Every non-JWT credential the auth middleware accepts must be unable to
+// become an interactive session. These all authenticate fine; none of them is
+// a session.
+func TestParseSessionToken_RejectsNonSessionCredentials(t *testing.T) {
+ cases := map[string]string{
+ "personal access token": "mul_0123456789abcdef0123456789abcdef01234567",
+ "agent task token": "mat_0123456789abcdef0123456789abcdef01234567",
+ "cloud node pat": "mcn_0123456789abcdef0123456789abcdef01234567",
+ "empty": "",
+ "garbage": "not-a-token",
+ "wrong secret": func() string {
+ s, _ := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
+ "sub": "user-1", "exp": time.Now().Add(time.Hour).Unix(),
+ }).SignedString([]byte("some-other-secret"))
+ return s
+ }(),
+ }
+ for name, token := range cases {
+ t.Run(name, func(t *testing.T) {
+ if _, err := ParseSessionToken(token); err != ErrNotSessionToken {
+ t.Errorf("err = %v, want ErrNotSessionToken", err)
+ }
+ })
+ }
+}
+
+// An expired JWT must not parse, which is what keeps the refresh endpoint
+// from being a resurrection mechanism even before ShouldRenewSession looks at
+// the clock.
+func TestParseSessionToken_RejectsExpiredToken(t *testing.T) {
+ expired := signSession(t, sessionClaims(t, time.Now().Add(-time.Minute), "sid-1"))
+ if _, err := ParseSessionToken(expired); err != ErrNotSessionToken {
+ t.Errorf("err = %v, want ErrNotSessionToken", err)
+ }
+}
+
+func TestSessionIDFromToken(t *testing.T) {
+ withSID := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), "sid-xyz"))
+ if got := SessionIDFromToken(withSID); got != "sid-xyz" {
+ t.Errorf("SessionIDFromToken() = %q, want %q", got, "sid-xyz")
+ }
+
+ legacy := signSession(t, sessionClaims(t, time.Now().Add(time.Hour), ""))
+ if got := SessionIDFromToken(legacy); got != "" {
+ t.Errorf("legacy token session id = %q, want empty", got)
+ }
+
+ if got := SessionIDFromToken("mul_deadbeef"); got != "" {
+ t.Errorf("PAT session id = %q, want empty", got)
+ }
+}
+
+// A session that is used at least once inside every renewal window never
+// expires. This is the behaviour the issue asks for, stated as a simulation
+// rather than as a property of one call.
+func TestSlidingSession_ContinuousUseOutlivesTTL(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", "720h") // 30 days
+ resetAuthTokenTTLForTest(t)
+
+ ttl := AuthTokenTTL()
+ claims := sessionClaims(t, time.Now().Add(ttl), "sid-live")
+
+ // Use the app every 10 days for 120 days — past both the old 30-day wall
+ // and the 90-day absolute cap that was considered and dropped.
+ now := time.Now()
+ for day := 10; day <= 120; day += 10 {
+ now = now.Add(10 * 24 * time.Hour)
+ expiresAt := SessionExpiry(claims)
+ if !expiresAt.After(now) {
+ t.Fatalf("session expired on day %d — an actively used session must not", day)
+ }
+ if !ShouldRenewSession(now, expiresAt) {
+ continue
+ }
+ token, _, err := RenewSessionToken(claims)
+ if err != nil {
+ t.Fatalf("day %d: RenewSessionToken: %v", day, err)
+ }
+ renewed, err := ParseSessionToken(token)
+ if err != nil {
+ t.Fatalf("day %d: renewed token does not parse: %v", day, err)
+ }
+ // RenewSessionToken always dates from the real clock, so re-stamp the
+ // simulated expiry to keep the loop honest about the TTL it grants.
+ renewed["exp"] = float64(now.Add(ttl).Unix())
+ claims = renewed
+ }
+
+ if sid, _ := claims["sid"].(string); sid != "sid-live" {
+ t.Errorf("session id changed across renewals: %q — CSRF binding would break", sid)
+ }
+}
+
+// The flip side: stop using the app and the session does die. Renewal removes
+// the scheduled logout, not expiry itself.
+func TestSlidingSession_IdleSessionStillExpires(t *testing.T) {
+ t.Setenv("AUTH_TOKEN_TTL", "720h")
+ resetAuthTokenTTLForTest(t)
+
+ ttl := AuthTokenTTL()
+ lastUsed := time.Now()
+ expiresAt := lastUsed.Add(ttl)
+
+ // Last request came in while the token still had more than half its life
+ // left, so nothing was renewed...
+ if ShouldRenewSession(lastUsed, expiresAt) {
+ t.Fatal("a freshly issued session must not be renewable")
+ }
+ // ...and the session is gone one TTL after it was issued.
+ if ShouldRenewSession(lastUsed.Add(ttl+time.Second), expiresAt) {
+ t.Error("an expired idle session must not be renewable")
+ }
+}
+
+// SessionIDFromToken must answer "which session is this" for a token whose
+// signature is ours, even once it has expired. It feeds CSRF validation, which
+// runs before authentication — returning "" for an expired token made a valid
+// CSRF value fail and turned session expiry into a 403 on the user's next
+// write instead of the 401 that logs them out.
+func TestSessionIDFromToken_ReadsExpiredTokens(t *testing.T) {
+ expired := signSession(t, sessionClaims(t, time.Now().Add(-24*time.Hour), "sid-expired"))
+ if got := SessionIDFromToken(expired); got != "sid-expired" {
+ t.Errorf("SessionIDFromToken(expired) = %q, want sid-expired", got)
+ }
+
+ // Still only OUR tokens: a forged one has no session to name.
+ forged, _ := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
+ "sub": "user-1", "sid": "forged", "exp": float64(time.Now().Add(-time.Hour).Unix()),
+ }).SignedString([]byte("some-other-secret"))
+ if got := SessionIDFromToken(forged); got != "" {
+ t.Errorf("SessionIDFromToken(forged) = %q, want empty", got)
+ }
+}
+
+// The authentication parser keeps enforcing expiry, which is what stops the
+// relaxed read above from leaking into anything that decides access. These two
+// answers must stay different for the same token.
+func TestParseSessionToken_StillEnforcesExpiryAfterTheSplit(t *testing.T) {
+ expired := signSession(t, sessionClaims(t, time.Now().Add(-time.Minute), "sid-x"))
+
+ if _, err := ParseSessionToken(expired); err != ErrNotSessionToken {
+ t.Errorf("ParseSessionToken(expired) err = %v, want ErrNotSessionToken", err)
+ }
+ if SessionIDFromToken(expired) == "" {
+ t.Error("SessionIDFromToken must still read the same token")
+ }
+}
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index dd03d46281..17bf517ee2 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -163,10 +163,20 @@ func (h *Handler) issueJWT(user db.User) (string, error) {
if auth.IsTemporarilyDisabledUser(uuidToString(user.ID), user.Email) {
return "", auth.ErrTemporarilyDisabledUser
}
+ // `sid` identifies this login for as long as it lasts: sliding renewal
+ // copies it forward, so it stays put while `exp` moves. The CSRF token is
+ // bound to it rather than to the token string, which is what lets the
+ // auth cookie be re-issued mid-session without invalidating CSRF tokens
+ // other tabs are already holding (MUL-7436).
+ sid, err := auth.NewSessionID()
+ if err != nil {
+ return "", err
+ }
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": uuidToString(user.ID),
"email": user.Email,
"name": user.Name,
+ "sid": sid,
"exp": time.Now().Add(auth.AuthTokenTTL()).Unix(),
"iat": time.Now().Unix(),
})
diff --git a/server/internal/handler/auth_google_error_code_test.go b/server/internal/handler/auth_google_error_code_test.go
index f0c85a50c4..d2387b2f2c 100644
--- a/server/internal/handler/auth_google_error_code_test.go
+++ b/server/internal/handler/auth_google_error_code_test.go
@@ -306,7 +306,7 @@ func TestGoogleLoginSuccessfulExistingUser(t *testing.T) {
// Exercise the issued JWT through the same middleware that accepts browser sessions.
meReq := httptest.NewRequest(http.MethodGet, "/users/me", nil)
meReq.AddCookie(authCookie)
- protected := middleware.Auth(h.Queries, nil, nil)(http.HandlerFunc(h.GetMe))
+ protected := middleware.Auth(h.Queries, nil, nil, nil)(http.HandlerFunc(h.GetMe))
var me UserResponse
testutil.Call(t, protected.ServeHTTP, meReq).Want(http.StatusOK).JSON(&me)
if me.ID != userID || me.Email != email {
diff --git a/server/internal/handler/session.go b/server/internal/handler/session.go
new file mode 100644
index 0000000000..ad375ba9c3
--- /dev/null
+++ b/server/internal/handler/session.go
@@ -0,0 +1,163 @@
+package handler
+
+import (
+ "errors"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/logger"
+)
+
+// RefreshSessionResponse is the body returned by RefreshSession.
+//
+// Token is present only for bearer-authenticated callers (Desktop, mobile),
+// which hold the session as a string and have to persist the new one. A
+// cookie-authenticated browser gets the renewed session as a Set-Cookie
+// header and never sees the JWT — handing it back in a readable body would
+// undo the point of the HttpOnly cookie.
+//
+// Renewed=false is a normal answer, not an error: it means the caller asked
+// before the session entered its renewal window. Callers should read
+// CheckAgainInSeconds rather than deciding a cadence for themselves.
+type RefreshSessionResponse struct {
+ Token string `json:"token,omitempty"`
+ ExpiresAt string `json:"expires_at"`
+ Renewed bool `json:"renewed"`
+ CheckAgainInSeconds int `json:"check_again_in_seconds"`
+}
+
+// RefreshSession extends the interactive session that authenticated this
+// request, when that session is inside its renewal window.
+//
+// Browsers do not need this endpoint — the auth middleware re-issues their
+// cookie inline on any authenticated safe request. It exists for the clients
+// that carry the session as a string and therefore need the new string back:
+// Desktop (localStorage) and mobile (Keychain). They call it at launch, when
+// returning to the foreground, and on use; the server owns the "is it time
+// yet" decision so no client ever has to read `exp` or trust its own clock.
+//
+// Only our own UI session JWTs are refreshable. A PAT (mul_), an agent task
+// token (mat_) and a cloud-node PAT (mcn_) all authenticate perfectly well at
+// the middleware, and every one of them must be refused here: none of them is
+// an interactive session, and exchanging a machine credential for one would
+// turn a scoped, revocable token into an unscoped, unrevocable one. An
+// expired JWT cannot reach this handler at all (the middleware rejects it),
+// and ShouldRenewSession refuses a non-positive remaining lifetime anyway —
+// renewal extends a live session, it never resurrects a dead one.
+func (h *Handler) RefreshSession(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ // The middleware resolved the credential to a user but does not pass the
+ // raw token forward, and renewal needs the claims themselves. Re-read it
+ // from the same two places extractToken looks, in the same order.
+ rawToken, fromCookie := sessionTokenFromRequest(r)
+ if rawToken == "" {
+ writeError(w, http.StatusBadRequest, "only interactive sessions can be refreshed")
+ return
+ }
+
+ claims, err := auth.ParseSessionToken(rawToken)
+ if err != nil {
+ // Reached by PAT / task-token / cloud-PAT callers: authenticated, but
+ // holding something that is not a session. 400 rather than 401 — the
+ // credential is fine, the request is not.
+ writeError(w, http.StatusBadRequest, "only interactive sessions can be refreshed")
+ return
+ }
+
+ // Defense in depth, mirroring RenewCurrentPersonalAccessToken: the
+ // middleware set X-User-ID from these very claims, so a mismatch means a
+ // header was forged past it. Refuse to mint a session for someone else.
+ if sub, _ := claims["sub"].(string); sub != userID {
+ writeError(w, http.StatusUnauthorized, "token does not belong to caller")
+ return
+ }
+
+ checkAgain := int(auth.SessionRenewCheckInterval().Seconds())
+ expiresAt := auth.SessionExpiry(claims)
+
+ if !auth.ShouldRenewSession(time.Now(), expiresAt) {
+ writeJSON(w, http.StatusOK, RefreshSessionResponse{
+ ExpiresAt: formatSessionExpiry(expiresAt),
+ Renewed: false,
+ CheckAgainInSeconds: checkAgain,
+ })
+ return
+ }
+
+ newToken, newExpiresAt, err := auth.RenewSessionToken(claims)
+ if err != nil {
+ if errors.Is(err, auth.ErrTemporarilyDisabledUser) {
+ writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)
+ return
+ }
+ slog.Warn("session refresh: failed to re-sign token",
+ append(logger.RequestAttrs(r), "error", err, "user_id", userID)...)
+ // The caller's current session is still valid — this failure costs it
+ // nothing but a retry, so answer with the unrenewed state rather than
+ // an error a client might mistake for a dead session.
+ writeJSON(w, http.StatusOK, RefreshSessionResponse{
+ ExpiresAt: formatSessionExpiry(expiresAt),
+ Renewed: false,
+ CheckAgainInSeconds: checkAgain,
+ })
+ return
+ }
+
+ resp := RefreshSessionResponse{
+ ExpiresAt: formatSessionExpiry(newExpiresAt),
+ Renewed: true,
+ CheckAgainInSeconds: checkAgain,
+ }
+
+ if fromCookie {
+ if err := auth.SetAuthCookies(w, newToken); err != nil {
+ slog.Warn("session refresh: failed to set auth cookies",
+ append(logger.RequestAttrs(r), "error", err)...)
+ writeJSON(w, http.StatusOK, RefreshSessionResponse{
+ ExpiresAt: formatSessionExpiry(expiresAt),
+ Renewed: false,
+ CheckAgainInSeconds: checkAgain,
+ })
+ return
+ }
+ if h.CFSigner != nil {
+ for _, cookie := range h.CFSigner.SignedCookies(newExpiresAt) {
+ http.SetCookie(w, cookie)
+ }
+ }
+ } else {
+ resp.Token = newToken
+ }
+
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// sessionTokenFromRequest mirrors middleware.extractToken: Authorization
+// header first, auth cookie second. The bool reports the cookie path, which
+// is what decides whether the renewed token may be written into the response
+// body.
+func sessionTokenFromRequest(r *http.Request) (token string, fromCookie bool) {
+ if authHeader := r.Header.Get("Authorization"); authHeader != "" {
+ if tokenString := strings.TrimPrefix(authHeader, "Bearer "); tokenString != authHeader {
+ return tokenString, false
+ }
+ }
+ if cookie, err := r.Cookie(auth.AuthCookieName); err == nil && cookie.Value != "" {
+ return cookie.Value, true
+ }
+ return "", false
+}
+
+func formatSessionExpiry(t time.Time) string {
+ if t.IsZero() {
+ return ""
+ }
+ return t.UTC().Format(time.RFC3339)
+}
diff --git a/server/internal/handler/session_test.go b/server/internal/handler/session_test.go
new file mode 100644
index 0000000000..f88dc27015
--- /dev/null
+++ b/server/internal/handler/session_test.go
@@ -0,0 +1,197 @@
+package handler
+
+import (
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// refreshSessionToken signs a session for the shared test user.
+//
+// Lifetimes are fractions of auth.AuthRenewThreshold() rather than literal
+// durations: AuthTokenTTL() is cached process-wide behind a sync.Once, so a
+// test cannot assume which value it resolved to.
+func refreshSessionToken(t *testing.T, remaining time.Duration, sid string) string {
+ t.Helper()
+ claims := jwt.MapClaims{
+ "sub": testUserID,
+ "email": handlerTestEmail,
+ "name": handlerTestName,
+ "exp": time.Now().Add(remaining).Unix(),
+ "iat": time.Now().Add(-time.Hour).Unix(),
+ }
+ if sid != "" {
+ claims["sid"] = sid
+ }
+ signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(auth.JWTSecret())
+ if err != nil {
+ t.Fatalf("sign session token: %v", err)
+ }
+ return signed
+}
+
+func bearerRefreshRequest(t *testing.T, token string) *http.Request {
+ t.Helper()
+ req := newRequest("POST", "/api/auth/refresh", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ return req
+}
+
+func cookieRefreshRequest(t *testing.T, token string) *http.Request {
+ t.Helper()
+ req := newRequest("POST", "/api/auth/refresh", nil)
+ req.AddCookie(&http.Cookie{Name: auth.AuthCookieName, Value: token})
+ return req
+}
+
+func TestRefreshSession_RenewsBearerSessionInsideWindow(t *testing.T) {
+ token := refreshSessionToken(t, auth.AuthRenewThreshold()/2, "sid-bearer")
+
+ var resp RefreshSessionResponse
+ testutil.Call(t, testHandler.RefreshSession, bearerRefreshRequest(t, token)).
+ Want(http.StatusOK).JSON(&resp)
+
+ if !resp.Renewed {
+ t.Fatalf("expected renewed=true, got %+v", resp)
+ }
+ if resp.Token == "" {
+ t.Fatal("a bearer client has to receive the new token — it has nowhere else to get it")
+ }
+ if resp.Token == token {
+ t.Error("renewal must produce a different token")
+ }
+ claims, err := auth.ParseSessionToken(resp.Token)
+ if err != nil {
+ t.Fatalf("returned token does not parse: %v", err)
+ }
+ if got, _ := claims["sid"].(string); got != "sid-bearer" {
+ t.Errorf("sid = %q, want sid-bearer — the session identity must survive renewal", got)
+ }
+ if resp.CheckAgainInSeconds <= 0 {
+ t.Error("clients need a server-supplied cadence; they must not invent one")
+ }
+}
+
+// Asking early is a normal answer, not an error: the client polls on a
+// cadence and most calls land outside the window.
+func TestRefreshSession_OutsideWindowIsANoOp(t *testing.T) {
+ token := refreshSessionToken(t, auth.AuthRenewThreshold()+auth.AuthRenewThreshold()/2, "sid-fresh")
+
+ var resp RefreshSessionResponse
+ testutil.Call(t, testHandler.RefreshSession, bearerRefreshRequest(t, token)).
+ Want(http.StatusOK).JSON(&resp)
+
+ if resp.Renewed {
+ t.Error("a session outside the renewal window must not be renewed")
+ }
+ if resp.Token != "" {
+ t.Error("an unrenewed response must not carry a token")
+ }
+ if resp.ExpiresAt == "" {
+ t.Error("the caller still needs to know when the current session ends")
+ }
+}
+
+// The browser's session is HttpOnly for a reason. Renewing it over this
+// endpoint must not hand the JWT back in a body any script can read.
+func TestRefreshSession_CookieModeDoesNotLeakTheToken(t *testing.T) {
+ token := refreshSessionToken(t, auth.AuthRenewThreshold()/2, "sid-cookie")
+
+ var resp RefreshSessionResponse
+ res := testutil.Call(t, testHandler.RefreshSession, cookieRefreshRequest(t, token)).
+ Want(http.StatusOK)
+ res.JSON(&resp)
+
+ if !resp.Renewed {
+ t.Fatalf("expected renewed=true, got %+v", resp)
+ }
+ if resp.Token != "" {
+ t.Error("a cookie-authenticated refresh must not return the JWT in the body")
+ }
+
+ var authCookie *http.Cookie
+ for _, c := range res.Result().Cookies() {
+ if c.Name == auth.AuthCookieName {
+ authCookie = c
+ }
+ }
+ if authCookie == nil {
+ t.Fatal("cookie mode must receive the renewed session as a Set-Cookie")
+ }
+ if !authCookie.HttpOnly {
+ t.Error("the renewed cookie must stay HttpOnly")
+ }
+ if authCookie.Value == token {
+ t.Error("the renewed cookie must carry a new token")
+ }
+}
+
+// Every machine credential the auth middleware accepts authenticates here
+// too. None of them may be exchanged for an interactive session: that would
+// turn a scoped, revocable token into an unscoped, unrevocable one.
+func TestRefreshSession_RejectsNonSessionCredentials(t *testing.T) {
+ cases := map[string]string{
+ "personal access token": "mul_0123456789abcdef0123456789abcdef01234567",
+ "agent task token": "mat_0123456789abcdef0123456789abcdef01234567",
+ "cloud node pat": "mcn_0123456789abcdef0123456789abcdef01234567",
+ }
+ for name, token := range cases {
+ t.Run(name, func(t *testing.T) {
+ testutil.Call(t, testHandler.RefreshSession, bearerRefreshRequest(t, token)).
+ Want(http.StatusBadRequest)
+ })
+ }
+
+ t.Run("no credential at all", func(t *testing.T) {
+ testutil.Call(t, testHandler.RefreshSession, newRequest("POST", "/api/auth/refresh", nil)).
+ Want(http.StatusBadRequest)
+ })
+}
+
+// An expired JWT never reaches this handler in production — the middleware
+// rejects it — but if it ever did, refresh must not be the thing that brings
+// it back to life.
+func TestRefreshSession_DoesNotReviveExpiredSession(t *testing.T) {
+ expired := refreshSessionToken(t, -time.Minute, "sid-dead")
+
+ testutil.Call(t, testHandler.RefreshSession, bearerRefreshRequest(t, expired)).
+ Want(http.StatusBadRequest)
+}
+
+// Defense in depth: X-User-ID is set by the middleware from these very
+// claims, so a mismatch means a header was forged past it.
+func TestRefreshSession_RejectsSubjectMismatch(t *testing.T) {
+ claims := jwt.MapClaims{
+ "sub": "00000000-0000-0000-0000-00000000dead",
+ "email": handlerTestEmail,
+ "exp": time.Now().Add(auth.AuthRenewThreshold() / 2).Unix(),
+ }
+ signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(auth.JWTSecret())
+ if err != nil {
+ t.Fatalf("sign: %v", err)
+ }
+
+ testutil.Call(t, testHandler.RefreshSession, bearerRefreshRequest(t, signed)).
+ Want(http.StatusUnauthorized)
+}
+
+// A legacy session (no sid) refreshes and acquires one, which is how clients
+// already signed in migrate onto the session-bound CSRF binding.
+func TestRefreshSession_MigratesLegacySession(t *testing.T) {
+ legacy := refreshSessionToken(t, auth.AuthRenewThreshold()/2, "")
+
+ var resp RefreshSessionResponse
+ testutil.Call(t, testHandler.RefreshSession, bearerRefreshRequest(t, legacy)).
+ Want(http.StatusOK).JSON(&resp)
+
+ if !resp.Renewed || resp.Token == "" {
+ t.Fatalf("a legacy session inside the window must renew, got %+v", resp)
+ }
+ if auth.SessionIDFromToken(resp.Token) == "" {
+ t.Error("the refreshed legacy session must carry a session id")
+ }
+}
diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.go
index 2551c448d8..e9bd644fe6 100644
--- a/server/internal/middleware/auth.go
+++ b/server/internal/middleware/auth.go
@@ -43,12 +43,20 @@ func rejectTemporarilyDisabledUser(w http.ResponseWriter, r *http.Request, userI
// SELECT and the last_used_at UPDATE — last_used_at is therefore refreshed
// at most once per TTL window per token, not per request.
//
+// cfSigner is optional; when non-nil, a session renewed here also gets fresh
+// CloudFront cookies. It is wired into THIS middleware rather than left to
+// RefreshCloudFrontCookies because renewal is what makes the two clocks
+// diverge: every route group that can renew must re-sign, and only the
+// renewer knows it renewed. A group that mounts Auth without the CDN
+// middleware (the plugin bridge) would otherwise slide the session forward
+// while leaving the CDN policy pinned to the original login.
+//
// cloudPAT is optional; when non-nil, tokens with the mcn_ prefix are
// validated by calling the Multica Cloud Fleet service rather than the
// local DB. When nil (Fleet URL unset) mcn_ tokens are rejected at the
// prefix branch — we don't fall through to the mul_ / JWT paths, since
// an mcn_ string is by construction not a valid mul_ PAT or JWT.
-func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATVerifier) func(http.Handler) http.Handler {
+func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATVerifier, cfSigner *auth.CloudFrontSigner) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// X-Actor-Source is server-set only — any value supplied by
@@ -276,6 +284,12 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATV
r.Header.Set("X-User-Email", email)
}
+ // Sliding session: a browser that keeps using the app keeps its
+ // cookie, instead of being logged out on the anniversary of its
+ // login. No-op until the session drops below half its TTL
+ // (MUL-7436).
+ r = renewCookieSession(w, r, claims, fromCookie, cfSigner)
+
next.ServeHTTP(w, r)
})
}
diff --git a/server/internal/middleware/auth_test.go b/server/internal/middleware/auth_test.go
index efd3cf01e0..8d019d6a66 100644
--- a/server/internal/middleware/auth_test.go
+++ b/server/internal/middleware/auth_test.go
@@ -61,7 +61,7 @@ func validClaims() jwt.MapClaims {
// authMiddleware returns the Auth middleware with nil queries (JWT-only tests).
func authMiddleware(next http.Handler) http.Handler {
- return Auth(nil, nil, nil)(next)
+ return Auth(nil, nil, nil, nil)(next)
}
func TestAuth_MissingHeader(t *testing.T) {
@@ -280,7 +280,7 @@ func TestAuth_InvalidPAT(t *testing.T) {
// boundary MUL-2600 introduces.
func TestAuth_StripsClientSuppliedActorSource(t *testing.T) {
var gotActorSource string
- mw := Auth(nil, nil, nil)
+ mw := Auth(nil, nil, nil, nil)
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotActorSource = r.Header.Get("X-Actor-Source")
w.WriteHeader(http.StatusOK)
@@ -315,7 +315,7 @@ func TestAuth_StripsClientSuppliedActorSource(t *testing.T) {
// since MUL-6951, act with the authority of that run's originator. MUL-3428.
func TestAuth_StripsForgedAgentIdentityHeaders(t *testing.T) {
var gotAgentID, gotTaskID string
- mw := Auth(nil, nil, nil)
+ mw := Auth(nil, nil, nil, nil)
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAgentID = r.Header.Get("X-Agent-ID")
gotTaskID = r.Header.Get("X-Task-ID")
@@ -358,7 +358,7 @@ func TestAuth_PATCacheHit(t *testing.T) {
cache.Set(context.Background(), hash, "cached-user-id", auth.AuthCacheTTL)
var gotUserID string
- mw := Auth(nil, cache, nil) // nil queries — only safe on cache hit
+ mw := Auth(nil, cache, nil, nil) // nil queries — only safe on cache hit
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUserID = r.Header.Get("X-User-ID")
w.WriteHeader(http.StatusOK)
@@ -383,7 +383,7 @@ func TestAuth_PATCacheHit(t *testing.T) {
// We don't fall through — an mcn_ string can't be a valid mul_ PAT or
// JWT, so any fall-through would be wasted work.
func TestAuth_MCN_NoVerifierConfigured(t *testing.T) {
- mw := Auth(nil, nil, nil)
+ mw := Auth(nil, nil, nil, nil)
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("next must not be called when verifier is unconfigured")
}))
@@ -412,7 +412,7 @@ func TestAuth_MCN_ValidTokenSetsUserID(t *testing.T) {
verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})
var gotUser, gotActorSource string
- mw := Auth(nil, nil, verifier)
+ mw := Auth(nil, nil, verifier, nil)
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUser = r.Header.Get("X-User-ID")
gotActorSource = r.Header.Get("X-Actor-Source")
@@ -450,7 +450,7 @@ func TestAuth_MCN_InvalidReturns401(t *testing.T) {
defer srv.Close()
verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})
- mw := Auth(nil, nil, verifier)
+ mw := Auth(nil, nil, verifier, nil)
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("next must not be called when token is invalid")
}))
@@ -474,7 +474,7 @@ func TestAuth_MCN_FleetUnreachableReturns503(t *testing.T) {
defer srv.Close()
verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})
- mw := Auth(nil, nil, verifier)
+ mw := Auth(nil, nil, verifier, nil)
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("next must not be called when fleet is unavailable")
}))
diff --git a/server/internal/middleware/cloudfront.go b/server/internal/middleware/cloudfront.go
index 79621b5efd..52d67ad914 100644
--- a/server/internal/middleware/cloudfront.go
+++ b/server/internal/middleware/cloudfront.go
@@ -11,13 +11,20 @@ import (
// on authenticated requests when the cookie is missing (expired or first request
// after login). This prevents 403s from the CDN when cookies expire before the
// user's session does.
+//
+// Renewal-time re-signing is NOT done here — it belongs to the auth
+// middleware, which is the only place that knows a session was renewed and is
+// mounted on every group that can renew one. This middleware only skips its
+// own work when that already happened, so a single response does not carry
+// two sets of CDN cookies (MUL-7436).
func RefreshCloudFrontCookies(signer *auth.CloudFrontSigner) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
if signer == nil {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if _, err := r.Cookie("CloudFront-Policy"); err != nil {
+ _, err := r.Cookie("CloudFront-Policy")
+ if err != nil && !SessionRenewed(r) {
ttl := auth.AuthTokenTTL()
for _, cookie := range signer.SignedCookies(time.Now().Add(ttl)) {
http.SetCookie(w, cookie)
diff --git a/server/internal/middleware/cloudfront_test.go b/server/internal/middleware/cloudfront_test.go
index f48bd2afa2..3f0273eaa5 100644
--- a/server/internal/middleware/cloudfront_test.go
+++ b/server/internal/middleware/cloudfront_test.go
@@ -101,3 +101,100 @@ func TestRefreshCloudFrontCookies_SkipsWhenCookiePresent(t *testing.T) {
t.Error("should not refresh cookies when CloudFront-Policy is already present")
}
}
+
+// The CDN cookies are signed for the lifetime of the session that created
+// them. Once sessions slide, a renewal that did not re-sign would leave the
+// policy pinned to the original login — and a session that now never expires
+// would 403 every asset once that policy lapsed.
+func TestAuth_ReSignsCloudFrontCookiesOnRenewal(t *testing.T) {
+ signer := testSigner(t)
+
+ var served bool
+ handler := Auth(nil, nil, nil, signer)(
+ RefreshCloudFrontCookies(signer)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ served = true
+ w.WriteHeader(http.StatusOK)
+ })),
+ )
+
+ req := cookieRequest(http.MethodGet, sessionToken(t, auth.AuthRenewThreshold()/2, "sid-cdn"))
+ // A live CloudFront policy is already present: without the renewal there
+ // would be nothing to do.
+ req.AddCookie(&http.Cookie{Name: "CloudFront-Policy", Value: "existing-policy"})
+
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if !served {
+ t.Fatal("request must still be served")
+ }
+ policies := cloudFrontPolicies(rec)
+ if len(policies) == 0 {
+ t.Fatal("a renewed session must re-sign the CloudFront cookies")
+ }
+ if policies[0].Value == "existing-policy" {
+ t.Error("CloudFront policy was not re-signed")
+ }
+ if !policies[0].Expires.After(time.Now().Add(auth.AuthRenewThreshold())) {
+ t.Errorf("re-signed CloudFront cookie expires at %s, which is not past the renewal threshold", policies[0].Expires)
+ }
+ // Exactly one: Auth re-signed, so RefreshCloudFrontCookies must stand down
+ // rather than put a second set on the same response.
+ if len(policies) != 1 {
+ t.Errorf("got %d CloudFront-Policy cookies, want exactly 1", len(policies))
+ }
+}
+
+// Not every group that mounts Auth also mounts RefreshCloudFrontCookies — the
+// plugin bridge does not. Renewal lives in Auth, so a safe GET there can slide
+// the session forward; if the CDN sync lived in the other middleware, that
+// route would leave the policy behind and 403 assets at the original TTL.
+func TestAuth_ReSignsCloudFrontCookiesWithoutTheCDNMiddleware(t *testing.T) {
+ signer := testSigner(t)
+
+ handler := Auth(nil, nil, nil, signer)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := cookieRequest(http.MethodGet, sessionToken(t, auth.AuthRenewThreshold()/2, "sid-bridge"))
+ req.AddCookie(&http.Cookie{Name: "CloudFront-Policy", Value: "existing-policy"})
+
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ policies := cloudFrontPolicies(rec)
+ if len(policies) != 1 || policies[0].Value == "existing-policy" {
+ t.Fatalf("a renewal on an Auth-only route must re-sign the CDN cookies, got %d cookie(s)", len(policies))
+ }
+}
+
+// Without a renewal, an existing policy cookie is still left alone — this is
+// the pre-existing behaviour and the reason responses aren't full of
+// Set-Cookie headers.
+func TestRefreshCloudFrontCookies_LeavesLivePolicyAloneWithoutRenewal(t *testing.T) {
+ signer := testSigner(t)
+
+ handler := RefreshCloudFrontCookies(signer)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.AddCookie(&http.Cookie{Name: "CloudFront-Policy", Value: "existing-policy"})
+
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if len(rec.Result().Cookies()) != 0 {
+ t.Error("an unrenewed request with a live policy must not re-sign")
+ }
+}
+
+func cloudFrontPolicies(rec *httptest.ResponseRecorder) []*http.Cookie {
+ var out []*http.Cookie
+ for _, c := range rec.Result().Cookies() {
+ if c.Name == "CloudFront-Policy" {
+ out = append(out, c)
+ }
+ }
+ return out
+}
diff --git a/server/internal/middleware/session_renewal.go b/server/internal/middleware/session_renewal.go
new file mode 100644
index 0000000000..75cd3d502e
--- /dev/null
+++ b/server/internal/middleware/session_renewal.go
@@ -0,0 +1,81 @@
+package middleware
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/multica-ai/multica/server/internal/auth"
+)
+
+type sessionRenewedCtxKey struct{}
+
+// SessionRenewed reports whether the auth middleware re-issued this request's
+// session cookie. RefreshCloudFrontCookies reads it so the CDN cookies are
+// re-signed in lockstep with the session instead of drifting until they
+// expire on their own.
+func SessionRenewed(r *http.Request) bool {
+ renewed, _ := r.Context().Value(sessionRenewedCtxKey{}).(bool)
+ return renewed
+}
+
+// renewCookieSession re-issues the browser's auth cookie when the session
+// that authenticated this request has dropped below half its TTL. It returns
+// the request to pass downstream — the same one when nothing was renewed.
+//
+// Three conditions gate it, and each rules out a specific way this could go
+// wrong:
+//
+// - Cookie auth only. A bearer-token client keeps its session in its own
+// storage; a Set-Cookie it never reads would leave the two copies
+// disagreeing about when the session ends. Those clients call
+// POST /api/auth/refresh instead.
+// - Safe methods only. Re-issuing the cookie changes the value the CSRF
+// token is checked against for pre-MUL-7436 cookies, so confining it to
+// methods that carry no CSRF check means a rotation can never invalidate
+// the very request that triggered it.
+// - Inside the renewal window. Outside it there is nothing to do, and
+// re-signing on every request would put a Set-Cookie on every response
+// for no gain.
+//
+// Every failure below is non-fatal and silent to the caller: the session that
+// authenticated this request is still valid for at least another TTL/2, so a
+// failed renewal costs one more chance at it, not the session.
+func renewCookieSession(w http.ResponseWriter, r *http.Request, claims jwt.MapClaims, fromCookie bool, cfSigner *auth.CloudFrontSigner) *http.Request {
+ if !fromCookie || !auth.IsSafeMethod(r.Method) {
+ return r
+ }
+ if !auth.ShouldRenewSession(time.Now(), auth.SessionExpiry(claims)) {
+ return r
+ }
+
+ token, expiresAt, err := auth.RenewSessionToken(claims)
+ if err != nil {
+ slog.Debug("auth: session renewal skipped", "path", r.URL.Path, "error", err)
+ return r
+ }
+
+ // Headers must be written before the handler starts the response body,
+ // which is why this runs ahead of next.ServeHTTP rather than after.
+ if err := auth.SetAuthCookies(w, token); err != nil {
+ slog.Warn("auth: failed to set renewed session cookies", "path", r.URL.Path, "error", err)
+ return r
+ }
+
+ // The CDN cookies are signed for the lifetime of the session that created
+ // them, so a renewal that did not re-sign would leave the policy pinned to
+ // the original login — and a session that now never expires would 403
+ // every image and attachment once that policy lapsed. Re-signing here,
+ // next to the renewal itself, is what keeps the two in lockstep on EVERY
+ // route group that can renew, not only the ones that also mount
+ // RefreshCloudFrontCookies.
+ if cfSigner != nil {
+ for _, cookie := range cfSigner.SignedCookies(expiresAt) {
+ http.SetCookie(w, cookie)
+ }
+ }
+
+ return r.WithContext(context.WithValue(r.Context(), sessionRenewedCtxKey{}, true))
+}
diff --git a/server/internal/middleware/session_renewal_test.go b/server/internal/middleware/session_renewal_test.go
new file mode 100644
index 0000000000..995a061e59
--- /dev/null
+++ b/server/internal/middleware/session_renewal_test.go
@@ -0,0 +1,355 @@
+package middleware
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/multica-ai/multica/server/internal/auth"
+)
+
+// sessionToken signs a cookie-mode session expiring `remaining` from now.
+//
+// Lifetimes are expressed as FRACTIONS of auth.AuthRenewThreshold(), never as
+// literal durations or offsets from it. AuthTokenTTL() is cached behind a
+// sync.Once for the life of the process, so whichever test in this package
+// touches it first decides the TTL every later test sees — currently
+// TestRefreshCloudFrontCookies_UsesAuthTokenTTL, which pins it to one hour.
+// A fraction holds whatever that value turns out to be.
+func sessionToken(t *testing.T, remaining time.Duration, sid string) string {
+ t.Helper()
+ claims := jwt.MapClaims{
+ "sub": "test-user-id",
+ "email": "[email protected]",
+ "exp": time.Now().Add(remaining).Unix(),
+ "iat": time.Now().Add(-time.Hour).Unix(),
+ }
+ if sid != "" {
+ claims["sid"] = sid
+ }
+ return generateToken(claims, auth.JWTSecret())
+}
+
+func cookieRequest(method, token string) *http.Request {
+ req := httptest.NewRequest(method, "/api/issues", nil)
+ req.AddCookie(&http.Cookie{Name: auth.AuthCookieName, Value: token})
+ return req
+}
+
+// renewedAuthCookie returns the auth cookie the middleware set, or "" when it
+// set none.
+func renewedAuthCookie(rec *httptest.ResponseRecorder) string {
+ for _, c := range rec.Result().Cookies() {
+ if c.Name == auth.AuthCookieName {
+ return c.Value
+ }
+ }
+ return ""
+}
+
+func runAuth(t *testing.T, req *http.Request) (*httptest.ResponseRecorder, bool) {
+ t.Helper()
+ called := false
+ handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+ return rec, called
+}
+
+func TestAuth_RenewsCookieSessionInsideWindow(t *testing.T) {
+ original := sessionToken(t, auth.AuthRenewThreshold()/2, "sid-renew")
+
+ rec, called := runAuth(t, cookieRequest(http.MethodGet, original))
+ if !called {
+ t.Fatal("request must still be served")
+ }
+
+ renewed := renewedAuthCookie(rec)
+ if renewed == "" {
+ t.Fatal("expected a renewed auth cookie")
+ }
+ if renewed == original {
+ t.Fatal("renewed cookie must carry a new token")
+ }
+
+ claims, err := auth.ParseSessionToken(renewed)
+ if err != nil {
+ t.Fatalf("renewed token does not parse: %v", err)
+ }
+ if got, _ := claims["sub"].(string); got != "test-user-id" {
+ t.Errorf("renewed sub = %q, want test-user-id", got)
+ }
+ // The session identity is what CSRF is bound to; renewal must not change it.
+ if got, _ := claims["sid"].(string); got != "sid-renew" {
+ t.Errorf("renewed sid = %q, want sid-renew", got)
+ }
+ if remaining := time.Until(auth.SessionExpiry(claims)); remaining <= auth.AuthRenewThreshold() {
+ t.Errorf("renewed session has %s left, expected more than the renewal threshold", remaining)
+ }
+}
+
+// Outside the window there is nothing to do, and a Set-Cookie on every
+// response would be pure noise.
+func TestAuth_DoesNotRenewOutsideWindow(t *testing.T) {
+ token := sessionToken(t, auth.AuthRenewThreshold()+auth.AuthRenewThreshold()/2, "sid-fresh")
+
+ rec, called := runAuth(t, cookieRequest(http.MethodGet, token))
+ if !called {
+ t.Fatal("request must still be served")
+ }
+ if got := renewedAuthCookie(rec); got != "" {
+ t.Error("a session outside the renewal window must not be re-issued")
+ }
+}
+
+// Rotating the auth cookie changes what a pre-MUL-7436 CSRF token is checked
+// against. Confining renewal to methods that carry no CSRF check means a
+// rotation can never invalidate the request that triggered it.
+func TestAuth_DoesNotRenewOnStateChangingMethods(t *testing.T) {
+ for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} {
+ t.Run(method, func(t *testing.T) {
+ token := sessionToken(t, auth.AuthRenewThreshold()/2, "sid-x")
+ req := cookieRequest(method, token)
+ // Cookie-mode writes need a valid CSRF token to get past the gate.
+ rec := httptest.NewRecorder()
+ if err := auth.SetAuthCookies(rec, token); err != nil {
+ t.Fatalf("SetAuthCookies: %v", err)
+ }
+ for _, c := range rec.Result().Cookies() {
+ if c.Name == auth.CSRFCookieName {
+ req.Header.Set("X-CSRF-Token", c.Value)
+ }
+ }
+
+ got, called := runAuth(t, req)
+ if !called {
+ t.Fatalf("%s request must still be served (status %d)", method, got.Code)
+ }
+ if cookie := renewedAuthCookie(got); cookie != "" {
+ t.Errorf("%s must not re-issue the auth cookie", method)
+ }
+ })
+ }
+}
+
+// A bearer-token client keeps the session in its own storage. A Set-Cookie it
+// never reads would leave the server and the client disagreeing about when
+// the session ends; those clients call POST /api/auth/refresh instead.
+func TestAuth_DoesNotRenewBearerSessions(t *testing.T) {
+ token := sessionToken(t, auth.AuthRenewThreshold()/2, "sid-bearer")
+ req := httptest.NewRequest(http.MethodGet, "/api/issues", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+
+ rec, called := runAuth(t, req)
+ if !called {
+ t.Fatal("request must still be served")
+ }
+ if got := renewedAuthCookie(rec); got != "" {
+ t.Error("a bearer-authenticated request must not be answered with a session cookie")
+ }
+}
+
+// Renewal extends a live session. An expired one is rejected outright — it
+// must not be renewed on the way to a 401, nor turned back into a live
+// session.
+func TestAuth_ExpiredCookieSessionIsRejectedNotRenewed(t *testing.T) {
+ expired := sessionToken(t, -time.Minute, "sid-dead")
+
+ rec, called := runAuth(t, cookieRequest(http.MethodGet, expired))
+ if called {
+ t.Fatal("an expired session must not authenticate")
+ }
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401", rec.Code)
+ }
+ if got := renewedAuthCookie(rec); got != "" {
+ t.Error("an expired session must not be re-issued")
+ }
+}
+
+// A session minted before `sid` existed renews and acquires one — this is how
+// everyone already signed in migrates onto the session-bound CSRF binding.
+func TestAuth_RenewsLegacySessionAndMintsSessionID(t *testing.T) {
+ legacy := sessionToken(t, auth.AuthRenewThreshold()/2, "")
+
+ rec, called := runAuth(t, cookieRequest(http.MethodGet, legacy))
+ if !called {
+ t.Fatal("request must still be served")
+ }
+ renewed := renewedAuthCookie(rec)
+ if renewed == "" {
+ t.Fatal("a legacy session inside the window must be renewed")
+ }
+ if auth.SessionIDFromToken(renewed) == "" {
+ t.Error("the renewed legacy session must carry a session id")
+ }
+}
+
+// Renewal is only ever reached from the JWT branch. An opaque credential has
+// no claims to copy forward and must pass through untouched.
+func TestAuth_DoesNotRenewOpaqueCredentials(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/issues", nil)
+ req.AddCookie(&http.Cookie{Name: auth.AuthCookieName, Value: "mul_0123456789abcdef0123456789abcdef01234567"})
+
+ rec, called := runAuth(t, req)
+ if called {
+ t.Fatal("an opaque token in the auth cookie must not authenticate as a session")
+ }
+ if got := renewedAuthCookie(rec); got != "" {
+ t.Error("an opaque credential must not produce a session cookie")
+ }
+}
+
+// The renewed cookie has to be a complete, usable session cookie — same
+// HttpOnly/Secure/SameSite posture as the one login sets, and accompanied by
+// a CSRF cookie. A renewal that drops HttpOnly would quietly downgrade every
+// browser session to a readable token.
+func TestAuth_RenewedCookiesKeepTheirSecurityPosture(t *testing.T) {
+ t.Setenv("FRONTEND_ORIGIN", "https://app.example.com")
+
+ rec, _ := runAuth(t, cookieRequest(http.MethodGet, sessionToken(t, auth.AuthRenewThreshold()/2, "sid-posture")))
+
+ var authCookie, csrfCookie *http.Cookie
+ for _, c := range rec.Result().Cookies() {
+ switch c.Name {
+ case auth.AuthCookieName:
+ authCookie = c
+ case auth.CSRFCookieName:
+ csrfCookie = c
+ }
+ }
+ if authCookie == nil {
+ t.Fatal("expected a renewed auth cookie")
+ }
+ if !authCookie.HttpOnly {
+ t.Error("renewed auth cookie must stay HttpOnly")
+ }
+ if !authCookie.Secure {
+ t.Error("renewed auth cookie must stay Secure on an https origin")
+ }
+ if authCookie.SameSite != http.SameSiteStrictMode {
+ t.Errorf("renewed auth cookie SameSite = %v, want Strict", authCookie.SameSite)
+ }
+ if csrfCookie == nil {
+ t.Fatal("renewal must also refresh the CSRF cookie")
+ }
+ if csrfCookie.HttpOnly {
+ t.Error("CSRF cookie must stay readable by the client")
+ }
+}
+
+// csrfHeadersFor runs the real cookie-setting path for mintedFor and copies
+// both CSRF cookies onto req as the headers a browser would echo back.
+//
+// mintedFor is a separate argument from the request's auth cookie on purpose:
+// a browser receives its CSRF cookies while the session is LIVE and keeps
+// presenting them afterwards, so a test about an expired session has to mint
+// from the live token and then present the expired one. Minting from the
+// expired token instead would be a scenario no browser can produce.
+func csrfHeadersFor(t *testing.T, req *http.Request, mintedFor string) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ if err := auth.SetAuthCookies(rec, mintedFor); err != nil {
+ t.Fatalf("SetAuthCookies: %v", err)
+ }
+ // Clients prefer the session-bound cookie, so mirror that here: the one
+ // header carries it when present, and the token-bound value otherwise.
+ var tokenBound string
+ for _, c := range rec.Result().Cookies() {
+ switch c.Name {
+ case auth.CSRFCookieName:
+ tokenBound = c.Value
+ case auth.SessionCSRFCookieName:
+ req.Header.Set(auth.CSRFHeaderName, c.Value)
+ }
+ }
+ if req.Header.Get(auth.CSRFHeaderName) == "" {
+ req.Header.Set(auth.CSRFHeaderName, tokenBound)
+ }
+}
+
+// A user whose session expired must be told their session expired. The CSRF
+// gate runs before the JWT is validated, so if it rejected an expired cookie
+// the user's first action after expiry — sending a comment, saving a setting —
+// answered 403 "CSRF validation failed" and the client just retried a failed
+// write. Only the 401 reaches the session-expiry path that returns them to the
+// login page, so CSRF has to let an expired-but-genuine cookie through and let
+// authentication be the thing that refuses it.
+func TestAuth_ExpiredSessionFailsAuthenticationNotCSRF(t *testing.T) {
+ // One session: cookies issued while it was live, presented after its JWT
+ // expired. `sid` is what ties the two together.
+ live := sessionToken(t, auth.AuthRenewThreshold()*2, "sid-expired")
+ expired := sessionToken(t, -time.Minute, "sid-expired")
+
+ req := cookieRequest(http.MethodPost, expired)
+ csrfHeadersFor(t, req, live)
+
+ rec, called := runAuth(t, req)
+ if called {
+ t.Fatal("an expired session must not authenticate")
+ }
+ if rec.Code == http.StatusForbidden {
+ t.Fatal("expired session was rejected by the CSRF gate; the client never learns the session ended")
+ }
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401", rec.Code)
+ }
+}
+
+// A client echoing the SESSION-bound value is the case that isolates the fix:
+// that value verifies only through `sid`, so if `sid` cannot be read from an
+// expired cookie there is no second binding to fall back on. It is also the
+// steady state, since the token-bound cookie goes away a release from now.
+func TestAuth_ExpiredSessionWithOnlySessionCSRFStillGets401(t *testing.T) {
+ live := sessionToken(t, auth.AuthRenewThreshold()*2, "sid-expired-only")
+ expired := sessionToken(t, -time.Minute, "sid-expired-only")
+
+ req := cookieRequest(http.MethodPost, expired)
+ csrfHeadersFor(t, req, live)
+ if req.Header.Get(auth.CSRFHeaderName) == "" {
+ t.Fatal("test needs a CSRF header carrying the session-bound value")
+ }
+
+ rec, called := runAuth(t, req)
+ if called {
+ t.Fatal("an expired session must not authenticate")
+ }
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401 (403 means the CSRF gate refused it first)", rec.Code)
+ }
+}
+
+// The same for a session that expired while carrying only the legacy cookie
+// pair — those users exist too until their session renews.
+func TestAuth_ExpiredLegacySessionFailsAuthenticationNotCSRF(t *testing.T) {
+ expired := sessionToken(t, -time.Minute, "")
+
+ req := cookieRequest(http.MethodPost, expired)
+ csrfHeadersFor(t, req, expired)
+
+ rec, _ := runAuth(t, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401 (got %d; 403 means CSRF refused it first)", rec.Code, rec.Code)
+ }
+}
+
+// A live session still has to pass the CSRF gate on a write — the fix above
+// must not have turned the gate off.
+func TestAuth_LiveSessionStillRequiresCSRF(t *testing.T) {
+ token := sessionToken(t, auth.AuthRenewThreshold()*2, "sid-live")
+
+ withHeaders := cookieRequest(http.MethodPost, token)
+ csrfHeadersFor(t, withHeaders, token)
+ if _, called := runAuth(t, withHeaders); !called {
+ t.Error("a live session with valid CSRF headers must be served")
+ }
+
+ if rec, called := runAuth(t, cookieRequest(http.MethodPost, token)); called || rec.Code != http.StatusForbidden {
+ t.Errorf("a write with no CSRF header must be 403, got %d (served=%v)", rec.Code, called)
+ }
+}