Skip to content
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

MIP2 组件沙盒方案 #5

Closed
PengXing opened this issue Jun 4, 2018 · 4 comments
Closed

MIP2 组件沙盒方案 #5

PengXing opened this issue Jun 4, 2018 · 4 comments

Comments

@PengXing
Copy link
Contributor

PengXing commented Jun 4, 2018

在这之前,我们确定的方案是 Context 方案,通过将组件的 script 包裹在我们的沙盒中,然后将全局的变量在这个沙盒中重新实现,达到屏蔽一些危险的变量和方法的目的,如下代码所示:

// sandbox.js
export let document = {
 // 不包含 createElement 方法
};

// component-a.js
let document = MIP.sandbox.document; // 重写 document 对象,编译时注入
export default new Vue({
  methods: {
    created() {
      let a = document.createElement('a') // 操作不被允许
    }
  }
});

后来发现这种方法很难控制, window 下的变量茫茫多,不仅有浏览器默认的变量,还有 MIP 里挂载到全局的变量,如:window._m, window.MIP_ROUTER 等等,这样的黑名单方案不可靠,经常需要升级,因此,我们将沙盒方案改为白盒方案只允许组件使用 window 中的某些变量和函数

白盒方案分为两步:

  • 开发者提交组件进行校验,校验全局变量是否有用到非白名单列表之内的变量或者函数
  • 运行时的沙盒,重写白名单列表的变量和函数,部分变量和函数改为 getter,不让用户修改,只能使用
@clark-t
Copy link
Contributor

clark-t commented Jun 4, 2018

组件构建沙盒方案:
为了避免用户使用 window、document 下面的一些危险方法导致站点体验变差,需要对用户使用的 window、document 对象进行严格的限制,具体的实现方案为:

  1. 判断哪些是全局变量(如 window、document、setTimeout);
  2. 将全局变量在构建时全部加上沙盒前缀(如 window -> MIP.sandbox.window、setTimeout -> MIP.sandbox.window.setTimeout、Promise -> MIP.sandbox.window.Promise);
  3. 允许用户使用哪些对象或方法,就可以通过控制 MIP.sandbox 对象的实现即可,比如允许用户使用 setTimeout,则沙盒代码中定义 MIP.sanbox.window.setTimeout 即可,不希望用户使用的,直接不做定义即可,从而实现沙盒的白名单机制;
  4. 关于代码中出现 this 的问题,目前想到的方案是构建时直接将 this 替换成 (this === window ? MIP.sandbox.window : this === document ? MIP.sandbox.document : this) 从而解决 function () {console.log(this)}.bind(undefined) 这类代码的 this 指向 window 的问题;

这样存在的一个问题就是 比如用户希望使用 zepto($)那么在构建的时候会变成 MIP.sandbox.window.$,也就意味着如果允许用户使用 zepto 的话,必须得在 sandbox 里定义一下才行,这也就意味着,每增加一个挂在到全局的允许用户使用的对象或方法,也都要在 sandbox 里定义,这样是否合理?

@Ricardo-Li
Copy link
Contributor

Ricardo-Li commented Jun 4, 2018

Document

只允许使用规定的全局变量,包括:

Properties

  • head
  • body
  • title
  • cookie
  • referrer
  • readyState
  • documentElement

Methods

  • createElement
  • createDocumentFragment
  • getElementById
  • getElementsByClassName
  • getElementsByName
  • getElementsByTagName
  • querySelector
  • querySelectorAll

@clark-t
Copy link
Contributor

clark-t commented Jun 4, 2018

以下是我目前整理出来的可能会用到的 window 下面的属性和方法,看看有没有遗漏的,事件监听 (如 onclick onscroll 这些)目前是全注释掉的,需要讨论下是否允许使用 window.onscroll = function () {} 的方式监听事件,还是说要求统一通过 addEventListener 去监听事件呢?

AbortController,
AbortSignal,
// AnalyserNode,


// AnimationEvent,
// ApplicationCache,
// ApplicationCacheErrorEvent,

Array,
ArrayBuffer,

// Attr,
// Audio,AudioBuffer,AudioBufferSourceNode,AudioContext,AudioDestinationNode,AudioListener,AudioNode,AudioParam,AudioParamMap,AudioProcessingEvent,AudioScheduledSourceNode,AudioWorklet,AudioWorkletNode,
// BarProp,

// BaseAudioContext,

