feat(web): serve short links on the shared app host #43
No files matched your search
@@ -0,0 +1,7 @@
|
||||
---
|
||||
'@goto/web': minor
|
||||
'@goto/worker': minor
|
||||
'@goto/cli': minor
|
||||
---
|
||||
|
||||
Allow the app host to serve short links when it is also listed under `domains`. App routes, assets, and development tooling paths are reserved on the shared host. The app no longer sends `/` to `/admin` by default; configure a domain's Root response to restore that shortcut.
|
||||
@@ -17,6 +17,10 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
const text = message.text();
|
||||
if (text.includes('push_state_deprecated')) navigationWarnings.push(text);
|
||||
});
|
||||
const root = await request.get('/', { maxRedirects: 0 });
|
||||
expect(root.status()).toBe(404);
|
||||
expect(root.headers().location).toBeUndefined();
|
||||
|
||||
const adminRedirect = await request.get('/admin', {
|
||||
headers: { accept: 'text/html' },
|
||||
maxRedirects: 0
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { expect, test } from './support/test.ts';
|
||||
|
||||
test('serves compiled app endpoints without shadowing public redirects', async ({ request }) => {
|
||||
test.use({ sharedAppHost: true });
|
||||
|
||||
test('serves the compiled app and short links on one host without shadowing other hosts', async ({
|
||||
request
|
||||
}) => {
|
||||
const health = await request.get('/healthz');
|
||||
expect(health.status()).toBe(200);
|
||||
|
||||
@@ -12,6 +16,29 @@ test('serves compiled app endpoints without shadowing public redirects', async (
|
||||
expect(asset.status()).toBe(200);
|
||||
expect((await asset.json()).version).toEqual(expect.any(String));
|
||||
|
||||
const staticPost = await request.post('/@static/favicon.svg', { maxRedirects: 0 });
|
||||
expect(staticPost.status()).toBe(405);
|
||||
expect(staticPost.headers().allow).toBe('GET, HEAD');
|
||||
|
||||
const source = await request.get('/src/lib/auth-client.ts', { maxRedirects: 0 });
|
||||
expect(source.status()).toBe(404);
|
||||
|
||||
const shortLink = await request.get('/docs', { maxRedirects: 0 });
|
||||
expect(shortLink.status()).toBe(302);
|
||||
expect(shortLink.headers().location).toBe('https://example.org/shared-docs');
|
||||
|
||||
const root = await request.get('/', { maxRedirects: 0 });
|
||||
expect(root.status()).toBe(302);
|
||||
expect(root.headers().location).toBe('https://example.org/shared-fallback');
|
||||
|
||||
const protectedPage = await request.get('/admin', {
|
||||
headers: { accept: 'text/html' },
|
||||
maxRedirects: 0
|
||||
});
|
||||
expect(protectedPage.status()).toBe(303);
|
||||
expect(protectedPage.headers().location).toBe('/signin?callbackUrl=%2Fadmin');
|
||||
expect(protectedPage.headers()['cache-control']).toBe('private, no-store');
|
||||
|
||||
for (const [path, destination] of [
|
||||
['/schema.json', 'public-schema'],
|
||||
['/%73chema.json', 'public-schema'],
|
||||
|
||||
@@ -23,8 +23,9 @@ await new Promise((resolve, reject) =>
|
||||
reservation.close((error) => (error ? reject(error) : resolve()))
|
||||
);
|
||||
process.env.PORT = String(address.port);
|
||||
const appHost = `localhost:${address.port}`;
|
||||
const configuration = {
|
||||
url: { app: `http://localhost:${address.port}`, worker: 'http://goto-worker:9000' },
|
||||
url: { app: `http://${appHost}`, worker: 'http://goto-worker:9000' },
|
||||
auth: { credentials: { username: 'example', password: 'e2e-only-password' } },
|
||||
analytics: { retention_months: Number(process.env.GOTO_E2E_RETENTION_MONTHS ?? '3') },
|
||||
domains: {
|
||||
@@ -55,6 +56,12 @@ const configuration = {
|
||||
}
|
||||
}
|
||||
};
|
||||
if (process.env.GOTO_E2E_SHARED_APP_HOST === '1') {
|
||||
configuration.domains[appHost] = {
|
||||
links: { '/docs': { url: 'https://example.org/shared-docs' } },
|
||||
fallback: { url: 'https://example.org/shared-fallback' }
|
||||
};
|
||||
}
|
||||
await writeFile(join(runtimeDirectory, 'config/goto.yaml'), JSON.stringify(configuration));
|
||||
if (process.env.GOTO_E2E_WORKER === '1') {
|
||||
await seedVisits();
|
||||
|
||||
@@ -56,11 +56,13 @@ async function stopServer(child: ChildProcess): Promise<void> {
|
||||
export const test = base.extend<{
|
||||
appServer: AppServer;
|
||||
withWorker: boolean;
|
||||
sharedAppHost: boolean;
|
||||
retentionMonths: 0 | 3 | 9 | 12;
|
||||
}>({
|
||||
withWorker: [false, { option: true }],
|
||||
sharedAppHost: [false, { option: true }],
|
||||
retentionMonths: [3, { option: true }],
|
||||
appServer: async ({ withWorker, retentionMonths }, use, testInfo) => {
|
||||
appServer: async ({ withWorker, sharedAppHost, retentionMonths }, use, testInfo) => {
|
||||
const directory = process.env.GOTO_E2E_BUILD_DIR;
|
||||
if (!directory) throw new Error('Missing E2E build directory');
|
||||
const child = fork(new URL('../server.js', import.meta.url), [], {
|
||||
@@ -68,6 +70,7 @@ export const test = base.extend<{
|
||||
...serverEnvironment(),
|
||||
GOTO_E2E_BUILD_DIR: directory,
|
||||
GOTO_E2E_WORKER: withWorker ? '1' : '0',
|
||||
GOTO_E2E_SHARED_APP_HOST: sharedAppHost ? '1' : '0',
|
||||
GOTO_E2E_RETENTION_MONTHS: String(retentionMonths)
|
||||
},
|
||||
execArgv: [],
|
||||
|
||||
@@ -2,7 +2,7 @@ import { loadConfig } from '@goto/config';
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { expect, test, vi } from 'vitest';
|
||||
import type { Application } from './application.js';
|
||||
import { handleIngress } from './dispatch.js';
|
||||
import { adminCacheControl, handleIngress } from './dispatch.js';
|
||||
import { requestApplication, requestContext } from './request-context.js';
|
||||
import { prepareSnapshot } from './snapshot.js';
|
||||
|
||||
@@ -58,6 +58,61 @@ test('canonical admin requests reach the adapter with captured application conte
|
||||
});
|
||||
});
|
||||
|
||||
test('reserved paths on a shared host bypass redirects and visit capture', () => {
|
||||
const shared = prepareSnapshot(
|
||||
loadConfig(
|
||||
{
|
||||
url: { app: 'https://go.example.test' },
|
||||
auth: { credentials: { username: 'example', password: 'unit-only-password' } },
|
||||
domains: {
|
||||
'go.example.test': {
|
||||
links: {
|
||||
'/src': { url: 'https://go.example.test/src/lib/docs', forward_path: true }
|
||||
},
|
||||
root: { url: 'https://go.example.test/admin' },
|
||||
fallback: { url: 'https://destination.example.test/fallback' }
|
||||
}
|
||||
}
|
||||
},
|
||||
{ env: {} }
|
||||
)
|
||||
);
|
||||
const recordVisit = vi.fn();
|
||||
const tracked = { ...application, currentSnapshot: () => shared, recordVisit };
|
||||
const normalizedAdmin = request('go.example.test', '/docs/../%61dmin/');
|
||||
expect(handleIngress(tracked, normalizedAdmin, {})).toBeUndefined();
|
||||
expect(requestContext(normalizedAdmin)?.snapshot).toBe(shared);
|
||||
expect(adminCacheControl(normalizedAdmin)).toBe('private, no-store');
|
||||
expect(handleIngress(tracked, request('go.example.test', '/admin'), {}, 'http')?.status).toBe(
|
||||
404
|
||||
);
|
||||
|
||||
const signIn = request('go.example.test', '/auth/sign-in/credentials');
|
||||
signIn.method = 'POST';
|
||||
expect(handleIngress(tracked, signIn, {})).toBeUndefined();
|
||||
expect(requestContext(signIn)?.snapshot).toBe(shared);
|
||||
|
||||
const rawReservedModule = request('go.example.test', '/src%2Flib/../guide');
|
||||
expect(handleIngress(tracked, rawReservedModule, {})).toBeUndefined();
|
||||
expect(requestContext(rawReservedModule)?.snapshot).toBe(shared);
|
||||
|
||||
const serveAsset = vi.fn();
|
||||
const asset = request('go.example.test', '/@static/favicon.svg');
|
||||
expect(handleIngress(tracked, asset, {}, 'https', serveAsset)).toBeUndefined();
|
||||
expect(requestContext(asset)?.snapshot).toBe(shared);
|
||||
expect(serveAsset).not.toHaveBeenCalled();
|
||||
expect(recordVisit).not.toHaveBeenCalled();
|
||||
|
||||
const link = handleIngress(tracked, request('go.example.test', '/src/guide'), {});
|
||||
expect(link?.headers.get('location')).toBe('https://go.example.test/src/lib/docs/guide');
|
||||
expect(recordVisit).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ domain: 'go.example.test', path: '/src', outcome: 'valid' })
|
||||
);
|
||||
|
||||
const root = handleIngress(tracked, request('go.example.test', '/'), {});
|
||||
expect(root?.headers.get('location')).toBe('https://go.example.test/admin');
|
||||
});
|
||||
|
||||
test('a redirect host with an explicit default port takes priority over the app origin', () => {
|
||||
const overlap = prepareSnapshot(
|
||||
loadConfig(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { reservedStaticPrefix } from '@goto/config';
|
||||
import { isReservedLinkPath, reservedStaticPrefix, type PreparedDomain } from '@goto/config';
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import type { Application } from './application.js';
|
||||
import { isLocalProbe, readIngress, type Ingress } from './ingress.js';
|
||||
@@ -7,25 +7,32 @@ import type { RedirectRequestHeaders } from './redirects/conditions.js';
|
||||
import { bindApplication, requestContext } from './request-context.js';
|
||||
import { captureVisit } from './visits/capture.js';
|
||||
import { renderPublicError } from './redirects/error.js';
|
||||
import type { ConfigurationSnapshot } from './snapshot.js';
|
||||
import type { ConfigurationSnapshot, Immutable } from './snapshot.js';
|
||||
|
||||
const noStoreRouteSegments = new Set(['admin', 'auth', 'signin']);
|
||||
|
||||
type PublishedAssetPath = NonNullable<ReturnType<typeof publishedAssetPath>>;
|
||||
type AssetMethod = 'GET' | 'HEAD';
|
||||
type RedirectHostAssetReader<AssetResponse> = (
|
||||
path: PublishedAssetPath,
|
||||
method: AssetMethod
|
||||
) => AssetResponse;
|
||||
|
||||
export function handleIngress<AssetResponse extends Response | Promise<Response> = never>(
|
||||
application: Application,
|
||||
request: IncomingMessage,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
defaultProtocol: 'http' | 'https' = 'https',
|
||||
serveRedirectHostAsset?: (path: PublishedAssetPath, method: 'GET' | 'HEAD') => AssetResponse
|
||||
serveRedirectHostAsset?: RedirectHostAssetReader<AssetResponse>
|
||||
): Response | AssetResponse | undefined {
|
||||
const ingress = readIngress(request, env, defaultProtocol);
|
||||
if (!ingress) return emptyResponse(400);
|
||||
const snapshot = application.currentSnapshot();
|
||||
const isAdminOrigin = ingress.url.origin === snapshot.configuration.url.app;
|
||||
const isRedirectHost = Object.hasOwn(snapshot.domains, ingress.host);
|
||||
if (!isAdminOrigin && !isRedirectHost) {
|
||||
const redirectDomain = Object.hasOwn(snapshot.domains, ingress.host)
|
||||
? snapshot.domains[ingress.host]
|
||||
: undefined;
|
||||
if (!isAdminOrigin && !redirectDomain) {
|
||||
if (isLocalProbe(request, ingress.url)) return emptyResponse(200);
|
||||
return emptyResponse(404);
|
||||
}
|
||||
@@ -34,22 +41,34 @@ export function handleIngress<AssetResponse extends Response | Promise<Response>
|
||||
const rawPathname = target.split('?', 1)[0]!;
|
||||
const method = request.method ?? 'GET';
|
||||
const assetMethod = method === 'GET' || method === 'HEAD' ? method : undefined;
|
||||
const decodedReservedPath = assetMethod ? decodeReservedStaticPath(rawPathname) : undefined;
|
||||
const assetPath = publishedAssetPath(decodedReservedPath);
|
||||
const isSharedHost = redirectDomain?.sharesAppHost === true;
|
||||
const needsDecodedPath = assetMethod !== undefined || isSharedHost;
|
||||
const decodedRawPathname = needsDecodedPath ? decodePathname(rawPathname) : undefined;
|
||||
const urlPathname = ingress.url.pathname;
|
||||
const isReservedPath = isSharedHost && isReservedRequestPath(decodedRawPathname, urlPathname);
|
||||
if (isReservedPath && !isAdminOrigin) return emptyResponse(404);
|
||||
|
||||
const assetPath = publishedAssetPath(decodedRawPathname);
|
||||
if (assetPath && assetMethod) {
|
||||
if (assetPath !== rawPathname) {
|
||||
const response = emptyResponse(308);
|
||||
response.headers.set('location', assetPath + target.slice(rawPathname.length));
|
||||
return response;
|
||||
}
|
||||
if (isRedirectHost && serveRedirectHostAsset) {
|
||||
return serveRedirectHostAsset(assetPath, assetMethod);
|
||||
}
|
||||
} else if (isRedirectHost) {
|
||||
if (decodedReservedPath) {
|
||||
const isRedirectOnlyHost = redirectDomain !== undefined && !isSharedHost;
|
||||
const assetReader = isRedirectOnlyHost ? serveRedirectHostAsset : undefined;
|
||||
const response = publishedAssetResponse(
|
||||
assetPath,
|
||||
assetMethod,
|
||||
target,
|
||||
rawPathname,
|
||||
assetReader
|
||||
);
|
||||
if (response !== undefined) return response;
|
||||
bindApplication(request, application, ingress.url.origin, snapshot);
|
||||
return;
|
||||
}
|
||||
|
||||
if (redirectDomain && !isReservedPath) {
|
||||
if (decodedRawPathname?.startsWith(reservedStaticPrefix)) {
|
||||
return renderPublicError(emptyResponse(404), ingress.url.origin, method);
|
||||
}
|
||||
return handleRedirectHostRequest(application, request, snapshot, ingress);
|
||||
return handleRedirectHostRequest(application, request, snapshot, ingress, redirectDomain);
|
||||
}
|
||||
|
||||
bindApplication(request, application, ingress.url.origin, snapshot);
|
||||
@@ -70,13 +89,28 @@ export function adminCacheControl(request: IncomingMessage): string | undefined
|
||||
}
|
||||
}
|
||||
|
||||
function publishedAssetResponse<AssetResponse extends Response | Promise<Response>>(
|
||||
path: PublishedAssetPath,
|
||||
method: AssetMethod,
|
||||
target: string,
|
||||
rawPathname: string,
|
||||
assetReader: RedirectHostAssetReader<AssetResponse> | undefined
|
||||
): Response | AssetResponse | undefined {
|
||||
if (path === rawPathname) return assetReader?.(path, method);
|
||||
|
||||
const query = target.slice(rawPathname.length);
|
||||
const response = emptyResponse(308);
|
||||
response.headers.set('location', path + query);
|
||||
return response;
|
||||
}
|
||||
|
||||
function handleRedirectHostRequest(
|
||||
application: Application,
|
||||
request: IncomingMessage,
|
||||
snapshot: ConfigurationSnapshot,
|
||||
ingress: Ingress
|
||||
ingress: Ingress,
|
||||
domain: Immutable<PreparedDomain>
|
||||
): Response {
|
||||
const domain = snapshot.domains[ingress.host]!;
|
||||
const method = request.method ?? 'GET';
|
||||
const redirect = resolveRedirect(
|
||||
domain,
|
||||
@@ -96,10 +130,20 @@ function handleRedirectHostRequest(
|
||||
return renderPublicError(redirect.response, ingress.url.origin, method);
|
||||
}
|
||||
|
||||
function decodeReservedStaticPath(rawPathname: string): string | undefined {
|
||||
function isReservedRequestPath(
|
||||
decodedRawPathname: string | undefined,
|
||||
urlPathname: string
|
||||
): boolean {
|
||||
if (decodedRawPathname !== undefined && isReservedLinkPath(decodedRawPathname)) return true;
|
||||
|
||||
// The app uses the URL-normalized path; short links use the raw target.
|
||||
const decodedUrlPathname = decodePathname(urlPathname);
|
||||
return decodedUrlPathname !== undefined && isReservedLinkPath(decodedUrlPathname);
|
||||
}
|
||||
|
||||
function decodePathname(pathname: string): string | undefined {
|
||||
try {
|
||||
const decoded = decodeURIComponent(rawPathname);
|
||||
if (decoded.startsWith(reservedStaticPrefix)) return decoded;
|
||||
return decodeURIComponent(pathname);
|
||||
} catch {
|
||||
// Malformed targets follow normal request handling.
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
export const GET: RequestHandler = ({ url }) => {
|
||||
redirect(303, new URL('/admin', url));
|
||||
};
|
||||
@@ -15,6 +15,7 @@
|
||||
"fallback": { "$ref": "#/$defs/RedirectResponse" },
|
||||
"domains": {
|
||||
"additionalProperties": false,
|
||||
"description": "List the host from url.app here to serve short links alongside the app. App routes, assets and development tooling paths are reserved on that host in all environments. The root response is configured separately.",
|
||||
"type": "object",
|
||||
"patternProperties": { "^(.*)$": { "default": {}, "$ref": "#/$defs/DomainConfiguration" } }
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ export { loadConfig, loadConfigFile, parseConfig } from './load.js';
|
||||
export { startConfigReloading } from './monitor.js';
|
||||
export { matchLink } from './matching.js';
|
||||
export { isSelfRedirect } from './redirect.js';
|
||||
export { isReservedLinkPath } from './routes.js';
|
||||
export {
|
||||
isCanonicalPath,
|
||||
normalizeHost,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { matchLink, type MatchingDomain } from './matching.js';
|
||||
import { normalizeHost, reservedStaticPrefix } from './paths.js';
|
||||
import { isReservedLinkPath } from './routes.js';
|
||||
|
||||
export function isSelfRedirect(
|
||||
destination: string,
|
||||
host: string,
|
||||
path: string,
|
||||
domain?: MatchingDomain
|
||||
domain?: MatchingDomain & { readonly sharesAppHost?: true }
|
||||
): boolean {
|
||||
const normalizedHost = normalizeHost(host);
|
||||
if (normalizedHost === undefined) return false;
|
||||
@@ -21,6 +22,7 @@ export function isSelfRedirect(
|
||||
const destinationPath = decodeURIComponent(url.pathname);
|
||||
if (destinationPath === path) return true;
|
||||
if (destinationPath.startsWith(reservedStaticPrefix)) return false;
|
||||
if (domain?.sharesAppHost && isReservedLinkPath(destinationPath)) return false;
|
||||
if (domain === undefined || path === '/' || destinationPath === '/') return false;
|
||||
const source = matchLink(domain, path);
|
||||
const target = matchLink(domain, destinationPath);
|
||||
|
||||
@@ -557,11 +557,76 @@ describe('effective domains', () => {
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects the admin host, noncanonical paths and reversed or empty validity windows', () => {
|
||||
const input = configurationInput();
|
||||
expect(() => loadConfig({ ...input, url: { app: 'https://go.example.com' } }, options)).toThrow(
|
||||
ConfigError
|
||||
it('allows the app host to have ordinary short links and an explicit Root', () => {
|
||||
const input = configurationInput({ '/administrator': { url: 'https://example.com/docs' } });
|
||||
const { domains } = loadConfig(
|
||||
{
|
||||
...input,
|
||||
url: { app: 'https://go.example.com' },
|
||||
domains: {
|
||||
'GO.example.com': {
|
||||
...input.domains['go.example.com'],
|
||||
root: { url: 'https://go.example.com/admin' }
|
||||
},
|
||||
'other.example.com': { links: { '/admin': { url: 'https://example.com' } } }
|
||||
}
|
||||
},
|
||||
options
|
||||
);
|
||||
expect(domains['go.example.com']?.root?.url).toBe('https://go.example.com/admin');
|
||||
expect(domains['go.example.com']?.links['/administrator']?.url).toBe(
|
||||
'https://example.com/docs'
|
||||
);
|
||||
expect(domains['other.example.com']?.links['/admin']?.url).toBe('https://example.com');
|
||||
});
|
||||
|
||||
it.each(['/signin/help', '/@vite/client'])(
|
||||
'reserves %s on the shared host even for case-sensitive links',
|
||||
(path) => {
|
||||
const input = configurationInput({
|
||||
[path]: { url: 'https://example.com', case_insensitive: false }
|
||||
});
|
||||
expect(() =>
|
||||
loadConfig({ ...input, url: { app: 'https://go.example.com' } }, options)
|
||||
).toThrowError(
|
||||
expect.objectContaining({
|
||||
issues: [
|
||||
{ path: '/domains/*/links/*', message: 'Path reserved for the app on the shared host' }
|
||||
]
|
||||
})
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects a reserved alias unless the link opts out of its domain default', () => {
|
||||
const url = 'https://example.com';
|
||||
const input = configurationInput({ '/Admin': { url } });
|
||||
const domains = {
|
||||
'go.example.com': {
|
||||
links: input.domains['go.example.com'].links,
|
||||
link_defaults: { case_insensitive: true }
|
||||
}
|
||||
};
|
||||
const shared = {
|
||||
...input,
|
||||
url: { app: 'https://go.example.com' },
|
||||
link_defaults: { case_insensitive: false },
|
||||
domains
|
||||
};
|
||||
expect(() => loadConfig(shared, options)).toThrowError(
|
||||
expect.objectContaining({
|
||||
issues: [
|
||||
{ path: '/domains/*/links/*', message: 'Path reserved for the app on the shared host' }
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
domains['go.example.com'].links['/Admin'] = { url, case_insensitive: false };
|
||||
const loaded = loadConfig(shared, options);
|
||||
expect(loaded.domains['go.example.com']?.links['/Admin']?.url).toBe(url);
|
||||
});
|
||||
|
||||
it('rejects noncanonical paths and reversed or empty validity windows', () => {
|
||||
expect(() =>
|
||||
loadConfig(configurationInput({ '/docs/': { url: 'https://example.com' } }), options)
|
||||
).toThrow(ConfigError);
|
||||
|
||||
@@ -14,6 +14,7 @@ export function buildRedirectDomainLookup(
|
||||
authoredLinkDefaults: object
|
||||
): Record<string, PreparedDomain> {
|
||||
const domains: Record<string, PreparedDomain> = Object.create(null);
|
||||
const adminHost = normalizeHost(new URL(configuration.url.app).host);
|
||||
for (const [key, domain] of Object.entries(configuration.domains)) {
|
||||
const host = normalizeHost(key)!;
|
||||
const links: Record<string, PreparedLink> = Object.create(null);
|
||||
@@ -31,6 +32,7 @@ export function buildRedirectDomainLookup(
|
||||
links,
|
||||
caseInsensitivePaths
|
||||
};
|
||||
if (host === adminHost) prepared.sharesAppHost = true;
|
||||
domains[host] = prepared;
|
||||
}
|
||||
return domains;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { reservedStaticPrefix } from './paths.js';
|
||||
|
||||
const reservedRouteSegments = new Set(['admin', 'auth', 'signin', '_app']);
|
||||
const reservedEndpoints = new Set([
|
||||
'/healthz',
|
||||
'/schema.json',
|
||||
'/@vite/client',
|
||||
'/@vite/env',
|
||||
'/__open-in-editor',
|
||||
'/.well-known/appspecific/com.chrome.devtools.json'
|
||||
]);
|
||||
const reservedPrefixes = [
|
||||
reservedStaticPrefix,
|
||||
'/@id/',
|
||||
'/@fs/',
|
||||
'/src/routes/',
|
||||
'/src/lib/',
|
||||
'/.svelte-kit/generated/',
|
||||
'/node_modules/.vite/'
|
||||
];
|
||||
|
||||
export function isReservedLinkPath(path: string): boolean {
|
||||
const firstSegment = path.split('/', 2)[1] ?? '';
|
||||
if (reservedRouteSegments.has(firstSegment)) return true;
|
||||
|
||||
const withoutTrailingSlash = path.endsWith('/') ? path.slice(0, -1) : path;
|
||||
if (reservedEndpoints.has(withoutTrailingSlash)) return true;
|
||||
|
||||
return reservedPrefixes.some((prefix) => path.startsWith(prefix));
|
||||
}
|
||||
@@ -354,7 +354,9 @@ export const GotoConfigurationSchema = Type.Object(
|
||||
link_defaults: ref(LinkDefaultsSchema, { default: {} }),
|
||||
fallback: Type.Optional(ref(RedirectResponseSchema)),
|
||||
domains: Type.Record(Type.String(), ref(DomainConfigurationSchema, { default: {} }), {
|
||||
additionalProperties: false
|
||||
additionalProperties: false,
|
||||
description:
|
||||
'List the host from url.app here to serve short links alongside the app. App routes, assets and development tooling paths are reserved on that host in all environments. The root response is configured separately.'
|
||||
})
|
||||
},
|
||||
{ $id: 'GotoConfiguration', additionalProperties: false, title: 'Goto configuration' }
|
||||
|
||||
@@ -40,6 +40,7 @@ export type PreparedLink = Omit<
|
||||
};
|
||||
|
||||
export interface PreparedDomain {
|
||||
sharesAppHost?: true;
|
||||
root: RedirectResponse | null;
|
||||
fallback: RedirectResponse | null;
|
||||
provenance: { fallback: SettingSource };
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ConfigError, toConfigIssue } from './errors.js';
|
||||
import { foldAsciiCase } from './matching.js';
|
||||
import { isCanonicalPath, normalizeHost } from './paths.js';
|
||||
import { isSelfRedirect } from './redirect.js';
|
||||
import { isReservedLinkPath } from './routes.js';
|
||||
import {
|
||||
GotoConfigurationSchema,
|
||||
configurationReferences,
|
||||
@@ -18,11 +19,10 @@ export function validateConfig(value: unknown): asserts value is GotoConfigurati
|
||||
);
|
||||
throw new ConfigError(issues);
|
||||
}
|
||||
const adminHost = normalizeHost(new URL(value.url.app).host);
|
||||
const hosts = new Set<string>();
|
||||
for (const [key, domain] of Object.entries(value.domains)) {
|
||||
const host = normalizeHost(key);
|
||||
if (!host || host === adminHost || hosts.has(host)) throw new ConfigError();
|
||||
if (!host || hosts.has(host)) throw new ConfigError();
|
||||
hosts.add(host);
|
||||
for (const [path, link] of Object.entries(domain.links)) {
|
||||
assertValidLinkPathAndDates(path, link);
|
||||
@@ -33,11 +33,18 @@ export function validateConfig(value: unknown): asserts value is GotoConfigurati
|
||||
export function validateRedirectDomainLookup(domains: Record<string, PreparedDomain>): void {
|
||||
for (const [host, domain] of Object.entries(domains)) {
|
||||
if (domain.root && isSelfRedirect(domain.root.url, host, '/')) throw new ConfigError();
|
||||
for (const path of Object.keys(domain.links)) {
|
||||
const alias = domain.caseInsensitivePaths[foldAsciiCase(path)];
|
||||
if (alias !== undefined && alias !== path) throw new ConfigError();
|
||||
}
|
||||
for (const [path, link] of Object.entries(domain.links)) {
|
||||
const foldedPath = foldAsciiCase(path);
|
||||
const alias = domain.caseInsensitivePaths[foldedPath];
|
||||
if (alias !== undefined && alias !== path) throw new ConfigError();
|
||||
const reservedPath = domain.sharesAppHost && isReservedLinkPath(path);
|
||||
const hasCaseAlias = domain.sharesAppHost && link.case_insensitive;
|
||||
const reservedAlias = hasCaseAlias && isReservedLinkPath(foldedPath);
|
||||
if (reservedPath || reservedAlias) {
|
||||
throw new ConfigError([
|
||||
{ path: '/domains/*/links/*', message: 'Path reserved for the app on the shared host' }
|
||||
]);
|
||||
}
|
||||
if (isSelfRedirect(link.url, host, path, domain)) throw new ConfigError();
|
||||
for (const rule of link.redirect ?? []) {
|
||||
if (isSelfRedirect(rule.to, host, path, domain)) throw new ConfigError();
|
||||
|
||||
Reference in new issue
Block a user