Skip to content

feat: Allow external remote functions to be whitelisted #14028

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

Closed
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
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
4 changes: 3 additions & 1 deletion 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,10 @@ function create_remotes(config, cwd) {
/** @type {import('types').ManifestData['remotes']} */
const remotes = [];

const externals = config.kit.remoteFunctions.allowedPaths.map((dir) => path.resolve(dir));

// TODO could files live in other directories, including node_modules?
for (const dir of [config.kit.files.lib, config.kit.files.routes]) {
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
5 changes: 3 additions & 2 deletions 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} manifest_cb
* @return {Promise<Promise<() => void>>}
*/
export async function dev(vite, vite_config, svelte_config) {
export async function dev(vite, vite_config, svelte_config, manifest_cb) {
installPolyfills();

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

manifest_cb(manifest_data);
if (manifest_error) {
manifest_error = null;
vite.ws.send({ type: 'full-reload' });
Expand Down
24 changes: 22 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 @@ -661,6 +661,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\`.`
)
);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe return a shim module that throws a error when imported here, rather than allow the 404?


let namespace = '__remote';
let uid = 1;
while (remotes.has(namespace)) namespace = `__remote${uid++}`;
Expand Down Expand Up @@ -835,7 +853,9 @@ 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, (_manifest_data) => {
manifest_data = _manifest_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_not_accessible = query(async () => 'external failure');
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');
16 changes: 16 additions & 0 deletions packages/kit/test/apps/basics/src/routes/remote/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<script>
import { browser } from '$app/environment';
import { refreshAll } from '$app/navigation';
import { external } from '../../external-remotes/external.remote.js';
import { external_not_accessible } from '../../external-not-accessible/external.remote.js';
import { add, get_count, set_count, set_count_server } from './query-command.remote.js';

let { data } = $props();
Expand All @@ -9,6 +11,8 @@
let release;

const count = browser ? get_count() : null; // so that we get a remote request in the browser
const external_result = browser ? external() : null;
const external_failure = browser ? external_not_accessible() : null;
</script>

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

<p id="external-success">
{#await external_result then result}{result}{/await}
</p>

<p id="external-failure">
{#await external_failure then result}
{result}
{:catch error}
{error}
{/await}
</p>
5 changes: 5 additions & 0 deletions packages/kit/test/apps/basics/svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,13 @@ const config = {
version: {
name: 'TEST_VERSION'
},

router: {
resolution: /** @type {'client' | 'server'} */ (process.env.ROUTER_RESOLUTION) || 'client'
},

remoteFunctions: {
allowedPaths: ['src/external-remotes']
}
}
};
Expand Down
7 changes: 7 additions & 0 deletions packages/kit/test/apps/basics/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1834,4 +1834,11 @@ test.describe('remote functions', () => {
await page.click('button:nth-of-type(4)');
await expect(page.locator('p')).toHaveText('success');
});

test('external remotes work', async ({ page }) => {
await page.goto('/remote');
await expect(page.locator('#external-success')).toHaveText('external success');
await expect(page.locator('#external-failure')).not.toHaveText('external failure');
await expect(page.locator('#external-failure')).toHaveText('Failed to execute remote function');
});
});
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