Hosting a static web-app on a custom domain with AWS S3 and Cloudflare

This is a step by step guide on hosting a static web-app on Amazon S3 and exposing it using a custom (https) domain through Cloudflare.

This article assumes some prior knowledge of both Amazon S3 and Cloudflare.

The example web-app used in the article will be hosted using a subdomain, however, the same approach will work for root domains as well.

About Amazon S3 and Cloudflare

If you are familiar with both S3 and Cloudflare you can skip this section.

Amazon S3 is a hosted storage service which allows you to upload files and configure permissions for these files. S3 also allows a so called bucket (a container for files) to be used as a static web hosting service. You can read more about Amazon S3 by visiting their site. https://aws.amazon.com/s3/

Cloudflare is a service which offers CDN, DNS and many other products. We'll be using it for its DNS product in this article. Read more about Cloudflare on their own site. https://www.cloudflare.com

Setting up a basic web-app

The first step is to create the code for a web app. For this example, I'll be using a simple `index.html` file which prints "An example web app …..". The only thing to note here is that you do need an «index» file to act as the entry point / root for your web-app.

The example web-app is be hosted at https://web-app-test.kinderas.com.

Configuring Amazon S3

Log in to the AWS console and navigate to the S3 service. Here you'll want to create a new bucket with the same name as the URL for your web app. It's important that the name of the bucket matches the name of the URL exactly, without the protocol (HTTP(s)), since S3 uses the bucket name for routing.

The example URL is web-app-test.kinderas.com, so we'll create a bucket with that name. Choose a region and click next and then next again.

The bucket name must match the URL

The bucket name must match the URL

On the third screen for the bucket creation wizard, uncheck the boxes under «Manage public Access control lists (ACLs) for selected buckets». If you forget this you can do it later by selecting the bucket and clicking the «Edit public access setting» button on the overview page.

Allow the bucket to be public

Allow the bucket to be public

In order to have S3 use this bucket for website hosting, we need to configure a couple of things. Click on the name of the bucket and select the «Properties» tab on the top. Find the «Static website hosting» tile and click it. For the «index document» enter the filename of the entry point file, in this example, this is called «index.html». You can also upload a file which is used for errors.

Note the «Endpoint» URL at the top of the dialog. We'll need this URL for testing and for configuring the domain in Cloudflare.

img3.png

Now we need to upload our web-app to have something to use for testing. Select the «Overview» tab in your bucket and upload your app, making sure that the «index.html» file is at the root of the bucket.

img4.png

The web-app will not work just yet. If you visit the endpoint URL from the static website dialog it will just give you a permission error. To make it work we'll need to allow access to the bucket from the outside world.

