diff --git a/src/main/java/run/halo/aipagebuilder/page/PagePreview.java b/src/main/java/run/halo/aipagebuilder/page/PagePreview.java index 19fe11b..f567e06 100644 --- a/src/main/java/run/halo/aipagebuilder/page/PagePreview.java +++ b/src/main/java/run/halo/aipagebuilder/page/PagePreview.java @@ -2,6 +2,7 @@ import java.net.URI; import java.util.List; +import java.util.stream.Stream; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.RenderingResponse; import org.springframework.web.reactive.function.server.ServerRequest; @@ -52,8 +53,12 @@ private Policy policy(ServerRequest request) { // Resources resolve against the origin actually serving the preview, which can // differ from the configured external URL used for public links. var base = origins.servingOrigin(request); - var sources = base == null ? List.of() - : allowedPrefixes().stream().map(prefix -> base + prefix).distinct().toList(); + // Public paths live below the context path, so every source must name it too. + var origin = scopedOrigin(base, request.requestPath().contextPath().value()); + var paths = Stream.concat(allowedPrefixes().stream(), PreviewPublicPaths.ALL.stream()) + .toList(); + var sources = origin == null ? List.of() + : paths.stream().map(prefix -> origin + prefix).distinct().toList(); // A trailing slash also allows resources below a configured deployment sub-path. var resourceSources = base == null ? "'unsafe-inline'" : base + "/ 'unsafe-inline'"; var connectSources = sources.isEmpty() ? "'none'" : String.join(" ", sources); @@ -64,6 +69,17 @@ private Policy policy(ServerRequest request) { + "; connect-src " + connectSources); } + /** Adds the deployment path the preview document is served under. */ + private static String scopedOrigin(String base, String contextPath) { + if (base == null || contextPath.isEmpty()) { + return base; + } + // The external URL fallback may already carry the configured path. Compare the + // suffix as plain text so a malformed authority or path cannot throw here. + var path = base.indexOf('/', base.indexOf("://") + 3); + return contextPath.equals(path < 0 ? "" : base.substring(path)) ? base : base + contextPath; + } + private List allowedPrefixes() { try { return publicApiCatalog.publicPathPrefixes(); diff --git a/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java b/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java index bf05693..3866d39 100644 --- a/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java +++ b/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java @@ -6,6 +6,8 @@ import java.util.HashMap; import java.util.Map; import org.jsoup.Jsoup; +import org.jsoup.nodes.DataNode; +import org.jsoup.nodes.Element; import org.reactivestreams.Publisher; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; @@ -100,9 +102,14 @@ public Mono writeAndFlushWith( private static String host(String html, URI base, String policy) { var child = Jsoup.parse(html); child.select("base").remove(); - child.head().prependElement("base").attr("href", base.toASCIIString()); + var baseElement = child.head().prependElement("base"); + baseElement.attr("href", base.toASCIIString()); child.head().prependElement("meta").attr("http-equiv", "Content-Security-Policy") .attr("content", policy); + // Run before any theme script so startup storage access succeeds in the opaque origin. + var shim = new Element("script").attr("data-ai-page-builder", "preview-storage"); + shim.appendChild(new DataNode(PreviewStorageShim.BODY)); + baseElement.after(shim); var source = Base64.getEncoder().encodeToString( child.outerHtml().getBytes(StandardCharsets.UTF_8)); var host = Jsoup.parse("" diff --git a/src/main/java/run/halo/aipagebuilder/page/PreviewAssetCorsFilter.java b/src/main/java/run/halo/aipagebuilder/page/PreviewAssetCorsFilter.java index 246db2f..0a6b587 100644 --- a/src/main/java/run/halo/aipagebuilder/page/PreviewAssetCorsFilter.java +++ b/src/main/java/run/halo/aipagebuilder/page/PreviewAssetCorsFilter.java @@ -10,10 +10,10 @@ /** * Sandboxed previews run in an opaque origin, so the theme CSS, module scripts and fonts they - * reference are cross-origin CORS requests. Those assets are public, so allow every origin - * without granting the preview page same-origin access to the site. The response must not - * depend on the request Origin: shared caches ignore {@code Vary: Origin}, and a cached - * no-CORS copy would keep breaking the preview. + * reference, as well as the feeds their widgets fetch, are cross-origin requests. Those + * resources are public, so allow every origin without granting the preview page same-origin + * access to the site. The response must not depend on the request Origin: shared caches ignore + * {@code Vary: Origin}, and a cached no-CORS copy would keep breaking the preview. */ @Component public class PreviewAssetCorsFilter implements AdditionalWebFilter { @@ -22,7 +22,8 @@ public class PreviewAssetCorsFilter implements AdditionalWebFilter { @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { var path = exchange.getRequest().getPath().pathWithinApplication().value(); - if (ASSET_PREFIXES.stream().anyMatch(path::startsWith)) { + if (ASSET_PREFIXES.stream().anyMatch(path::startsWith) + || PreviewPublicPaths.matches(path)) { exchange.getResponse().getHeaders() .set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); } diff --git a/src/main/java/run/halo/aipagebuilder/page/PreviewPublicPaths.java b/src/main/java/run/halo/aipagebuilder/page/PreviewPublicPaths.java new file mode 100644 index 0000000..a28d617 --- /dev/null +++ b/src/main/java/run/halo/aipagebuilder/page/PreviewPublicPaths.java @@ -0,0 +1,16 @@ +package run.halo.aipagebuilder.page; + +import java.util.List; + +/** Public site documents that sandboxed theme widgets may fetch. */ +final class PreviewPublicPaths { + static final List ALL = List.of("/rss.xml", "/feed.xml", "/sitemap.xml", "/feed/"); + + private PreviewPublicPaths() { + } + + static boolean matches(String path) { + return ALL.stream().anyMatch(publicPath -> publicPath.endsWith("/") + ? path.startsWith(publicPath) : path.equals(publicPath)); + } +} diff --git a/src/main/java/run/halo/aipagebuilder/page/PreviewStorageFilter.java b/src/main/java/run/halo/aipagebuilder/page/PreviewStorageFilter.java new file mode 100644 index 0000000..d1325de --- /dev/null +++ b/src/main/java/run/halo/aipagebuilder/page/PreviewStorageFilter.java @@ -0,0 +1,72 @@ +package run.halo.aipagebuilder.page; + +import java.nio.charset.StandardCharsets; +import java.util.regex.Pattern; +import org.reactivestreams.Publisher; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.http.server.reactive.ServerHttpResponseDecorator; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilterChain; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import run.halo.app.security.AdditionalWebFilter; + +/** + * Injects the preview storage shim into rendered preview documents. The document body is + * produced by the theme view, so it is rewritten here rather than in the renderer. Only HTML + * responses for the two preview routes are touched; errors and other routes pass through. + */ +@Component +public class PreviewStorageFilter implements AdditionalWebFilter { + private static final Pattern PATH = Pattern.compile( + "/apis/console\\.api\\.aipagebuilder\\.halo\\.run/v1alpha1/pages/[^/]+/" + + "(?:revisions/[^/]+/)?preview"); + + @Override + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + var request = exchange.getRequest(); + var path = request.getPath().pathWithinApplication().value(); + if (!HttpMethod.GET.equals(request.getMethod()) || !PATH.matcher(path).matches()) { + return chain.filter(exchange); + } + return chain.filter(exchange.mutate() + .response(new InjectingResponse(exchange.getResponse())).build()); + } + + private static final class InjectingResponse extends ServerHttpResponseDecorator { + InjectingResponse(ServerHttpResponse delegate) { + super(delegate); + } + + @Override + public Mono writeWith(Publisher body) { + return DataBufferUtils.join(body).flatMap(buffer -> { + var type = getHeaders().getContentType(); + if (buffer.readableByteCount() == 0 || type == null + || !MediaType.TEXT_HTML.isCompatibleWith(type)) { + return super.writeWith(Mono.just(buffer)); + } + final String html; + try { + html = buffer.toString(StandardCharsets.UTF_8); + } finally { + DataBufferUtils.release(buffer); + } + var bytes = PreviewStorageShim.inject(html).getBytes(StandardCharsets.UTF_8); + getHeaders().setContentLength(bytes.length); + return super.writeWith(Mono.just(bufferFactory().wrap(bytes))); + }); + } + + @Override + public Mono writeAndFlushWith( + Publisher> body) { + return writeWith(Flux.from(body).concatMap(Flux::from)); + } + } +} diff --git a/src/main/java/run/halo/aipagebuilder/page/PreviewStorageShim.java b/src/main/java/run/halo/aipagebuilder/page/PreviewStorageShim.java new file mode 100644 index 0000000..82d466e --- /dev/null +++ b/src/main/java/run/halo/aipagebuilder/page/PreviewStorageShim.java @@ -0,0 +1,162 @@ +package run.halo.aipagebuilder.page; + +import java.util.regex.Pattern; + +/** + * Replaces storage APIs that a sandboxed preview cannot reach. A sandboxed document has an + * opaque origin, so reading {@code localStorage}, {@code sessionStorage} or + * {@code document.cookie} throws a SecurityError. Themes read them while starting, and an + * unguarded access aborts the rest of their scripts. The shim keeps the synchronous API + * backed by memory, so values live only for the current preview document. + */ +final class PreviewStorageShim { + // Comments are matched so a literal "" inside one cannot capture the shim, and + // quoted attribute values may contain ">" without ending the tag early. Possessive + // quantifiers keep long attributes from recursing the matcher into a StackOverflowError. + private static final Pattern HEAD = Pattern.compile( + "|\"']++|\"[^\"]*+\"|'[^']*+')*+)?>", + Pattern.CASE_INSENSITIVE | Pattern.DOTALL); + private static final Pattern DOCTYPE = + Pattern.compile("]*>", Pattern.CASE_INSENSITIVE); + + static final String BODY = """ + (function () { + function memory() { + var data = new Map(); + var api = { + getItem: function (key) { + key = String(key); + return data.has(key) ? data.get(key) : null; + }, + setItem: function (key, value) { + data.set(String(key), String(value)); + }, + removeItem: function (key) { + data.delete(String(key)); + }, + clear: function () { + data.clear(); + }, + key: function (index) { + // Web Storage converts the argument to an unsigned long before indexing. + index = +index >>> 0; + var keys = Array.from(data.keys()); + return index < keys.length ? keys[index] : null; + } + }; + Object.defineProperty(api, 'length', { + get: function () { return data.size; }, + configurable: true + }); + return new Proxy(api, { + get: function (target, prop) { + if (typeof prop === 'symbol') return target[prop]; + if (prop in target) return target[prop]; + // A missing item reads as undefined, like native storage; getItem keeps null. + return data.has(String(prop)) ? data.get(String(prop)) : undefined; + }, + set: function (target, prop, value) { + api.setItem(prop, value); + return true; + }, + has: function (target, prop) { + if (typeof prop === 'symbol') return prop in target; + return prop in target || data.has(String(prop)); + }, + deleteProperty: function (target, prop) { + if (typeof prop !== 'symbol') api.removeItem(prop); + return true; + }, + ownKeys: function () { return Array.from(data.keys()); }, + getOwnPropertyDescriptor: function (target, prop) { + if (typeof prop === 'symbol') return undefined; + if (prop in target) return Object.getOwnPropertyDescriptor(target, prop); + if (!data.has(String(prop))) return undefined; + return { + value: api.getItem(prop), + writable: true, + enumerable: true, + configurable: true + }; + } + }); + } + ['localStorage', 'sessionStorage'].forEach(function (name) { + try { + if (window[name]) return; + } catch (error) { + // The sandbox rejects access; install the in-memory replacement below. + } + try { + Object.defineProperty(window, name, { value: memory(), configurable: true }); + } catch (error) { + // Leave the native error in place when the property cannot be replaced. + } + }); + try { + void document.cookie; + } catch (error) { + var jar = Object.create(null); + Object.defineProperty(document, 'cookie', { + configurable: true, + get: function () { + return Object.keys(jar).map(function (key) { + return key + '=' + jar[key]; + }).join('; '); + }, + set: function (value) { + var parts = String(value).split(';'); + var pair = parts.shift(); + var index = pair.indexOf('='); + if (index <= 0) return; + var name = pair.slice(0, index).trim(); + // A past expiry deletes the cookie, as it would in a real jar. Max-Age wins + // over Expires, and an attribute that does not parse is ignored. + var maxAge = null; + var expires = null; + parts.forEach(function (attribute) { + var at = attribute.indexOf('='); + var key = (at < 0 ? attribute : attribute.slice(0, at)).trim().toLowerCase(); + var raw = at < 0 ? '' : attribute.slice(at + 1).trim(); + if (key === 'max-age' && /^-?\\d+$/.test(raw)) maxAge = Number(raw); + if (key === 'expires') { + var parsed = Date.parse(raw); + // Keep an earlier valid date when a repeated attribute does not parse. + if (!isNaN(parsed)) expires = parsed; + } + }); + var expired = maxAge !== null ? maxAge <= 0 + : expires !== null && expires < Date.now(); + if (expired) delete jar[name]; + else jar[name] = pair.slice(index + 1).trim(); + } + }); + } + })(); + """; + + private PreviewStorageShim() { + } + + static String script() { + return ""; + } + + /** Inserts the shim as early as possible without reserializing the rest of the page. */ + static String inject(String html) { + var head = HEAD.matcher(html); + while (head.find()) { + if (head.group().startsWith("x"); + assertThat(injected).startsWith("x"); + } + + @Test + void longAttributeValuesDoNotExhaustTheMatcherStack() { + var value = "a".repeat(10_000); + var injected = PreviewStorageShim.inject( + "x"); + assertThat(injected).startsWith(" b\">x"); + assertThat(injected).startsWith(" b\">x"); + } +} diff --git a/ui/src/components/HistoryPanel.vue b/ui/src/components/HistoryPanel.vue index 9f27447..b2a7ad1 100644 --- a/ui/src/components/HistoryPanel.vue +++ b/ui/src/components/HistoryPanel.vue @@ -92,8 +92,9 @@ const previewLink = computed(() => ) const previewSrc = computed(() => (view.value === 'preview' ? previewLink.value : '')) // Load the revision preview directly, exactly like the "运行" tab: the server sets a -// sandbox CSP (opaque origin, public APIs only), and the iframe adds allow-scripts without -// allow-same-origin. Scripts run in isolation, and theme assets load via the CORS filter. +// sandbox CSP (opaque origin, public APIs and feeds only), and the iframe adds allow-scripts +// without allow-same-origin. Scripts run in isolation, and theme assets load via the CORS +// filter. const { loading: previewLoading, error: previewError,