Repository navigation
Restore theme storage and feed access in previews #55
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c68f872
fix(preview): restore storage and feed access for theme scripts
ruibaby ad19be8
fix(preview): scope CSP sources and harden the storage shim
ruibaby 0be8bb9
fix(preview): match native storage key conversion
ruibaby da37ce6
Merge branch 'main' into fix/preview-storage-access
ruibaby a090833
Merge branch 'main' into fix/preview-storage-access
ruibaby File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
src/main/java/run/halo/aipagebuilder/page/PreviewPublicPaths.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<String> 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)); | ||
| } | ||
| } |
72 changes: 72 additions & 0 deletions
72
src/main/java/run/halo/aipagebuilder/page/PreviewStorageFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<Void> 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<Void> writeWith(Publisher<? extends DataBuffer> 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<Void> writeAndFlushWith( | ||
| Publisher<? extends Publisher<? extends DataBuffer>> body) { | ||
| return writeWith(Flux.from(body).concatMap(Flux::from)); | ||
| } | ||
| } | ||
| } |
162 changes: 162 additions & 0 deletions
162
src/main/java/run/halo/aipagebuilder/page/PreviewStorageShim.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 "<head>" 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( | ||
| "<!--.*?-->|<head(?:\\s(?:[^>\"']++|\"[^\"]*+\"|'[^']*+')*+)?>", | ||
| Pattern.CASE_INSENSITIVE | Pattern.DOTALL); | ||
| private static final Pattern DOCTYPE = | ||
| Pattern.compile("<!doctype[^>]*>", 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 "<script data-ai-page-builder=\"preview-storage\">" + BODY + "</script>"; | ||
| } | ||
|
|
||
| /** 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("<!--")) { | ||
| continue; | ||
| } | ||
| return insertAt(html, head.end()); | ||
| } | ||
| // Keep the doctype first so a document without <head> stays in standards mode. | ||
| var doctype = DOCTYPE.matcher(html); | ||
| return insertAt(html, doctype.find() ? doctype.end() : 0); | ||
| } | ||
|
|
||
| private static String insertAt(String html, int index) { | ||
| return html.substring(0, index) + script() + html.substring(index); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.