All files / near-membrane-dom/dist index.mjs.js

96.51% Statements 83/86
90.2% Branches 46/51
100% Functions 7/7
96.47% Lines 82/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265        37x         37x         168x       168x 168x     167x   1x     167x 129x         38x 38x 38x 38x                   38x 38x       60x 60x   60x   60x 62048x   62048x     61868x       60x                                                                 94x 94x 94x 94x   94x 94x                   37x 37x 37x 37x 37x         130x     130x     130x 130x 130x 130x 130x       132x 1x     131x   131x 1x                         130x     130x 130x 130x   130x 30x     130x   130x 37x 37x         130x             130x 130x   1x             130x       130x           130x           130x 130x 130x           130x 94x 94x 94x 94x         130x           130x         129x   129x 129x 129x 129x   1x             1x     130x       10529x        
import './custom-devtools-formatter.mjs.js';
import { getFilteredGlobalOwnKeys, createBlueConnector, VirtualEnvironment, createRedConnector, linkIntrinsics, assignFilteredGlobalDescriptorsFromPropertyDescriptorMap } from '@locker/near-membrane-base';
import { toSafeWeakMap, ReflectGetPrototypeOf, ReflectOwnKeys, ReflectDeleteProperty, toSafeWeakSet, WeakSetCtor, WeakMapCtor, TypeErrorCtor, ObjectAssign, ReflectApply, isObject } from '@locker/near-membrane-shared';
import { rootWindow, IS_CHROMIUM_BROWSER, HTMLIFrameElementProtoContentWindowGetter, DocumentProtoOpen, DocumentProtoClose, IS_OLD_CHROMIUM_BROWSER, ElementProtoRemove, DocumentProtoCreateElement, DocumentProtoBodyGetter, NodeProtoLastChildGetter, HTMLElementProtoStyleGetter, ElementProtoSetAttribute, NodeProtoAppendChild } from '@locker/near-membrane-shared-dom';
const blueDocumentToRecordMap = toSafeWeakMap(new WeakMap()); // Chromium based browsers have a bug that nulls the result of `window`
// getters in detached iframes when the property descriptor of `window.window`
// is retrieved.
// https://bugs.chromium.org/p/chromium/issues/detail?id=1305302
 
const unforgeablePoisonedWindowKeys = IS_CHROMIUM_BROWSER ? ['window'] : undefined;
 
function getCachedGlobalObjectReferences(globalObject) {
  const {
    window
  } = globalObject;
  let record;
  let document; // Suppress errors thrown on cross-origin opaque windows.
 
  try {
    ({
      document
    } = globalObject);
    record = blueDocumentToRecordMap.get(document); // eslint-disable-next-line no-empty
  } catch (_unused) {
    return undefined;
  }
 
  if (record) {
    return record;
  } // Cache references to object values that can't be replaced
  // window -> Window -> WindowProperties -> EventTarget
 
 
  const WindowProto = ReflectGetPrototypeOf(window);
  const WindowPropertiesProto = ReflectGetPrototypeOf(WindowProto);
  const EventTargetProto = ReflectGetPrototypeOf(WindowPropertiesProto);
  record = {
    document,
    DocumentProto: ReflectGetPrototypeOf(document),
    window,
    WindowProto: ReflectGetPrototypeOf(window),
    WindowPropertiesProto: ReflectGetPrototypeOf(WindowProto),
    EventTargetProto,
    // Some simulated browser environments, e.g. those using JSDOM, may lack an EventTargetProto.
    EventTargetProtoOwnKeys: EventTargetProto ? ReflectOwnKeys(EventTargetProto) : []
  };
  blueDocumentToRecordMap.set(document, record);
  return record;
}
 
