Skip to content

Commit

Permalink
prevent accessing /__data.json for standalone endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Jun 3, 2022
1 parent 56e5178 commit d1b639c
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 12 deletions.
31 changes: 19 additions & 12 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,26 @@ export async function respond(request, options, state) {
}
}

if (route?.type === 'page') {
const normalized = normalize_path(url.pathname, options.trailing_slash);

if (normalized !== url.pathname && !state.prerendering?.fallback) {
if (route) {
if (route.type === 'page') {
const normalized = normalize_path(url.pathname, options.trailing_slash);

if (normalized !== url.pathname && !state.prerendering?.fallback) {
return new Response(undefined, {
status: 301,
headers: {
'x-sveltekit-normalize': '1',
location:
// ensure paths starting with '//' are not treated as protocol-relative
(normalized.startsWith('//') ? url.origin + normalized : normalized) +
(url.search === '?' ? '' : url.search)
}
});
}
} else if (is_data_request) {
// requesting /__data.json should fail for a standalone endpoint
return new Response(undefined, {
status: 301,
headers: {
'x-sveltekit-normalize': '1',
location:
// ensure paths starting with '//' are not treated as protocol-relative
(normalized.startsWith('//') ? url.origin + normalized : normalized) +
(url.search === '?' ? '' : url.search)
}
status: 404
});
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function get() {
return {
body: {
answer: 42
}
};
}
11 changes: 11 additions & 0 deletions packages/kit/test/apps/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,17 @@ test.describe.parallel('Endpoints', () => {
'name=SvelteKit; path=/; HttpOnly'
]);
});

test('Standalone endpoint is not accessible via /__data.json suffix', async ({ request }) => {
const r1 = await request.get('/endpoint-output/simple', {
headers: { accept: 'application/json' }
});

expect(await r1.json()).toEqual({ answer: 42 });

const r2 = await request.get('/endpoint-output/simple/__data.json');
expect(r2.status()).toBe(404);
});
});

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

0 comments on commit d1b639c

Please sign in to comment.