Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Admin SPA Authentication hardening (#13990)

Damian Legawiecf0bd93024c8b
diff --git a/CLAUDE.md b/CLAUDE.md
index ca94fb30d3..9c54c352c4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -38,6 +38,7 @@ Current plans:
- `5.4-6.0-custom-fields-rename.md` — Rename Metafields → Custom Fields (5.4 API bridge + 6.0 model rename)
- `5.4-centralized-translations-admin.md` — Centralized Translations admin page under Products, overview grid + bulk CSV import/export
- `5.4-metafield-translations.md` — Translate MetafieldDefinition names + Metafield text values (ShortText, LongText, RichText) via Mobility translation tables
+- `5.5-admin-auth-cookie-refresh.md` — Move admin SPA refresh token to httpOnly cookie, access token in memory, double-submit CSRF, server-side logout that destroys RefreshToken row. Breaking change shipped as a single coordinated bump (admin-sdk is unreleased)
Completed plans:
- `5.4-store-api-bridges.md` — Bridge 6.0 naming into 5.4 Store API (implemented, PR #13782)
diff --git a/docs/plans/5.5-admin-auth-cookie-refresh.md b/docs/plans/5.5-admin-auth-cookie-refresh.md
new file mode 100644
index 0000000000..ae06490965
--- /dev/null
+++ b/docs/plans/5.5-admin-auth-cookie-refresh.md
@@ -0,0 +1,246 @@
+# Admin Auth — Cookie-Backed Refresh Tokens
+
+**Status:** Design Finalized — implementation on PR for Spree 5.5
+**Target:** Spree 5.5
+**Depends on:** `6.0-admin-spa.md`
+**Related:** `6.0-platform-auth.md` (broader auth direction, lands in 6.0)
+**Author:** Damian Legawiec
+**Last updated:** 2026-05-06
+
+## Summary
+
+The Admin SPA currently stores both the JWT access token and the long-lived refresh token in `localStorage`, where any JavaScript on the page can read them. This plan moves the refresh token into an `HttpOnly` signed cookie scoped to `/api/v3/admin/auth`, keeps the short-lived access token in JS memory only, and introduces a real server-side logout that destroys the `Spree::RefreshToken` row. Server-to-server integrations using secret API keys are unaffected.
+
+The design follows Saleor's storefront Auth SDK pattern — access token in memory, refresh token in httpOnly cookie — adapted to our existing `Spree::RefreshToken` rotation infrastructure. CSRF protection is delivered by the **`SameSite` + CORS allowlist** combination already in place; no separate CSRF token is issued.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Refresh token delivery:** `Set-Cookie` on `/auth/login` and `/auth/refresh`. Never returned in the JSON response body.
+- **Cookie attributes:** `HttpOnly; SameSite=Lax; Path=/api/v3/admin/auth` in dev, `HttpOnly; Secure; SameSite=None; Path=/api/v3/admin/auth` in production. Cookie is **signed** via Rails `cookies.signed` for tamper-evidence.
+- **Cookie name:** `spree_admin_refresh_token`.
+- **Access token storage:** React state only. No `localStorage`, no `sessionStorage`.
+- **CSRF protection:** Provided by the combination of (a) `SameSite=Lax`/`SameSite=None` cookie attributes and (b) `Spree::AllowedOrigin` enforced via `Rack::Cors` with `credentials: true`. **No separate CSRF token is issued or verified.** Reasoning: a cross-origin attacker cannot pass the CORS preflight (Origin not on the allowlist), and `SameSite` blocks cross-site form/POST autosubmits independently. A double-submit token would only add value if the AllowedOrigin allowlist were misconfigured (`*`) or if XSS happened on a different allowlisted origin — both scenarios where deeper problems outweigh the CSRF mitigation, and where an in-memory CSRF token has the same XSS exposure as the access token anyway.
+- **Cookie scope:** `Path=/api/v3/admin/auth` so the refresh cookie is only sent to login/refresh/logout, never on `/products`, `/orders`, etc.
+- **Logout:** new `POST /api/v3/admin/auth/logout` endpoint clears the cookie via `Set-Cookie` with `Max-Age=0` and destroys the `Spree::RefreshToken` row server-side (matching the hard-delete pattern in `RefreshToken#rotate!`). Idempotent — succeeds even when no session exists.
+- **No special-casing for secret-key clients:** secret-key flows never hit `/auth/login` (they use the key directly). The backend sets cookies unconditionally on login responses; non-browser clients ignore `Set-Cookie`.
+- **Local development:** uses Vite proxy (`/api/*` → `:3000`) so the SPA is same-origin with the API. Cookie attributes are environment-conditional: `SameSite=Lax` without `Secure` in dev, `SameSite=None; Secure` in production.
+- **Bootstrap:** SPA calls `/auth/refresh` on cold load before rendering authenticated routes. Success → in-memory access token, render. Failure → render `/login`.
+- **No backwards compatibility window:** `@spree/admin-sdk` is unreleased (Developer Preview, `next` dist-tag) so we don't need a transition period. The 5.5 release ships the cookie-only contract directly: refresh token only via cookie, no `refresh_token` field in response bodies, no `params[:refresh_token]` body fallback.
+- **Admin JWT TTL is 5 minutes (separate from storefront).** A new `Spree::Api::Config[:admin_jwt_expiration]` (default 300s) is consumed only by `Spree::Api::V3::Admin::AuthController#jwt_expiration`. The general `Spree::Api::Config[:jwt_expiration]` (default 3600s) continues to govern Store API tokens — customer JWTs have lower blast radius and don't justify the refresh chatter. SPA's background refresh schedule is `4m30s` (30s before expiry); 401-driven refresh handles the rest.
+- **CORS:** no changes. `Spree::AllowedOrigin` + `credentials: true` on `/api/v3/admin/*` already supports browser cookies.
+
+## Design Details
+
+### Cookie contract
+
+| Cookie | Attributes (production) | Attributes (development) | Set on | Cleared on |
+|---|---|---|---|---|
+| `spree_admin_refresh_token` | `HttpOnly; Secure; SameSite=None; Path=/api/v3/admin/auth` (signed) | `HttpOnly; SameSite=Lax; Path=/api/v3/admin/auth` (signed) | `/auth/login`, `/auth/refresh` (rotation) | `/auth/logout`, refresh failure |
+
+Cookie expiry: `Max-Age` matches the refresh token's natural lifetime (`Spree::RefreshToken` config, default 30 days). On refresh, the cookie is re-issued with the new value and a fresh `Max-Age` (sliding window).
+
+### Why no CSRF token?
+
+Classic CSRF assumes the attacker can trigger an authenticated request from a different origin and only needs the cookie to be auto-attached. Three independent defenses already block this for our setup:
+
+1. **`SameSite=Lax`** (dev) blocks cross-site POSTs entirely. The cookie won't be attached.
+2. **`SameSite=None; Secure`** (prod) is the only mode that allows cross-site cookie attachment, and it is constrained by:
+3. **CORS preflight + `Spree::AllowedOrigin`** — for any cross-origin authenticated POST, the browser sends an `OPTIONS` preflight. `Rack::Cors` echoes `Access-Control-Allow-Origin` only for origins on `Spree::AllowedOrigin`. An attacker's origin (`evil.com`) is not on the allowlist, the preflight fails, and the browser blocks the actual POST. The cookie is never sent.
+
+A double-submit CSRF token would only add value in two narrow scenarios:
+- A merchant misconfigures `AllowedOrigin` (e.g. adds `*`). The CSRF token would still hold, but this is "defense against the merchant breaking their own allowlist."
+- XSS on a *different* allowlisted origin (e.g. their storefront). An in-memory CSRF token would technically not be readable from the storefront's JS, but at that point the attacker controls a trusted page and can do significantly more damage than CSRF would unlock.
+
+Storing the CSRF token in `localStorage` or JS memory gives it the same XSS exposure profile as the access token — when XSS lands on the admin SPA itself, both leak together. So a CSRF token wouldn't add real defense over what we already have, while adding real complexity (cookie/header plumbing, edge cases around rotation, document.cookie reads). Skipped deliberately.
+
+### Backend — `Spree::Api::V3::Admin::AuthController`
+
+#### `POST /api/v3/admin/auth/login`
+
+Request body unchanged: `{ email, password, provider? }`.
+
+Response body:
+```json
+{
+ "token": "eyJ...",
+ "user": { ... }
+}
+```
+
+`Set-Cookie` header:
+- `spree_admin_refresh_token=<signed_value>; HttpOnly; Secure; SameSite=None; Path=/api/v3/admin/auth; Max-Age=2592000` (production)
+- `spree_admin_refresh_token=<signed_value>; HttpOnly; SameSite=Lax; Path=/api/v3/admin/auth; Max-Age=2592000` (development)
+
+#### `POST /api/v3/admin/auth/refresh`
+
+Request: empty body. Reads refresh token from `cookies.signed[:spree_admin_refresh_token]`.
+
+If cookie missing → 401 `invalid_refresh_token`.
+If cookie present but `Spree::RefreshToken.active.find_by(token: ...)` returns nil → clear the cookie and return 401 `invalid_refresh_token` (the cookie pointed to a revoked or expired row).
+On success → rotate the row (`RefreshToken#rotate!`), set the new cookie, return `{ token, user }`.
+
+#### `POST /api/v3/admin/auth/logout`
+
+Request: empty body. No CSRF check; the only credential is the cookie. (CSRF defense applies via SameSite + CORS as described above.)
+
+Behavior:
+- Look up `Spree::RefreshToken.active.find_by(token: cookie_value)`.
+- If found, `destroy!` it.
+- `Set-Cookie` with `Max-Age=0` to clear the cookie.
+- Return `204 No Content` whether or not the row was found (idempotent).
+
+### `sdk-core` — `credentials` seam
+
+`RequestConfig` gains an optional field:
+
+```ts
+export interface RequestConfig {
+ baseUrl: string
+ fetchFn: typeof fetch
+ retryConfig: Required<RetryConfig> | false
+ credentials?: RequestCredentials // 'omit' | 'same-origin' | 'include'
+}
+```
+
+Threaded into the `fetch()` call:
+
+```ts
+const response = await config.fetchFn(url.toString(), {
+ method,
+ headers: requestHeaders,
+ body: body ? JSON.stringify(body) : undefined,
+ credentials: config.credentials,
+})
+```
+
+No behavior change for the Store SDK (omits the field). When `baseUrl` is empty (browser → Vite proxy), the SDK resolves the relative path against `window.location.origin` so `new URL` doesn't throw.
+
+### `@spree/admin-sdk` — cookie auth + logout
+
+`AdminClientConfig` gains an optional field:
+
+```ts
+/** Send cookies on cross-origin requests. Defaults to 'include' for cookie-based auth. */
+credentials?: RequestCredentials
+```
+
+Default is `'include'` — admin clients are always browser-driven or proxied; secret-key flows ignore cookies harmlessly.
+
+`AdminAuthResource`:
+
+```ts
+auth = {
+ login(credentials): Promise<AuthTokens> // POST /auth/login
+ refresh(): Promise<AuthTokens> // POST /auth/refresh, no body
+ logout(): Promise<void> // POST /auth/logout
+}
+```
+
+`AuthTokens` is `{ token, user }` — no `refresh_token`.
+
+The constructor's `secretKey || jwtToken` guard is relaxed so a cookie-auth SPA can boot empty and bootstrap via `auth.refresh()`.
+
+### Admin SPA — `auth-provider.tsx`
+
+Storage:
+- **Removed:** `TOKEN_KEY`, `REFRESH_TOKEN_KEY`, `USER_KEY` localStorage entries.
+- **Removed:** `localStorage.getItem(TOKEN_KEY)` from `packages/admin/src/client.ts` (initial token now empty).
+- **Kept:** `useState` for token, user, isLoading.
+- **New:** `isInitializing` state — true until cold-load `/auth/refresh` settles.
+
+Bootstrap flow on mount:
+```ts
+useEffect(() => {
+ refreshAccessToken()
+ .then((success) => { if (success) scheduleRefresh() })
+ .finally(() => setIsInitializing(false))
+}, [])
+```
+
+Route guards (`_authenticated.tsx`, `login.tsx`, `_authenticated/index.tsx`) wait for `isInitializing === false` before deciding to redirect. `main.tsx` calls `router.invalidate()` when auth state changes so the guards re-run with fresh context.
+
+Login flow: unchanged shape, no localStorage writes.
+
+Logout flow: calls `adminClient.auth.logout()`, then clears React state + refresh timer. Network failure on logout still clears local state (server-side row will expire naturally).
+
+401 handler: unchanged — calls refresh, retries. The handler doesn't need to know that refresh now reads from cookies; that's encapsulated in the SDK.
+
+### Local dev — Vite proxy
+
+`packages/admin/vite.config.ts` proxies `/api/*` to `http://localhost:3000` so the SPA is same-origin with the Rails API. Same-origin keeps `SameSite=Lax` cookies working without HTTPS. Production builds (with `VITE_SPREE_API_URL` set to the absolute API origin) hit cross-origin and use `SameSite=None; Secure`.
+
+`packages/admin/src/client.ts`:
+
+```ts
+const baseUrl = import.meta.env.VITE_SPREE_API_URL || ''
+export const adminClient = createAdminClient({
+ baseUrl,
+ // No initial token — auth-provider bootstraps via /auth/refresh on mount.
+})
+```
+
+## Migration Path
+
+Shipping as a single coordinated PR for Spree 5.5. Backend, SDK and SPA all change at once because `@spree/admin-sdk` is unreleased (Developer Preview / `next` dist-tag) and the SPA is its only consumer — there are no external clients to coordinate with.
+
+The work landed in two commits on the PR branch:
+
+### Commit 1 — Cookie-Backed Refresh Tokens
+- New concern `Spree::Api::V3::Admin::AuthCookies` (cookie helper, env-conditional attributes).
+- `AuthController#create` sets cookie; remove `refresh_token` from response body.
+- `AuthController#refresh` reads refresh token from cookie only.
+- `AuthController#logout` new action — destroys row + clears cookie.
+- Routes: add `POST /api/v3/admin/auth/logout`.
+- `sdk-core`: add `credentials` to `RequestConfig`, thread to fetch. Resolve relative URLs against `window.location.origin` when `baseUrl` is empty.
+- `admin-sdk`: default `credentials: 'include'`, drop `refresh_token` from `AuthTokens`, `auth.refresh()` no body, `auth.logout()` new action, relax constructor guard.
+- Vite proxy on `packages/admin/vite.config.ts` so the SPA is same-origin with the API in dev.
+- `auth-provider.tsx` rewrite — in-memory token + bootstrap via `/auth/refresh`, no `localStorage`.
+- `isInitializing` plumbed through router context; guards in `_authenticated.tsx`, `_authenticated/index.tsx`, `login.tsx`.
+- `main.tsx`: `router.invalidate()` on auth state change.
+- RSpec: cookie set/clear, refresh rotation, logout destroys row, missing-cookie 401, missing-row 401 + cookie-clear.
+- Vitest: credentials passthrough, refresh sends no body, logout reaches the endpoint.
+- Changeset for `@spree/admin-sdk`.
+
+No model or migration changes — reuses existing `RefreshToken` infrastructure.
+
+### Commit 2 — Reduce Admin JWT TTL to 5 minutes
+- New `Spree::Api::Config[:admin_jwt_expiration]` preference (300s default).
+- `Admin::AuthController` overrides `jwt_expiration` to read the admin-specific config.
+- SPA refresh interval shortened to `4m30s` to match.
+- Storefront JWT TTL untouched (still 3600s) — customer tokens have lower blast radius.
+
+### Follow-up — OpenAPI + docs
+1. Regenerate admin OpenAPI spec.
+2. Update `packages/admin/README.md` auth section.
+3. Update developer docs in `docs/developer/` if they describe the old shape.
+
+## Constraints on Current Work
+
+Until this lands:
+
+- **Don't add features that depend on the refresh token being readable in JS.** No "show me my session expiry" UI built off the localStorage value, no analytics on token rotation timing from the client. Server-driven only.
+- **Don't write new admin code that reads `localStorage.getItem('spree_admin_token')` outside the auth provider.** The token belongs in React state and the SDK, not scattered.
+- **New admin endpoints that mutate state should not reuse the `Path=/api/v3/admin/auth` scope** — that path is reserved for auth flows specifically so the refresh cookie's blast radius stays minimal.
+- **Don't broaden `Spree::AllowedOrigin` to `*`.** The CORS allowlist is now load-bearing for CSRF defense, not just access control.
+
+## Open Questions
+
+- **Multi-tab coordination:** if a user logs out in tab A, tab B still has a valid in-memory access token until its next refresh attempt (which will 401, trigger a refresh that fails because the row was destroyed, and bounce to login). Acceptable, or should we add a `BroadcastChannel` to coordinate? Recommend: defer, ship without.
+- **HMR remounts log the user out in dev:** AuthProvider remount → in-memory token resets → bootstrap fires `/auth/refresh` which should re-hydrate. If the bootstrap is slow or the user is on a route that fires data fetches before bootstrap settles, they may see brief 401s before re-hydration completes. Production never HMRs, so this is dev-only friction.
+- **Mobile app / non-browser admin clients:** if anyone embeds the admin in a webview without cookie support, the cookie path breaks. Currently no known case. Document the SPA's browser-only assumption.
+- **Refresh token rotation telemetry:** today we log refresh rotations to `Spree::RefreshToken` rows. Cookie-based flow keeps this. Worth surfacing as an admin "active sessions" UI in a follow-up?
+- **Instant access-token revocation:** stateless JWTs are valid until their `exp` claim regardless of server-side state, so logout doesn't immediately kill an in-flight access token (worst case ~5 min until natural expiry). Three follow-up options exist (5-min TTL — already done; per-user `tokens_invalid_before` stamp; full JTI denylist with cache-backed lookup). Do nothing further unless an active-sessions UI or compliance requirement demands it.
+- **Active sessions UI:** `Spree::RefreshToken` already records `ip_address` + `user_agent` per rotation. A "see and revoke active sessions" admin screen would unlock JTI revocation as a natural follow-up. Defer.
+
+## References
+
+- `docs/plans/6.0-platform-auth.md` — broader auth direction
+- `docs/plans/6.0-admin-spa.md` — admin SPA architecture
+- `spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb` — current implementation
+- `spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb` — JWT layer
+- `packages/admin/src/providers/auth-provider.tsx` — SPA auth provider
+- `packages/sdk-core/src/request.ts` — shared HTTP layer
+- [Saleor Auth SDK](https://saleor.io/blog/saleor-auth-sdk) — reference design (refresh in cookie, access in memory)
+- [OWASP — JWT for Java Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html#token-storage-on-client-side) — storage guidance
+- [MDN — `SameSite` cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) — cross-site behavior
+- [Rack::Cors](https://github.com/cyu/rack-cors) — `credentials: true` semantics
diff --git a/packages/admin-sdk/.changeset/admin-cookie-auth.md b/packages/admin-sdk/.changeset/admin-cookie-auth.md
new file mode 100644
index 0000000000..32905c605b
--- /dev/null
+++ b/packages/admin-sdk/.changeset/admin-cookie-auth.md
@@ -0,0 +1,19 @@
+---
+'@spree/admin-sdk': minor
+---
+
+Cookie-backed admin authentication. The refresh token now lives in an `HttpOnly` signed cookie scoped to `/api/v3/admin/auth` instead of being returned in JSON; the access token is the only thing the SPA holds in memory. This eliminates the most attractive XSS target on the admin SPA and adds a real server-side logout that destroys the refresh-token row.
+
+CSRF protection is provided by the combination of the cookie's `SameSite` attribute and the existing `Spree::AllowedOrigin` allowlist enforced via `Rack::Cors` — no separate CSRF token is issued or required by the SDK.
+
+**Note on bump type:** `@spree/admin-sdk` is on a 0.x version line (`next` dist-tag, Developer Preview). Per semver §4 and Changesets convention, breaking changes on 0.x packages bump the minor — moving to `major` would mean 1.0.0 and signal API stability we do not yet guarantee. The changes below are breaking; coordinated with the server-side change shipping in Spree 5.5.
+
+**Breaking changes:**
+
+- `AuthTokens` no longer contains `refresh_token`. The shape is `{ token, user }`.
+- `client.auth.refresh()` takes no arguments — it reads the refresh-token cookie. Previously it required `{ refresh_token }` in the body.
+- New `client.auth.logout()` — POSTs to `/api/v3/admin/auth/logout`, which destroys the refresh-token row server-side and clears the auth cookie. Idempotent.
+- `createAdminClient()` now defaults to `credentials: 'include'` so cookies flow on cross-origin requests. Override via `createAdminClient({ credentials: 'omit' })` if needed.
+- The `secretKey || jwtToken` constructor guard has been relaxed: a cookie-auth SPA may start with neither and bootstrap by calling `auth.refresh()` immediately. Server-to-server callers should still pass `secretKey`.
+
+When using `baseUrl: ''` (e.g. with a Vite dev proxy), the SDK now resolves the relative path against `window.location.origin` so `new URL` doesn't throw.
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index ce3d4dd1d7..d104e52c85 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -33,8 +33,8 @@ export interface DashboardAnalytics {
}
export interface AuthTokens {
+ /** Short-lived JWT access token. Goes in `Authorization: Bearer`. Keep in memory only. */
token: string
- refresh_token?: string
user: {
id: string
email: string
@@ -278,11 +278,26 @@ export class AdminClient {
// ============================================
readonly auth = {
+ /**
+ * Exchange credentials for an access token. The refresh token is delivered as an
+ * HttpOnly cookie scoped to `/api/v3/admin/auth` — never returned in the response body.
+ */
login: (credentials: LoginCredentials, options?: RequestOptions): Promise<AuthTokens> =>
this.request<AuthTokens>('POST', '/auth/login', { ...options, body: credentials }),
- refresh: (params: { refresh_token: string }, options?: RequestOptions): Promise<AuthTokens> =>
- this.request<AuthTokens>('POST', '/auth/refresh', { ...options, body: params }),
+ /**
+ * Rotate the refresh cookie and obtain a new access token. Driven entirely by the
+ * `spree_admin_refresh_token` HttpOnly cookie + `X-CSRF-Token` header (set by the SDK).
+ */
+ refresh: (options?: RequestOptions): Promise<AuthTokens> =>
+ this.request<AuthTokens>('POST', '/auth/refresh', options),
+
+ /**
+ * Revoke the current refresh token server-side and clear auth cookies.
+ * Idempotent: succeeds even when no session exists.
+ */
+ logout: (options?: RequestOptions): Promise<void> =>
+ this.request<void>('POST', '/auth/logout', options),
}
// ============================================
diff --git a/packages/admin-sdk/src/client.ts b/packages/admin-sdk/src/client.ts
index 0d8d540be2..f53364ff00 100644
--- a/packages/admin-sdk/src/client.ts
+++ b/packages/admin-sdk/src/client.ts
@@ -3,7 +3,7 @@ import { createRequestFn, resolveRetryConfig, SpreeError } from '@spree/sdk-core
import { AdminClient } from './admin-client'
export interface AdminClientConfig {
- /** Base URL of the Spree API (e.g., 'https://api.mystore.com') */
+ /** Base URL of the Spree API (e.g., 'https://api.mystore.com'). Use '' for relative URLs (Vite proxy). */
baseUrl: string
/** Secret API key for server-to-server integrations (mutually exclusive with jwtToken) */
secretKey?: string
@@ -15,6 +15,12 @@ export interface AdminClientConfig {
fetch?: typeof fetch
/** Retry configuration. Enabled by default. Pass false to disable. */
retry?: RetryConfig | false
+ /**
+ * Credentials mode for cross-origin requests. Defaults to `'include'` so the
+ * admin refresh-token cookie is sent on `/api/v3/admin/auth/*`. Override when
+ * embedding in environments where cookies should not flow.
+ */
+ credentials?: RequestCredentials
}
export interface Client extends AdminClient {
@@ -31,14 +37,15 @@ export interface Client extends AdminClient {
}
export function createAdminClient(config: AdminClientConfig): Client {
- if (!config.secretKey && config.jwtToken === undefined) {
- throw new Error('Admin client requires either secretKey or jwtToken')
- }
-
const baseUrl = config.baseUrl.replace(/\/$/, '')
const fetchFn = config.fetch || fetch.bind(globalThis)
const retryConfig = resolveRetryConfig(config.retry)
- const requestConfig: RequestConfig = { baseUrl, fetchFn, retryConfig }
+ const requestConfig: RequestConfig = {
+ baseUrl,
+ fetchFn,
+ retryConfig,
+ credentials: config.credentials ?? 'include',
+ }
let currentToken = config.jwtToken
let currentStoreId = config.storeId
diff --git a/packages/admin-sdk/tests/auth.test.ts b/packages/admin-sdk/tests/auth.test.ts
new file mode 100644
index 0000000000..353063e4fe
--- /dev/null
+++ b/packages/admin-sdk/tests/auth.test.ts
@@ -0,0 +1,68 @@
+import { HttpResponse, http } from 'msw'
+import { beforeEach, describe, expect, it } from 'vitest'
+import { createAdminClient } from '../src'
+import { server } from './mocks/server'
+
+const BASE_URL = 'https://demo.spreecommerce.org'
+const API_PREFIX = `${BASE_URL}/api/v3/admin`
+
+describe('auth', () => {
+ describe('login', () => {
+ beforeEach(() => {
+ server.use(
+ http.post(`${API_PREFIX}/auth/login`, async ({ request }) => {
+ const body = (await request.json()) as { email: string; password: string }
+ return HttpResponse.json({
+ token: 'jwt_access_token',
+ user: { id: 'usr_1', email: body.email, first_name: 'A', last_name: 'B' },
+ })
+ }),
+ )
+ })
+
+ it('returns { token, user } and does not include refresh_token in body', async () => {
+ const client = createAdminClient({ baseUrl: BASE_URL })
+ const res = await client.auth.login({ email: '[email protected]', password: 'p' })
+ expect(res.token).toBe('jwt_access_token')
+ expect(res.user.email).toBe('[email protected]')
+ expect((res as Record<string, unknown>).refresh_token).toBeUndefined()
+ })
+ })
+
+ describe('refresh', () => {
+ it('POSTs to /auth/refresh with no body — refresh cookie carries the credential', async () => {
+ let observedBody: string | null = null
+ server.use(
+ http.post(`${API_PREFIX}/auth/refresh`, async ({ request }) => {
+ observedBody = await request.text()
+ return HttpResponse.json({
+ token: 'new_jwt',
+ user: { id: 'usr_1', email: '[email protected]', first_name: null, last_name: null },
+ })
+ }),
+ )
+
+ const client = createAdminClient({ baseUrl: BASE_URL })
+ const res = await client.auth.refresh()
+
+ expect(observedBody).toBe('') // no body sent — credential is the cookie
+ expect(res.token).toBe('new_jwt')
+ })
+ })
+
+ describe('logout', () => {
+ it('POSTs to /auth/logout and resolves to undefined', async () => {
+ let hit = false
+ server.use(
+ http.post(`${API_PREFIX}/auth/logout`, () => {
+ hit = true
+ return new HttpResponse(null, { status: 204 })
+ }),
+ )
+
+ const client = createAdminClient({ baseUrl: BASE_URL })
+ await expect(client.auth.logout()).resolves.toBeUndefined()
+ expect(hit).toBe(true)
+ })
+ })
+})
diff --git a/packages/admin/README.md b/packages/admin/README.md
index 99be2055e2..df873428b9 100644
--- a/packages/admin/README.md
+++ b/packages/admin/README.md
@@ -86,16 +86,22 @@ src/
### Authentication
-JWT-based, with automatic token refresh:
+JWT access token in memory + refresh token in an HttpOnly signed cookie. See `docs/plans/5.5-admin-auth-cookie-refresh.md` for the full design.
-- Login → `POST /api/v3/admin/auth/login` returns `{ token, refresh_token, user }`
-- Access token stored in React context + `localStorage`; refresh token in `localStorage`
-- Background refresh every 58 minutes
-- 401 responses trigger an automatic refresh via the SDK's `onUnauthorized` hook, then retry the original request
-- All concurrent refreshes are serialized to prevent double-rotation
+- Login → `POST /api/v3/admin/auth/login` returns `{ token, user }`. The server also sets `spree_admin_refresh_token` — an HttpOnly signed cookie scoped to `/api/v3/admin/auth`, invisible to JS.
+- Access token stays in React state only — **no `localStorage`**, no `sessionStorage`.
+- On cold load, the SPA calls `POST /api/v3/admin/auth/refresh` (cookie-driven) to bootstrap. Routes wait for `auth.isInitializing === false` before redirecting.
+- Background refresh every 58 minutes (the JWT defaults to a 1-hour TTL).
+- 401 responses trigger an automatic refresh via the SDK's `onUnauthorized` hook, then retry the original request.
+- Logout → `POST /api/v3/admin/auth/logout` destroys the refresh-token row server-side and clears the cookie. The in-memory state is cleared regardless of whether the network call succeeds.
+- Concurrent refresh attempts are serialized to prevent double-rotation under StrictMode/HMR.
+
+CSRF defense comes from the cookie's `SameSite` attribute combined with the `Spree::AllowedOrigin` allowlist enforced via `Rack::Cors`. There is no double-submit CSRF token — see the plan doc for the reasoning.
Public routes (login) sit at the root; everything else is gated by `routes/_authenticated.tsx`.
+In dev, `vite.config.ts` proxies `/api/*` → `http://localhost:3000` so the SPA is same-origin with the Rails API and `SameSite=Lax` cookies work without HTTPS. In production, set `VITE_SPREE_API_URL` to the absolute API origin — the backend issues `SameSite=None; Secure` automatically when `Rails.env.production?`.
+
### Permissions
Permissions are **server-driven**. On login, `GET /api/v3/admin/me` returns the user's CanCanCan abilities serialized as JSON. The SPA mirrors them via:
diff --git a/packages/admin/src/client.ts b/packages/admin/src/client.ts
index 3bb6fc9b04..9256230ab8 100644
--- a/packages/admin/src/client.ts
+++ b/packages/admin/src/client.ts
@@ -1,10 +1,13 @@
import { createAdminClient } from '@spree/admin-sdk'
-const baseUrl = import.meta.env.VITE_SPREE_API_URL || 'http://localhost:3000'
-
-const TOKEN_KEY = 'spree_admin_token'
+// In dev, the Vite proxy forwards /api/* to the Rails server (same-origin to the browser).
+// In prod, VITE_SPREE_API_URL points at the absolute API URL (cross-origin → cookies need
+// SameSite=None; Secure, which the backend handles based on Rails.env).
+// Empty baseUrl → relative URLs → uses the proxy in dev, absolute origin in prod builds
+// only if the env var is set; when set, the SDK prepends it.
+const baseUrl = import.meta.env.VITE_SPREE_API_URL || ''
export const adminClient = createAdminClient({
baseUrl,
- jwtToken: localStorage.getItem(TOKEN_KEY) ?? '',
+ // No initial token — auth-provider bootstraps via /auth/refresh on mount.
})
diff --git a/packages/admin/src/providers/auth-provider.tsx b/packages/admin/src/providers/auth-provider.tsx
index bbf525a82a..fb2356d95d 100644
--- a/packages/admin/src/providers/auth-provider.tsx
+++ b/packages/admin/src/providers/auth-provider.tsx
@@ -1,5 +1,6 @@
import { createContext, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
import { adminClient } from '@/client'
+import { router } from '@/router'
interface AuthUser {
id: string
@@ -12,29 +13,27 @@ interface AuthContextValue {
user: AuthUser | null
token: string | null
isAuthenticated: boolean
+ /** True while the cold-load `/auth/refresh` bootstrap is in flight. Routes should wait. */
+ isInitializing: boolean
+ /** True while the user is actively signing in (login form). */
isLoading: boolean
login: (email: string, password: string) => Promise<void>
- logout: () => void
+ logout: () => Promise<void>
}
export const AuthContext = createContext<AuthContextValue | null>(null)
-const TOKEN_KEY = 'spree_admin_token'
-const REFRESH_TOKEN_KEY = 'spree_admin_refresh_token'
-const USER_KEY = 'spree_admin_user'
-
-// Refresh 2 minutes before expiry (JWT default is 1 hour)
-const REFRESH_INTERVAL_MS = 58 * 60 * 1000
+// Refresh ~30s before the JWT expires (default 5min TTL).
+// 401s on slow requests are still handled via adminClient.onUnauthorized retry.
+const REFRESH_INTERVAL_MS = 4 * 60 * 1000 + 30 * 1000
export function AuthProvider({ children }: { children: ReactNode }) {
- const [token, setToken] = useState<string | null>(() => localStorage.getItem(TOKEN_KEY))
- const [user, setUser] = useState<AuthUser | null>(() => {
- const stored = localStorage.getItem(USER_KEY)
- return stored ? JSON.parse(stored) : null
- })
+ const [token, setToken] = useState<string | null>(null)
+ const [user, setUser] = useState<AuthUser | null>(null)
+ const [isInitializing, setIsInitializing] = useState(true)
const [isLoading, setIsLoading] = useState(false)
const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- // Serialize all refresh calls — prevents double-rotation from StrictMode/HMR
+ // Serialize all refresh calls — prevents double-rotation from StrictMode/HMR.
const refreshPromiseRef = useRef<Promise<boolean> | null>(null)
const clearRefreshTimer = useCallback(() => {
@@ -44,47 +43,37 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, [])
- const clearTokens = useCallback(() => {
+ // beforeLoad guards capture context at navigation time. Invalidate the router
+ // here so any pending guards re-run with the fresh auth state.
+ const applySession = useCallback((accessToken: string, authUser: AuthUser) => {
+ adminClient.setToken(accessToken)
+ setToken(accessToken)
+ setUser(authUser)
+ router.invalidate()
+ }, [])
+
+ const clearSession = useCallback(() => {
+ adminClient.setToken('')
setToken(null)
setUser(null)
- localStorage.removeItem(TOKEN_KEY)
- localStorage.removeItem(REFRESH_TOKEN_KEY)
- localStorage.removeItem(USER_KEY)
clearRefreshTimer()
+ router.invalidate()
}, [clearRefreshTimer])
- const storeTokens = useCallback(
- (accessToken: string, refreshToken: string, authUser: AuthUser) => {
- adminClient.setToken(accessToken)
- setToken(accessToken)
- setUser(authUser)
- localStorage.setItem(TOKEN_KEY, accessToken)
- localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken)
- localStorage.setItem(USER_KEY, JSON.stringify(authUser))
- },
- [],
- )
-
const doRefresh = useCallback(async (): Promise<boolean> => {
- const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY)
- if (!refreshToken) return false
-
try {
- const response = await adminClient.auth.refresh({ refresh_token: refreshToken })
- if (response.refresh_token) {
- storeTokens(response.token, response.refresh_token, response.user)
- }
+ const res = await adminClient.auth.refresh()
+ applySession(res.token, res.user)
return true
} catch {
- clearTokens()
+ clearSession()
return false
}
- }, [storeTokens, clearTokens])
+ }, [applySession, clearSession])
- // Serialize: if a refresh is already in-flight, return the same promise
+ // Serialize: if a refresh is already in flight, await the same promise.
const refreshAccessToken = useCallback((): Promise<boolean> => {
if (refreshPromiseRef.current) return refreshPromiseRef.current
-
const promise = doRefresh().finally(() => {
refreshPromiseRef.current = null
})
@@ -104,21 +93,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
async (email: string, password: string) => {
setIsLoading(true)
try {
- const response = await adminClient.auth.login({ email, password })
- storeTokens(response.token, response.refresh_token!, response.user)
+ const res = await adminClient.auth.login({ email, password })
+ applySession(res.token, res.user)
scheduleRefresh()
} finally {
setIsLoading(false)
}
},
- [storeTokens, scheduleRefresh],
+ [applySession, scheduleRefresh],
)
- const logout = useCallback(() => {
- clearTokens()
- }, [clearTokens])
+ const logout = useCallback(async () => {
+ try {
+ await adminClient.auth.logout()
+ } catch {
+ // Network/server failures shouldn't trap the user — clear locally regardless.
+ // The server-side refresh row will expire naturally if the call didn't reach it.
+ } finally {
+ clearSession()
+ }
+ }, [clearSession])
- // Register 401 handler: refresh token and retry the failed request
+ // Register the 401 handler: refresh token (driven by cookie) and let the SDK retry.
// biome-ignore lint/correctness/useExhaustiveDependencies: only run on mount
useEffect(() => {
adminClient.onUnauthorized(async () => {
@@ -128,19 +124,20 @@ export function AuthProvider({ children }: { children: ReactNode }) {
})
}, []) // eslint-disable-line react-hooks/exhaustive-deps
- // On mount: refresh the token if we have a refresh token stored
+ // Cold-load bootstrap: try to refresh from the cookie. If we get an access token,
+ // hydrate the in-memory state. If not, stay logged out — routes will redirect to /login.
// biome-ignore lint/correctness/useExhaustiveDependencies: only run on mount
useEffect(() => {
- const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY)
- if (!refreshToken) {
- if (token) clearTokens()
- return
- }
-
- refreshAccessToken().then((success) => {
- if (success) scheduleRefresh()
- })
-
+ refreshAccessToken()
+ .then((success) => {
+ if (success) scheduleRefresh()
+ })
+ .finally(() => {
+ setIsInitializing(false)
+ // Guards return early while isInitializing — invalidate so they re-run
+ // now that the cold-load decision has settled.
+ router.invalidate()
+ })
return clearRefreshTimer
}, []) // eslint-disable-line react-hooks/exhaustive-deps
@@ -150,6 +147,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
user,
token,
isAuthenticated: !!token,
+ isInitializing,
isLoading,
login,
logout,
diff --git a/packages/admin/src/routes/__root.tsx b/packages/admin/src/routes/__root.tsx
index dfe16996d1..22d127e26a 100644
--- a/packages/admin/src/routes/__root.tsx
+++ b/packages/admin/src/routes/__root.tsx
@@ -5,6 +5,7 @@ import type { Permissions } from '@/providers/permission-provider'
interface RouterContext {
auth: {
isAuthenticated: boolean
+ isInitializing: boolean
token: string | null
}
permissions: Permissions
diff --git a/packages/admin/src/routes/_authenticated.tsx b/packages/admin/src/routes/_authenticated.tsx
index d2553cbf39..20100da4a9 100644
--- a/packages/admin/src/routes/_authenticated.tsx
+++ b/packages/admin/src/routes/_authenticated.tsx
@@ -2,6 +2,10 @@ import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
export const Route = createFileRoute('/_authenticated')({
beforeLoad: ({ context }) => {
+ // Wait for the cold-load `/auth/refresh` bootstrap before deciding to redirect —
+ // otherwise an authenticated user with a valid refresh cookie would be bounced
+ // to /login during the first render pass.
+ if (context.auth.isInitializing) return
if (!context.auth.isAuthenticated) {
throw redirect({ to: '/login' })
}
diff --git a/packages/admin/src/routes/_authenticated/index.tsx b/packages/admin/src/routes/_authenticated/index.tsx
index 3e1b14810a..e76bc33131 100644
--- a/packages/admin/src/routes/_authenticated/index.tsx
+++ b/packages/admin/src/routes/_authenticated/index.tsx
@@ -2,7 +2,12 @@ import { createFileRoute, redirect } from '@tanstack/react-router'
import { adminClient } from '@/client'
export const Route = createFileRoute('/_authenticated/')({
- beforeLoad: async () => {
+ beforeLoad: async ({ context }) => {
+ // Wait for bootstrap; the parent _authenticated guard will redirect to /login
+ // if we end up unauthenticated. Without this guard, we'd fire a /store request
+ // with no token during cold load and trigger a refresh loop.
+ if (context.auth.isInitializing || !context.auth.isAuthenticated) return
+
// Fetch the current store to get its prefixed ID for the URL
try {
const store = await adminClient.store.get()
diff --git a/packages/admin/src/routes/login.tsx b/packages/admin/src/routes/login.tsx
index 648d6717bd..79f09e0ede 100644
--- a/packages/admin/src/routes/login.tsx
+++ b/packages/admin/src/routes/login.tsx
@@ -18,6 +18,8 @@ type LoginForm = z.infer<typeof loginSchema>
export const Route = createFileRoute('/login')({
beforeLoad: ({ context }) => {
+ // Same reasoning as in _authenticated.tsx — don't decide while bootstrap is in flight.
+ if (context.auth.isInitializing) return
if (context.auth.isAuthenticated) {
throw redirect({ to: '/' }) // Will redirect to /$storeId via _authenticated/index
}
diff --git a/packages/admin/vite.config.ts b/packages/admin/vite.config.ts
index 1b043bc98b..9c4c431b6d 100644
--- a/packages/admin/vite.config.ts
+++ b/packages/admin/vite.config.ts
@@ -11,4 +11,15 @@ export default defineConfig({
'@': path.resolve(__dirname, './src'),
},
},
+ // Proxy /api to the Rails server so the SPA is same-origin with the API in dev.
+ // Same-origin keeps the refresh-token cookie working under SameSite=Lax without
+ // needing HTTPS (production cross-origin uses SameSite=None; Secure).
+ server: {
+ proxy: {
+ '/api': {
+ target: process.env.VITE_SPREE_API_URL || 'http://localhost:3000',
+ changeOrigin: true,
+ },
+ },
+ },
})
diff --git a/packages/sdk-core/src/request.ts b/packages/sdk-core/src/request.ts
index 241ec6a60d..42bc0ef090 100644
--- a/packages/sdk-core/src/request.ts
+++ b/packages/sdk-core/src/request.ts
@@ -95,6 +95,11 @@ export interface RequestConfig {
baseUrl: string
fetchFn: typeof fetch
retryConfig: Required<RetryConfig> | false
+ /**
+ * Credentials mode for cross-origin requests. Pass `'include'` for cookie-based auth.
+ * Defaults to fetch's built-in default (`'same-origin'` in browsers) when omitted.
+ */
+ credentials?: RequestCredentials
}
export interface AuthConfig {
@@ -123,8 +128,17 @@ export function createRequestFn(
const currency = options.currency ?? defaults?.currency
const country = options.country ?? defaults?.country
- // Build URL with query params
- const url = new URL(`${config.baseUrl}${basePath}${path}`)
+ // Build URL with query params.
+ // `new URL(path)` throws on a relative path. When baseUrl is empty (browser
+ // hitting a same-origin proxy like Vite dev), resolve against window.location.
+ const browserOrigin = typeof window !== 'undefined' ? window.location.origin : undefined
+ const urlBase = config.baseUrl || browserOrigin
+ if (!urlBase) {
+ throw new TypeError(
+ 'sdk-core: baseUrl is required in non-browser environments (no window.location to resolve relative URLs against)',
+ )
+ }
+ const url = new URL(`${config.baseUrl}${basePath}${path}`, urlBase)
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) {
@@ -187,6 +201,7 @@ export function createRequestFn(
method,
headers: requestHeaders,
body: body ? JSON.stringify(body) : undefined,
+ credentials: config.credentials,
})
if (!response.ok) {
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/auth_cookies.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/auth_cookies.rb
new file mode 100644
index 0000000000..f89a6067f4
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/auth_cookies.rb
@@ -0,0 +1,62 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Cookie-based delivery for admin refresh tokens.
+ #
+ # Refresh token: HttpOnly signed cookie at /api/v3/admin/auth — invisible to JS,
+ # tamper-evident via Rails' cookie signing.
+ #
+ # CSRF protection:
+ # We deliberately do NOT use a CSRF token here. The threat model is fully
+ # covered by the combination of:
+ # - SameSite=Lax (dev) / SameSite=None; Secure (prod) on the refresh cookie
+ # - Spree::AllowedOrigin allowlist enforced via Rack::Cors with credentials: true
+ # - CORS preflight blocking cross-origin requests from non-allowlisted Origins
+ # A double-submit CSRF token would only add value if the AllowedOrigin allowlist
+ # were misconfigured or if an XSS happened on a different allowlisted origin —
+ # both scenarios where a defender's deeper problem outweighs CSRF mitigation.
+ # See docs/plans/5.5-admin-auth-cookie-refresh.md for the full reasoning.
+ module AuthCookies
+ extend ActiveSupport::Concern
+
+ # ActionController::API drops Cookies — re-include it on the auth controller only.
+ # Rest of the admin API stays cookie-free and stateless.
+ included do
+ include ActionController::Cookies
+ end
+
+ REFRESH_COOKIE_NAME = :spree_admin_refresh_token
+ COOKIE_PATH = '/api/v3/admin/auth'.freeze
+
+ private
+
+ def set_refresh_cookie(refresh_token)
+ cookies.signed[REFRESH_COOKIE_NAME] = base_cookie_attributes.merge(
+ value: refresh_token.token,
+ expires: refresh_token.expires_at,
+ path: COOKIE_PATH,
+ httponly: true
+ )
+ end
+
+ def clear_refresh_cookie
+ cookies.delete(REFRESH_COOKIE_NAME, path: COOKIE_PATH)
+ end
+
+ def refresh_token_from_cookie
+ cookies.signed[REFRESH_COOKIE_NAME].presence
+ end
+
+ def base_cookie_attributes
+ if Rails.env.production?
+ { secure: true, same_site: :none }
+ else
+ { secure: false, same_site: :lax }
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
index 199ab50f2b..f105a4a277 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
@@ -3,12 +3,14 @@ module Spree
module V3
module Admin
class AuthController < Admin::BaseController
+ include Spree::Api::V3::Admin::AuthCookies
+
skip_scope_check!
rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSE
rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :refresh, with: RATE_LIMIT_RESPONSE
- skip_before_action :authenticate_admin!, only: [:create, :refresh]
+ skip_before_action :authenticate_admin!, only: [:create, :refresh, :logout]
# POST /api/v3/admin/auth/login
def create
@@ -19,6 +21,8 @@ module Spree
if result.success?
user = result.value
+ refresh_token = Spree::RefreshToken.create_for(user, request_env: request_env_for_token)
+ set_refresh_cookie(refresh_token)
render json: auth_response(user)
else
render_error(
@@ -31,12 +35,12 @@ module Spree
# POST /api/v3/admin/auth/refresh
def refresh
- refresh_token_value = params[:refresh_token]
+ refresh_token_value = refresh_token_from_cookie
if refresh_token_value.blank?
return render_error(
code: ERROR_CODES[:invalid_refresh_token],
- message: 'refresh_token is required',
+ message: 'Refresh token cookie missing',
status: :unauthorized
)
end
@@ -44,6 +48,7 @@ module Spree
refresh_token = Spree::RefreshToken.active.find_by(token: refresh_token_value)
if refresh_token.nil?
+ clear_refresh_cookie
return render_error(
code: ERROR_CODES[:invalid_refresh_token],
message: 'Invalid or expired refresh token',
@@ -53,12 +58,18 @@ module Spree
user = refresh_token.user
new_refresh_token = refresh_token.rotate!(request_env: request_env_for_token)
+ set_refresh_cookie(new_refresh_token)
- render json: {
- token: generate_jwt(user, audience: JWT_AUDIENCE_ADMIN),
- refresh_token: new_refresh_token.token,
- user: admin_user_serializer.new(user, params: serializer_params).to_h
- }
+ render json: auth_response(user)
+ end
+
+ # POST /api/v3/admin/auth/logout
+ def logout
+ refresh_token_value = refresh_token_from_cookie
+ Spree::RefreshToken.active.find_by(token: refresh_token_value)&.destroy if refresh_token_value.present?
+
+ clear_refresh_cookie
+ head :no_content
end
private
@@ -94,11 +105,8 @@ module Spree
end
def auth_response(user)
- refresh_token = Spree::RefreshToken.create_for(user, request_env: request_env_for_token)
-
{
token: generate_jwt(user, audience: JWT_AUDIENCE_ADMIN),
- refresh_token: refresh_token.token,
user: admin_user_serializer.new(user, params: serializer_params).to_h
}
end
@@ -113,6 +121,12 @@ module Spree
def admin_user_serializer
Spree.api.admin_admin_user_serializer
end
+
+ # Admin tokens have higher blast radius than customer tokens, so they get a
+ # shorter TTL (5 min by default) — overrides the storefront default (1h).
+ def jwt_expiration
+ Spree::Api::Config[:admin_jwt_expiration]
+ end
end
end
end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index d462f2c154..78e1213f08 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -103,6 +103,7 @@ Spree::Core::Engine.add_routes do
# Authentication
post 'auth/login', to: 'auth#create'
post 'auth/refresh', to: 'auth#refresh'
+ post 'auth/logout', to: 'auth#logout'
# Dashboard
namespace :dashboard do
diff --git a/spree/api/lib/spree/api/configuration.rb b/spree/api/lib/spree/api/configuration.rb
index 8cd4c7e228..7fff758eea 100644
--- a/spree/api/lib/spree/api/configuration.rb
+++ b/spree/api/lib/spree/api/configuration.rb
@@ -9,7 +9,8 @@ module Spree
preference :api_v2_content_type, :string, default: 'application/vnd.api+json'
preference :api_v2_per_page_limit, :integer, default: 500
- preference :jwt_expiration, :integer, default: 3600 # 1 hour in seconds
+ preference :jwt_expiration, :integer, default: 3600 # 1 hour in seconds (customer/store JWT default)
+ preference :admin_jwt_expiration, :integer, default: 300 # 5 minutes — admin tokens have higher blast radius
preference :jwt_secret_key, :string, default: nil
preference :refresh_token_expiry, :integer, default: 2_592_000 # 30 days in seconds
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb
index 8c26c8faa7..c03286c83c 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb
@@ -5,99 +5,101 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
include_context 'API v3 Admin'
+ let(:refresh_cookie_name) { Spree::Api::V3::Admin::AuthCookies::REFRESH_COOKIE_NAME.to_s }
+
+ # Set-Cookie can be a String (joined) or Array of strings depending on Rack version.
+ # Normalize to a single string for substring matching.
+ def set_cookie_string
+ Array(response.headers['Set-Cookie']).join("\n")
+ end
+
+ def set_cookie_for(name)
+ set_cookie_string.split("\n").find { |line| line.start_with?("#{name}=") }
+ end
+
+ # Decode a signed cookie value the way Rails would on a subsequent request,
+ # so tests can assert against the underlying refresh token without re-signing.
+ def decode_signed_cookie(name)
+ encoded = response.cookies[name]
+ return nil if encoded.blank?
+ request.cookies[name] = encoded
+ request.cookie_jar.signed[name]
+ end
+
describe 'POST #create (login)' do
let!(:existing_admin) { create(:admin_user, password: 'password123', password_confirmation: 'password123') }
- context 'without any authentication headers' do
- it 'authenticates with email and password' do
+ context 'with valid credentials' do
+ it 'returns { token, user } and omits refresh_token from body' do
post :create, params: { email: existing_admin.email, password: 'password123' }
expect(response).to have_http_status(:ok)
expect(json_response['token']).to be_present
- expect(json_response['refresh_token']).to be_present
- expect(json_response['user']).to be_present
+ expect(json_response).not_to have_key('refresh_token')
expect(json_response['user']['email']).to eq(existing_admin.email)
end
- it 'returns a JWT with admin audience and correct claims' do
+ it 'sets a signed HttpOnly refresh cookie scoped to /api/v3/admin/auth' do
post :create, params: { email: existing_admin.email, password: 'password123' }
- token = json_response['token']
- secret = Rails.application.secret_key_base
- payload = JWT.decode(token, secret, true, algorithm: 'HS256').first
-
- expect(payload['aud']).to eq('admin_api')
- expect(payload['user_type']).to eq('admin')
- expect(payload['user_id']).to eq(existing_admin.id)
- expect(payload['iss']).to eq('spree')
- expect(payload['exp']).to be > Time.current.to_i
- expect(payload['jti']).to be_present
+ line = set_cookie_for('spree_admin_refresh_token')
+ expect(line).to be_present
+ expect(line).to include('httponly')
+ expect(line).to include('path=/api/v3/admin/auth')
+ # In dev/test env (non-production), SameSite=Lax and no Secure flag
+ expect(line).to include('samesite=lax')
+ expect(line).not_to match(/;\s*secure/i)
end
- it 'returns user data in the response' do
- post :create, params: { email: existing_admin.email, password: 'password123' }
+ it 'creates a RefreshToken row matching the signed cookie value' do
+ expect {
+ post :create, params: { email: existing_admin.email, password: 'password123' }
+ }.to change(Spree::RefreshToken, :count).by(1)
- expect(json_response['user']).to have_key('id')
- expect(json_response['user']).to have_key('email')
+ decoded = decode_signed_cookie(refresh_cookie_name)
+ expect(decoded).to be_present
+ expect(Spree::RefreshToken.find_by(token: decoded)).to be_present
end
- end
- context 'with secret API key header (also works)' do
- before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }
-
- it 'authenticates successfully' do
+ it 'returns a JWT with admin audience and correct claims' do
post :create, params: { email: existing_admin.email, password: 'password123' }
- expect(response).to have_http_status(:ok)
- expect(json_response['token']).to be_present
- end
- end
-
- context 'with explicit email provider' do
- it 'authenticates successfully' do
- post :create, params: { provider: 'email', email: existing_admin.email, password: 'password123' }
-
- expect(response).to have_http_status(:ok)
- expect(json_response['token']).to be_present
+ payload = JWT.decode(json_response['token'], Rails.application.secret_key_base, true, algorithm: 'HS256').first
+ expect(payload['aud']).to eq('admin_api')
+ expect(payload['user_type']).to eq('admin')
+ expect(payload['user_id']).to eq(existing_admin.id)
+ expect(payload['exp']).to be > Time.current.to_i
end
end
context 'invalid credentials' do
- it 'returns unauthorized for wrong password' do
+ it 'returns unauthorized for wrong password and sets no cookie' do
post :create, params: { email: existing_admin.email, password: 'wrong' }
expect(response).to have_http_status(:unauthorized)
expect(json_response['error']['code']).to eq('authentication_failed')
+ expect(set_cookie_for('spree_admin_refresh_token')).to be_nil
end
it 'returns unauthorized for non-existent email' do
post :create, params: { email: '[email protected]', password: 'password123' }
expect(response).to have_http_status(:unauthorized)
- expect(json_response['error']['code']).to eq('authentication_failed')
end
- it 'returns unauthorized for missing email' do
- post :create, params: { password: 'password123' }
-
- expect(response).to have_http_status(:unauthorized)
- end
-
- it 'returns unauthorized for missing password' do
- post :create, params: { email: existing_admin.email }
-
- expect(response).to have_http_status(:unauthorized)
- end
+ it 'returns the same error code for existing and non-existing emails (no timing leak)' do
+ post :create, params: { email: existing_admin.email, password: 'wrong' }
+ existing_code = json_response['error']['code']
- it 'returns unauthorized for empty credentials' do
- post :create, params: { email: '', password: '' }
+ post :create, params: { email: '[email protected]', password: 'wrong' }
+ nonexistent_code = json_response['error']['code']
- expect(response).to have_http_status(:unauthorized)
+ expect(existing_code).to eq(nonexistent_code)
end
end
context 'with unsupported provider' do
- it 'returns bad request' do
+ it 'returns 400 invalid_provider' do
post :create, params: { provider: 'unsupported', email: existing_admin.email, password: 'password123' }
expect(response).to have_http_status(:bad_request)
@@ -112,57 +114,46 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
post :create, params: { email: regular_user.email, password: 'password123' }
expect(response).to have_http_status(:unauthorized)
- expect(json_response['error']['code']).to eq('authentication_failed')
end
end
-
- it 'does not leak timing information between existing and non-existing emails' do
- # Both should return the same error code regardless of whether the email exists
- post :create, params: { email: existing_admin.email, password: 'wrong' }
- existing_error = json_response['error']['code']
-
- post :create, params: { email: '[email protected]', password: 'wrong' }
- nonexistent_error = json_response['error']['code']
-
- expect(existing_error).to eq(nonexistent_error)
- end
end
describe 'POST #refresh' do
let(:refresh_token) { Spree::RefreshToken.create_for(admin_user, request_env: { ip_address: '127.0.0.1', user_agent: 'test' }) }
- context 'with valid refresh token' do
- it 'returns a new access token and rotated refresh token' do
- post :refresh, params: { refresh_token: refresh_token.token }
+ context 'with a valid refresh cookie' do
+ before do
+ request.cookie_jar.signed[refresh_cookie_name] = refresh_token.token
+ end
+
+ it 'returns a new access token, rotates the refresh row, and omits refresh_token from body' do
+ old_value = refresh_token.token
+
+ post :refresh
expect(response).to have_http_status(:ok)
expect(json_response['token']).to be_present
- expect(json_response['refresh_token']).to be_present
- expect(json_response['refresh_token']).not_to eq(refresh_token.token)
- end
-
- it 'returns user data' do
- post :refresh, params: { refresh_token: refresh_token.token }
+ expect(json_response).not_to have_key('refresh_token')
- expect(json_response['user']).to be_present
- expect(json_response['user']['email']).to eq(admin_user.email)
+ new_value = decode_signed_cookie(refresh_cookie_name)
+ expect(new_value).to be_present
+ expect(new_value).not_to eq(old_value)
+ expect(Spree::RefreshToken.find_by(token: old_value)).to be_nil
+ expect(Spree::RefreshToken.find_by(token: new_value)).to be_present
end
- it 'returns a JWT with admin audience' do
- post :refresh, params: { refresh_token: refresh_token.token }
-
- token = json_response['token']
- secret = Rails.application.secret_key_base
- payload = JWT.decode(token, secret, true, algorithm: 'HS256').first
+ it 'returns user data and admin-audience JWT' do
+ post :refresh
+ expect(json_response['user']['email']).to eq(admin_user.email)
+ payload = JWT.decode(json_response['token'], Rails.application.secret_key_base, true, algorithm: 'HS256').first
expect(payload['aud']).to eq('admin_api')
- expect(payload['user_type']).to eq('admin')
expect(payload['user_id']).to eq(admin_user.id)
end
end
- context 'without refresh token' do
- it 'returns unauthorized' do
+ context 'with no refresh cookie' do
+ it 'returns 401 invalid_refresh_token' do
post :refresh
expect(response).to have_http_status(:unauthorized)
@@ -170,12 +161,43 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
end
end
- context 'with invalid refresh token' do
- it 'returns unauthorized' do
- post :refresh, params: { refresh_token: 'invalid_token' }
+ context 'with a refresh cookie pointing to a missing/expired RefreshToken row' do
+ it 'clears the refresh cookie and returns 401 invalid_refresh_token' do
+ request.cookie_jar.signed[refresh_cookie_name] = 'rt_does_not_exist'
+
+ post :refresh
expect(response).to have_http_status(:unauthorized)
expect(json_response['error']['code']).to eq('invalid_refresh_token')
+ expect(set_cookie_for('spree_admin_refresh_token')).to include('=;')
+ end
+ end
+ end
+
+ describe 'POST #logout' do
+ let(:refresh_token) { Spree::RefreshToken.create_for(admin_user, request_env: { ip_address: '127.0.0.1', user_agent: 'test' }) }
+
+ context 'with a valid refresh cookie' do
+ before do
+ request.cookie_jar.signed[refresh_cookie_name] = refresh_token.token
+ end
+
+ it 'destroys the RefreshToken row and clears the cookie' do
+ token_id = refresh_token.id
+
+ post :logout
+
+ expect(response).to have_http_status(:no_content)
+ expect(Spree::RefreshToken.where(id: token_id)).to be_empty
+ expect(set_cookie_for('spree_admin_refresh_token')).to include('=;')
+ end
+ end
+
+ context 'without any cookie (already logged out)' do
+ it 'returns 204 idempotently' do
+ post :logout
+
+ expect(response).to have_http_status(:no_content)
end
end
end
@@ -183,7 +205,6 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
describe 'response headers' do
it 'sets no-store cache control' do
post :create, params: { email: '[email protected]', password: 'whatever' }
-
expect(response.headers['Cache-Control']).to include('no-store')
end
end