diff --git a/apps/edge/src/dispatch.ts b/apps/edge/src/dispatch.ts index df27d830c..7c5295495 100644 --- a/apps/edge/src/dispatch.ts +++ b/apps/edge/src/dispatch.ts @@ -16,6 +16,7 @@ import type { Place } from './headers.ts' import { APP_SESSION_COOKIE, appPolicyOf, + appSessionCookies, BINDING_COOKIE, cookiesOf, headersFromApp, @@ -109,7 +110,7 @@ async function redeem(visit: Visit): Promise { if (!body.success) return failure(visit, 'APP_HANDOFF_INVALID') const answer = await visit.hub.createAppSession(body.data) if (answer.kind === 'DONE') { - return redirect(visit, '/', [setCookie(APP_SESSION_COOKIE, answer.value.session, visit.place)]) + return redirect(visit, '/', appSessionCookies(answer.value.session, visit.place)) } if (answer.kind === 'REFUSED' && answer.code === 'APP_HANDOFF_INVALID') { return failure(visit, 'APP_HANDOFF_INVALID') @@ -219,7 +220,7 @@ async function dispatch(request: Request, env: Env, exports: Exports): Promise { +test('cookies particionados no iframe: o vínculo, a sessão e o apagar, que leva também a forma da aba', async () => { const first = await edge().fetch('/', { headers: IN_FRAME }) const redeemed = await edge({ hub: () => Response.json({ session: SESSION }, { status: 201 }), @@ -27,8 +27,11 @@ test('cookies particionados no iframe: o vínculo, a sessão e o apagar de cada headers: { ...IN_FRAME, Cookie: `__Host-conexus-app=${SESSION}` }, }) const cookies = [first, redeemed, expired].flatMap((response) => response.headers.getSetCookie()) - assert.equal(cookies.length, 4) - for (const cookie of cookies) assert.match(cookie, DISPATCHER_COOKIE) + assert.equal(cookies.length, 5) + assert.deepEqual( + cookies.filter((cookie) => !DISPATCHER_COOKIE.test(cookie)), + ['__Host-conexus-app=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0'], + ) }) /** The value of the `frame-ancestors` directive, the policy's last. */ diff --git a/apps/edge/src/dispatcher-tab.test.ts b/apps/edge/src/dispatcher-tab.test.ts index c9217fc3c..129ee3459 100644 --- a/apps/edge/src/dispatcher-tab.test.ts +++ b/apps/edge/src/dispatcher-tab.test.ts @@ -3,25 +3,35 @@ import { test } from 'node:test' import { APP_ORIGIN, CODE, EXAMPLE_CALL, edge, problem, SESSION } from './test-edge.ts' // The app's own tab coming back with a live Hub session: app, Hub, the pass and the app again, all -// 303s. Safari drops a `Partitioned` cookie set at the end of a redirect chain that left the site -// and came back (WebKit bug 306194, Safari 26.2 on macOS and iOS), so a tab whose session cookie is -// partitioned never keeps the pass's session and runs the chain until "too many redirects". +// 303s. In WebKit a `Partitioned` cookie is not reliably sent back to a tab after a redirect chain +// (WebKit bugs 316066 and 306194). The jar models what the founder's loop showed, not either bug: +// the partitioned session that the pass's answer writes never comes back, and the chain runs until +// "too many redirects". const HUB = 'https://hub.conexus.fun' const MAX_HOPS = 16 -/** A tab's cookie jar on the app's host, as Safari keeps it at the top level. */ -function safariTab() { +/** + * How a browser keeps the tab's cookies. `partitions`: a `Partitioned` cookie is kept apart from an + * unpartitioned one of the same name (CHIPS); `returnsLatePartitioned`: a partitioned cookie written + * after the Hub comes back. + */ +type Browser = { partitions: boolean; returnsLatePartitioned: boolean } +const WEBKIT: Browser = { partitions: true, returnsLatePartitioned: false } +const CHROMIUM: Browser = { partitions: true, returnsLatePartitioned: true } +const NO_CHIPS: Browser = { partitions: false, returnsLatePartitioned: true } + +/** A tab's cookie jar on the app's host, at the top level; the older cookie is sent first. */ +function tabOf(browser: Browser) { const jar = new Map() return { - header: () => [...jar].map(([name, value]) => `${name}=${value}`).join('; '), + header: () => [...jar.values()].join('; '), store(lines: readonly string[], crossings: number) { for (const line of lines) { const [pair = '', ...attributes] = line.split('; ') - const at = pair.indexOf('=') - if (attributes.includes('Max-Age=0')) jar.delete(pair.slice(0, at)) - else if (!(attributes.includes('Partitioned') && crossings >= 2)) { - jar.set(pair.slice(0, at), pair.slice(at + 1)) - } + const partitioned = browser.partitions && attributes.includes('Partitioned') + const key = `${pair.slice(0, pair.indexOf('='))}${partitioned ? '; Partitioned' : ''}` + if (attributes.includes('Max-Age=0')) jar.delete(key) + else if (!partitioned || crossings < 2 || browser.returnsLatePartitioned) jar.set(key, pair) } }, } @@ -34,7 +44,7 @@ function hubOpens(url: URL): string { } /** Follows the 303s as a tab does, from the app's address, until a page or `MAX_HOPS`. */ -async function visit(door: ReturnType, tab: ReturnType) { +async function visit(door: ReturnType, tab: ReturnType) { const hops: string[] = [] let at = new URL('/', APP_ORIGIN) let crossings = 0 @@ -74,16 +84,45 @@ function liveHub(request: Request): Response { return Response.json(EXAMPLE_CALL) } +const STALE = `__Host-conexus-app=${'v'.repeat(43)}; Path=/; Secure; HttpOnly` + +/** The app session cookies the tab sends once the app opened. */ +function sessionsOf(tab: ReturnType): string[] { + return tab + .header() + .split('; ') + .filter((pair) => pair.startsWith('__Host-conexus-app=')) +} + test('aba que volta ao app com o Hub aberto: a passagem leva ao app, sem laço de redirecionamentos', async () => { - const { hops, response } = await visit(edge({ hub: liveHub }), safariTab()) + const tab = tabOf(WEBKIT) + const { hops, response } = await visit(edge({ hub: liveHub }), tab) assert.deepEqual(hops, ['/', 'hub', '/__conexus/passagem', '/']) assert.equal(await response?.text(), 'Olá, Ana Souza.') + assert.deepEqual(sessionsOf(tab), [`__Host-conexus-app=${SESSION}`]) }) test('aba com a sessão do app vencida e o Hub aberto: apagada, e o app abre na volta', async () => { - const tab = safariTab() - tab.store([`__Host-conexus-app=${'v'.repeat(43)}; Path=/; Secure; HttpOnly; SameSite=Lax`], 0) + const tab = tabOf(WEBKIT) + tab.store([`${STALE}; SameSite=Lax`], 0) + const { hops, response } = await visit(edge({ hub: liveHub }), tab) + assert.deepEqual(hops, ['/', 'hub', '/__conexus/passagem', '/']) + assert.equal(await response?.text(), 'Olá, Ana Souza.') +}) + +test('aba com a sessão particionada de antes, vencida: as duas formas saem, e fica só a nova', async () => { + const tab = tabOf(CHROMIUM) + tab.store([`${STALE}; SameSite=None; Partitioned`], 0) + const { hops, response } = await visit(edge({ hub: liveHub }), tab) + assert.deepEqual(hops, ['/', 'hub', '/__conexus/passagem', '/']) + assert.equal(await response?.text(), 'Olá, Ana Souza.') + assert.deepEqual(sessionsOf(tab), [`__Host-conexus-app=${SESSION}`]) +}) + +test('navegador que ignora Partitioned: apagar a forma antiga não leva a sessão nova', async () => { + const tab = tabOf(NO_CHIPS) const { hops, response } = await visit(edge({ hub: liveHub }), tab) assert.deepEqual(hops, ['/', 'hub', '/__conexus/passagem', '/']) assert.equal(await response?.text(), 'Olá, Ana Souza.') + assert.deepEqual(sessionsOf(tab), [`__Host-conexus-app=${SESSION}`]) }) diff --git a/apps/edge/src/dispatcher.test.ts b/apps/edge/src/dispatcher.test.ts index d445769fb..815cbd443 100644 --- a/apps/edge/src/dispatcher.test.ts +++ b/apps/edge/src/dispatcher.test.ts @@ -5,6 +5,8 @@ import { serveApp } from '@conexus/app-contract' import { BINDING, CODE, EXAMPLE_CALL, edge, HOST, pageText, problem, SESSION } from './test-edge.ts' const COOKIE_ATTRIBUTES = 'Path=/; Secure; HttpOnly; SameSite=Lax' +const PARTITIONED_DELETED = + '__Host-conexus-app=; Path=/; Secure; HttpOnly; SameSite=None; Partitioned; Max-Age=0' const HUB = 'https://hub.conexus.fun' const HUB_OPEN = `${HUB}/apps/open` @@ -41,7 +43,7 @@ test('primeira visita com vínculo: o mesmo, sem cookie novo', async () => { assert.equal(hashOf(BINDING), '8BtXImJhrjdWuTk24cTmuEn5pbCTP6O5GEO_QZW52WQ') }) -test('passagem certa: sessão, vínculo mantido para a passagem da outra aba e 303 a /', async () => { +test('passagem certa: a forma particionada antiga apagada, sessão, vínculo mantido e 303 a /', async () => { const door = edge({ hub: () => Response.json({ session: SESSION }, { status: 201 }) }) const response = await door.fetch(`/__conexus/passagem?code=${CODE}`, { headers: { Cookie: `__Host-conexus-binding=${BINDING}` }, @@ -49,6 +51,7 @@ test('passagem certa: sessão, vínculo mantido para a passagem da outra aba e 3 assert.equal(response.status, 303) assert.equal(response.headers.get('Location'), '/') assert.deepEqual(response.headers.getSetCookie(), [ + PARTITIONED_DELETED, `__Host-conexus-app=${SESSION}; ${COOKIE_ATTRIBUTES}`, ]) const [call] = door.hubCalls @@ -81,7 +84,7 @@ test('passagem sem vínculo ou sem código: 403, sem perguntar ao Hub', async () assert.equal(door.hubCalls.length, 0) }) -test('sessão que o Hub não aceita (401): apagada, e de volta ao Hub', async () => { +test('sessão que o Hub não aceita (401): apagada nas duas formas, e de volta ao Hub', async () => { const door = edge({ hub: () => problem('APP_SESSION_INVALID') }) const response = await door.fetch('/', { headers: { Cookie: `__Host-conexus-app=${SESSION}; __Host-conexus-binding=${BINDING}` }, @@ -92,6 +95,7 @@ test('sessão que o Hub não aceita (401): apagada, e de volta ao Hub', async () `${HUB_OPEN}?host=${HOST}&binding=${hashOf(BINDING)}`, ) assert.deepEqual(response.headers.getSetCookie(), [ + PARTITIONED_DELETED, `__Host-conexus-app=; ${COOKIE_ATTRIBUTES}; Max-Age=0`, ]) assert.equal(door.appCalls.length, 0) diff --git a/apps/edge/src/headers.ts b/apps/edge/src/headers.ts index 02788aa90..0aa7a5edb 100644 --- a/apps/edge/src/headers.ts +++ b/apps/edge/src/headers.ts @@ -40,8 +40,9 @@ export function placeOf(headers: Headers): Place { * A cookie of the browser's session on this host only (security S17). In the Hub's Prévia, * `SameSite=None` reaches the framed app and `Partitioned` keeps it to the Hub's frame, as vibesdk's * preview cookie (`spacePreviewToken.ts:60-83`). The tab's is `SameSite=Lax`, which no frame of - * another site receives: Safari drops a `Partitioned` cookie set at the end of the tab's redirect - * chain from the Hub (WebKit bug 306194). An empty value deletes it. + * another site receives: in WebKit a `Partitioned` cookie is not reliably sent back to a tab after + * a redirect chain (WebKit bugs 316066 and 306194); which of them loops a tab was not reproduced. + * An empty value deletes it. */ export function setCookie(name: string, value: string, place: Place): string { const lifetime = value === '' ? '; Max-Age=0' : '' @@ -49,6 +50,20 @@ export function setCookie(name: string, value: string, place: Place): string { return `${name}=${value}; Path=/; Secure; HttpOnly; ${site}${lifetime}` } +/** + * The app session's lines; an empty session deletes it. The browser keeps the partitioned and the + * unpartitioned cookie of one name apart, so a delete names both forms, as GitBook's logout does + * (`visitors.ts:419-426`). A tab kept the partitioned form before it moved to `SameSite=Lax`, and + * writing the new one deletes that form first: a browser that ignores `Partitioned` reads that line + * as a delete of the same cookie. + */ +export function appSessionCookies(session: string, place: Place): string[] { + const partitioned = setCookie(APP_SESSION_COOKIE, '', 'FRAME') + if (session === '') return [partitioned, setCookie(APP_SESSION_COOKIE, '', 'TAB')] + const written = setCookie(APP_SESSION_COOKIE, session, place) + return place === 'TAB' ? [partitioned, written] : [written] +} + /** The request's headers as the app receives them: without the dispatcher's cookies or session. */ export function headersToApp(from: Headers): Headers { const headers = new Headers(from)