Skip to content

feat: whitelist external remote functions #14156

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions .changeset/whole-symbols-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

feat: allow external remote functions (such as from `node_modules`) to be whitelisted
3 changes: 3 additions & 0 deletions packages/kit/src/core/config/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ const get_defaults = (prefix = '') => ({
moduleExtensions: ['.js', '.ts'],
output: { preloadStrategy: 'modulepreload', bundleStrategy: 'split' },
outDir: join(prefix, '.svelte-kit'),
remoteFunctions: {
allowedPaths: []
},
router: {
type: 'pathname',
resolution: 'client'
Expand Down
4 changes: 4 additions & 0 deletions packages/kit/src/core/config/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,10 @@ const options = object(
})
}),

remoteFunctions: object({
allowedPaths: string_array([])
}),

router: object({
type: list(['pathname', 'hash']),
resolution: list(['client', 'server'])
Expand Down
5 changes: 3 additions & 2 deletions packages/kit/src/core/sync/create_manifest_data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,9 @@ function create_remotes(config, cwd) {
/** @type {import('types').ManifestData['remotes']} */
const remotes = [];

// TODO could files live in other directories, including node_modules?
for (const dir of [config.kit.files.lib, config.kit.files.routes]) {
const externals = config.kit.remoteFunctions.allowedPaths.map((dir) => path.resolve(dir));

for (const dir of [config.kit.files.lib, config.kit.files.routes, ...externals]) {
if (!fs.existsSync(dir)) continue;

for (const file of walk(dir)) {
Expand Down
9 changes: 9 additions & 0 deletions packages/kit/src/exports/public.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,15 @@ export interface KitConfig {
*/
origin?: string;
};
remoteFunctions?: {
/**
* A list of external paths that are allowed to provide remote functions.
* By default, remote functions are only allowed inside the `routes` and `lib` folders.
*
* Accepts absolute paths or paths relative to the project root.
*/
allowedPaths?: string[];
};
router?: {
/**
* What type of client-side router to use.
Expand Down
4 changes: 3 additions & 1 deletion packages/kit/src/exports/vite/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ const vite_css_query_regex = /(?:\?|&)(?:raw|url|inline)(?:&|$)/;
* @param {import('vite').ViteDevServer} vite
* @param {import('vite').ResolvedConfig} vite_config
* @param {import('types').ValidatedConfig} svelte_config
* @param {(manifest_data: import('types').ManifestData) => void} set_manifest_data
* @return {Promise<Promise<() => void>>}
*/
export async function dev(vite, vite_config, svelte_config) {
export async function dev(vite, vite_config, svelte_config, set_manifest_data) {
installPolyfills();

const async_local_storage = new AsyncLocalStorage();
Expand Down Expand Up @@ -108,6 +109,7 @@ export async function dev(vite, vite_config, svelte_config) {
function update_manifest() {
try {
({ manifest_data } = sync.create(svelte_config));
set_manifest_data(manifest_data);

if (manifest_error) {
manifest_error = null;
Expand Down
22 changes: 20 additions & 2 deletions packages/kit/src/exports/vite/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
sveltekit_server
} from './module_ids.js';
import { import_peer } from '../../utils/import.js';
import { compact } from '../../utils/array.js';
import { compact, conjoin } from '../../utils/array.js';
import { build_remotes, treeshake_prerendered_remotes } from './build/build_remote.js';

const cwd = process.cwd();
Expand Down Expand Up @@ -668,6 +668,24 @@ Tips:
}
}

if (!manifest_data.remotes.some((remote) => remote.hash === hashed)) {
const relative_path = path.relative(dev_server.config.root, id);
const fn_names = [...remotes.values()].flat().map((name) => `"${name}"`);
const has_multiple = fn_names.length !== 1;
console.warn(
colors
.bold()
.yellow(
`Remote function${has_multiple ? 's' : ''} ${conjoin(fn_names)} from ${relative_path} ${has_multiple ? 'are' : 'is'} not accessible by default.`
)
);
console.warn(
colors.yellow(
`To whitelist ${has_multiple ? 'them' : 'it'}, add "${path.dirname(relative_path)}" to \`kit.remoteFunctions.allowedPaths\` in \`svelte.config.js\`.`
)
);
}

let namespace = '__remote';
let uid = 1;
while (remotes.has(namespace)) namespace = `__remote${uid++}`;
Expand Down Expand Up @@ -842,7 +860,7 @@ Tips:
* @see https://vitejs.dev/guide/api-plugin.html#configureserver
*/
async configureServer(vite) {
return await dev(vite, vite_config, svelte_config);
return await dev(vite, vite_config, svelte_config, (data) => (manifest_data = data));
},

/**
Expand Down
9 changes: 1 addition & 8 deletions packages/kit/src/runtime/server/cookie.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { parse, serialize } from 'cookie';
import { conjoin } from '../../utils/array.js';
import { normalize_path, resolve } from '../../utils/url.js';
import { add_data_suffix } from '../pathname.js';

Expand Down Expand Up @@ -286,11 +287,3 @@ export function add_cookies_to_headers(headers, cookies) {
}
}
}

/**
* @param {string[]} array
*/
function conjoin(array) {
if (array.length <= 2) return array.join(' and ');
return `${array.slice(0, -1).join(', ')} and ${array.at(-1)}`;
}
9 changes: 9 additions & 0 deletions packages/kit/src/utils/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,12 @@
export function compact(arr) {
return arr.filter(/** @returns {val is NonNullable<T>} */ (val) => val != null);
}

/**
* Joins an array of strings with commas and 'and'.
* @param {string[]} array
*/
export function conjoin(array) {
if (array.length <= 2) return array.join(' and ');
return `${array.slice(0, -1).join(', ')} and ${array.at(-1)}`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { query } from '$app/server';

export const external = query(async () => 'external success');
11 changes: 11 additions & 0 deletions packages/kit/test/apps/basics/src/routes/remote/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
import { browser } from '$app/environment';
import { refreshAll } from '$app/navigation';
import { add, get_count, set_count, set_count_server } from './query-command.remote.js';
import { external } from '../../external-remotes/allowed.remote.js';

let { data } = $props();

let command_result = $state(null);
let release;

const count = browser ? get_count() : null; // so that we get a remote request in the browser

const external_result = browser ? external() : null;
</script>

<p id="echo-result">{data.echo_result}</p>
Expand Down Expand Up @@ -65,3 +68,11 @@
<button id="refresh-remote-only" onclick={() => refreshAll({ includeLoadFunctions: false })}>
refreshAll (remote functions only)
</button>

<p id="external-allowed">
{#await external_result then result}
{result}
{:catch error}
{error}
{/await}
</p>
3 changes: 3 additions & 0 deletions packages/kit/test/apps/basics/svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ const config = {
},
router: {
resolution: /** @type {'client' | 'server'} */ (process.env.ROUTER_RESOLUTION) || 'client'
},
remoteFunctions: {
allowedPaths: ['src/external-remotes']
}
}
};
Expand Down
13 changes: 9 additions & 4 deletions packages/kit/test/apps/basics/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1027,7 +1027,7 @@
expect(page).toHaveURL(offline_url);
});

test('data-sveltekit-preload does not abort ongoing navigation', async ({ page }) => {

Check warning on line 1030 in packages/kit/test/apps/basics/test/client.test.js

View workflow job for this annotation

GitHub Actions / test-kit-server-side-route-resolution (build)

flaky test: data-sveltekit-preload does not abort ongoing navigation

retries: 2
await page.goto('/data-sveltekit/preload-data/offline');

await page.locator('#slow-navigation').dispatchEvent('click');
Expand Down Expand Up @@ -1661,7 +1661,7 @@
await page.goto('/remote');
await expect(page.locator('#count-result')).toHaveText('0 / 0 (false)');
// only the calls in the template are done, not the one in the load function
expect(request_count).toBe(2);
expect(request_count).toBe(3);
});

test('command returns correct sum and refreshes all data by default', async ({ page }) => {
Expand All @@ -1675,7 +1675,7 @@
await expect(page.locator('#command-result')).toHaveText('2');
await expect(page.locator('#count-result')).toHaveText('2 / 2 (false)');
await page.waitForTimeout(100); // allow all requests to finish
expect(request_count).toBe(4); // 1 for the command, 3 for the refresh
expect(request_count).toBe(5); // 1 for the command, 4 for the refresh
});

test('command returns correct sum and does client-initiated single flight mutation', async ({
Expand Down Expand Up @@ -1798,7 +1798,7 @@

await page.click('#refresh-all');
await page.waitForTimeout(100); // allow things to rerun
expect(request_count).toBe(3);
expect(request_count).toBe(4);
});

test('refreshAll({ includeLoadFunctions: false }) reloads remote functions only', async ({
Expand All @@ -1812,7 +1812,7 @@

await page.click('#refresh-remote-only');
await page.waitForTimeout(100); // allow things to rerun
expect(request_count).toBe(2);
expect(request_count).toBe(3);
});

test('validation works', async ({ page }) => {
Expand All @@ -1834,4 +1834,9 @@
await page.click('button:nth-of-type(4)');
await expect(page.locator('p')).toHaveText('success');
});

test('external remote whitelisting works', async ({ page }) => {
await page.goto('/remote');
await expect(page.locator('#external-allowed')).toHaveText('external success');
});
});
9 changes: 9 additions & 0 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,15 @@ declare module '@sveltejs/kit' {
*/
origin?: string;
};
remoteFunctions?: {
/**
* A list of external paths that are allowed to provide remote functions.
* By default, remote functions are only allowed inside the `routes` and `lib` folders.
*
* Accepts absolute paths or paths relative to the project root.
*/
allowedPaths?: string[];
};
router?: {
/**
* What type of client-side router to use.
Expand Down
Loading