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

apply set-cookie headers from page dependencies #4588

Merged
merged 9 commits into from
Apr 15, 2022
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: 5 additions & 0 deletions .changeset/eight-files-think.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Apply set-cookie headers from page dependencies
2 changes: 2 additions & 0 deletions packages/adapter-static/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@
},
"devDependencies": {
"@sveltejs/kit": "workspace:*",
"cookie": "^0.5.0",
"devalue": "^2.0.1",
"playwright-chromium": "^1.21.0",
"port-authority": "^1.1.2",
"set-cookie-parser": "^2.4.8",
"sirv": "^2.0.0",
"svelte": "^3.44.2",
"typescript": "^4.6.2",
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@types/mime": "^2.0.3",
"@types/node": "^16.11.11",
"@types/sade": "^1.7.3",
"@types/set-cookie-parser": "^2.4.2",
"amphtml-validator": "^1.0.35",
"cookie": "^0.5.0",
"cross-env": "^7.0.3",
Expand All @@ -36,6 +37,7 @@
"port-authority": "^1.1.2",
"rollup": "^2.60.2",
"selfsigned": "^2.0.0",
"set-cookie-parser": "^2.4.8",
"sirv": "^2.0.0",
"svelte": "^3.44.2",
"svelte-check": "^2.5.0",
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ export default [
plugins: [
resolve({
extensions: ['.mjs', '.js', '.ts']
})
}),
commonjs()
]
},

Expand Down
25 changes: 25 additions & 0 deletions packages/kit/src/runtime/server/page/cookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @param {string} hostname
* @param {string} [constraint]
*/
export function domain_matches(hostname, constraint) {
if (!constraint) return true;

const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;

if (hostname === normalized) return true;
return hostname.endsWith('.' + normalized);
}

/**
* @param {string} path
* @param {string} [constraint]
*/
export function path_matches(path, constraint) {
if (!constraint) return true;

const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;

if (path === normalized) return true;
return path.startsWith(normalized + '/');
}
42 changes: 42 additions & 0 deletions packages/kit/src/runtime/server/page/cookie.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { test } from 'uvu';
import * as assert from 'uvu/assert';
import { domain_matches, path_matches } from './cookie.js';

const domains = {
positive: [
['localhost'],
['example.com', 'example.com'],
['sub.example.com', 'example.com'],
['example.com', '.example.com'],
['sub.example.com', '.example.com']
]
};

const paths = {
positive: [['/'], ['/foo', '/'], ['/foo', '/foo'], ['/foo/', '/foo'], ['/foo', '/foo/']],

negative: [
['/', '/foo'],
['/food', '/foo']
]
};

domains.positive.forEach(([hostname, constraint]) => {
test(`${hostname} / ${constraint}`, () => {
assert.ok(domain_matches(hostname, constraint));
});
});

paths.positive.forEach(([path, constraint]) => {
test(`${path} / ${constraint}`, () => {
assert.ok(path_matches(path, constraint));
});
});

paths.negative.forEach(([path, constraint]) => {
test(`! ${path} / ${constraint}`, () => {
assert.ok(!path_matches(path, constraint));
});
});

test.run();
51 changes: 41 additions & 10 deletions packages/kit/src/runtime/server/page/load_node.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import * as cookie from 'cookie';
import * as set_cookie_parser from 'set-cookie-parser';
import { normalize } from '../../load.js';
import { respond } from '../index.js';
import { is_root_relative, resolve } from '../../../utils/url.js';
import { create_prerendering_url_proxy } from './utils.js';
import { is_pojo, lowercase_keys, normalize_request_method } from '../utils.js';
import { coalesce_to_error } from '../../../utils/error.js';
import { domain_matches, path_matches } from './cookie.js';

/**
* @param {{
Expand Down Expand Up @@ -41,10 +44,10 @@ export async function load_node({
/** @type {Array<import('./types').Fetched>} */
const fetched = [];

/**
* @type {string[]}
*/
let set_cookie_headers = [];
const cookies = cookie.parse(event.request.headers.get('cookie') || '');

/** @type {import('set-cookie-parser').Cookie[]} */
const new_cookies = [];

