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

Multiple cookies are not set on endpoints #3502

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/proud-bananas-love.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

allow setting multiple set-cookie headers
139 changes: 65 additions & 74 deletions packages/kit/src/core/dev/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { respond } from '../../runtime/server/index.js';
import { __fetch_polyfill } from '../../install-fetch.js';
import { create_app } from '../create_app/index.js';
import create_manifest_data from '../create_manifest_data/index.js';
import { getRawBody, setResponse } from '../../node.js';
import { getRequest, setResponse } from '../../node.js';
import { SVELTE_KIT, SVELTE_KIT_ASSETS } from '../constants.js';
import { get_mime_lookup, resolve_entry, runtime } from '../utils.js';
import { coalesce_to_error } from '../../utils/error.js';
Expand Down Expand Up @@ -143,11 +143,9 @@ export async function create_plugin(config, cwd) {
if (!req.url || !req.method) throw new Error('Incomplete request');
if (req.url === '/favicon.ico') return not_found(res);

const url = new URL(
`${vite.config.server.https ? 'https' : 'http'}://${req.headers.host}${req.url}`
);
const base = `${vite.config.server.https ? 'https' : 'http'}://${req.headers.host}`;

const decoded = decodeURI(url.pathname);
const decoded = decodeURI(new URL(base + req.url).pathname);

if (decoded.startsWith(assets)) {
const pathname = decoded.slice(assets.length);
Expand Down Expand Up @@ -207,76 +205,70 @@ export async function create_plugin(config, cwd) {
assets
});

let body;
let request;

try {
body = await getRawBody(req);
request = await getRequest(base, req);
} catch (/** @type {any} */ err) {
res.statusCode = err.status || 400;
return res.end(err.reason || 'Invalid request body');
}

const rendered = await respond(
new Request(url.href, {
headers: /** @type {Record<string, string>} */ (req.headers),
method: req.method,
body
}),
{
amp: config.kit.amp,
dev: true,
floc: config.kit.floc,
get_stack: (error) => {
vite.ssrFixStacktrace(error);
return error.stack;
},
handle_error: (error, event) => {
vite.ssrFixStacktrace(error);
hooks.handleError({
error,
event,

// TODO remove for 1.0
// @ts-expect-error
get request() {
throw new Error(
'request in handleError has been replaced with event. See /~https://github.com/sveltejs/kit/pull/3384 for details'
);
}
});
},
hooks,
hydrate: config.kit.hydrate,
manifest,
method_override: config.kit.methodOverride,
paths: {
base: config.kit.paths.base,
assets
},
prefix: '',
prerender: config.kit.prerender.enabled,
read: (file) => fs.readFileSync(path.join(config.kit.files.assets, file)),
root,
router: config.kit.router,
target: config.kit.target,
template: ({ head, body, assets }) => {
let rendered = load_template(cwd, config)
.replace(/%svelte\.assets%/g, assets)
// head and body must be replaced last, in case someone tries to sneak in %svelte.assets% etc
.replace('%svelte.head%', () => head)
.replace('%svelte.body%', () => body);

if (amp) {
const result = amp.validateString(rendered);

if (result.status !== 'PASS') {
const lines = rendered.split('\n');

/** @param {string} str */
const escape = (str) =>
str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

rendered = `<!doctype html>
const rendered = await respond(request, {
amp: config.kit.amp,
dev: true,
floc: config.kit.floc,
get_stack: (error) => {
vite.ssrFixStacktrace(error);
return error.stack;
},
handle_error: (error, event) => {
vite.ssrFixStacktrace(error);
hooks.handleError({
error,
event,

// TODO remove for 1.0
// @ts-expect-error
get request() {
throw new Error(
'request in handleError has been replaced with event. See /~https://github.com/sveltejs/kit/pull/3384 for details'
);
}
});
},
hooks,
hydrate: config.kit.hydrate,
manifest,
method_override: config.kit.methodOverride,
paths: {
base: config.kit.paths.base,
assets
},
prefix: '',
prerender: config.kit.prerender.enabled,
read: (file) => fs.readFileSync(path.join(config.kit.files.assets, file)),
root,
router: config.kit.router,
target: config.kit.target,
template: ({ head, body, assets }) => {
let rendered = load_template(cwd, config)
.replace(/%svelte\.assets%/g, assets)
// head and body must be replaced last, in case someone tries to sneak in %svelte.assets% etc
.replace('%svelte.head%', () => head)
.replace('%svelte.body%', () => body);

if (amp) {
const result = amp.validateString(rendered);

if (result.status !== 'PASS') {
const lines = rendered.split('\n');

/** @param {string} str */
const escape = (str) =>
str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

rendered = `<!doctype html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
Expand Down Expand Up @@ -307,14 +299,13 @@ export async function create_plugin(config, cwd) {
)
.join('\n\n')}
`;
}
}
}

return rendered;
},
trailing_slash: config.kit.trailingSlash
}
);
return rendered;
},
trailing_slash: config.kit.trailingSlash
});

if (rendered) {
setResponse(res, rendered);
Expand Down
36 changes: 12 additions & 24 deletions packages/kit/src/core/preview/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import https from 'https';
import { join, resolve } from 'path';
import sirv from 'sirv';
import { pathToFileURL } from 'url';
import { getRawBody } from '../../node.js';
import { getRequest, setResponse } from '../../node.js';
import { __fetch_polyfill } from '../../install-fetch.js';
import { SVELTE_KIT, SVELTE_KIT_ASSETS } from '../constants.js';
import { to_headers } from '../../utils/http.js';

/** @param {string} dir */
const mutable = (dir) =>
Expand Down Expand Up @@ -80,32 +79,21 @@ export async function preview({
const initial_url = req.url;

const render_handler = async () => {
if (!req.method) throw new Error('Incomplete request');

let body;

try {
body = await getRawBody(req);
} catch (/** @type {any} */ err) {
res.statusCode = err.status || 400;
return res.end(err.reason || 'Invalid request body');
}

if (initial_url.startsWith(config.kit.paths.base)) {
const protocol = use_https ? 'https' : 'http';
const host = req.headers['host'];

const rendered = await app.render(
new Request(`${protocol}://${host}${initial_url}`, {
method: req.method,
headers: to_headers(req.headers),
body
})
);

res.writeHead(rendered.status, Object.fromEntries(rendered.headers));
if (rendered.body) res.write(new Uint8Array(await rendered.arrayBuffer()));
res.end();
let request;

try {
req.url = initial_url;
request = await getRequest(`${protocol}://${host}`, req);
} catch (/** @type {any} */ err) {
res.statusCode = err.status || 400;
return res.end(err.reason || 'Invalid request body');
}

setResponse(res, await app.render(request));
} else {
res.statusCode = 404;
res.end('Not found');
Expand Down
14 changes: 11 additions & 3 deletions packages/kit/src/node.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Readable } from 'stream';

/** @type {import('@sveltejs/kit/node').GetRawBody} */
export function getRawBody(req) {
function get_raw_body(req) {
return new Promise((fulfil, reject) => {
const h = req.headers;

Expand Down Expand Up @@ -55,13 +55,21 @@ export async function getRequest(base, req) {
return new Request(base + req.url, {
method: req.method,
headers: /** @type {Record<string, string>} */ (req.headers),
body: await getRawBody(req)
body: await get_raw_body(req) // TODO stream rather than buffer
});
}

/** @type {import('@sveltejs/kit/node').SetResponse} */
export async function setResponse(res, response) {
res.writeHead(response.status, Object.fromEntries(response.headers));
/** @type {import('../types/helper').ResponseHeaders} */
const headers = Object.fromEntries(response.headers);

if (response.headers.has('set-cookie')) {
// @ts-expect-error (headers.raw() is non-standard)
headers['set-cookie'] = response.headers.raw()['set-cookie'];
}

res.writeHead(response.status, headers);

if (response.body instanceof Readable) {
response.body.pipe(res);
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/test/apps/basics/src/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const handle = sequence(
}

const response = await resolve(event, { ssr: !event.url.pathname.startsWith('/no-ssr') });
response.headers.set('set-cookie', 'name=SvelteKit; path=/; HttpOnly');
response.headers.append('set-cookie', 'name=SvelteKit; path=/; HttpOnly');

return response;
}
Expand Down
7 changes: 7 additions & 0 deletions packages/kit/test/apps/basics/src/routes/set-cookie/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function get() {
return {
headers: {
'set-cookie': ['answer=42; HttpOnly', 'problem=comma, separated, values; HttpOnly']
}
};
}
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 @@ -444,6 +444,21 @@ test.describe.parallel('Endpoints', () => {
server.close();
}
});

test('multiple set-cookie on endpoints using GET', async ({ request }) => {
const response = await request.get('/set-cookie');

const cookies = response
.headersArray()
.filter((obj) => obj.name === 'set-cookie')
.map((obj) => obj.value);

expect(cookies).toEqual([
'answer=42; HttpOnly',
'problem=comma, separated, values; HttpOnly',
'name=SvelteKit; path=/; HttpOnly'
]);
});
});

test.describe.parallel('Encoded paths', () => {
Expand Down