Skip to content

The agent that grows with you

fix(desktop): scope the session-cookie mirror by partition and gate the 401 replay

Austin Pickett84f87a18c0ad
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 782c1cdd6da..c61d0a7688f 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -360,9 +360,12 @@ import { registerNativeNotifications } from './notification-ipc'
import { isExpectedOauthNavigationAbort } from './oauth-navigation'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
-import { mintGatewayWsTicket as mintOauthGatewayWsTicket, requestWithOauthFallback } from './oauth-rest-request'
+import {
+ mintGatewayWsTicket as mintOauthGatewayWsTicket,
+ requestWithOauthFallback,
+ shouldReplayAfterCookie401
+} from './oauth-rest-request'
import { wireOauthSessionResponse } from './oauth-session-response'
-import { remoteSessionCookies } from './remote-session-cookies'
import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'
import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'
import { bundledPayload, installIdForRoot, type PayloadInfo } from './payload-backend'
@@ -450,6 +453,7 @@ import {
revalidateSuspectPooledRemoteBackends
} from './remote-liveness'
import { resolveRemoteOauthTicket, rosterSourceEnumerationTimeoutMs } from './remote-oauth-ticket'
+import { remoteSessionCookies } from './remote-session-cookies'
import {
attachRemoteRequestHeaderListener,
collectRemoteHeaderSources,
@@ -7398,18 +7402,17 @@ function warmOauthCookieStore(url?) {
// connection-config.ts (cookiesHaveSession / cookiesHaveLiveSession). See
// that module for details.
-// #61457: snapshot the partition jar's session cookies for this gateway into
-// the in-memory mirror. Best-effort: a failed read just means the next
-// response's Set-Cookie capture populates the mirror instead.
-async function captureRemoteSessionCookiesIntoMirror(baseUrl) {
- const sess = getOauthSessionForUrl(baseUrl)
-
- if (!sess) {
+// #61457: snapshot a partition jar's session cookies for this gateway into
+// the in-memory mirror, keyed by the SAME partition the jar belongs to.
+// Best-effort: a failed read just means the next response's Set-Cookie
+// capture populates the mirror instead.
+async function captureRemoteSessionCookiesIntoMirror(sess, partition, baseUrl) {
+ if (!sess || !partition) {
return
}
try {
- remoteSessionCookies.recordFromJar(baseUrl, await sess.cookies.get({ url: baseUrl }))
+ remoteSessionCookies.recordFromJar(partition, baseUrl, await sess.cookies.get({ url: baseUrl }))
} catch (error) {
rememberLog(`Remote session cookie mirror capture failed: ${error?.message || error}`)
}
@@ -7595,7 +7598,11 @@ function openOauthLoginWindow(
} else {
// #61457: the jar just got the fresh session cookies — mirror them
// into memory immediately, before the jar can drop them again.
- void captureRemoteSessionCookiesIntoMirror(baseUrl)
+ void captureRemoteSessionCookiesIntoMirror(
+ sess,
+ resolveOauthPartitionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind }),
+ baseUrl
+ )
resolve({ baseUrl, ok: true })
}
}
@@ -7709,15 +7716,21 @@ function openOauthLoginWindow(
// drop the `hermes_session*` cookies (Windows %3A profile folders, lazy
// hydration, flush races) and `useSessionCookies: true` then intermittently
// omits the cookie → 401 `no_cookie` right after a successful sign-in. Two
-// mitigations, both keyed by origin:
+// mitigations, both keyed by the request's resolved OAuth partition + origin
+// (the same owner the jar itself is scoped to, so same-origin gateways on
+// separate jars stay separate here too):
// 1. an explicit `Cookie` header built from the in-memory session-cookie
// mirror (remote-session-cookies.ts) — an explicit header bypasses the
// network stack's jar lookup entirely, and every `Set-Cookie` observed
// here (and in the login window) feeds the mirror back; and
// 2. one forced silent re-login + single retry when the gateway still
-// answers 401. Safe even for mutations: a 401 means the server rejected
-// the request before executing it.
+// answers 401 — ONLY when shouldReplayAfterCookie401 holds: the 401 is
+// the auth gate's pre-handler refusal AND the operation is idempotent or
+// vouched replay-safe (`options.replayOn401`). Anything else keeps the
+// no-replay rule of requestWithOauthFallback.
function fetchJsonViaOauthSession(url, options: any = {}) {
+ const partition = resolveOauthPartitionForUrl(url)
+
const attempt = (): Promise<unknown> =>
new Promise((resolve, reject) => {
const sess = getOauthSessionForUrl(url)
@@ -7761,7 +7774,7 @@ function fetchJsonViaOauthSession(url, options: any = {}) {
// Explicit mirror cookies ride last so an existing caller-supplied
// Cookie header still wins, and the mirror never clobbers intent.
- const mirroredCookies = remoteSessionCookies.cookieHeaderFor(url)
+ const mirroredCookies = remoteSessionCookies.cookieHeaderFor(partition, url)
if (mirroredCookies && headerBag.Cookie === undefined && headerBag.cookie === undefined) {
headerBag.Cookie = mirroredCookies
@@ -7792,7 +7805,7 @@ function fetchJsonViaOauthSession(url, options: any = {}) {
clearTimer: (): void => clearTimeout(timer),
resolve,
reject,
- onSetCookies: setCookie => remoteSessionCookies.record(url, setCookie)
+ onSetCookies: setCookie => remoteSessionCookies.record(partition, url, setCookie)
})
})
request.on('error', error => {
@@ -7812,12 +7825,12 @@ function fetchJsonViaOauthSession(url, options: any = {}) {
})
return attempt().catch(async error => {
- if (Number(error?.statusCode) !== 401) {
+ if (!shouldReplayAfterCookie401(error, options)) {
throw error
}
// Stale mirror + dead jar: force one silent re-login, then retry once.
- remoteSessionCookies.clear(url)
+ remoteSessionCookies.clear(partition, url)
try {
await openOauthLoginWindow(new URL(url).origin, { silent: true })
diff --git a/apps/desktop/electron/oauth-rest-request.test.ts b/apps/desktop/electron/oauth-rest-request.test.ts
index 5e7e6dc28e8..df423a904d0 100644
--- a/apps/desktop/electron/oauth-rest-request.test.ts
+++ b/apps/desktop/electron/oauth-rest-request.test.ts
@@ -3,7 +3,64 @@ import { expect, test } from 'vitest'
import { httpStatusError } from './api-transport'
import { isGatewayAuthRejection } from './connection-config'
import { NativeAuthChangedError } from './native-access-token'
-import { mintGatewayWsTicket, requestWithOauthFallback } from './oauth-rest-request'
+import { mintGatewayWsTicket, requestWithOauthFallback, shouldReplayAfterCookie401 } from './oauth-rest-request'
+
+const GATE_401 = () =>
+ httpStatusError(
+ 401,
+ JSON.stringify({ error: 'unauthenticated', detail: 'Unauthorized', reason: 'no_cookie', login_url: '/login' })
+ )
+
+test('a cookie 401 is replayed only for a gate refusal on an idempotent or vouched operation', () => {
+ // Pre-auth gate refusal + idempotent method → replay.
+ expect(shouldReplayAfterCookie401(GATE_401(), { method: 'GET' })).toBe(true)
+ expect(shouldReplayAfterCookie401(GATE_401(), {})).toBe(true)
+ expect(shouldReplayAfterCookie401(GATE_401(), { method: 'HEAD' })).toBe(true)
+ expect(
+ shouldReplayAfterCookie401(
+ httpStatusError(401, JSON.stringify({ error: 'session_expired', reason: 'invalid_or_expired_session' })),
+ { method: 'GET' }
+ )
+ ).toBe(true)
+
+ // Gate refusal on a mutation: only when the caller vouches for the operation.
+ expect(shouldReplayAfterCookie401(GATE_401(), { method: 'POST' })).toBe(false)
+ expect(shouldReplayAfterCookie401(GATE_401(), { method: 'POST', replayOn401: true })).toBe(true)
+ expect(shouldReplayAfterCookie401(GATE_401(), { method: 'DELETE', replayOn401: 'yes' })).toBe(false)
+
+ // An application-level 401 (endpoint/plugin/backend; no gate shape) never replays.
+ expect(shouldReplayAfterCookie401(httpStatusError(401, 'rejected'), { method: 'GET' })).toBe(false)
+ expect(
+ shouldReplayAfterCookie401(httpStatusError(401, JSON.stringify({ error: 'forbidden_tool' })), { method: 'GET' })
+ ).toBe(false)
+ expect(
+ shouldReplayAfterCookie401(httpStatusError(401, JSON.stringify({ error: 'unauthenticated' })), { method: 'GET' })
+ ).toBe(false)
+ expect(shouldReplayAfterCookie401(GATE_401(), { method: 'POST' })).toBe(false)
+
+ // Not a 401 at all.
+ expect(
+ shouldReplayAfterCookie401(httpStatusError(403, JSON.stringify({ error: 'unauthenticated', reason: 'x' })), {})
+ ).toBe(false)
+ expect(shouldReplayAfterCookie401(new Error('socket reset'), {})).toBe(false)
+})
+
+test('ws-ticket minting vouches for replay on a cookie 401', async () => {
+ let seen: any
+
+ await mintGatewayWsTicket('https://gw.test', {
+ ensureNativeAccessToken: async () => null,
+ fetchJson: async () => ({}),
+ fetchJsonViaOauthSession: async (_url, options) => {
+ seen = options
+
+ return { ticket: 't' }
+ }
+ })
+
+ expect(seen.method).toBe('POST')
+ expect(seen.replayOn401).toBe(true)
+})
test('native failures remain transport failures unless an independent cookie session succeeds', async () => {
for (const nativeError of [new Error('timeout'), httpStatusError(503, 'down'), new Error('malformed response')]) {
diff --git a/apps/desktop/electron/oauth-rest-request.ts b/apps/desktop/electron/oauth-rest-request.ts
index fc79111cafa..158d77742a8 100644
--- a/apps/desktop/electron/oauth-rest-request.ts
+++ b/apps/desktop/electron/oauth-rest-request.ts
@@ -1,4 +1,4 @@
-import { readStatusCode } from './api-transport'
+import { readJsonErrorBody, readStatusCode } from './api-transport'
import { isGatewayAuthRejection } from './connection-config'
import { type NativeAccessTokenOptions, NativeAuthChangedError } from './native-access-token'
import { shouldRotateNativeTokenAfterRejection } from './native-auth-decisions'
@@ -57,6 +57,41 @@ export interface MintGatewayWsTicketDeps {
fetchJsonViaOauthSession: (url: string, options: any) => Promise<any>
}
+/**
+ * Whether a cookie-mode 401 may be answered by ONE silent re-login and a
+ * single resubmission of the same request (#61457). The no-replay rule above
+ * stands for arbitrary mutations; a replay needs BOTH:
+ * - pre-effect evidence: the 401 body carries the dashboard auth gate's
+ * structured `{error: unauthenticated|session_expired, reason}` shape,
+ * which the middleware emits before any route handler runs; and
+ * - a replay-safe operation: an idempotent method (GET/HEAD), or the caller
+ * vouching for the operation with `replayOn401: true` (ticket minting).
+ */
+export function shouldReplayAfterCookie401(
+ error: unknown,
+ options: { method?: unknown; replayOn401?: unknown } = {}
+): boolean {
+ if (readStatusCode(error) !== 401) {
+ return false
+ }
+
+ const body = readJsonErrorBody(error)
+
+ const gateRefusal =
+ body !== null &&
+ (body.error === 'unauthenticated' || body.error === 'session_expired') &&
+ typeof body.reason === 'string' &&
+ body.reason.length > 0
+
+ if (!gateRefusal) {
+ return false
+ }
+
+ const method = String(options.method || 'GET').toUpperCase()
+
+ return method === 'GET' || method === 'HEAD' || options.replayOn401 === true
+}
+
/** Ticket minting is replay-safe, unlike arbitrary REST mutations. */
export async function mintGatewayWsTicket(
baseUrl: string,
@@ -64,7 +99,8 @@ export async function mintGatewayWsTicket(
headers: Record<string, string> = {}
): Promise<string> {
const url = `${baseUrl}/api/auth/ws-ticket`
- const options = { method: 'POST', timeoutMs: 8_000, headers }
+ // replayOn401: a ticket that was never issued has no effect to double.
+ const options = { method: 'POST', timeoutMs: 8_000, headers, replayOn401: true }
const ticketFrom = async (request: Promise<any>): Promise<string> => {
const body = await request
diff --git a/apps/desktop/electron/remote-session-cookies.test.ts b/apps/desktop/electron/remote-session-cookies.test.ts
index 774bd0ca26e..6fd74206fbf 100644
--- a/apps/desktop/electron/remote-session-cookies.test.ts
+++ b/apps/desktop/electron/remote-session-cookies.test.ts
@@ -1,20 +1,37 @@
import { describe, expect, it } from 'vitest'
-import { originKeyFor, parseSetCookie, RemoteSessionCookieStore } from './remote-session-cookies'
+import { cookiePathMatches, originKeyFor, parseSetCookie, RemoteSessionCookieStore } from './remote-session-cookies'
+
+const LEGACY = 'persist:hermes-remote-oauth'
+const CONN_A = 'persist:hermes-remote-oauth-conn-a'
+const CONN_B = 'persist:hermes-remote-oauth-conn-b'
describe('parseSetCookie', () => {
- it('takes the first Name=Value pair and ignores attributes', () => {
+ it('takes the first Name=Value pair and keeps the effective path', () => {
expect(parseSetCookie('hermes_session=abc123; Path=/; HttpOnly; SameSite=Lax')).toEqual({
name: 'hermes_session',
- value: 'abc123'
+ value: 'abc123',
+ path: '/',
+ expired: false
})
+ expect(parseSetCookie('hermes_session=abc; Path=/gw-a; HttpOnly')?.path).toBe('/gw-a')
+ // A missing or non-absolute Path falls back to "/".
+ expect(parseSetCookie('a=1')?.path).toBe('/')
+ expect(parseSetCookie('a=1; Path=relative')?.path).toBe('/')
+ })
+
+ it('flags deletions: Max-Age<=0, a past Expires, or an empty value', () => {
+ expect(parseSetCookie('hermes_session=; Path=/; Max-Age=0')?.expired).toBe(true)
+ expect(parseSetCookie('hermes_session=x; Max-Age=-1')?.expired).toBe(true)
+ expect(parseSetCookie('hermes_session=x; Expires=Thu, 01 Jan 1970 00:00:00 GMT')?.expired).toBe(true)
+ expect(parseSetCookie('hermes_session=x; Max-Age=900')?.expired).toBe(false)
+ expect(parseSetCookie('hermes_session=; Path=/')?.expired).toBe(true)
})
it('returns null for unparsable headers', () => {
expect(parseSetCookie('')).toBeNull()
expect(parseSetCookie('nonsense')).toBeNull()
expect(parseSetCookie('=value')).toBeNull()
- expect(parseSetCookie('name=')).toBeNull()
})
})
@@ -27,50 +44,104 @@ describe('originKeyFor', () => {
})
})
+describe('cookiePathMatches', () => {
+ it('implements RFC 6265 path-match', () => {
+ expect(cookiePathMatches('/', '/api/status')).toBe(true)
+ expect(cookiePathMatches('/gw-a', '/gw-a')).toBe(true)
+ expect(cookiePathMatches('/gw-a', '/gw-a/api')).toBe(true)
+ expect(cookiePathMatches('/gw-a/', '/gw-a/api')).toBe(true)
+ expect(cookiePathMatches('/gw-a', '/gw-ab/api')).toBe(false)
+ expect(cookiePathMatches('/gw-a', '/gw-b/api')).toBe(false)
+ })
+})
+
describe('RemoteSessionCookieStore', () => {
- it('records Set-Cookie headers and serializes a Cookie header per origin', () => {
+ it('records Set-Cookie headers and serializes a Cookie header per partition+origin', () => {
const store = new RemoteSessionCookieStore()
- store.record('https://gw.example.com/api/auth/login', 'hermes_session=abc; Path=/; HttpOnly')
- store.record('https://gw.example.com/api/other', ['refresh=xyz; Path=/', 'broken'])
+ store.record(LEGACY, 'https://gw.example.com/api/auth/login', 'hermes_session=abc; Path=/; HttpOnly')
+ store.record(LEGACY, 'https://gw.example.com/api/other', ['refresh=xyz; Path=/', 'broken'])
- expect(store.cookieHeaderFor('https://gw.example.com/api/auth/ws-ticket')).toBe('hermes_session=abc; refresh=xyz')
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/api/auth/ws-ticket')).toBe(
+ 'hermes_session=abc; refresh=xyz'
+ )
// Origin-scoped: another gateway sees nothing.
- expect(store.cookieHeaderFor('https://other.example.com/api')).toBeNull()
+ expect(store.cookieHeaderFor(LEGACY, 'https://other.example.com/api')).toBeNull()
+ // Partition-scoped: the same origin on a different jar sees nothing.
+ expect(store.cookieHeaderFor(CONN_A, 'https://gw.example.com/api/auth/ws-ticket')).toBeNull()
})
- it('overwrites a cookie when the gateway rotates it', () => {
+ it('keeps same-origin sub-path gateways on separate partitions apart (A→B→A)', () => {
const store = new RemoteSessionCookieStore()
+ const a = 'https://gw.example.com/gw-a/api/auth/ws-ticket'
+ const b = 'https://gw.example.com/gw-b/api/auth/ws-ticket'
+
+ store.record(CONN_A, a, 'hermes_session=session-a; Path=/')
+ store.record(CONN_B, b, 'hermes_session=session-b; Path=/')
+ // Back to A: B's later credential must not have replaced A's.
+ expect(store.cookieHeaderFor(CONN_A, a)).toBe('hermes_session=session-a')
+ expect(store.cookieHeaderFor(CONN_B, b)).toBe('hermes_session=session-b')
+
+ // A B-only 401 clears only B.
+ store.clear(CONN_B, b)
+ expect(store.cookieHeaderFor(CONN_B, b)).toBeNull()
+ expect(store.cookieHeaderFor(CONN_A, a)).toBe('hermes_session=session-a')
+ })
- store.record('https://gw.example.com', 'hermes_session=old; Path=/')
- store.record('https://gw.example.com', 'hermes_session=new; Path=/')
+ it('honours cookie Path scope within one partition+origin', () => {
+ const store = new RemoteSessionCookieStore()
- expect(store.cookieHeaderFor('https://gw.example.com/')).toBe('hermes_session=new')
+ store.record(LEGACY, 'https://gw.example.com/gw-a/', 'hermes_session=scoped; Path=/gw-a')
+ store.record(LEGACY, 'https://gw.example.com/', 'shared=1; Path=/')
+
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/gw-a/api/status')).toBe(
+ 'hermes_session=scoped; shared=1'
+ )
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/gw-b/api/status')).toBe('shared=1')
})
- it('seeds from a session jar read', () => {
+ it('overwrites a cookie when the gateway rotates it and deletes it on an expiring Set-Cookie', () => {
const store = new RemoteSessionCookieStore()
- store.recordFromJar('https://gw.example.com', [
- { name: 'hermes_session', value: 'jar-value' },
+ store.record(LEGACY, 'https://gw.example.com', 'hermes_session=old; Path=/')
+ store.record(LEGACY, 'https://gw.example.com', 'hermes_session=new; Path=/')
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/')).toBe('hermes_session=new')
+
+ store.record(LEGACY, 'https://gw.example.com', 'hermes_session=; Path=/; Max-Age=0')
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/')).toBeNull()
+ })
+
+ it('seeds from a session jar read, keeping the jar path', () => {
+ const store = new RemoteSessionCookieStore()
+
+ store.recordFromJar(LEGACY, 'https://gw.example.com', [
+ { name: 'hermes_session', value: 'jar-value', path: '/' },
+ { name: 'scoped', value: 's', path: '/gw-a' },
{ name: '', value: 'x' },
{ value: 'no-name' }
])
- expect(store.cookieHeaderFor('https://gw.example.com/x')).toBe('hermes_session=jar-value')
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/x')).toBe('hermes_session=jar-value')
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/gw-a/x')).toBe('hermes_session=jar-value; scoped=s')
})
- it('clear drops only the target origin (or everything)', () => {
+ it('clear drops the target partition+origin, a whole partition, or everything', () => {
const store = new RemoteSessionCookieStore()
- store.record('https://gw.example.com', 'a=1; Path=/')
- store.record('https://other.example.com', 'b=2; Path=/')
+ store.record(LEGACY, 'https://gw.example.com', 'a=1; Path=/')
+ store.record(LEGACY, 'https://other.example.com', 'b=2; Path=/')
+ store.record(CONN_A, 'https://gw.example.com', 'c=3; Path=/')
+
+ store.clear(LEGACY, 'https://gw.example.com/api/status')
+ expect(store.cookieHeaderFor(LEGACY, 'https://gw.example.com/')).toBeNull()
+ expect(store.cookieHeaderFor(LEGACY, 'https://other.example.com/')).toBe('b=2')
+ expect(store.cookieHeaderFor(CONN_A, 'https://gw.example.com/')).toBe('c=3')
- store.clear('https://gw.example.com/api/status')
- expect(store.cookieHeaderFor('https://gw.example.com/')).toBeNull()
- expect(store.cookieHeaderFor('https://other.example.com/')).toBe('b=2')
+ store.clear(LEGACY)
+ expect(store.cookieHeaderFor(LEGACY, 'https://other.example.com/')).toBeNull()
+ expect(store.cookieHeaderFor(CONN_A, 'https://gw.example.com/')).toBe('c=3')
store.clear()
- expect(store.cookieHeaderFor('https://other.example.com/')).toBeNull()
+ expect(store.cookieHeaderFor(CONN_A, 'https://gw.example.com/')).toBeNull()
})
})
diff --git a/apps/desktop/electron/remote-session-cookies.ts b/apps/desktop/electron/remote-session-cookies.ts
index 56a422b327a..72c99a77119 100644
--- a/apps/desktop/electron/remote-session-cookies.ts
+++ b/apps/desktop/electron/remote-session-cookies.ts
@@ -1,7 +1,7 @@
/**
* remote-session-cookies.ts
*
- * In-memory per-origin session-cookie mirror for remote gateways (#61457).
+ * In-memory session-cookie mirror for remote gateways (#61457).
*
* The `persist:hermes-remote-oauth` partition family is supposed to keep the
* dashboard `hermes_session*` cookies on disk, but in the field the Chromium
@@ -12,27 +12,55 @@
*
* This module is the belt-and-braces fix: capture every `Set-Cookie` the
* gateway sends (login window navigations AND authed REST responses) into a
- * process-lifetime map keyed by origin, and let `fetchJsonViaOauthSession`
- * attach them as an explicit `Cookie` header — an explicit header is never
- * subject to the network stack's jar-lookup flakiness.
+ * process-lifetime map, and let `fetchJsonViaOauthSession` attach them as an
+ * explicit `Cookie` header — an explicit header is never subject to the
+ * network stack's jar-lookup flakiness.
+ *
+ * Scoping mirrors the jar it shadows, never something weaker:
+ * - the map is keyed by the resolved OAuth PARTITION (the same owner
+ * `resolveOauthPartition` picks for the request — per-connection for
+ * non-primary registered remotes, #92183) and then by origin, so two
+ * same-origin gateways that ride separate jars never see each other's
+ * credentials through this mirror either;
+ * - each cookie keeps its effective `Path` and is only presented to requests
+ * whose path matches it (RFC 6265 §5.1.4);
+ * - a `Set-Cookie` with `Max-Age<=0`, a past `Expires`, or an empty value
+ * DELETES the mirror entry, so a server-side sign-out is honoured.
*
* Secrets stay in process memory only (never persisted to disk), and
- * `clear(origin)` drops a stale identity so an old session can never cross
- * into a newly selected one.
+ * `clear(partition, origin)` drops a stale identity so an old session can
+ * never cross into a newly selected one.
*/
export interface ParsedCookie {
name: string
value: string
+ /** Effective cookie path (`Path=` attribute, else `/`). */
+ path: string
+ /** True when the header asks the client to delete the cookie. */
+ expired: boolean
+}
+
+interface MirroredCookie {
+ value: string
+ path: string
+}
+
+function normalizeCookiePath(raw: string | undefined): string {
+ const path = String(raw ?? '').trim()
+
+ // RFC 6265 §5.1.4: an empty or non-absolute Path attribute falls back to
+ // the default path; the gateway always sets Path=/ so "/" is the fallback.
+ return path.startsWith('/') ? path : '/'
}
-/** `Name=Value` from the first attribute pair of a Set-Cookie header; null when unparsable. */
+/** First `Name=Value` pair plus effective path/deletion of a Set-Cookie header; null when unparsable. */
export function parseSetCookie(header: string): ParsedCookie | null {
if (typeof header !== 'string' || !header.trim()) {
return null
}
- const firstPair = header.split(';', 1)[0] ?? ''
+ const [firstPair = '', ...attributes] = header.split(';')
const eq = firstPair.indexOf('=')
if (eq <= 0) {
@@ -42,11 +70,37 @@ export function parseSetCookie(header: string): ParsedCookie | null {
const name = firstPair.slice(0, eq).trim()
const value = firstPair.slice(eq + 1).trim()
- if (!name || !value) {
+ if (!name) {
return null
}
- return { name, value }
+ let path: string | undefined
+ // An empty value is how some servers clear a cookie; treat it as deletion.
+ let expired = !value
+
+ for (const attribute of attributes) {
+ const attrEq = attribute.indexOf('=')
+ const attrName = (attrEq >= 0 ? attribute.slice(0, attrEq) : attribute).trim().toLowerCase()
+ const attrValue = attrEq >= 0 ? attribute.slice(attrEq + 1).trim() : ''
+
+ if (attrName === 'path') {
+ path = attrValue
+ } else if (attrName === 'max-age') {
+ const seconds = Number(attrValue)
+
+ if (Number.isFinite(seconds) && seconds <= 0) {
+ expired = true
+ }
+ } else if (attrName === 'expires') {
+ const at = Date.parse(attrValue)
+
+ if (Number.isFinite(at) && at <= Date.now()) {
+ expired = true
+ }
+ }
+ }
+
+ return { name, value, path: normalizeCookiePath(path), expired }
}
/** `protocol//host` origin key for a request URL; null when not http(s). */
@@ -64,19 +118,62 @@ export function originKeyFor(url: string): string | null {
}
}
+function requestPathFor(url: string): string {
+ try {
+ return new URL(url).pathname || '/'
+ } catch {
+ return '/'
+ }
+}
+
+/** RFC 6265 §5.1.4 path-match. */
+export function cookiePathMatches(cookiePath: string, requestPath: string): boolean {
+ if (cookiePath === requestPath) {
+ return true
+ }
+
+ if (!requestPath.startsWith(cookiePath)) {
+ return false
+ }
+
+ return cookiePath.endsWith('/') || requestPath.charAt(cookiePath.length) === '/'
+}
+
export class RemoteSessionCookieStore {
- private readonly byOrigin = new Map<string, Map<string, string>>()
+ /** partition → origin → cookie name → mirrored cookie */
+ private readonly byPartition = new Map<string, Map<string, Map<string, MirroredCookie>>>()
+
+ private jarFor(partition: string, origin: string, create: boolean): Map<string, MirroredCookie> | undefined {
+ let origins = this.byPartition.get(partition)
+
+ if (!origins) {
+ if (!create) {
+ return undefined
+ }
- /** Record every parsable cookie from a response's `Set-Cookie` header(s). */
- record(url: string, setCookie: string | string[] | undefined | null): void {
+ origins = new Map()
+ this.byPartition.set(partition, origins)
+ }
+
+ let jar = origins.get(origin)
+
+ if (!jar && create) {
+ jar = new Map()
+ origins.set(origin, jar)
+ }
+
+ return jar
+ }
+
+ /** Record every parsable cookie from a response's `Set-Cookie` header(s); deletions are honoured. */
+ record(partition: string, url: string, setCookie: string | string[] | undefined | null): void {
const origin = originKeyFor(url)
- if (!origin || !setCookie) {
+ if (!partition || !origin || !setCookie) {
return
}
const headers = Array.isArray(setCookie) ? setCookie : [setCookie]
- let jar = this.byOrigin.get(origin)
for (const header of headers) {
const parsed = parseSetCookie(header)
@@ -85,60 +182,77 @@ export class RemoteSessionCookieStore {
continue
}
- if (!jar) {
- jar = new Map()
- this.byOrigin.set(origin, jar)
+ if (parsed.expired) {
+ this.jarFor(partition, origin, false)?.delete(parsed.name)
+
+ continue
}
- jar.set(parsed.name, parsed.value)
+ this.jarFor(partition, origin, true)!.set(parsed.name, { value: parsed.value, path: parsed.path })
}
}
/** Seed the mirror from a session jar read (`sess.cookies.get({url})` results). */
- recordFromJar(url: string, cookies: Array<{ name?: unknown; value?: unknown }> | null | undefined): void {
+ recordFromJar(
+ partition: string,
+ url: string,
+ cookies: Array<{ name?: unknown; value?: unknown; path?: unknown }> | null | undefined
+ ): void {
const origin = originKeyFor(url)
- if (!origin || !Array.isArray(cookies)) {
+ if (!partition || !origin || !Array.isArray(cookies)) {
return
}
for (const cookie of cookies) {
if (typeof cookie?.name === 'string' && typeof cookie?.value === 'string' && cookie.name && cookie.value) {
- let jar = this.byOrigin.get(origin)
-
- if (!jar) {
- jar = new Map()
- this.byOrigin.set(origin, jar)
- }
-
- jar.set(cookie.name, cookie.value)
+ this.jarFor(partition, origin, true)!.set(cookie.name, {
+ value: cookie.value,
+ path: normalizeCookiePath(typeof cookie.path === 'string' ? cookie.path : undefined)
+ })
}
}
}
- /** Serialize the origin's mirror as a `Cookie` header value; null when empty. */
- cookieHeaderFor(url: string): string | null {
+ /** Serialize the partition+origin mirror as a `Cookie` header for this request path; null when empty. */
+ cookieHeaderFor(partition: string, url: string): string | null {
const origin = originKeyFor(url)
- const jar = origin ? this.byOrigin.get(origin) : undefined
+ const jar = partition && origin ? this.jarFor(partition, origin, false) : undefined
if (!jar || jar.size === 0) {
return null
}
- return [...jar.entries()].map(([name, value]) => `${name}=${value}`).join('; ')
+ const requestPath = requestPathFor(url)
+
+ const pairs = [...jar.entries()]
+ .filter(([, cookie]) => cookiePathMatches(cookie.path, requestPath))
+ .map(([name, cookie]) => `${name}=${cookie.value}`)
+
+ return pairs.length ? pairs.join('; ') : null
}
- /** Drop one origin's mirror (stale identity / forced re-login); omit to clear everything. */
- clear(originOrUrl?: string): void {
+ /**
+ * Drop one partition's mirror for an origin (stale identity / forced
+ * re-login). Omit the url to drop the whole partition; omit both to clear
+ * everything.
+ */
+ clear(partition?: string, originOrUrl?: string): void {
+ if (!partition) {
+ this.byPartition.clear()
+
+ return
+ }
+
if (!originOrUrl) {
- this.byOrigin.clear()
+ this.byPartition.delete(partition)
return
}
const origin = originKeyFor(originOrUrl) ?? originOrUrl
- this.byOrigin.delete(origin)
+ this.byPartition.get(partition)?.delete(origin)
}
}