/** @type {import('types').LoadOutput} */
let loaded;
Expand All @@ -60,7 +63,9 @@ export async function load_node({
: {};

if (shadow.cookies) {
set_cookie_headers.push(...shadow.cookies);
shadow.cookies.forEach((header) => {
new_cookies.push(set_cookie_parser.parseString(header));
});
}

if (shadow.error) {
Expand Down Expand Up @@ -166,9 +171,23 @@ export async function load_node({
if (opts.credentials !== 'omit') {
uses_credentials = true;

const cookie = event.request.headers.get('cookie');
const authorization = event.request.headers.get('authorization');

// combine cookies from the initiating request with any that were
// added via set-cookie
const combined_cookies = { ...cookies };

for (const cookie of new_cookies) {
if (!domain_matches(event.url.hostname, cookie.domain)) continue;
if (!path_matches(resolved, cookie.path)) continue;

combined_cookies[cookie.name] = cookie.value;
}

const cookie = Object.entries(combined_cookies)
.map(([name, value]) => `${name}=${value}`)
.join('; ');

if (cookie) {
opts.headers.set('cookie', cookie);
}
Expand Down Expand Up @@ -231,6 +250,15 @@ export async function load_node({
response = await options.hooks.externalFetch.call(null, external_request);
}

const set_cookie = response.headers.get('set-cookie');
if (set_cookie) {
new_cookies.push(
...set_cookie_parser
.splitCookiesString(set_cookie)
.map((str) => set_cookie_parser.parseString(str))
);
}

const proxy = new Proxy(response, {
get(response, key, _receiver) {
async function text() {
Expand All @@ -239,9 +267,8 @@ export async function load_node({
/** @type {import('types').ResponseHeaders} */
const headers = {};
for (const [key, value] of response.headers) {
if (key === 'set-cookie') {
set_cookie_headers = set_cookie_headers.concat(value);
} else if (key !== 'etag') {
// TODO skip others besides set-cookie and etag?
if (key !== 'set-cookie' && key !== 'etag') {
headers[key] = value;
}
}
Expand Down Expand Up @@ -362,7 +389,11 @@ export async function load_node({
loaded: normalize(loaded),
stuff: loaded.stuff || stuff,
fetched,
set_cookie_headers,
set_cookie_headers: new_cookies.map((new_cookie) => {
const { name, value, ...options } = new_cookie;
// @ts-expect-error
return cookie.serialize(name, value, options);
}),
uses_credentials
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/** @type {import('./a.json').RequestHandler} */
export function get({ url }) {
const answer = url.searchParams.get('answer') || '42';

return {
headers: {
'set-cookie': `answer=${answer}; HttpOnly; Path=/load/set-cookie-fetch`
},
body: {}
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** @type {import('./b.json').RequestHandler} */
export function get({ request }) {
const cookie = request.headers.get('cookie');

const match = /answer=([^;]+)/.exec(cookie);
const answer = +match?.[1];

return {
body: {
answer
},
headers: {
'set-cookie': `doubled=${answer * 2}; HttpOnly; Path=/load/set-cookie-fetch`
}
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<script context="module">
export async function load({ fetch, url }) {
await fetch(`/load/set-cookie-fetch/a.json${url.search}`);
const res = await fetch('/load/set-cookie-fetch/b.json');
const { answer } = await res.json(); // need to read the response so it gets serialized

return {
props: { answer }
};
}
</script>

<script>
/** @type {number} */
export let answer;
</script>

<h1>the answer is {answer}</h1>
15 changes: 15 additions & 0 deletions packages/kit/test/apps/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1331,6 +1331,21 @@ test.describe.parallel('Load', () => {
await clicknav('[href="/load/props/about"]');
expect(await page.textContent('p')).toBe('Data: undefined');
});

test('server-side fetch respects set-cookie header', async ({ page, context }) => {
await context.clearCookies();

await page.goto('/load/set-cookie-fetch');
expect(await page.textContent('h1')).toBe('the answer is 42');

const cookies = {};
for (const cookie of await context.cookies()) {
cookies[cookie.name] = cookie.value;
}

expect(cookies.answer).toBe('42');
expect(cookies.doubled).toBe('84');
});
});

test.describe.parallel('Method overrides', () => {
Expand Down
18 changes: 18 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.