// BatteryManager,
// BeforeInstallPromptEvent,
// BeforeUnloadEvent,
// BiquadFilterNode,

Blob,
// BlobEvent,
// Bluetooth,BluetoothCharacteristicProperties,BluetoothDevice,BluetoothRemoteGATTCharacteristic,BluetoothRemoteGATTDescriptor,BluetoothRemoteGATTServer,BluetoothRemoteGATTService,BluetoothUUID,

Boolean,

// BroadcastChannel,

// BudgetService,

// ByteLengthQueuingStrategy,
// CDATASection,
// CSS,CSSConditionRule,CSSFontFaceRule,CSSGroupingRule,CSSImageValue,CSSImportRule,CSSKeyframeRule,CSSKeyframesRule,CSSKeywordValue,CSSMathInvert,CSSMathMax,CSSMathMin,CSSMathNegate,CSSMathProduct,CSSMathSum,CSSMathValue,CSSMatrixComponent,CSSMediaRule,CSSNamespaceRule,CSSNumericArray,CSSNumericValue,CSSPageRule,CSSPerspective,CSSPositionValue,CSSRotate,CSSRule,CSSRuleList,CSSScale,CSSSkew,CSSSkewX,CSSSkewY,CSSStyleDeclaration,CSSStyleRule,CSSStyleSheet,CSSStyleValue,CSSSupportsRule,CSSTransformComponent,CSSTransformValue,CSSTranslate,CSSUnitValue,CSSUnparsedValue,CSSVariableReferenceValue,

// Cache,
// CacheStorage,

// CanvasCaptureMediaStreamTrack,CanvasGradient,CanvasPattern,CanvasRenderingContext2D,

// ChannelMergerNode,ChannelSplitterNode,
// CharacterData,
// Clipboard,ClipboardEvent,
// CloseEvent,
// Comment,
// CompositionEvent,ConstantSourceNode,ConvolverNode,CountQueuingStrategy,Credential,CredentialsContainer,Crypto,CryptoKey,

// CustomElementRegistry,
CustomEvent,
DOMError,DOMException,
// DOMImplementation,DOMMatrix,DOMMatrixReadOnly,DOMParser,DOMPoint,DOMPointReadOnly,DOMQuad,DOMRect,DOMRectReadOnly,DOMStringList,DOMStringMap,DOMTokenList,

// DataTransfer,DataTransferItem,DataTransferItemList,
// DataView,
Date,

// DelayNode,

// DeviceMotionEvent,
// DeviceOrientationEvent,

// Document,DocumentFragment,DocumentType,

// DragEvent,

// DynamicsCompressorNode,
// Element,

Error,

// ErrorEvent,EvalError,

// Event,EventSource,EventTarget,

// FederatedCredential,

File,FileList,FileReader,Float32Array,Float64Array,

// FocusEvent,FontFace,FontFaceSetLoadEvent,

FormData,Function,

// GainNode,Gamepad,GamepadButton,GamepadEvent,
// HTMLAllCollection,HTMLAnchorElement,HTMLAreaElement,HTMLAudioElement,HTMLBRElement,HTMLBaseElement,HTMLBodyElement,HTMLButtonElement,HTMLCanvasElement,HTMLCollection,HTMLContentElement,HTMLDListElement,HTMLDataElement,HTMLDataListElement,HTMLDetailsElement,HTMLDialogElement,HTMLDirectoryElement,HTMLDivElement,HTMLDocument,HTMLElement,HTMLEmbedElement,HTMLFieldSetElement,HTMLFontElement,HTMLFormControlsCollection,HTMLFormElement,HTMLFrameElement,HTMLFrameSetElement,HTMLHRElement,HTMLHeadElement,HTMLHeadingElement,HTMLHtmlElement,HTMLIFrameElement,HTMLImageElement,HTMLInputElement,HTMLLIElement,HTMLLabelElement,HTMLLegendElement,HTMLLinkElement,HTMLMapElement,HTMLMarqueeElement,HTMLMediaElement,HTMLMenuElement,HTMLMetaElement,HTMLMeterElement,HTMLModElement,HTMLOListElement,HTMLObjectElement,HTMLOptGroupElement,HTMLOptionElement,HTMLOptionsCollection,HTMLOutputElement,HTMLParagraphElement,HTMLParamElement,HTMLPictureElement,HTMLPreElement,HTMLProgressElement,HTMLQuoteElement,HTMLScriptElement,HTMLSelectElement,HTMLShadowElement,HTMLSlotElement,HTMLSourceElement,HTMLSpanElement,HTMLStyleElement,HTMLTableCaptionElement,HTMLTableCellElement,HTMLTableColElement,HTMLTableElement,HTMLTableRowElement,HTMLTableSectionElement,HTMLTemplateElement,HTMLTextAreaElement,HTMLTimeElement,HTMLTitleElement,HTMLTrackElement,HTMLUListElement,HTMLUnknownElement,HTMLVideoElement,
// HashChangeEvent,

