My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Sunday, February 23, 2014

goto didn't fail;

it actually worked pretty well, and this is just my quick take on the infamous goto fail; security issue Apple had recently, an issue perfectly explained in this Adam Langley Weblog post.

what is wrong, in a sentence

Citing Adam Langley, here in my opinion exactly what is wrong in the modern software industry:
If I compile with -Wall (enable all warnings), neither GCC 4.8.2 or Clang 3.3 from Xcode make a peep about the dead code. That's surprising to me ...
Do you see that? Adam trusted the compiler to solve logic problems for him, without even mentioning for a second that a basic test would have shown the problem against an expected output apparently impossible to reach/obtain.
Bear in mind this post is not about Adam and the fact I am surprised too his example didn't warn, but that sentence represents way properly the common thinking in the actual industry, IMO (so please Adam don't take it personally, thanks).

syntax has nothing to do with security

every programming language has its own syntax gotchas, but this does not mean that every program is written badly or it can fail. The amount of criticism behind brackets, indentation, parenthesis, or the goto statement, even from the wired post, is embarhassing:
Using “goto” statements in any form has long been considered a poor programming practice, though everyone does it anyway.
It's way too easy to blame a statement and make this story a light emphasis on how bad is goto and everyone using it should burn in hell ... I wouldn't even be surprised if Apple will remove such statement from everywhere in XCode so that can go along with what really went wrong in this story ...
Truth is, an accidental early function return would have caused exactly same problem, stop blaming goto then!

missing tests and 100% code coverage

everyone knows testing might be hard and time consuming, but it does not matter how respected is your OS timeline if all your software does is to easily expose stuff due lack of time to test the most basic part of the security data exchange ... do you know what I mean?

a gently myth buster on SW development

just to remember what is not SW development about ... shall we?
  1. compilers and compiled languages do not automatically make your software secure; you can type by accident the function/method detractMoney(amount) twice and let the user with 200% less money ... now tell her it was her paying twice by accident ...
  2. linter do not make your code safer neither; indeed linters are more about code readability and practices, these have nothing to do with security and specially in JS world you must be a fool to think that varname === undefined will solve anything in your code
  3. tests are not an option, and for gosh sake this must be 120% true when "enterprise" or security related code is in place. It does not matter how cool is your programming language or the tool you are using to build your software, until you have a very high/good code coverage via any sort of test you can think of, you might be, at that point, good to go but it won't be never late to add a test or be sure that something else, just a change, didn't cause a regression
Before I've met great developers that couldn't stress more about testing everything, I've worked for companies that didn't care about tests, used the classic excuse "we have no time for that" or believed that the programming language, since compiled, was better than JavaScript and error/disaster prone by default because of types or some magic death code elimination.

This is bullshit, and I don't expect such kind of bullshit from #1 corporates that will silently pass behind the scene covered by simplification of a problem that has never been caused by missing brackets, parenthesis, or a goto statement.

Get real and solve your real problems, 'cause your scanned finger prints smells already rotten knowing that SSL abc wasn't triply reviewed, and passed to production miserably without a good code coverage for it.

Thanks for listening!
P.S. this case was just too fuzzed to not be used as example where tests outperform compilers and linters but this post has really nothing strictly to do with Apple itself! Any company/corporate lacking tests (unit, integration, smoke, etc) could easily fail in security, as well as everything else, problems

Thursday, February 20, 2014

the underestimated problem about script async attribute

While authoritative bloggers seems to suggest script async attribute as the holy grail on HTML documents for non blocking JavaScript overall performance, you might probably know async behavior is not necessarily desired at all, here I'll try to explain why.

first of all: why script async

Before talking badly about this attribute, it's necessary to understand reasons behind.
async attribute aim is to not block network traffic.
Differently from deferred, where the order of scripts is preserved and the fact scripts will be parsed and executed before the DOMContentLoaded event would be regularly fired, async scripts download and parse might occur at any time before or after the DOMContentLoaded as well as the onload event have been already fired.

<script async="shenanigans">

Yes, if your library, framework, utility, entire Web App, relies for some reason to the DOMContentLoaded event listener, or even the classic window.onload event, in order to initialize anything, such attribute will not guarantee that behavior at all: it's the other way round!
If the script tag is on top of the head of your page, the only place where defer or async make sense in order to not block the download of anything else in the page, it might be executed while the document is still donwloading as well as after everything else, in terms of DOM, has been interpreted already.
This situation is the most common one and not the less probable as you might think, 'cause the moment your script tag is interpreted, is the moment the browser knows already the content of the page.
From that point, to trigger a DOMContentLoaded event takes really nothing, milliseconds speaking.
If your script add that listener after, your script will never be triggered.

