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
4 changes: 2 additions & 2 deletions studio/src/features/preview/PreviewLoading.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useTranslate } from '../../../vendor/stacki/src/lib/i18n/useTranslate';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { handshakeWait, HANDSHAKE_LIMITS, pagePath, parsePreviewError, retryOffered, type HandshakeWait } from './previewHandshake';
import { handshakeWait, HANDSHAKE_LIMITS, pagePath, parsePreviewError, retryOffered, samePage, type HandshakeWait } from './previewHandshake';
import { STARTUP_LIMITS, type StartupView } from '../startup/startupStages';
import { STARTUP_STAGE_KEYS } from '../startup/startupText';
import { useElapsed } from '../startup/useElapsed';
Expand Down Expand Up @@ -66,7 +66,7 @@ export function usePreviewLoading(url: string | undefined, container: React.RefO
window.removeEventListener('message', receive);
};
}, [url, container, key, session]);
const shown = url !== undefined && ready !== undefined && ready.session === session && ready.path === pagePath(url, location.href);
const shown = url !== undefined && ready !== undefined && ready.session === session && samePage(ready.path, pagePath(url, location.href));
// The long-wait clock runs from when the loader appeared, not from the last URL change: an address
// that keeps being replaced must not keep postponing the message that says what is missing.
useEffect(() => {
Expand Down
16 changes: 16 additions & 0 deletions studio/src/features/preview/previewHandshake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,22 @@ export function retryOffered(attempt: number): boolean {
*/
export const PREVIEW_ENTRY_PATH = '/__studio-entry';
// `base` is required: a made-up host here would end up in the built bundle (the no-tracking scan rejects unknown hosts).
/**
* Whether the page a frame reports is the page Studio asked for. Studio asks for
* slashless routes; a site with `trailingSlash: 'always'` serves them at /about/
* (pageNavigation.ts sends the frame there), so the two spellings are one page.
*/
export function samePage(reported: string, asked: string): boolean {
return withoutTrailingSlash(reported) === withoutTrailingSlash(asked);
}

function withoutTrailingSlash(path: string): string {
const query = path.indexOf('?');
const pathname = query === -1 ? path : path.slice(0, query);
const search = query === -1 ? '' : path.slice(query);
return (pathname.replace(/\/+$/, '') || '/') + search;
}

export function pagePath(url: string, base: string): string {
const parsed = new URL(url, base);
if (parsed.pathname === PREVIEW_ENTRY_PATH) {
Expand Down
11 changes: 11 additions & 0 deletions studio/src/server/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { ReferencedError } from '../shared/referencedError';
import { fileStamps, parseFileStampRequest } from '../features/apps/pageFileStamps';
import { saveAsset } from '../features/storage/assetStorage';
import { interceptBrowserReloads } from '../features/preview/browserReloads';
import { slashRedirect } from './pageNavigation';
import { assertRouteAllowed, connectionRole, requestRole, RoleRefusal, routeRule } from '../features/roles/serverAccess';
import type { RoleView } from '../../vendor/stacki/shared/properties/projectRoles';
import { assertEditorRequest, routeReadsBody } from '../features/roles/editorRoutes';
Expand Down Expand Up @@ -611,6 +612,16 @@ function configureStudioRequests(
next();
return;
}
const fetchMode = request.headers['sec-fetch-mode'];
const slashed = slashRedirect(
{ method: request.method ?? 'GET', pathname, search: url.search, fetchMode: typeof fetchMode === 'string' ? fetchMode : undefined },
options.trailingSlash,
);
if (slashed !== undefined) {
response.writeHead(302, { Location: slashed, 'Cache-Control': 'no-store' });
response.end();
return;
}
if (pathname !== '/studio' && !pathname.startsWith('/studio/')) {
next();
return;
Expand Down
56 changes: 56 additions & 0 deletions studio/src/server/pageNavigation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Astro's dev server serves exactly one spelling of a page's path when the site
// sets `trailingSlash`: under 'always' it serves /about/ and answers /about with a
// 404 help page. Studio names pages by slashless routes (routeFor), and both the
// local preview-url answer and the hosted entry redirect send the canvas there as
// is, so on an 'always' site every page but the home page loaded Astro's 404, its
// editor script never answered, and the canvas stopped at "taking a little longer".
//
// The container is the one place that knows the site's setting in every host, so
// a page navigation that misses the slash is redirected to the spelling Astro
// serves. Fetches, writes, files and Studio's own paths are never touched, and
// 'never' needs nothing: Studio's routes never end in a slash.
import { assert } from '../../vendor/stacki/shared/core/assert';

/** What the redirect decision reads from a request: nothing else about it matters. */
export interface PageNavigation {
readonly method: string;
readonly pathname: string;
readonly search: string;
/** `Sec-Fetch-Mode`; 'navigate' for a frame or tab loading a page. */
readonly fetchMode: string | undefined;
}

/** The address Astro serves this page at, when the request asked for another spelling of it. */
export function slashRedirect(request: PageNavigation, trailingSlash: string): string | undefined {
assert(request.pathname.startsWith('/'), 'A request path is a site path');
if (trailingSlash !== 'always') {
return undefined;
}
if (request.fetchMode !== 'navigate') {
return undefined;
}
if (request.method !== 'GET' && request.method !== 'HEAD') {
return undefined;
}
if (request.pathname.endsWith('/')) {
return undefined;
}
if (isToolingPath(request.pathname)) {
return undefined;
}
// An extension means a file (/feed.xml, /llms.txt), which keeps its shape under every
// setting; this is how Astro checks it too.
const last = request.pathname.slice(request.pathname.lastIndexOf('/') + 1);
if (last.includes('.')) {
return undefined;
}
return `${request.pathname}/${request.search}`;
}

// Studio's own routes (/studio/…), its preview internals (/__avb/…, /__studio-entry) and
// Vite's and Astro's (/@vite/…, /_astro/…) are not site pages.
function isToolingPath(pathname: string): boolean {
return (
pathname === '/studio' || pathname.startsWith('/studio/') || pathname.startsWith('/__') || pathname.startsWith('/@') || pathname.startsWith('/_astro/')
);
}
49 changes: 49 additions & 0 deletions studio/test/pageNavigation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Goal: on a site with `trailingSlash: 'always'`, a canvas opened on a slashless page
// route reaches the page instead of Astro's 404. Method: call the redirect decision
// with the requests a canvas, a fetch, a write and tooling make, for each setting.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { slashRedirect } from '../src/server/pageNavigation';
import { samePage } from '../src/features/preview/previewHandshake';

const visit = (pathname: string, search = '') => ({ method: 'GET', pathname, search, fetchMode: 'navigate' });

test('a page navigation missing the slash on an always-slash site is sent to the spelling Astro serves', () => {
assert.equal(slashRedirect(visit('/about'), 'always'), '/about/');
assert.equal(slashRedirect(visit('/work/acme', '?x=1'), 'always'), '/work/acme/?x=1');
assert.equal(slashRedirect({ ...visit('/about'), method: 'HEAD' }, 'always'), '/about/');
});
test('served paths, files, Studio and tooling paths, and other settings are left alone', () => {
for (const pathname of [
'/',
'/about/',
'/feed.xml',
'/llms.txt',
'/studio',
'/studio/api/project',
'/__avb/preview',
'/__studio-entry',
'/@vite/client',
'/_astro/x',
]) {
assert.equal(slashRedirect(visit(pathname), 'always'), undefined, pathname);
}
assert.equal(slashRedirect(visit('/about'), 'ignore'), undefined);
assert.equal(slashRedirect(visit('/about'), 'never'), undefined);
});
test('fetches and writes are never redirected', () => {
assert.equal(slashRedirect({ ...visit('/about'), fetchMode: 'cors' }, 'always'), undefined);
assert.equal(slashRedirect({ ...visit('/about'), fetchMode: undefined }, 'always'), undefined);
assert.equal(slashRedirect({ ...visit('/about'), method: 'POST' }, 'always'), undefined);
});
test('a request path that is not a site path is a programmer error', () => {
assert.throws(() => slashRedirect(visit('about'), 'always'), /A request path is a site path/);
});
test('the canvas takes the page it asked for at /about when the frame reports /about/', () => {
assert.equal(samePage('/about/', '/about'), true);
assert.equal(samePage('/about', '/about'), true);
assert.equal(samePage('/', '/'), true);
assert.equal(samePage('/work/acme/?x=1', '/work/acme?x=1'), true);
assert.equal(samePage('/about/', '/contact'), false);
assert.equal(samePage('/about/?x=1', '/about?x=2'), false);
});