Skip to content
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 @@ -98,6 +98,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
23 changes: 14 additions & 9 deletions packages/kit/src/core/sync/create_manifest_data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,15 +480,20 @@ function create_remotes(config, cwd) {
/** @type {import('types').ManifestData['remotes']} */
const remotes = [];

// TODO could files live in other directories, including node_modules?
for (const file of walk(config.kit.files.src)) {
if (extensions.some((ext) => file.endsWith(ext))) {
const posixified = posixify(path.relative(cwd, `${config.kit.files.src}/${file}`));

remotes.push({
hash: hash(posixified),
file: posixified
});
const externals = config.kit.remoteFunctions.allowedPaths.map((dir) => path.resolve(dir));

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

for (const file of walk(dir)) {
if (extensions.some((ext) => file.endsWith(ext))) {
const posixified = posixify(path.relative(cwd, `${dir}/${file}`));

remotes.push({
hash: hash(posixified),
file: posixified
});
}
}
}

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 @@ -675,6 +675,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 @@ -34,7 +34,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';
import { should_ignore } from './static_analysis/utils.js';

Expand Down Expand Up @@ -706,6 +706,24 @@ async function kit({ svelte_config }) {
}
}

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 @@ -880,7 +898,7 @@ async function kit({ svelte_config }) {
* @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';
import { text_encoder } from '../utils.js';
Expand Down Expand Up @@ -287,11 +288,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 @@ -8,13 +8,16 @@
set_count_server,
resolve_deferreds
} 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 @@ -85,4 +88,12 @@
<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>
<button id="resolve-deferreds" onclick={() => resolve_deferreds()}>Resolve Deferreds</button>
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: ['./external-remotes']
}
}
};
Expand Down
11 changes: 8 additions & 3 deletions packages/kit/test/apps/basics/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1667,7 +1667,7 @@ test.describe('remote functions', () => {
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 but does not refresh data by default', async ({ page }) => {
Expand Down Expand Up @@ -1804,7 +1804,7 @@ test.describe('remote functions', () => {

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 @@ -1818,7 +1818,7 @@ test.describe('remote functions', () => {

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('command tracks pending state', async ({ page }) => {
Expand Down Expand Up @@ -1860,6 +1860,11 @@ test.describe('remote functions', () => {
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');
});

test('command pending state is tracked correctly', async ({ page }) => {
await page.goto('/remote');

Expand Down
2 changes: 1 addition & 1 deletion packages/kit/test/apps/basics/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const config = {
plugins: [sveltekit()],
server: {
fs: {
allow: [path.resolve('../../../src')]
allow: [path.resolve('../../../src'), path.resolve('external-remotes')]
}
}
};
Expand Down
9 changes: 9 additions & 0 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,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