fixing the DOMContentLoaded

Long time ago, DOMContentLoaded in Firefox was the revolution for scripting initialization ... today this event looks ugly and unreliable, with its capital letters in the event type description, its past in the verb form compared with load which is not loaded indeed, and at the same time is the most used event ever for anything that would like to operate before the user.
In this universal common case, it's ridiculous that such event, happened in the past as Loaded would suggest, will never trigger again in the document unless somebody manually tries to do so, screwing all libraries, frameworks, or application logic, that forgot to removeEventListener once such event used for initialization has been fired ... you know what I mean?

Once For All: Fixed!

This script has no license on purpose ... I don't really care if you remember me once you used this script on top of your page and inline, I really don't want you to even think about this post once you can sleep well thinking the DOMContentLoaded event triggered your initialization script ... really, just use this script for reliability sake and forget about problems related to asynchronously loaded scripts and libraries.
Anything that will trust such event, will be triggered ... and yes, all CSP can be used as well without problems so ... no excuses, just enjoy!

Wednesday, February 19, 2014

quick repo updates

  • ./testardo sandbox.scrollTo(element) now works so well it can be tested with testardo itself
  • IE8 now supports XMLHttpRequest addEventListener, removeEventListener, and dispatch(event) on readystatechange event, normalized as well as everything else
  • eddy.js now passes all tests in IE8 too thanks to previous update plus it fixes a problem with obj.boundTo(method) weirdly unspotted before (huge bug that needs latest update)
For all Bower related projects, tags and versions should have been updated too.
Take care!

Monday, February 10, 2014

trapping an ES6 Proxy inside a with statement

restyle.js from Andrea Giammarchi on Vimeo.

update 2 to play with(restyle.properties){...} having a closure for variables and functions ... here an example ;-)

update I've been putting together explained ideas in both Proxy and a restyle.properties version that should work already in every ES5 capable environment.
Both files share the same alpha utilities file that can and will be enriched from time to time!
You can test current status directly in this page and you can also click the parsed area to have a link to share.
See how natural it feels? .. Now, imagine all browser prefixes are automagically added and you could also write around functions and variables to reuse code as you can already do in restyle ;-)
enjoy
too good and too powerful to be left ignored as pattern, while testing handy ways to make web developers life easier with a tool born for that as restyle is, I couldn't stop admiring how powerful is a with statement when a Proxy is passed as argument.

Next Tooling Level

Seriously, have a look at this Proxy:
var CSSProxy = new Proxy(
  {
    // borrowed from from eddy.js
    // https://github.com/WebReflection/eddy
    boundTo: function (method) {
      return this.$[method] || (
        this.$[method] = this._[method].bind(this)
      );
    },
    // CSS properties that clash with window
    special: /^(?:top|scroll)$/,
    // common camelCase RegExp
    find: /([a-z])([A-Z])/g,
    // common camelCase to camel-case replacement
    replace: function (m, $1, $2) {
      return $1 + '-' + $2.toLowerCase();
    },
    // a collection of already bound methods
    // it avoids blowed RAM for no reason
    // as eddy.js boundTo method does by default
    $: {},
    // the target.utility namespace
    _: {
      // in this case an hex example
      hex: function (r, g, b) {
        return '#'.concat(
          ('0' + r.toString(16)).slice(-2),
          ('0' + g.toString(16)).slice(-2),
          ('0' + b.toString(16)).slice(-2)
        );
      },
      // to write directly url('path.ext')
      url: function(src) {
        return 'url("' + src + '");'
      }
    }
  },
  // the proxy
  {
    // inside a with, everything that is not there
    // will be checked here
    has: function (target, name) {
      return  window.hasOwnProperty(name) ?
          target.special.test(name) : true;
    },
    // when .has(name) returns true ...
    get: function (target, name, receiver) {
      // either it's a method from here
      return target._.hasOwnProperty(name) ?
        // and it should be bound
        target.boundTo(name) :
        // or is a value name
        name.replace(
          target.find,
          target.replace
        );
    }
  }
);

The What And The How