Select the «Permissions» tab from the top of the bucket settings and then select the «Bucket policy» tab. You should now see the «Bucket policy editor». First We’ll create a simple policy to verify that the basic are working. Paste the JSON below into the editor and do notice the «YOUR BUCKET NAME HERE» part, replace that part with your bucket name. See the image below for a full example using the name from the example web-app.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::YOUR BUCKET NAME HERE/*"
        }
    ]
}
Replace the bucket name with your own bucket name

Replace the bucket name with your own bucket name

The policy above grants public access to anybody wanting to visit your web-app at the S3 generated URL. If this is all you want, then you are done. However, if you want to use browser features dependent on https you'll want to read on.

Next, we'll modify the permissions to only allow traffic from Cloudflare. We'll do this by adding a condition to the policy stating that only IP addresses from Cloudflare should be able to access the bucket.

The new full policy looks like this (below). Notice the «YOUR BUCKET NAME HERE» on line 9. You know what to do. Update it, save it. You will no longer be able to access the bucket from the S3 URL. Moving on to the Cloudflare setup below the policy gist. In the gist we are whitelisting the Cloudflare URLs found here: https://www.cloudflare.com/ips/

Configuring Cloudflare

Important note about security! Configuring Cloudflare to expose your web-app on an https URL does not mean that the traffic from Cloudflare to the S3 bucket is encrypted. It only implies to the browser that the web-app is hosted on an https server, allowing certain features which would otherwise be unavailable.

Log in to Cloudflare and navigate to the DNS tab. You'll need the URL from the static website dialog in the S3 setup section.

Add a new CNAME record. In this example, I'm using a subdomain so I'll add «web-app-test» for the «Name» field and then the URL (without http://) from the static website dialog in the S3 setup in the «Domain» field. Leave the little orange cloud on. Click «Add record».

img6.png

If you have the Crypto -> SSL section of Cloudflare set to "Full" you'll need to take an additional step. If it's set to "Flexible" you are done and the URL should work. Please don't change this setting in the SSL tab to Flexible if it’s set to Full, doing this will affect your entire domain!

[Optional - see above]. In Cloudflare, go to «Page Rules» and create a new rule. The rule should state that when a request to the web-app is encountered it should use "Flexible" SSL. See the image below for how this applies to the example URL.

Replace the URL used with your own url

Replace the URL used with your own url

You can now test your web-app at the proper URL, for this example that would be https://web-app-test.kinderas.com

Sources

AWS: Using Elastic Beanstalk as a private backend for the API Gateway

When working with an API Gateway in Amazon Web Services (AWS) you typically don't want the services themselves to be publicly available on the Internet. A public service would only create the need for extra layers of protections such as client certificates or service keys, neither of which would properly prevent a, for example, a DoS attack. A better approach is to either use Lambdas (which are private by default) or (if you can't use Lambdas) simply keep the services within a private cloud (a «VPC» in Amazon terminology) and provide access to them only through the API itself.

This quick-guide intends to explain the basics of configuring a private backend/service utilizing an Elastic Beanstalk app (EBS) residing within a VPC. The methods of the EBS will be made available through the API Gateway using a VPC Link.

Note: As of this writing the AWS API Gateway only allows a maximum of 5 VPC Links for one API Gateway in the same account. You can ask to have this limit increased through AWS support.

VPC

First, you will need to configure a Virtual Private Cloud (VPC), I will not cover this step here since it would require a separate post. However, I would recommend that you take a look at the following video for directions if you're unsure how to accomplish this step.

Elastic Beanstalk

The second step is setting up an Elastic Beanstalk (EBS) application. (This guide assumes you're using the AWS console). One of the advantage of using EBS over pure EC2 instances is that EBS comes with a bunch of pre-configured features such as auto scaling and rolling updates. You can achieve the same goal (private service) using a just some EC2 instances and a Network Load Balancer (click the link to see how) of course, but for this guide I'll assume that you are using an EBS application.

The first step is to create an EBS application, followed by creating a new environment. The environment is actually where all the configuration takes place. Refer to https://aws.amazon.com/elasticbeanstalk for more information on how EBS actually works.

When setting up a new environment choose the "Web server environment" for now. Give your environment a name and choose a platform (I'm using Node.js). Just use the "Sample application" if you don't have a finished app bundle.

Important: Click the «Configure more options» button, not the «Create Environment»!

Associating an Elastic Beanstalk environment with a VPC must be done during initial setup of the environment. It cannot be done after the environment has been created.

more options.png

After you have clicked the «Configure more options» button you’ll find yourself on the «Configure <your env name>» page and you’ll see three radio buttons titled «Configuration presets». Choose the «High availability» option. This will give us the option to configure a Load Balancer. Now open / «modify» the «Load Balancer» tile. Choose the «Network Load balancer» and click «Save». The API Gateway VPC Link will only work with Network load balancers.

In the «Network» tile (left bottom one), select the VPC you have already created. Under «Load Balancer settings» the «Visibility» setting should be «Internal» since this service should not be accessible from the Internet. Select the private subnets (for all zones in your VPC) for both the load balancer and the subnets. No public subnets should be checked. Click «Save».

Setup anything else like scaling and so on and then click "Create environment».

API Gateway

Create an API Gateway if you haven't done so already.

  1. In the left menu, select «VPC links»

  2. Give the VPC link a name and select the Load Balancer you created under the EBS section in the «Target NLB». It will only show the (cryptic) name of the load balancer here, but if you go to the EC2 service, and select «load balancers» you can match any tags to the Load Balancer name.

  3. Click «Create».

While you wait for the connection to be created you can configure the API. I would recommend using stage variables to store a reference to the VPC link id. This would allow you to easier maintain several stages pointing to separate backends. AWS documentation for using stage variables to refer to a VPC link.

To configure a method in the api using the VPC link, see the following image.

api.png

In this example the «VPC link» is set as a stage variable, the same goes for the «Endpoint URI». As already stated, but worth repeating, this is a good idea because it makes it considerable easier to deal with multiple stages. You have to set this up for each of the methods in your api.

That’s it.

Useful links:

WKWebView and JavaScript in iOS 8 - using Swift

Note that the code and some of the concepts in this post are outdated

In this article I'll be briefly covering using WKWebView (new in iOS 8 and OS X 10.10) to communicate with content in a web-page using user scripts and script messages. This basically means injecting JavaScript into a web-page and receiving messages from the web-page whenever the web-page call back to your native application. All the example code will be written using Apple new language - Swift and of course JavaScript.

This example builds upon the Getting started with WKWebView using Swift in iOS 8 article which explains how to get started with WKWebView, read that one first.

There are two main concepts you'll need to understand when using the new WKWebView for JavaScript communication. These are user scripts and script messages.

User scripts

In short, user scripts are pieces of JavaScript which are injected into the web-page the WKWebView is loading. A user script is either injected and run before the content (DOM) has loaded or after the DOM is finished loading. A user script can do anything a "regular" JavaScript script can do on the page, including manipulating the DOM and calling any existing JavaScript methods in the page which was loaded. A user script is how your native application talks to JavaScript.

Script messages

This is how any script on the web-page can communicate back to your native app. A script message exposes a method in JavaScript which any can be called by any script in the web-page. You will need to define a handler in you native app which handles incoming messages from the web-site. A script message can originate from a user script or any other script loaded into the web-page handled by the WKWebView.

The demo application

In this small demo application we'll look at how to change the color of a DOM element by calling a JavaScript method from our native application while at the same time listening for asynchronous messages sent from the JavaScript in the html page to the native application. Let's get started!

To communicate between a web-page and WKWebView we need two main elements.

  1. A web-page with some JavaScript for which the WKWebView can load

  2. A WKWebView native application which talks to the web-page

The web-page

The web-page is really simple. There are two files, one «index.html» file which is the web-page and one «main.js» file which «index.html» includes at the end of its body tag.

The content of the JavaScript «main.js» is as follows. (the complete code including the HTML can be found at the bottom of the article)

function callNativeApp () {
    try {
        webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
    } catch(err) {
        console.log('The native context does not exist yet');
    }
}

setTimeout(function () {
    callNativeApp();
}, 5000);

function redHeader() {
    document.querySelector('h1').style.color = "red";
}

When this script loads it will wait 5 seconds and then call the «callNativeApp» method. The only thing to note here is the "callbackHandler". This is the name of the script message handler we will define later in the native application.

Also, I'm wrapping the callback to "webkit.messageHandlers....." in a try catch block to avoid the script falling over when it's running outside of a native app context.

There is also a tiny function which will change the header in the HTML page to a red color when run, well use this later.

You can load this web-page from a server or simply include it in your app. I'll be loading it from a local server to simulate a more realistic example.

The native application

The first thing you need to do is to point the WKWebView we created in the previous article to the new test URL. You'll need to include you own path here. If you're wondering how to set this up please refer to the Getting started with WKWebView using Swift in iOS 8 article this article build upon.

var url = NSURL(string:"http://localhost/WKJSDemo/")
var req = NSURLRequest(URL:url)
self.webView!.loadRequest(req)

The WKWebView configuration

In «Getting started with WKWebView using Swift in iOS 8» we initialized the WKWebView with no parameters, like so: self.webView = WKWebView()

This is fine for simply loading a web-page. Now however we want to inject some script into the page and this calls for some additional configuration.

The WKWebView constructor has a «configuration» parameter which takes a WKWebViewConfiguration instance. Several things can be set on this, like settings for the WebView for example turning JavaScript on or off and so on. What we need though is the userContentController property of the WKWebViewConfiguration.

The userContentController property expects an instance of WKUserContentController which has a method called addUserScript. We utilize this method to add the user script. Phew! Let's look at a simple example.

The first thing to do is to create a content controller. 

var contentController = WKUserContentController();

Now we need a user script to pass into the addUserScript method of the content controller.

var userScript = WKUserScript(
    source: "redHeader()",
    injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
    forMainFrameOnly: true
)

contentController.addUserScript(userScript)

Our JavaScript (source) is in this case a call to the «redHeader» function we defined in the JavaScript file. The «injectionTime» parameter tells the user script that it should be run when the body of the HTML page has been loaded. The other way of doing this would be to specify «AtDocumentStart» which would run the script before the body element was loaded. The «forMainFrameOnly» parameter simply says that this script will only be injected for the main frame of the HTML page. The next line adds the userScript to the contentController.

Great, now we need to create a configuration and then add the contentController to it and pass the configuration into the WebView constructor.

var config = WKWebViewConfiguration()
config.userContentController = contentController
        
self.webView = WKWebView(
    frame: self.containerView.bounds,
    configuration: config
)

Now try to run it, you should see a HTML page with a red header.

Note that the WKWebView constructor requires a "frame" parameter. This tells the web view how big it should be and is very common pattern in UIKit classes.

Having the JavaScript call the native app

Now that we know how to call JavaScript methods from the native app we'll want to let the JavaScript methods call back to the native app. As we have discussed, this is done by utilizing «script messages».

Adding the delegate method

To be able to receive events from JavaScript your ViewController needs to conform the «WKScriptMessageHandler» protocol. This means two things. We need to inherit from «WKScriptMessageHandler» and implement the «userContentController» delegate method. Let's start with extending the suprtclass.

class ViewController: UIViewController, WKScriptMessageHandler

Here we update the ViewController to include the «WKScriptMessageHandler». This will give you an error, this is because we haven't yet implemented the «userContentController» delegate method. We'll do this now.

func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!) {
    if(message.name == "callbackHandler") {
        println("JavaScript is sending a message \(message.body)")
    }
}

Notice that we check if the message name is «callbackHandler». Remember back to that line in the JavaScript which read «webkit.messageHandlers.callbackHandler.postMessage..». Here in the native method which receives the script message we need to verify that the message is what we expect it to be. If the message is what we expect we print the body of the message to the console.

Next up, we need to tell the web view to start listening for events from JavaScript. This is done by adding a script handler to the contentController. So, just below the line where we call «addUserScript», we now add:

contentController.addScriptMessageHandler(
    self,
    name: "callbackHandler"
)

The first parameter «self» means that the script message delegate is the ViewController. If you wanted to handle script messages in another class you could pass that class here. The name is the name which will be used in the JavaScript to call the native «userContentController» delegate method.

Try to run it. The header should now be read and after five seconds you should get a message in the Xcode console. Success!

All the code

Web-page

index.html

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            body {
                padding-top: 40px; 
            }
        </style>
        <title>WKWebView Demo</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <h1>WKWebView Test</h1>
        <script type="text/javascript" src="main.js"></script>
    </body>
</html>

main.js (JavaScript)

function callNativeApp () {
    try {
        webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
    } catch(err) {
        console.log('The native context does not exist yet');
    }
}

setTimeout(function () {
    callNativeApp();
}, 5000);

function redHeader() {
    document.querySelector('h1').style.color = "red";
}

ViewController.swift

import UIKit
import WebKit

class ViewController: UIViewController, WKScriptMessageHandler {
    
    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?
                            
    override func loadView() {
        super.loadView()
        
        var contentController = WKUserContentController();
        var userScript = WKUserScript(
            source: "redHeader()",
            injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
            forMainFrameOnly: true
        )
        contentController.addUserScript(userScript)
        contentController.addScriptMessageHandler(
            self,
            name: "callbackHandler"
        )
        
        var config = WKWebViewConfiguration()
        config.userContentController = contentController
        
        self.webView = WKWebView(
            frame: self.containerView.bounds,
            configuration: config
        )
        self.view = self.webView!
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var url = NSURL(string:"http://localhost/~jornki/tests/WKDemo/")
        var req = NSURLRequest(URL:url)
        self.webView!.loadRequest(req)
    }
    
    func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!) {
        if(message.name == "callbackHandler") {
            println("JavaScript is sending a message \(message.body)")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Getting started with WKWebView using Swift in iOS 8

In iOS 8 and Mac OS X Yosemite Apple introduces the new WKWebView and the Swift language among a slew of other amazing stuff. In this article we'll take a quick look at how you can get started writing Swift by implementing a basic browser using the WKWebView class.

For more information about Swift and WKWebView, please visit http://developer.apple.com

Disclaimer: Swift is a brand new language and also new to me, so I'm not stating that the code in this article in any represents the "correct" way of doing things. If you think something is wrong or should have been done differently please do add a comment.

Setting it up

Open xCode 6 and create a Single Page View Application (iOS) project and select a Swift as the project language. This will create a «Main.storyboard» file and a «ViewController.swift» file which are the two files we are concerned with in this article.

Importing WebKit

Open «ViewController.swift» and add an import statement for WebKit using import WebKit, put this line just below the existing UIKit import statement. We need to do this since the WKWebView class is now a part of WebKit itself.

Creating an outlet

Next create an outlet to reference the container view in Interface Builder. Enter the following at the top of the «ViewController» class.

@IBOutlet var containerView : UIView = nil

This piece of code allows the «ViewController» to get a reference to our WKWebView. To finish this connection select the «Main.storyboard» in the assistant editor, so you can see both the storyboard and the «ViewController». To tell the view in interface builder to reference this outlet you can make a connection by dragging from the outlet to the view and letting go.

Creating a variable for the webView

Back in «ViewController.swift», below the containerView outlet make a variable

var webView: WKWebView?

The question mark means that the webView property / variable is a wrapped variable, which again means that this variable might be empty and that it does not have the properties of WKWebView, because it's of type WKWebView? - riiight.

Think about it this way; As the word "wrapped" implies, the webView variable is wrapped inside a "container" which might be empty, but it might also contain something, in our case this is hopefully a WKWebView, but for now it's nothing in it.

We'll get back to what this means in practice when we reference this variable later.

Instantiating the webView

Back in «ViewController.swift» lets create an override for ´loadView´ and write the initialization for the WebView there. This function will look like this:

override func loadView() {
    super.loadView()
    self.webView = WKWebView()
    self.view = self.webView
}

After calling super (which you should always do when overriding methods) we instantiate the webView itself

self.webView = WKWebView()

and then we tell the current view of the viewController (self) that the webView is the view we need to show

self.view = self.webView.

You might be thinking that we could have just instantiated the WKWebView when defining the variable, and we could have, for this simple example. However later on when you actually need to pass parameters to the WKWebView() constructor, this approach will make more sense.

Loading and showing a web-page

Moving on.. lets load a webpage! In the viewDidLoad function, which should be defined in ViewController.swift already, type the following:

override func viewDidLoad() {
    super.viewDidLoad()
    var url = NSURL(string:"http://www.kinderas.com/")
    var req = NSURLRequest(URL:url)
    self.webView!.loadRequest(req)
}

Now run your application! It should load this web-page in the simulator, how's that for meta!

Let's take a look at this code. The first line defines an NSURL using the NSURL(string:) constructor. The next line constructs a NSURLRequest using the url constructed on the previous line. Then we tell the webView to load the request. Notice how self.webView is referenced using the ! at the end. This goes back to the part where we created the webView variable using the ?. Since webView is wrapped it actually refers to the "container" and not the WKWebView instance, which is what we want. Therefore we need to unwrap it and we do this using the !.

Summary

In this article we have briefly touched on using Swift and the brand spanking new WKWebView which is available in iOS 8 and Mac OS X Yosemite. We have seen how a WKWebView can be initialized and rendered to the screen and we have seen how to use Swift when interacting with CocoaTouch.

All the code

The whole ViewController.swift file now looks like this:

import UIKit
import WebKit

class ViewController: UIViewController {
    
    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?
                            
    override func loadView() {
        super.loadView()
        
        self.webView = WKWebView()
        self.view = self.webView!
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        var url = NSURL(string:"http://www.kinderas.com/")
        var req = NSURLRequest(URL:url)
        self.webView!.loadRequest(req)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

A simple drawing app using JavaScript

The HTML Canvas element was introduced by Apple in 2004. It was originally created to power the Dashboard concept introduced in OS X 10.4. The Canvas element was a part of Apple WebKit from 2004, in 2005 it became a part of Mozilla browsers and then Opera. Today, all browsers worth using sports support for the Canvas element. In this article I'll investigate demo involving a simple line drawing on a Canvas element.

To be a proper red line drawing application today there are several considerations to be taken into account.

  • You must support both touch devices and dusty old mouse enabled devices

  • You must take Hi-res or retina devices into consideration. You wouldn't want blurry red lines now would you.

  • The thing needs to be performant and cool..and red

Take a look at the full CoffeeScript code for the demo. It has a bunch of comments.

Supporting touch and mouse events

if 'ontouchstart' of window
# .. then switch to touch mode
@mode = 'touch'

From line 8 in the code. Here we check if the event «ontouchstart» exists in the window object. If it does we know that this device supports touch events. We then keep this result in the «mode» property for use later on. Easy peasy. Let's add som listeners.

if @mode is 'touch'
canvas.addEventListener 'touchstart', @, false
canvas.addEventListener 'touchmove', @, false
canvas.addEventListener 'touchcancel', @, false
else
canvas.addEventListener 'mousedown', @, false
canvas.addEventListener 'mouseup', @, false

We use the «mode» property and add touch and mouse listeners. Note that we do not add any listeners for when the mouse is moving, this we do in the mouse up and down events. See the section at the end of the article as an explanation as to why.

So, what the hell does it mean to add a listener to "@"? In CoffeeScrip the "@" is the same as "this" in JavaScript. By adding event listeners to "this" we can implement the half-magical «handleEvent» method. This method will not only handle all events on "this", but it will also maintain scope, removing the need for «Function.bind». If you didn't know that, you mind has just been blown - right?! Moving on.

Supporting retina quality graphics

This is a tiny bit trickier, but not much. What we need is to know the scale factor of the display of the device. We can then use this number to calculate the size of the canvas itself and how lines are drawn.

Let's start with finding the scale factor.

@scaleFactor = window.devicePixelRatio || 1;

If there is a property on window called «devicePixelRatio» we use that value, if not we default to 1, which basically means that it's a "normal" display or a piece of shit old browser. The «devicePixelRatio» will output a multiplier, like 2 for the iPad Mini Retina. This number gives us the value on which to multiply.

Scaling the canvas element correctly

Calculating the size of the actual canvas element looks something like this (if you want the canvas to span the entire browser window).

canvas.width = window.innerWidth * @scaleFactor
canvas.height = window.innerHeight * @scaleFactor

On a "normal" display the width of the canvas would be equal to the inner width of the window. On an iPad Mini Retina it would be «innerWidth x 2», because the «scaleFactor» of the iPad Mini Retina is 2.

It's important to note that the canvas element is now twice or more the size of what you intend to display it at. You fix that by setting the style width and height to the intended display size, which in the case of an iPad Mini Retina will be half the size of the canvas backing store (the actual drawing size).

Scaling the drawing context

@ctx = canvas.getContext '2d'
@ctx.strokeStyle = 'rgba(255,0,0,1)'
@ctx.lineWidth = 5 * @scaleFactor

The «ctx» property holds the 2d drawing context of the canvas. On the second line we tell the context that any lines drawn, should be red - of course. On the third line the thickness of the line is set and like we did with the canvas backing store we multiply with the scale factor. Remember that a canvas on the iPad Mini Retina is twice the size of what it's displayed as (yep, yep). If we didn't multiply the line thickness if would actually display at 2.5..and that would be stupid because we want it to look the same everywhere, except it will look sharper on retina displays.

@ctx.moveTo e.touches[0].pageX * @scaleFactor, e.touches[0].pageY * @scaleFactor
#...
@ctx.lineTo e.touches[0].pageX * @scaleFactor, e.touches[0].pageY * @scaleFactor

The same multiplication also needs to happen every time we either move the drawing pointer or draw a line. If we didn't do this the line would be drawn with an offset of the finger or the cursor - again, we don't want that. And that's it, ha!

Other stuff

For mouse mode, it's also a good idea to remove the «mosemove» listener when the move isn't pressed. This way you won't get a bunch of events firing all over the place when you really don't need them.

That's all folks.