Headers,
// History,

// IDBCursor,IDBCursorWithValue,IDBDatabase,IDBFactory,IDBIndex,IDBKeyRange,IDBObjectStore,IDBOpenDBRequest,IDBRequest,IDBTransaction,IDBVersionChangeEvent,

// Audio 相关
// IIRFilterNode,

// IdleDeadline,

Image,ImageBitmap,
// ImageBitmapRenderingContext,ImageCapture,ImageData,

Infinity,

// InputDeviceCapabilities,InputEvent,

Int16Array,Int32Array,Int8Array,

// IntersectionObserver,IntersectionObserverEntry,Intl,

JSON,

// KeyboardEvent,LocalNTP,

// Location,

// MIDIAccess,MIDIConnectionEvent,MIDIInput,MIDIInputMap,MIDIMessageEvent,MIDIOutput,MIDIOutputMap,MIDIPort,

Map,Math,

// MediaCapabilities,MediaCapabilitiesInfo,MediaDeviceInfo,MediaDevices,MediaElementAudioSourceNode,MediaEncryptedEvent,MediaError,MediaKeyMessageEvent,MediaKeySession,MediaKeyStatusMap,MediaKeySystemAccess,MediaKeys,MediaList,MediaQueryList,MediaQueryListEvent,MediaRecorder,MediaSettingsRange,MediaSource,MediaStream,MediaStreamAudioDestinationNode,MediaStreamAudioSourceNode,MediaStreamEvent,MediaStreamTrack,MediaStreamTrackEvent,
// MessageChannel,MessageEvent,MessagePort,
// MimeType,MimeTypeArray,MouseEvent,
MutationEvent,MutationObserver,MutationRecord,NaN,
// NamedNodeMap,NavigationPreloadManager,
Navigator,
// NetworkInformation,Node,NodeFilter,NodeIterator,NodeList,
Notification,
Number,Object,
// OfflineAudioCompletionEvent,OfflineAudioContext,
// Option,
// OscillatorNode,OverconstrainedError,PageTransitionEvent,PannerNode,PasswordCredential,Path2D,
// PaymentAddress,PaymentRequest,PaymentRequestUpdateEvent,PaymentResponse,
// Performance,PerformanceEntry,PerformanceLongTaskTiming,PerformanceMark,PerformanceMeasure,PerformanceNavigation,PerformanceNavigationTiming,PerformanceObserver,PerformanceObserverEntryList,PerformancePaintTiming,PerformanceResourceTiming,PerformanceServerTiming,PerformanceTiming,PeriodicWave,PermissionStatus,Permissions,
// PhotoCapabilities,
// Plugin,PluginArray,PointerEvent,PopStateEvent,Presentation,PresentationAvailability,PresentationConnection,PresentationConnectionAvailableEvent,PresentationConnectionCloseEvent,PresentationConnectionList,PresentationReceiver,PresentationRequest,ProcessingInstruction,ProgressEvent,
Promise,
// PromiseRejectionEvent,
Proxy,
// PushManager,PushSubscription,PushSubscriptionOptions,
// RTCCertificate,RTCDTMFSender,RTCDTMFToneChangeEvent,RTCDataChannel,RTCDataChannelEvent,RTCIceCandidate,RTCPeerConnection,RTCPeerConnectionIceEvent,RTCRtpContributingSource,RTCRtpReceiver,RTCRtpSender,RTCSessionDescription,RTCStatsReport,RTCTrackEvent,
// RadioNodeList,Range,RangeError,
ReadableStream,ReferenceError,Reflect,RegExp,
// RemotePlayback,
Request,
// ResizeObserver,ResizeObserverEntry,
Response,
// SVGAElement,SVGAngle,SVGAnimateElement,SVGAnimateMotionElement,SVGAnimateTransformElement,SVGAnimatedAngle,SVGAnimatedBoolean,SVGAnimatedEnumeration,SVGAnimatedInteger,SVGAnimatedLength,SVGAnimatedLengthList,SVGAnimatedNumber,SVGAnimatedNumberList,SVGAnimatedPreserveAspectRatio,SVGAnimatedRect,SVGAnimatedString,SVGAnimatedTransformList,SVGAnimationElement,SVGCircleElement,SVGClipPathElement,SVGComponentTransferFunctionElement,SVGDefsElement,SVGDescElement,SVGDiscardElement,SVGElement,SVGEllipseElement,SVGFEBlendElement,SVGFEColorMatrixElement,SVGFEComponentTransferElement,SVGFECompositeElement,SVGFEConvolveMatrixElement,SVGFEDiffuseLightingElement,SVGFEDisplacementMapElement,SVGFEDistantLightElement,SVGFEDropShadowElement,SVGFEFloodElement,SVGFEFuncAElement,SVGFEFuncBElement,SVGFEFuncGElement,SVGFEFuncRElement,SVGFEGaussianBlurElement,SVGFEImageElement,SVGFEMergeElement,SVGFEMergeNodeElement,SVGFEMorphologyElement,SVGFEOffsetElement,SVGFEPointLightElement,SVGFESpecularLightingElement,SVGFESpotLightElement,SVGFETileElement,SVGFETurbulenceElement,SVGFilterElement,SVGForeignObjectElement,SVGGElement,SVGGeometryElement,SVGGradientElement,SVGGraphicsElement,SVGImageElement,SVGLength,SVGLengthList,SVGLineElement,SVGLinearGradientElement,SVGMPathElement,SVGMarkerElement,SVGMaskElement,SVGMatrix,SVGMetadataElement,SVGNumber,SVGNumberList,SVGPathElement,SVGPatternElement,SVGPoint,SVGPointList,SVGPolygonElement,SVGPolylineElement,SVGPreserveAspectRatio,SVGRadialGradientElement,SVGRect,SVGRectElement,SVGSVGElement,SVGScriptElement,SVGSetElement,SVGStopElement,SVGStringList,SVGStyleElement,SVGSwitchElement,SVGSymbolElement,SVGTSpanElement,SVGTextContentElement,SVGTextElement,SVGTextPathElement,SVGTextPositioningElement,SVGTitleElement,SVGTransform,SVGTransformList,SVGUnitTypes,SVGUseElement,SVGViewElement,
// Screen,ScreenOrientation,ScriptProcessorNode,SecurityPolicyViolationEvent,Selection,
// ServiceWorker,ServiceWorkerContainer,ServiceWorkerRegistration,
Set,
// ShadowRoot,SharedWorker,SourceBuffer,SourceBufferList,SpeechSynthesisEvent,SpeechSynthesisUtterance,StaticRange,StereoPannerNode,
// Storage,
// StorageEvent,
// StorageManager,
String,
// StylePropertyMap,StylePropertyMapReadOnly,StyleSheet,StyleSheetList,SubtleCrypto,
Symbol,
// SyncManager,
SyntaxError,
// TaskAttributionTiming,
// Text,TextDecoder,TextEncoder,TextEvent,TextMetrics,TextTrack,TextTrackCue,TextTrackCueList,TextTrackList,
// TimeRanges,Touch,TouchEvent,TouchList,TrackEvent,TransitionEvent,TreeWalker,
TypeError,
// UIEvent,
URIError,URL,URLSearchParams,
// USB,USBAlternateInterface,USBConfiguration,USBConnectionEvent,USBDevice,USBEndpoint,USBInTransferResult,USBInterface,USBIsochronousInTransferPacket,USBIsochronousInTransferResult,USBIsochronousOutTransferPacket,USBIsochronousOutTransferResult,USBOutTransferResult,
Uint16Array,Uint32Array,Uint8Array,Uint8ClampedArray,
// VTTCue,ValidityState,VisualViewport,WaveShaperNode,WeakMap,WeakSet,WebAssembly,
// WebGL2RenderingContext,WebGLActiveInfo,WebGLBuffer,WebGLContextEvent,WebGLFramebuffer,WebGLProgram,WebGLQuery,WebGLRenderbuffer,WebGLRenderingContext,WebGLSampler,WebGLShader,WebGLShaderPrecisionFormat,WebGLSync,WebGLTexture,WebGLTransformFeedback,WebGLUniformLocation,WebGLVertexArrayObject,
// WebKitAnimationEvent,WebKitCSSMatrix,WebKitMutationObserver,WebKitTransitionEvent,