function filterWindowKeys(keys) {
  const result = [];
  let resultOffset = 0;
 
  for (let i = 0, {
    length
  } = keys; i < length; i += 1) {
    const key = keys[i];
 
    if ( // Filter out unforgeable property keys that cannot be installed.
    key !== 'document' && key !== 'location ' && key !== 'top' && key !== 'window' && // Remove other browser specific unforgeables.
    key !== 'chrome') {
      result[resultOffset++] = key;
    }
  }
 
  return result;
}
/**
 * global descriptors are a combination of 3 set of descriptors:
 * - first, the key of the red descriptors define the descriptors
 *   provided by the browser when creating a brand new window.
 * - second, once we know the base keys, we get the actual descriptors
 *   from the blueDescriptors, since those are the one we want to provide
 *   access to via the membrane.
 * - third, the user of this library can provide endowments, which define
 *   global descriptors that should be installed into the sandbox on top
 *   of the base descriptors.
 *
 * Note: The main reason for using redDescriptors as the base keys instead
 * of blueDescriptor is because there is no guarantee that this library is
 * the first one to be evaluated in the host app, which means it has no ways
 * to determine what is a real DOM API vs app specific globals.
 *
 * Quirk: The only quirk here is for the case in which this library runs
 * after some other code that patches some of the DOM APIs. This means
 * the installed proxy in the sandbox will point to the patched global
 * API in the blue realm, rather than the original, because we don't have
 * a way to access the original anymore. This should not be a deal-breaker
 * if the patched API behaves according to the spec.
 *
 * The result of this method is a descriptor map that contains everything
 * that will be installed (via the membrane) as global descriptors in
 * the red realm.
 */
 
 
function removeWindowDescriptors(unsafeDescs) {
  // Remove unforgeable descriptors that cannot be installed.
  ReflectDeleteProperty(unsafeDescs, 'document');
  ReflectDeleteProperty(unsafeDescs, 'location');
  ReflectDeleteProperty(unsafeDescs, 'top');
  ReflectDeleteProperty(unsafeDescs, 'window'); // Remove other browser specific unforgeables.
 
  ReflectDeleteProperty(unsafeDescs, 'chrome');
  return unsafeDescs;
}
/**
 * Initialization operation to capture and cache all unforgeable references
 * and their respective descriptor maps before any other code runs, this
 * usually help because this library runs before anything else that can poison
 * the environment.
 */
 
 
getCachedGlobalObjectReferences(rootWindow);
const IFRAME_SANDBOX_ATTRIBUTE_VALUE = 'allow-same-origin allow-scripts';
const revoked = toSafeWeakSet(new WeakSetCtor());
const blueCreateHooksCallbackCache = toSafeWeakMap(new WeakMapCtor());
let defaultGlobalOwnKeys = null;
 
function createDetachableIframe(doc) {
  var _ReflectApply;
 
  const iframe = ReflectApply(DocumentProtoCreateElement, doc, ['iframe']); // It is impossible to test whether the NodeProtoLastChildGetter branch is
  // reached in a normal Karma test environment.
 
  const parent = (_ReflectApply = ReflectApply(DocumentProtoBodyGetter, doc, [])) != null ? _ReflectApply :
  /* istanbul ignore next */
  ReflectApply(NodeProtoLastChildGetter, doc, []);
  const style = ReflectApply(HTMLElementProtoStyleGetter, iframe, []);
  style.display = 'none';
  ReflectApply(ElementProtoSetAttribute, iframe, ['sandbox', IFRAME_SANDBOX_ATTRIBUTE_VALUE]);
  ReflectApply(NodeProtoAppendChild, parent, [iframe]);
  return iframe;
}
 
