Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/edge/src/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type { Place } from './headers.ts'
import {
APP_SESSION_COOKIE,
appPolicyOf,
appSessionCookies,
BINDING_COOKIE,
cookiesOf,
headersFromApp,
Expand Down Expand Up @@ -109,7 +110,7 @@ async function redeem(visit: Visit): Promise<Response> {
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')
Expand Down Expand Up @@ -219,7 +220,7 @@ async function dispatch(request: Request, env: Env, exports: Exports): Promise<R
const answer = await visit.hub.checkAppCall({ host: visit.label, session: session.data })
if (answer.kind === 'DONE') return toApp(visit, answer.value, session.data)
if (answer.kind === 'REFUSED' && answer.code === 'APP_SESSION_INVALID') {
return toHub(visit, [setCookie(APP_SESSION_COOKIE, '', place)])
return toHub(visit, appSessionCookies('', place))
}
const refusal = answer.kind === 'REFUSED' ? CHECK_REFUSALS[answer.code] : undefined
return failure(
Expand Down
9 changes: 6 additions & 3 deletions apps/edge/src/dispatcher-frame.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const IN_FRAME = { 'Sec-Fetch-Dest': 'iframe', 'Sec-Fetch-Site': 'cross-site' }
const DISPATCHER_COOKIE =
/^__Host-conexus-(binding|app)=[^;]*; Path=\/; Secure; HttpOnly; SameSite=None; Partitioned(; Max-Age=0)?$/

test('cookies particionados no iframe: o vínculo, a sessão e o apagar de cada um', async () => {
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 }),
Expand All @@ -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. */
Expand Down
69 changes: 54 additions & 15 deletions apps/edge/src/dispatcher-tab.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>()
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)
}
},
}
Expand All @@ -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<typeof edge>, tab: ReturnType<typeof safariTab>) {
async function visit(door: ReturnType<typeof edge>, tab: ReturnType<typeof tabOf>) {
const hops: string[] = []
let at = new URL('/', APP_ORIGIN)
let crossings = 0
Expand Down Expand Up @@ -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<typeof tabOf>): 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}`])
})
8 changes: 6 additions & 2 deletions apps/edge/src/dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down Expand Up @@ -41,14 +43,15 @@ 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}` },
})
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
Expand Down Expand Up @@ -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}` },
Expand All @@ -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)
Expand Down
19 changes: 17 additions & 2 deletions apps/edge/src/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,30 @@ 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' : ''
const site = place === 'FRAME' ? 'SameSite=None; Partitioned' : 'SameSite=Lax'
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)
Expand Down
Loading