Imagine you are writing through JS some CSS property for a server side/node.js pre-processor ...
with (CSSProxy) {
  console.log({
    // r, g, b to HEX value
    color: hex(100, 50, 150),   // #643296
    textAlign: center,          // 'center'
    backgroundRepeat: noRepeat, // 'no-repeat'
    content: noCloseQuote       // 'no-close-quote'
  });
}
Now, combine this with restyle(object) power:
with (CSSProxy) {
  var myApp = restyle({
    'html, body': {
      color: red,
      background: {
        image: url("image.png"),
        color: black,
        position: top
      }
    },
    section: {
      overflow: hidden,
      display: block,
    
    }
  });
}
Now, I don't know what you think but I believe this combination kicks every other CSS via JS processor out of the competition!

P.S. yeah, this is freaking cool stuff I am pretty sure somebody will complain about and shut it down as it was already for the awesome with statement :-(
ES3 FTW!

Saturday, February 08, 2014

restyle.js - a simplified CSS approach

Before you think about "yet another CSS preprocessor", I'd like to inform you that I've asked around to few common, well known, CSS or general web developers and it looks like this little script was still missing ... once you'll realize what is this about, you'll probably wonder yourself "how come nobody has done this already?".
My idea is that somebody probably did but I am not sure in 0.8KB minzipped and compatible with both server and client down to IE6 ... so here I am talking about restyle.

update Published object specifications explaining how the object is parsed and what will produce.
P.S. yes, absurd.js inspired somehow restyle except absurd.js won't work in your browser at runtime (yet?) does way more in about 26KB (~9KB gzipped) while restyle does not implement any magic.
Please read F.A.Q. to know more or check the restyle VS absurd page with basic features compared.

restyle.js

restyle is a function that provided a JS object creates and place in the DOM its CSS representation, using by default all possible prefixes. i.e.
var addedStyle = restyle({
  body: {
    color: '#FFF',
    background: {
      image: 'url(bla.bla)',
      color: '#000'
    }
  }
});
will result in this CSS, the string only in node.js world, a whole object in the DOM/browser world.
body {
  color: #FFF;
  background-image: url(bla.bla);
  background-color: #000;
}
to remove this new style at any time in DOM/browsers:
addedStyle.remove();
this is nothing impressive with standard styles but it becomes very handy when prefixes are in place.
restyle({
  'div > button:first-child': {
    transform: 'rotate(30deg)'
  }
}, ['moz', 'webkit']);
will become
div > button:first-child {
  -webkit-transform: rotate(30deg);
  -moz-transform: rotate(30deg);
  transform: rotate(30deg);
}
while the following
restyle({
  'body > div': {
    animation: {
      name: 'spin',
      duration: '4s'
    }
  },
  '@keyframes spin': {
    from: {
      transform: 'rotate(0deg)'
    },
    to: {
      transform: 'rotate(360deg)'
    }
  }
});
will become this
body > div{
  -webkit-animation-name:spin;
  -moz-animation-name:spin;
  -ms-animation-name:spin;
  -o-animation-name:spin;
  animation-name:spin;
  -webkit-animation-duration:4s;
  -moz-animation-duration:4s;
  -ms-animation-duration:4s;
  -o-animation-duration:4s;
  animation-duration:4s;
}
@-webkit-keyframes spin{
  from{
    -webkit-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -webkit-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-moz-keyframes spin{
  from{
    -moz-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -moz-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-ms-keyframes spin{
  from{
    -ms-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -ms-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@-o-keyframes spin{
  from{
    -o-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -o-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
@keyframes spin{
  from{
    -webkit-transform:rotate(0deg);
    -moz-transform:rotate(0deg);
    -ms-transform:rotate(0deg);
    -o-transform:rotate(0deg);
    transform:rotate(0deg);
  }
  to{
    -webkit-transform:rotate(360deg);
    -moz-transform:rotate(360deg);
    -ms-transform:rotate(360deg);
    -o-transform:rotate(360deg);
    transform:rotate(360deg);
  }
}
and so on ... this has few advantages if done at runtime:
  • it simplifies prefixes hell effortless
  • it confines all new changes in one style element that can be dropped at any time
  • it can associate or create complex styles inline for custom components preserving size
  • it is compatible with runtime/dynamic properties for any sort of screen/case/device
Used without prefixes on the server side, it can be a pre-processor of the pre-processor, able to use variables at runtime in a JS way, instead of using SASS and company.

Moar Info and Conclusions

Everything open sourced in github, restyle is also an npm and a bower module.
If you think you got everything already, feel free to test some syntax or verify if it works for your browser at runtime ... and that's correct, it should work even in IE6 ;-)
enjoy

following

there are experiments in place able to make restyle magic, follow up in the next post if you want to know more.

update on why the DOM result has so many prefixes?

Every time we write CSS for other browsers vendors too we are creating useless noise in the file for the current browser. This is because we don't serve the CSS file accordingly with the current browser, we simply define all prefixes hoping one will be used from the current visiting browser.
Since no concrete size will be compromise when used at runtime, restyle, by default, has exactly the same careless behavior: it just create prefixes for everything simply trusting the normal browser behavior that what should work and be understood via prefix will work, everything else will be ignored, where last non prefixed version should be prevalent.
There is no way to feature detect properly weird or early CSS behaviors per each vendor, it will blow the code size and complicate the logic resulting in a non so present, past, and future proof behavior as the current one.
That said, you can pass the Array you want if at runtime you think all those prefixes are pointless, restyle purpose is to keep it simple and work ...
Although, if you have any hint on how to do this properly everywhere without adding more than 3 lines of code to the source :P I'll be happy to listen to you ;)
In node.js case, you should probably use a more complex preprocessor after creating CSS via restyle with the benefit that used logic can be applied eventually at runtime too.

Saturday, February 01, 2014

eddy.js goes promisish

This is a quick one about the tiny library I am using the most for personal projects: eddy.js

Promised Events

eddy makes the creation of event driven logic and application the easiest possible you can imagine.
var obj = {};

// at any time, in any place
obj.on('event', doSomething);
The unobtrusive, memory safe and lazily attached EventTarget logic you can even overwrite whenever you like to anywhere in your code, cannot solve tasks in a way ES6 Promises would.

... but what if I told you ...

... that jQuery nailed it in a similar way since ever?

.when(something, happened)

A very basic example of this new method is a classic document.ready approach indeed:
// even if lazily loaded!
document.when('ready', function(e){
  console.log('we are ready to go');
});

// later, even loaded asynchronously
// with or without AMD
document.when('ready', initLibrary);
Even if manually dispatched, handlers that has been fired once will not fire again unless re-attached but even doing so, these won't be fired twice if previously attached.
The best of both worlds, where listeners are stored by reference once, without the possibility to be fired more than once.
.once() is indeed the closest example to .when() except once adds a new listener, if not previously added, regardless the operation happened already in the past.
With this .when() method we are sure that the very first time the event happens, every other listener could benefit from that result.

result but no implicit reject

The "fulfill" part of this concept is provided by the way we dispatch the event either with .trigger('DOM-like', details) or .emit('node-like', null, value).
Any listener will receive the event or value passed the very first time the fulfill occurs but there is no way to understand a rejected value if not analyzing arguments.
A reject can be easily simulated indeed via .trigger('DOM-like', new Error('problem')) or .emit('node-like', new Error('problem'), null) so that any listener could handle failures.

improved .boundTo()

Another small change to library has been enriching Object#boundTo() signature so that it is possible to assign if not present once and at runtime.
I've found myself repeating this kind of pattern over and over:
obj.on('evt',
  obj.someMethod || (
  obj.someMethod = function(e) {
    // everything I need
  }
));
With the current improvement to boundTo, which I found more appropriate than creating another method for all objects, we can simply do this:
obj.on(
  'evt',
  obj.boundTo('someMethod', function(e) {
    // everything I need
  })
);
Above code will assign the second function argument only once and only if someMethod has not been assigned already. If a bound version is not required, then we could go in a less elegant way and either use the initial approach I've showed or simply addressing the property after:
obj.on(
  'evt',
  // not the bound version
  obj.boundTo('someMethod', function(e) {
    // everything I need
  }).someMethod // there it is!
);
The method does not create indeed a bound copy of the function as property, it rather addresses it once per property.

boundTo(Caveat)

It's very simple to create a foot-gun. If we address two different functions with the same property name only the first one will be used and never the last. In this case is highly recommended to delete obj.someMethod before using again boundTo ease.

Summary

eddy.js is becoming addictive and I am holding back myself every time I'd like to add some new cool thing trying to avoid mistakes old libraries did and keeping it simple and unobtrusive but I strongly suggest you to give it a shot.
Enjoy!