function createIframeVirtualEnvironment(globalObject, providedOptions) {
  if (typeof globalObject !== 'object' || globalObject === null) {
    throw new TypeErrorCtor('Missing global object virtualization target.');
  }
 
  const blueRefs = getCachedGlobalObjectReferences(globalObject);
 
  if (typeof blueRefs !== 'object' || blueRefs === null) {
    throw new TypeErrorCtor('Invalid virtualization target.');
  }
 
  const {
    distortionCallback,
    defaultPolicy,
    endowments,
    globalObjectShape,
    instrumentation,
    keepAlive = true,
    liveTargetCallback,
    signSourceCallback // eslint-disable-next-line prefer-object-spread
 
  } = ObjectAssign({
    __proto__: null
  }, providedOptions);
  const iframe = createDetachableIframe(blueRefs.document);
  const redWindow = ReflectApply(HTMLIFrameElementProtoContentWindowGetter, iframe, []);
  const shouldUseDefaultGlobalOwnKeys = typeof globalObjectShape !== 'object' || globalObjectShape === null;
 
  if (shouldUseDefaultGlobalOwnKeys && defaultGlobalOwnKeys === null) {
    defaultGlobalOwnKeys = filterWindowKeys(getFilteredGlobalOwnKeys(redWindow));
  }
 
  let blueConnector = blueCreateHooksCallbackCache.get(blueRefs.document);
 
  if (blueConnector === undefined) {
    blueConnector = createBlueConnector(globalObject);
    blueCreateHooksCallbackCache.set(blueRefs.document, blueConnector);
  } // Install default TrustedTypes policy in the virtual environment.
  // @ts-ignore trustedTypes does not exist on GlobalObject
 
 
  Iif (typeof redWindow.trustedTypes !== 'undefined' && isObject(defaultPolicy)) {
    // @ts-ignore trustedTypes does not exist on GlobalObject
    redWindow.trustedTypes.createPolicy('default', defaultPolicy);
  }
 
  const {
    eval: redIndirectEval
  } = redWindow;
  const env = new VirtualEnvironment({
    blueConnector,
    redConnector: createRedConnector(signSourceCallback ? sourceText => redIndirectEval(signSourceCallback(sourceText)) : redIndirectEval),
    distortionCallback,
    instrumentation,
    liveTargetCallback,
    revokedProxyCallback: keepAlive ? revokedProxyCallback : undefined,
    signSourceCallback
  });
  linkIntrinsics(env, globalObject); // window
  // window.document
  // In browsers globalThis is === window.
 
  Iif (typeof globalThis === 'undefined') {
    // Support for globalThis was added in Chrome 71.
    // However, environments like Android emulators are running Chrome 69.
    env.link('window', 'document');
  } else {
    // document is === window.document.
    env.link('document');
  } // window.__proto__ (aka Window.prototype)
  // window.__proto__.__proto__ (aka WindowProperties.prototype)
  // window.__proto__.__proto__.__proto__ (aka EventTarget.prototype)
 
 
  env.link('__proto__', '__proto__', '__proto__');
  env.remapProto(blueRefs.document, blueRefs.DocumentProto);
  env.lazyRemapProperties(blueRefs.window, shouldUseDefaultGlobalOwnKeys ? defaultGlobalOwnKeys : filterWindowKeys(getFilteredGlobalOwnKeys(globalObjectShape)), // Chromium based browsers have a bug that nulls the result of `window`
  // getters in detached iframes when the property descriptor of `window.window`
  // is retrieved.
  // https://bugs.chromium.org/p/chromium/issues/detail?id=1305302
  keepAlive ? undefined : unforgeablePoisonedWindowKeys);
 
  if (endowments) {
    const filteredEndowments = {};
    assignFilteredGlobalDescriptorsFromPropertyDescriptorMap(filteredEndowments, endowments);
    removeWindowDescriptors(filteredEndowments);
    env.remapProperties(blueRefs.window, filteredEndowments);
  } // We intentionally skip remapping Window.prototype because there is nothing
  // in it that needs to be remapped.
 
 
  env.lazyRemapProperties(blueRefs.EventTargetProto, blueRefs.EventTargetProtoOwnKeys); // We don't remap `blueRefs.WindowPropertiesProto` because it is "magical"
  // in that it provides access to elements by id.
  //
  // Once we get the iframe info ready, and all mapped, we can proceed to
  // detach the iframe only if `options.keepAlive` isn't true.
 
  if (keepAlive) {
    // @TODO: Temporary hack to preserve the document reference in Firefox.
    // https://bugzilla.mozilla.org/show_bug.cgi?id=543435
    const {
      document: redDocument
    } = redWindow; // Revoke the proxies of the redDocument and redWindow to prevent access.
 
    revoked.add(redDocument);
    revoked.add(redWindow);
    ReflectApply(DocumentProtoOpen, redDocument, []);
    ReflectApply(DocumentProtoClose, redDocument, []);
  } else {
    Iif (IS_OLD_CHROMIUM_BROWSER) {
      // For Chromium < v86 browsers we evaluate the `window` object to
      // kickstart the realm so that `window` persists when the iframe is
      // removed from the document.
      redIndirectEval('window');
    }
 
    ReflectApply(ElementProtoRemove, iframe, []);
  }
 
  return env;
}
 
function revokedProxyCallback(value) {
  return revoked.has(value);
}
 
export { createIframeVirtualEnvironment as default };