Comments (4)
组件构建沙盒方案:
为了避免用户使用 window、document 下面的一些危险方法导致站点体验变差,需要对用户使用的 window、document 对象进行严格的限制,具体的实现方案为:
- 判断哪些是全局变量(如 window、document、setTimeout);
- 将全局变量在构建时全部加上沙盒前缀(如 window -> MIP.sandbox.window、setTimeout -> MIP.sandbox.window.setTimeout、Promise -> MIP.sandbox.window.Promise);
- 允许用户使用哪些对象或方法,就可以通过控制 MIP.sandbox 对象的实现即可,比如允许用户使用 setTimeout,则沙盒代码中定义 MIP.sanbox.window.setTimeout 即可,不希望用户使用的,直接不做定义即可,从而实现沙盒的白名单机制;
- 关于代码中出现 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 里定义,这样是否合理?
from mip2.
Document
只允许使用规定的全局变量,包括:
Properties
- head
- body
- title
- cookie
- referrer
- readyState
- documentElement
Methods
- createElement
- createDocumentFragment
- getElementById
- getElementsByClassName
- getElementsByName
- getElementsByTagName
- querySelector
- querySelectorAll
from mip2.
以下是我目前整理出来的可能会用到的 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
from mip2.
沙盒方案最终通过 mip-sandbox 统一实现:
from mip2.
Related Issues (20)
- 沙盒开放 document.referrer 读权限
- iframe里的页面mip-fixed组件不再有固定效果(IOS环境) HOT 1
- 怎么停用已经生效的mip HOT 1
- mip-link打开iframe页面无法正确计算高度的问题(IOS12,IOS13环境)
- [sandbox] 申请 swanInvoke
- 反馈:docs/news/index.md
- 反馈:docs/components/dynamic-content/mip-form.md HOT 3
- MIP 头部 bar 固定样式会被网站自自定义样式影响
- mip-video 在安卓qq浏览器脱离文档流
- 反馈:docs/news/index.md HOT 1
- 非白名单 npm 列表 HOT 1
- 反馈:docs/components/layout/mip-tabs.md HOT 1
- 独立域名的mip站点到底如何正确退出,恢复成H5移动站 HOT 1
- 反馈:docs/components/presentation/mip-rem.md HOT 1
- vue 组件在注册的时候会执行两次
- m-bind:href 浏览器上显示 href="{"tel":""}"
- MIP Cache 服务下线,请问这个项目是不维护了吗? HOT 2
- @baidu/fc-jmy-client-capabilities包申请加白
- 官网https://www.mipengine.org/证书过期好几个月了 HOT 1
- mip2+vue怎么配置跳转?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mip2.