// WebSocket,
// WheelEvent,Window,Worker,Worklet,
WritableStream,
// XMLDocument,
XMLHttpRequest,
// XMLHttpRequestEventTarget,
// XMLHttpRequestUpload,
// XMLSerializer,
// XPathEvaluator,XPathExpression,XPathResult,XSLTProcessor,

addEventListener,
// alert,applicationCache,atob,blur,btoa,caches,
cancelAnimationFrame,
// cancelIdleCallback,captureEvents,chrome,clear,
clearInterval,
clearTimeout,
// clientInformation,close,closed,configData,confirm,

console,
// copy,
createImageBitmap,
// crypto,
// customElements,

// WARNING
// debug,

decodeURI,
decodeURIComponent,
// defaultStatus,defaultstatus,
devicePixelRatio,
dispatchEvent,
// dir,dirxml,
document,
encodeURI,
encodeURIComponent,
escape,

// eval,
// event,
// external,
fetch,
// find,
// focus,

// frameElement,frames,
// getChromeUILanguage,
getComputedStyle,
// getEventListeners,
// getSelection,
history,
indexedDB,

innerHeight,innerWidth,
// inspect,
isFinite,isNaN,isSecureContext,
// keys,lastDdllogResponse,
length,
localStorage,
location,
// locationbar,
matchMedia,
// menubar,
// monitor,monitorEvents,moveBy,moveTo,name,
navigator,
// numDdllogResponsesReceived,offscreenBuffering,onDdllogResponse,
// onabort,onafterprint,onanimationend,onanimationiteration,onanimationstart,onappinstalled,onauxclick,onbeforeinstallprompt,onbeforeprint,onbeforeunload,onblur,oncancel,oncanplay,oncanplaythrough,onchange,onclick,onclose,oncontextmenu,oncuechange,ondblclick,ondevicemotion,ondeviceorientation,ondeviceorientationabsolute,ondrag,ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,onerror,onfocus,ongotpointercapture,onhashchange,oninput,oninvalid,onkeydown,onkeypress,onkeyup,onlanguagechange,onload,onloadeddata,onloadedmetadata,onloadstart,onlostpointercapture,onmessage,onmessageerror,onmousedown,onmouseenter,onmouseleave,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,onoffline,ononline,onpagehide,onpageshow,onpause,onplay,onplaying,onpointercancel,onpointerdown,onpointerenter,onpointerleave,onpointermove,onpointerout,onpointerover,onpointerup,onpopstate,onprogress,onratechange,onrejectionhandled,onreset,onresize,onscroll,onsearch,onseeked,onseeking,onselect,onstalled,onstorage,onsubmit,onsuspend,ontimeupdate,ontoggle,ontransitionend,onunhandledrejection,onunload,onvolumechange,onwaiting,onwebkitanimationend,onwebkitanimationiteration,onwebkitanimationstart,onwebkittransitionend,onwheel,
// open,openDatabase,opener,origin,
outerHeight,outerWidth,pageXOffset,pageYOffset,

// parent,
parseFloat,parseInt,
// performance,personalbar,
// postMessage,
// print,profile,profileEnd,prompt,queryObjects,releaseEvents,
removeEventListener,
requestAnimationFrame,
// requestIdleCallback,resizeBy,resizeTo,
screen,screenLeft,screenTop,screenX,screenY,scroll,scrollBy,scrollTo,scrollX,scrollY,scrollbars,
// self,
sessionStorage,
setInterval,setTimeout,
// speechSynthesis,status,statusbar,stop,styleMedia,table,tilesAreLoaded,toolbar,top,undebug,
undefined,
unescape,
// unmonitor,unmonitorEvents,values,visualViewport,
webkitCancelAnimationFrame,
// webkitMediaStream,webkitRTCPeerConnection,
webkitRequestAnimationFrame,
// webkitRequestFileSystem,webkitResolveLocalFileSystemURL,webkitSpeechGrammar,webkitSpeechGrammarList,webkitSpeechRecognition,webkitSpeechRecognitionError,webkitSpeechRecognitionEvent,webkitStorageInfo,webkitURL,
window

@clark-t
Copy link
Contributor

clark-t commented Jun 21, 2018

沙盒方案最终通过 mip-sandbox 统一实现:

mip-sandbox

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants