Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow withCredentials for XHR #557

Merged
merged 3 commits into from
Feb 24, 2024
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
11 changes: 11 additions & 0 deletions scripts/server.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ exports.createServer = function (port, enableAtomics) {
if (url.pathname === '/') {
res.writeHead(301, { Location: '/tests/' });
return res.end();
} else if (url.pathname === '/api/cookie') {
const name = url.searchParams.get('name');
let date = new Date();
date.setTime(date.getTime() + 24 * 60 * 60 * 1000); // 24 hours from now
let expires = date.toUTCString();
res.writeHead(200, {
'Set-Cookie': `${name}=1; Path=/; Domain=localhost; expires=${expires}; SameSite=Lax;`,
'Access-Control-Allow-Origin': req.headers.origin ? req.headers.origin : '*',
'Access-Control-Allow-Credentials': 'true',
});
return res.end();
} else if (url.pathname.endsWith('post')) {
res.writeHead(200);
let body = '';
Expand Down
9 changes: 2 additions & 7 deletions src/lib/sandbox/read-main-platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@ import {
serializeConfig,
} from '../utils';
import { config, docImpl, libPath, mainWindow } from './main-globals';
import {
InterfaceType,
InterfaceInfo,
InterfaceMember,
InitWebWorkerData,
} from '../types';
import { InterfaceType, InterfaceInfo, InterfaceMember, InitWebWorkerData } from '../types';

export const readMainPlatform = () => {
const elm = docImpl.createElement('i');
Expand Down Expand Up @@ -66,7 +61,7 @@ export const readMainPlatform = () => {
$config$,
$interfaces$: readImplementations(impls, initialInterfaces),
$libPath$: new URL(libPath, mainWindow.location as any) + '',
$origin$: origin
$origin$: origin,
};

addGlobalConstructorUsingPrototype(
Expand Down
5 changes: 5 additions & 0 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,11 @@ export interface PartytownConfig {
get?: GetHook;
set?: SetHook;
apply?: ApplyHook;
/**
* When set to true, the Partytown Web Worker will respect the `withCredentials` option of XMLHttpRequests.
* Default: false
*/
allowXhrCredentials?: boolean;
/**
* An absolute path to the root directory which Partytown library files
* can be found. The library path must start and end with a `/`.
Expand Down
5 changes: 1 addition & 4 deletions src/lib/web-worker/init-web-worker.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
commaSplit,
webWorkerCtx,
} from './worker-constants';
import { commaSplit, webWorkerCtx } from './worker-constants';
import type { InitWebWorkerData, PartytownInternalConfig } from '../types';

export const initWebWorker = (initWebWorkerData: InitWebWorkerData) => {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/web-worker/worker-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const addStorageApi = (

get length() {
if (isSameOrigin) {
return getter(win, [storageName, 'length'])
return getter(win, [storageName, 'length']);
} else {
warnCrossOrigin('length', storageName, env);
}
Expand Down
6 changes: 5 additions & 1 deletion src/lib/web-worker/worker-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,11 @@ export const createWindow = (
args[1] = resolveUrl(env, args[1], 'xhr');
(super.open as any)(...args);
}
set withCredentials(_: any) {}
set withCredentials(_: boolean) {
if (webWorkerCtx.$config$.allowXhrCredentials) {
super.withCredentials = _;
}
}
toString() {
return str;
}
Expand Down
8 changes: 8 additions & 0 deletions tests/platform/fetch/fetch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ test('fetch', async ({ page }) => {
const testFetchJson = page.locator('#testFetchJson');
await expect(testFetchJson).toHaveText('{"mph":88}');

await page.waitForSelector('.testFetchCookie');
const testFetchCookie = page.locator('#testFetchCookie');
await expect(testFetchCookie).toContainText('server-test-fetch=1');

await page.waitForSelector('.testXMLHttpRequest');
const testXMLHttpRequest = page.locator('#testXMLHttpRequest');
await expect(testXMLHttpRequest).toHaveText('text');
Expand All @@ -22,4 +26,8 @@ test('fetch', async ({ page }) => {

const testXMLHttpRequestCstrNative = page.locator('#testXMLHttpRequestCstrNative');
await expect(testXMLHttpRequestCstrNative).toHaveText('true');

await page.waitForSelector('.testXMLHttpRequestCookie');
const testXMLHttpRequestCookie = page.locator('#testXMLHttpRequestCookie');
await expect(testXMLHttpRequestCookie).toContainText('server-test-xhr=1');
});
39 changes: 39 additions & 0 deletions tests/platform/fetch/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,24 @@ <h1>fetch() / XMLHttpRequest</h1>
</script>
</li>

<li>
<strong>fetch Set-Cookie</strong>
<code>
<span id="testFetchCookie"></span>
</code>
<script type="text/partytown">
(async function () {
const url = new URL('/api/cookie?name=server-test-fetch', location.origin);
const elm = document.getElementById('testFetchCookie');
const rsp = await fetch(url, {
credentials: 'include',
});
elm.textContent = document.cookie;
elm.className = 'testFetchCookie';
})();
</script>
</li>

<li>
<strong>XMLHttpRequest</strong>
<code id="testXMLHttpRequest"></code>
Expand Down Expand Up @@ -161,6 +179,27 @@ <h1>fetch() / XMLHttpRequest</h1>
</script>
</li>

<li>
<strong>XMLHttpRequest Set-Cookie</strong>
<code>
<span id="testXMLHttpRequestCookie"></span>
</code>
<script type="text/partytown">
(async function () {
const url = new URL('/api/cookie?name=server-test-xhr', location.origin);
const elm = document.getElementById('testXMLHttpRequestCookie');
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', function () {
elm.textContent = document.cookie;
elm.className = 'testXMLHttpRequestCookie';
});
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.send();
})();
</script>
</li>

<script type="text/partytown">
(function () {
document.body.classList.add('completed');
Expand Down
Loading