Skip to content
Open
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
11 changes: 10 additions & 1 deletion packages/client/src/client/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ export class SSEClientTransport implements Transport {
const fetchImpl = this._redirects(
(eventSourceFetch ? (this._dpop?.(eventSourceFetch as FetchLike) ?? eventSourceFetch) : (this._fetch ?? fetch)) as FetchLike
);
let responseUrl: URL | undefined;
let redirect: string | undefined;
return new Promise((resolve, reject) => {
this._eventSource = new EventSource(this._url.href, {
Expand All @@ -264,6 +265,13 @@ export class SSEClientTransport implements Transport {
...init,
headers
});
if (response.url) {
try {
responseUrl = new URL(response.url);
} catch {
// fall back to this._url
}
}
redirect = this._unfollowedRedirect(url, response);

if (response.status === 401) {
Expand Down Expand Up @@ -334,7 +342,8 @@ export class SSEClientTransport implements Transport {
const messageEvent = event as MessageEvent;

try {
this._endpoint = new URL(messageEvent.data, this._url);
const baseUrl = responseUrl ?? this._url;
this._endpoint = new URL(messageEvent.data, baseUrl);
if (this._endpoint.origin !== this._url.origin) {
throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
}
Expand Down
60 changes: 60 additions & 0 deletions packages/client/test/client/redirects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,32 @@ describe('redirects', () => {
expect(otherRequests[0]).toMatchObject({ method: 'GET', url: '/sse', headers: { 'x-api-key': 'key-1' } });
});

test('SSE endpoint event still rejects foreign-origin endpoints after a cross-origin redirect', async () => {
const redirectedRequests: Recorded[] = [];
const redirected = record(
redirectedRequests,
sseEndpoint((_req, res) => {
res.writeHead(202).end();
})
);
const redirectedUrl = await listenOnRandomPort(redirected);
try {
handle = redirectTo(new URL('/sse', redirectedUrl));

await expect(sseWith(follow).start()).rejects.toThrow(
`Endpoint origin does not match connection origin: ${redirectedUrl.origin}`
);
expect(redirectedRequests).toEqual([
{ method: 'GET', url: '/sse', body: '', headers: expect.objectContaining({ 'x-api-key': 'key-1' }) }
]);
} finally {
await transport?.close();
transport = undefined;
redirected.closeAllConnections();
await new Promise(resolve => redirected.close(resolve));
}
});

test('SSE POST to another origin is followed with its headers and body', async () => {
handle = sseEndpoint(toOther);
const client = await sseStarted(follow);
Expand Down Expand Up @@ -545,6 +571,40 @@ describe('redirects', () => {
});

describe("'same-origin' is the default", () => {
test.each<[string, string, string]>([
['/new/sse', 'messages?sessionId=test', '/new/messages?sessionId=test'],
['/new/sse/', 'messages?sessionId=test', '/new/sse/messages?sessionId=test'],
['/new/sse', '/new/messages?sessionId=test', '/new/messages?sessionId=test']
])(
'SSE endpoint %s with data %s resolves POST to %s after same-origin redirect',
async (redirectedPath, endpointData, expectedPostUrl) => {
handle = (req, res, recorded) => {
if (req.method === 'GET' && req.url === '/old/sse') {
redirectTo(redirectedPath)(req, res, recorded);
return;
}
if (req.method === 'GET' && req.url === redirectedPath) {
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.write(`event: endpoint\ndata: ${endpointData}\n\n`);
return;
}
res.writeHead(202).end();
};
const client = new SSEClientTransport(new URL('/old/sse', endpointUrl), { requestInit });
client.onerror = () => {};
transport = client;
await client.start();

await client.send(notification);

expect(endpointRequests.at(-1)).toMatchObject({
method: 'POST',
url: expectedPostUrl,
body: JSON.stringify(notification)
});
}
);

describe.each(started)('%s', (_name, create) => {
test.each([undefined, 'same-origin', 'other'] as const)(
'set to %s, a redirect to another origin is not followed',
Expand Down
Loading