webapp_previews.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """Credential-free preview assets: private HTML crosses only a parent/frame message."""
  2. from fastapi import Depends, FastAPI
  3. from fastapi.responses import HTMLResponse, Response
  4. from hermes_cli.web_server_surface import route_on
  5. # Previews keep the freedom they have under no policy at all (any http(s) library, image,
  6. # fetch, worker or embed); their isolation is the opaque sandbox, not a source list.
  7. _GUEST_SOURCES = (
  8. "default-src 'none'; "
  9. "script-src * data: blob: 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'; "
  10. "style-src * data: 'unsafe-inline'; img-src * data: blob:; font-src * data:; "
  11. "media-src * data: blob:; connect-src * data: blob:; worker-src * data: blob:; "
  12. "frame-src * data: blob: about:; object-src 'none'; base-uri * about:; "
  13. "frame-ancestors 'self'"
  14. )
  15. PREVIEW_POLICY = f"{_GUEST_SOURCES}; sandbox allow-scripts; form-action 'none'"
  16. # Plugin `SandboxedFrame` data: HTML (the SDK's allowlist, never allow-same-origin): the
  17. # outer iframe's own sandbox attribute narrows this ceiling to what the plugin asked for,
  18. # and a nested frame can never hold a flag its parent lacks.
  19. GUEST_SANDBOX = (
  20. "allow-downloads allow-forms allow-orientation-lock allow-pointer-lock allow-presentation allow-scripts"
  21. )
  22. GUEST_POLICY = f"{_GUEST_SOURCES}; sandbox {GUEST_SANDBOX}; form-action *"
  23. # D3's CSV/TSV parsers need `new Function` within the opaque preview origin.
  24. # An inner sandbox keeps file previews inert while the shell receives their HTML.
  25. PREVIEW_HTML = """<!doctype html><html><head><meta charset="utf-8">
  26. <style>html,body,iframe{width:100%;height:100%;margin:0;border:0;display:block}</style>
  27. </head><body><script>
  28. const frame = document.createElement('iframe');
  29. frame.referrerPolicy = 'no-referrer';
  30. frame.title = 'Preview content';
  31. const transferableTypes = [
  32. 'MessagePort', 'ReadableStream', 'WritableStream', 'TransformStream', 'ImageBitmap',
  33. 'OffscreenCanvas', 'VideoFrame', 'AudioData', 'ArrayBuffer', 'MediaStreamTrack', 'RTCDataChannel'
  34. ].map(name => globalThis[name]).filter(type => typeof type === 'function');
  35. // An explicit stack: a deeply nested payload that cloning accepts must not
  36. // overflow the call stack. Children are pushed in reverse to keep their order.
  37. function transfersFor(event) {
  38. const transfers = new Set(event.ports);
  39. const seen = new Set();
  40. const pending = [event.data];
  41. while (pending.length) {
  42. const value = pending.pop();
  43. if (!value || typeof value !== 'object' || seen.has(value)) continue;
  44. seen.add(value);
  45. let children = [];
  46. if (transferableTypes.some(type => value instanceof type)) {
  47. transfers.add(value);
  48. } else if (value instanceof Map) {
  49. value.forEach((item, key) => children.push(key, item));
  50. } else if (value instanceof Set) {
  51. children = [...value];
  52. } else if (value instanceof Error) {
  53. children = [value.cause, value.errors];
  54. } else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype ||
  55. Object.getPrototypeOf(value) === null) {
  56. children = Object.values(value);
  57. }
  58. for (let index = children.length - 1; index >= 0; index--) pending.push(children[index]);
  59. }
  60. return [...transfers];
  61. }
  62. // A missing target (no guest frame yet) fails both posts, so its ports are closed.
  63. function relay(target, event) {
  64. let transfers = [...event.ports];
  65. try {
  66. transfers = transfersFor(event);
  67. target.postMessage(event.data, '*', transfers);
  68. } catch {
  69. try {
  70. target.postMessage(event.data, '*');
  71. } catch {
  72. for (const value of transfers) {
  73. if (typeof globalThis.MessagePort === 'function' && value instanceof MessagePort) value.close();
  74. }
  75. }
  76. }
  77. }
  78. addEventListener('message', event => {
  79. if (event.source === parent && parent !== window &&
  80. event.origin === new URL(location.href).origin &&
  81. event.data?.type === 'hermes-preview-document' && typeof event.data.html === 'string') {
  82. const guest = typeof event.data.sandbox === 'string';
  83. frame.setAttribute('sandbox', guest ? event.data.sandbox : event.data.scripts === true ? 'allow-scripts' : '');
  84. // A plugin's onLoad means its guest document loaded, not this shell.
  85. frame.onload = guest ? () => parent.postMessage({type: 'hermes-guest-loaded'}, '*') : null;
  86. frame.srcdoc = event.data.html;
  87. document.body.append(frame);
  88. } else if (event.source === parent && event.origin === new URL(location.href).origin) {
  89. relay(frame.contentWindow, event);
  90. } else if (event.source === frame.contentWindow) {
  91. relay(parent, event);
  92. }
  93. });
  94. </script></body></html>"""
  95. # An external same-origin loader can run under the blob wrapper's inherited app CSP.
  96. PREVIEW_LOADER = """const frame = document.querySelector('iframe[data-preview-html]');
  97. function send() {
  98. frame.contentWindow.postMessage({type: 'hermes-preview-document',
  99. html: frame.dataset.previewHtml, scripts: true}, '*');
  100. }
  101. frame.addEventListener('load', send);
  102. send();
  103. """
  104. def mount_preview_assets(application: FastAPI) -> None:
  105. """Public Webapp assets receive authorized content only via parent messages."""
  106. dependencies = [Depends(route_on("browser_files"))]
  107. @application.get("/assets/webapp-preview.html", dependencies=dependencies)
  108. async def preview_document():
  109. return HTMLResponse(PREVIEW_HTML, headers={
  110. "Content-Security-Policy": PREVIEW_POLICY,
  111. "Cache-Control": "no-store",
  112. "Referrer-Policy": "no-referrer",
  113. "X-Content-Type-Options": "nosniff",
  114. })
  115. @application.get("/assets/webapp-guest.html", dependencies=dependencies)
  116. async def guest_document():
  117. return HTMLResponse(PREVIEW_HTML, headers={
  118. "Content-Security-Policy": GUEST_POLICY,
  119. "Cache-Control": "no-store",
  120. "Referrer-Policy": "no-referrer",
  121. "X-Content-Type-Options": "nosniff",
  122. })
  123. @application.get("/assets/webapp-preview.js", dependencies=dependencies)
  124. async def preview_loader():
  125. return Response(PREVIEW_LOADER, media_type="text/javascript", headers={
  126. "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
  127. })