<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Calvin Metcalf on Medium]]></title>
        <description><![CDATA[Stories by Calvin Metcalf on Medium]]></description>
        <link>https://medium.com/@CWMma?source=rss-4c0611cce96f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2Aw83xHY3nzwbqv-IO4qAQ.jpeg</url>
            <title>Stories by Calvin Metcalf on Medium</title>
            <link>https://medium.com/@CWMma?source=rss-4c0611cce96f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:09:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@CWMma/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to upload files with Fetch to Node.js (without using FormData)]]></title>
            <link>https://medium.com/@CWMma/how-to-upload-files-with-fetch-to-node-js-without-using-formdata-687e35ba1ab6?source=rss-4c0611cce96f------2</link>
            <guid isPermaLink="false">https://medium.com/p/687e35ba1ab6</guid>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Calvin Metcalf]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 13:22:39 GMT</pubDate>
            <atom:updated>2019-03-04T14:06:26.024Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m writing this because I was looking to show one of my colleagues how to do this and I couldn’t find any good references.</p><p>If you look up how to upload a file with fetch, you will find a lot <a href="http://shiya.io/using-fetch-to-upload-a-file/">of</a> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Uploading_a_file">examples</a> that use the FormData object. <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData">FormData</a> is honestly not a bad option if you need to upload multiple objects but for a single one it can be a pain, mainly how complex it can be to parse on the server side.</p><h3>Uploading from the browser</h3><p>Instead for a single file you can use a <a href="https://developer.mozilla.org/en-US/docs/Web/API/File">file object</a>. The gist of this is that any time you have a fine input (i.e. &lt;input id=&#39;my-file&#39; type=&#39;file/&gt;) If you access the element in the DOM (e.g. with document.getElementById(&#39;my-file&#39;)) then that element will have a ‘files’ attribute which is a list of file objects (I say list and not array because it’s special <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileList">FileList</a> object). In the (common) case that your input only allows a single file to be uploaded then you can get it from the input element with document.getElementById(&#39;my-file&#39;).files[0]. This can be passed directly to fetch with</p><pre>const file = document.getElementById(&#39;my-file&#39;).files[0];<br>fetch(&#39;htts://yoururls.fake/mypath&#39;, {<br>  body: file,<br>  method: &#39;POST&#39;,// or &#39;PUT&#39;,<br>  headers: {<br>    &#39;content-type&#39;: file.type // likely there for common types<br>  }<br>});</pre><h3>Reading it in Node.js</h3><p>Reading the file you in node.js is shockingly easy (to me at least, I’m embarrassed to say it took me far longer then I care to admit to realize I could do this). Using <a href="https://www.npmjs.com/package/pump">pump</a>:</p><pre>app.post(&#39;/mypath&#39;, (req, res) =&gt; {<br>  pump(req, streamThatDealsWithFile, err =&gt; {<br>    if (err) {<br>      // handle err<br>    }<br>    // handle success<br>  });<br>});</pre><p>The <a href="https://nodejs.org/api/http.html#http_class_http_incomingmessage">req</a> object in a web request is a <a href="https://nodejs.org/api/stream.html#stream_readable_streams">readable stream</a> and you don’t actually need anything special to access it.</p><p>You could also access the data the following way</p><pre>app.post(&#39;/mypath&#39;, (req, res) =&gt; {<br>  let dataParts = [Buffer.alloc(0)]; <br>  // this is so Buffer.concat doesn&#39;t error if nothing comes;<br>  req.on(&#39;data&#39;, d=&gt;dataParts.push(d));<br>  req.on(&#39;error&#39;, res.sendStatus(500);<br>  req.on(&#39;close&#39;, ()=&gt; {<br>    const fullData = Buffer.concat(dataParts);<br>    // you can do stuff with the data now <br>  });<br>});</pre><p>Though in more complicated cases you probably don’t want to do this and instead stream the incoming data.</p><p>Lastly if you are using promises/async functions in your app (perhaps with co-router) then you’d want to rewrite the above as</p><pre><br>const drainStream = stream =&gt;<br>  new Promise((resolve, reject) =&gt;<br>    let dataParts = [Buffer.alloc(0)]; <br>    // this is so Buffer.concat doesn’t error if nothing comes;<br>    stream.on(‘data’, d=&gt;dataParts.push(d));<br>    stream.on(‘error’, reject);<br>    stream.on(‘close’, ()=&gt; {<br>      resolve(Buffer.concat(dataParts));<br>    });<br>  });<br>app.post(‘/mypath’, async (req, res) =&gt; {<br> const data = await drainStream(req);<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=687e35ba1ab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to convert your library to ES6]]></title>
            <link>https://medium.com/@CWMma/how-to-convert-your-library-to-es6-3084810c2060?source=rss-4c0611cce96f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3084810c2060</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Calvin Metcalf]]></dc:creator>
            <pubDate>Thu, 20 Jul 2017 14:35:39 GMT</pubDate>
            <atom:updated>2017-07-20T14:35:39.067Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Some quick do’s and don’ts (mainly don’ts) about converting your library to ES6 modules.</p><p>Quick note: This is about how to convert your library to ES6 modules, it is not about how to right a library from scratch in ES6, the main focus is on how to avoid accidentally introduce backwards compatibility.</p><h3>Don’t Import *</h3><p>When converting a module you should avoid doing any import * as foo from ./bar.js,this is the most important thing. When you import a module like this you get none of the benifits of ES6 modules while getting some significant drawbacks. <br>Quick whats the difference between way1 and way2 in b.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/242252462fbad3b0fbaa459414cd4599/href">https://medium.com/media/242252462fbad3b0fbaa459414cd4599/href</a></iframe><p>The answer is that way2 is a normal JS object with 2 methods, while way1 is an exotic module object that is not extendable and is frozen.</p><h3>What should you do instead</h3><p>If its part of the public facing API (aka you are taking what you import and assigning it to something) make an object and export it instead.<br>If you’re using it internally (like it’s a utils module or something), just import the keys you need, even if its a lot of keys, if its not all of them you should probably use named imports.</p><h3>Socratic Documentation</h3><h4>But doesn’t using export default on an object defeat the purpose of ES6 modules and prevent dead code elimination?</h4><p>Yes but so does import * as foo</p><h4>Is this actually a problem?</h4><p><a href="https://github.com/calvinmetcalf/leaflet-ajax/issues/49#issuecomment-316472463">yes</a> <a href="https://github.com/Leaflet/Leaflet/issues/5589">it</a> <a href="https://github.com/tomchadwin/qgis2web/issues/522">is</a></p><h4>But my library doesn’t rely on people extending any of the objects with new methods</h4><p>You’re probably okay then just be aware it’s a difference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgtM0_rycxN4AvWnE5Suew.jpeg" /><figcaption>here’s a picture of my dog so that medium is will show a preview image.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3084810c2060" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Whats new for streams in Node 8]]></title>
            <link>https://medium.com/@CWMma/whats-new-for-streams-in-node-8-736d431083df?source=rss-4c0611cce96f------2</link>
            <guid isPermaLink="false">https://medium.com/p/736d431083df</guid>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Calvin Metcalf]]></dc:creator>
            <pubDate>Wed, 31 May 2017 14:01:19 GMT</pubDate>
            <atom:updated>2017-06-01T12:15:01.483Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>There are a couple new things landing in streams in Node 8</p><h3>Destroy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*0VmHwQHC3Cp5azcYxDOAUw.gif" /><figcaption>cleaning up resources</figcaption></figure><p>First up we have a new standardized method to destroy streams, all streams will now have a standardized .destroy() method. This method takes a single optional argument which is an error object. Calling this method destroys the stream and cleans up any underlying resources, if you pass in an error then that is the equivalent of saying ‘destroy this stream because of this error’ and error events are passed along.</p><p>In keeping with other stream methods you can also define a _destroy method on the prototype or pass a function in the in the constructor options under the name ‘destroy’ if you need to define a custom method of destroying something</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*EjEKas_Sz2LDUrgK1ggNLg.gif" /><figcaption>custom destroy method</figcaption></figure><p>This function will have 2 things passed to it, an error and a callback. The error may be null. The idea is that you clean up any resources being used by your stream and then call the callback with the passed in error (if it exists) or if you encountered an error trying to destroy stuff, then call it with that one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*hXHtm2QqX6cL16F3-v1kfA.gif" /><figcaption>default destroy methods</figcaption></figure><p>The idea is that you usually want to pass the error through to the callback but there may be certain types of errors or certain situations where you need to swallow the error.</p><p>These are the default ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8043cc3d47d359c40aed8b14e04382ea/href">https://medium.com/media/8043cc3d47d359c40aed8b14e04382ea/href</a></iframe><p>Since they actually do stuff you need to remember to do the closing yourself if implementing it yourself not a big issue for most of them, but if I was implementing a transform stream I’d probably use super:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52534ff636c0510e299eddd7737505b2/href">https://medium.com/media/52534ff636c0510e299eddd7737505b2/href</a></iframe><p>though fyi this won’t work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8e3df87274f8c18de95fe5cae27d19/href">https://medium.com/media/be8e3df87274f8c18de95fe5cae27d19/href</a></iframe><p>I’ll leave it as an exercise for the ready to figure out why, but do this instead</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4caacead52fe97faf864a6a5716260a2/href">https://medium.com/media/4caacead52fe97faf864a6a5716260a2/href</a></iframe><h3>Final</h3><p>Before getting into the new feature lets discuss the .flush method on transform streams and some of it’s shortcomings. First it’s only on transform streams, so it doesn’t help you on readable, writable, or regular duplex streams. Second it’s tied to the readable half of the transform stream, so if you do async stuff inside of it it only prevents the readable half of the transform stream from closing, the writable half will have closed on the next tick after flush was called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*o6dikFgJfzuuTSuniVpN6w.gif" /></figure><p>Final on the other hand is defined on writable, so it’s also available on duplex and transform streams, and the writable stream won’t close until you call the callback in final (in a transform stream this also causes the readable side to not close because the readable side always waits for the writable side to end) how to use it is pretty much the same as flush, except also on writable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84f6cb37cc992a8f9e45f1e6614ec5e3/href">https://medium.com/media/84f6cb37cc992a8f9e45f1e6614ec5e3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*rNBnP82U9_SzJx5gTCMobw.gif" /></figure><p>Final is really helpful when you have a writable stream that needs to clean up or finish up as it ends. For instance I have a module that streams records into a remote service but batches them up to avoid excessive API calls, final is now a non hacky way to do this as previously I could monkey patch the end method (which I did) or put a transform stream in front of it (which I didn’t do because I wanted the API to be a regular writable stream).</p><p>More generally I’d also recommend that you should probably use final instead of flush anywhere you were previously using flush in transform streams. There may be a few specific places where you need flush but if your doing something that esoteric you hopefully know what your doing. You can likely look forward to a debate soon about whether to soft depreciate flush going forward or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=736d431083df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[doing something simple]]></title>
            <link>https://medium.com/@CWMma/doing-something-simple-5cdc65c416ba?source=rss-4c0611cce96f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cdc65c416ba</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[browserify]]></category>
            <dc:creator><![CDATA[Calvin Metcalf]]></dc:creator>
            <pubDate>Thu, 01 Sep 2016 14:01:04 GMT</pubDate>
            <atom:updated>2016-09-06T14:44:44.102Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>browser: cache setTimeout and clearTimeout to isolate from global</blockquote><p>Several months ago (June 9th of this year to be exact) a pull request with the above title was opened on <a href="https://github.com/defunctzombie/node-process">node-process,</a> a library that I help maintain which provides a shim for the process object for use in browserify, webpack and other non-node environments. At the end of the day the majority of what it does is simply provide a shim for process.nextTick and what this pull request was doing was making it so that if somebody mucked around with setTimeout (i.e. for testing), the process.nextTick shim would still work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*83tPv-owdhMibqcRE2yJhg.gif" /><figcaption>actual picture of the test suite in action</figcaption></figure><p>I thought nothing of it as it seemed like the right approach to take; we use setTimeout to generate the initial async call for process.nextTick (we don’t use it for recursive calls) and we also use clearTimeout in the code so we’d need to save a reference to that as well. The <a href="https://github.com/defunctzombie/node-process/pull/58/files">pull was very simple</a> and included a test so it seemed like a win. This turned out to not be the case; within the day of merging it we had 2 issues open.</p><h3>I intentionally shim setTimeout so I can test streams synchronously</h3><p>It would seem somebody was making setTimeout be synchronous so that node streams would be synchronous to make writing browser test for code that uses streams be easier to manage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*KfgCYKpusPUCDM7SVeMnIQ.png" /><figcaption>relevant XKCD</figcaption></figure><p>I couldn’t fix this without reverting the previous change, but in the end we decided not to fix this for a couple reasons.</p><ol><li>The fact we use setTimeout is explicitly not part of our public api, we haven’t always used setTimeout and we might not in the future.</li><li>Given the choice of the code working when people want to stub something unrelated or synchronize async code for convenience, I think not breaking when things are stubbed is a better choice.</li><li>Switching my hat to member of the node streams working group, this does not do what you think it does; streams code often acts in very different ways depending on whether stuff was synchronous or not, so this isn’t actually testing what you think it is.</li></ol><p>This ended up being the easy one.</p><h3>ReferenceError: clearTimeout is not defined</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LEMIN-QRqWdUTgP1JOACMw.gif" /><figcaption>Metaphorically what you’re doing if you wrap unknown code in use strict</figcaption></figure><p>Suddenly we were getting reports of errors thrown because setTimeout and clearTimeout, this is because setTimeout was being referenced outside of functions so there would be a reference to it even if process.nextTick wasn’t called, and some blunders wrap their code globally in ‘use strict’ meaning we get the error (yeah don’t do this with code that you didn’t write). The usual fix for this is to refer to setTimeout (or whatever) as methods of the global object (window, self, global, etc) but if we couldn’t count on setTimeout being there we wouldn’t be able to count on knowing what the global was called or even if ‘this’ would be defined (because it’s executed in a non method function in strict mode) so <a href="https://github.com/defunctzombie/node-process/commit/782189e8be2460ce6765efcde474fcaef49ec9e6">we make the code somewhat more complex</a>.</p><h3>TypeError: Invalid Calling Object</h3><p>You can’t call setTimeout or clearTimeout as a method on any old object (unless you are in node) only as a method of the global object or null/undefined (<a href="https://html.spec.whatwg.org/multipage/webappapis.html#dom-settimeout">the spec</a> seams to touch on this obliquely). Now how does this apply here as we are simply calling setTimeout as a normal function, we just happen to refer to it from a different variable, that should matter, right?</p><p>There is one function in JavaScript (that I know of, off the top of my head) that does behave differently if it is called with a different name: eval. Guess what the cause of our problem is? eval. Are these related? probably not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*FFiMMfrhaXNBB0TjH4B2vw.gif" /><figcaption>Shocked! that eval + IE explodes</figcaption></figure><p>It would seem that <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8282928/">in IE (and Edge)</a> if your code is executed via eval and setTimeout is renamed then a bug in IE (and Edge) will incorrectly get the wrong context for the the function call. The reason they are even using eval is because webpack uses it for evaluation code in some of their 6 dev modes in order to make source maps better. The <a href="https://github.com/defunctzombie/node-process/commit/0d0b1e5f70c476a6cbfcf5398d1d441665b2ab46">fix it to just use .call</a>. This will fix it right?</p><h3>Nope</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*vjkkIe19GBx7qJKrZVVksQ.gif" /><figcaption>How IE9 is acting</figcaption></figure><p>Short term solution is to <a href="https://github.com/defunctzombie/node-process/commit/ce3bd6f0f8e6e6d8571b21d83036438241b0af4f?w=0">avoid using the cached timeout unless somebody has actually changed the global one</a> thus sidestepping the problem the 99% of time people are running code with eval in IE. Except the error shows even when not using eval but only in IE9, it turns out that in IE9 there is a bug where clearTimeout (but not setTimeout) may not be called with null as the context. Why? who knows probably Steve Balmer being spiteful. The <a href="https://github.com/defunctzombie/node-process/commit/b1fc89b0c4706aa7693af3adbd4513e749b736ba">fix for this</a> adds some further complications (though it is intentionally broad to catch further corner cases that could pop up) but does feature some my favorite comments I’ve had to write.</p><h3>Further Down the Rabbit Hole</h3><p>Do you ever run code which defines globals like setTimeout latter in the execution of the script after your dependencies have run? I don’t because that seems like a recipe for disaster, but somebody does because their code isn’t working. A fix is <a href="https://github.com/defunctzombie/node-process/commit/f238268e778d8f45fe096d16f32547976b676c3c?w=0">fairly straight forward</a> and most of the effort on my part was in writing tests.</p><p>This brings the <a href="https://github.com/defunctzombie/node-process/compare/e481e478c838f7f09a68f28facdbf6345b4dd99d...master">total changes needed to do something simple such as cache setTimeout</a> up to something rivaling the rest of the process.nextTick shim.</p><h3>Denouement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgwQUam0FpqjadIkJl2FPA.png" /><figcaption>environments wouldn’t actually fit in there</figcaption></figure><p>I mean first off the most obvious thing I’ve learned is that this library is uses way more widely then just browserify, one somewhat assumes that setTimeout is going to be shimmed before node process is but there will always be stranger environments to execute your code. But now it works god damn it and you can shim setTimeout even if you are in an environment that doesn’t have it so you defined it latter and your whole script was evaluated via eval in IE9.</p><p>In all honestly these aren’t even the <a href="http://calvinmetcalf.com/post/128703345468/mistaken-assumptions-in-javascript">weirdest bugs we’ve had</a> on this project.</p><p>Updated 12:30 EDT 9/1/2016:</p><ul><li>Changed link to correct setTimeout spec thanks <a href="https://twitter.com/domenic">Domenic Denicola</a>.</li><li>Added link to Edge bug thanks to <a href="https://twitter.com/nolanlawson">Nolan Lawson</a>.</li></ul><p>Updated 10:42 EDT 9/6/2016</p><ul><li>spelling fixes thanks to <a href="https://twitter.com/ISmyrnow">Ishmael Smyrnow</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cdc65c416ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security in Offline First Apps]]></title>
            <link>https://medium.com/offline-camp/offline-first-security-59bf4800e82a?source=rss-4c0611cce96f------2</link>
            <guid isPermaLink="false">https://medium.com/p/59bf4800e82a</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Calvin Metcalf]]></dc:creator>
            <pubDate>Fri, 08 Jul 2016 14:06:01 GMT</pubDate>
            <atom:updated>2019-06-12T14:12:25.699Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="http://offlinefirst.org/camp">Offline Camp</a> I participated in a session on security of <a href="http://offlinefirst.org/">Offline First</a> web apps. We were able to pick out a couple different areas where security would be an issue for Offline First apps.</p><h3>Data Validation</h3><p>Imagine a regular non Offline First app: a user enters data, which is sent to a server, which validates it before putting it in the database. The setup would look something like this:</p><pre>user enters data → send to server → server validates → server adds to database</pre><p>A naïve Offline First app built with PouchDB or similar might have a setup where a user enters data, the app validates the data and then adds it to the local database which is synced to the remote database, e.g.:</p><pre>user enters data → app validates → app adds to local database → sync local database to remote database</pre><p>The reason this is naïve is because you <strong>cannot trust the client</strong>. Anybody can add things to that local database and if they do it will be synced to the remote database where it could wreak any amount of havoc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*cvm3lt9uaip0xjf7JG1k8Q.gif" /></figure><p>The solution is to treat data on the client as untrusted and to add a validation step to the replication to ignore or reject any document that doesn’t conform to the schema or does something it’s not supposed to.</p><p>Adding validation to the sync process adds an additional complication: the client side state can diverge from the server held state; this could theoretically be used for nefarious means to screw up a local install in a way that won’t sync in order to trick somebody to do something.</p><h3>Shared computers</h3><p>Sometimes you need to log into an app from your parents’ house, on a sketchy computer at the library, or at work, and you neither want nor need the data saved locally. We’re not going to cover the likely usability issue of attempting to sync the whole database when a user quickly needs a specific piece of information; instead we’ll focus on breadcrumbs left behind.</p><p>No matter how you handle logging out (see next), if you store stuff in IndexedDB you have to write your app like the databases will still be there when the user leaves and that is going to leak anywhere from just the username to all of the data depending on the setup.</p><p>Just have the user use incognito mode might be your first reaction. But there are 2 problems with that: First, most users won’t ever notice how your bank’s website explicitly makes you choose public or private with no default. That’s because most users will probably 90% of the time want it to be saved, but if you just had a checkbox or similar most users would check the box on autopilot the other 10% of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*WgQJmsy46prIP9ZrMErZJQ.jpeg" /><figcaption>Jorts for reference</figcaption></figure><p>The other issue with incognito mode is Safari. Instead of having all storage APIs (e.g. local storage, IndexedDB) be empty when opening incognito mode and cleared when closing incognito mode, Safari takes the <a href="http://jort.technology/">jort sort approach</a> and removes all storage APIs when in incognito mode, breaking your app instead of making it ephemeral.</p><p>It is probably a good idea to have an online first version of your app which doesn’t save any data locally especially if your app has a lot of data or sensitive data. You could do this in P<a href="https://pouchdb.com/">ouchDB</a> easily by just swapping in a memory back end or directly using the remote DB with the HTTP back end.</p><p>Put another way, the workflow in Offline First apps where you haven’t made an account is usually to make it local only, and then if they want to make an account, sync it to the remote server. I’d suggest that when you sign into an account on a computer where you haven’t done anything with the app yet it by default be remote only until the user explicitly syncs it locally.</p><h3>Logging Out</h3><p>Whenever I’m using our laptop and my wife asks for it I always hit logout on the laptop before giving it to her. This isn’t because I’m afraid of her seeing anything, but to prevent another incident like when Taylor Swift showed up in my Rdio favorites.</p><p>For the rest of us who either have more paranoid significant others, a computer that only has one account, or actual things they need to hide, your app needs some way to log out and allow somebody else to log in, preferably being able to do this while offline (if both users have already used the app). But first a digression…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*JiakDMNQvXHvP_KVxdFHpQ.gif" /><figcaption>platypuses (platypi?) are weird</figcaption></figure><p>There is no such thing as perfect or ‘the best’ when it comes to security. There are always trade-offs. For instance, using one time pads to encrypt messages has been mathematically proven to be unbreakable assuming the pad is kept secure and only used once. The drawbacks, such as the pad having to be as long or longer then the message and the requirements that the pad be delivered via secure channels mean that in practice if you have those secure channels, you can just use those for your message and otherwise use a crypt scheme, which instead of being unbreakable ever, is <em>merely </em>unbreakable<em> </em>before the heat death of the universe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*xzvtQE1NIbQEhsDs68DTFQ.jpeg" /><figcaption>The author with a Koala … for research purposes</figcaption></figure><p>A more concrete example would be cumbersome password requirements (e.g. password must be changed every 2 weeks or password must contain an uppercase and lowercase letter, a symbol, a real number, a <a href="https://en.wikipedia.org/wiki/Runic_(Unicode_block)">Unicode rune</a> such as ᛃ or ᚸ, and a picture of a marsupial or monotreme); while these policies <a href="https://xkcd.com/936/">sometimes</a> lead to more complex passwords, they also lead to passwords which are harder to remember, making people more likely to <a href="http://boingboing.net/2016/06/28/healthcare-workers-prioritize.html">write them down on post-it notes stuck to their monitor</a>. To put it another way, it doesn’t matter how strong your locks are if somebody props the door open because constantly unlocking it was too time consuming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*aZ2O8b-Jf3cZt5YEgUsHhw.jpeg" /><figcaption>Shiba Inu for reference</figcaption></figure><p>Why am I bringing this up? To explain why I’m about to disappoint anyone who was looking to be told a simple rule they could apply blindly without thinking. Instead we’re going to come up with a set of different strategies to fit apps ranging from ‘Sync Pictures of Shiba Inus’ to ‘<a href="https://en.wikipedia.org/wiki/LGBT_rights_in_Saudi_Arabia#Criminal_Procedure">Grindr</a> <a href="http://www.independent.co.uk/news/world/africa/grindr-urges-lgbt-community-to-hide-their-identities-as-egypt-persecutes-nations-gay-community-9757652.html">for</a> <a href="http://www.huffingtonpost.co.uk/2014/04/02/atheists-classified-terrorists-new-saudi-arabian-laws_n_5075129.html?utm_hp_ref=uk-religion">Saudi Arabian Atheists</a>’. Some things to bear in mind when we discuss them:</p><p>Having an app without security features is only a problem if people use it like it <em>does</em> have security features. Do you think all men on Ashley Madison would have used their real names if they had known the level of security on that site? In other words, if your app stores stuff in plain text in local storage, tell the user this, it may be ok (the user likely stores documents in plane text on their hard drive anyway), but if it’s not, they now know they need to rely on the operating system’s security measures, not the app’s.</p><p>People are fundamentally lazy. This is not a judgment against people, it’s just that there isn’t enough time to do everything you want to do, so people either cut corners or get nothing done. Ergo people tend to value their time rather highly so time-consuming security measures should only be required if they are actually necessary.</p><p>Your app is not special, so don’t expect people to treat it like it is. Your app is not Facebook, or Instagram, or Snapchat, or whatever tweens are using these days, so don’t expect the stunning popularity of your app to cause people to jump through hoops. Your app is probably not even Lastpass or Keybase so don’t expect people to give up features or convenience for security features they don’t really need.</p><h4>Just delete the database</h4><p>I’d like to contrast this from actually logging out of the app. Logging out of an app implies you should be able to log back into it. Your app isn’t much of an Offline First app if logging out of it when offline prevents you from using it again until you get the internet again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*VH_ZEO4ANcnH1DnQYYT1YQ.gif" /><figcaption>destroy all evidence</figcaption></figure><p>While this is better then nothing (i.e. having to go into the bowels of your browser’s storage preferences to delete the data), it’s not optimal. Besides the aforementioned fact that it really wouldn’t be an Offline First app, there is the fact that this would make logging off asynchronous, i.e. you could click logout and then close your browser fast enough to prevent it from finishing. This is opposed to just removing a key from local storage which is synchronous and should have less of a problem with this.</p><h4>No password, Database name based on username</h4><p>In the least secure way to do it, you base the database name on the username (i.e. appname_username or something) and then save the username in local storage. To sign them out you’d just delete the username from local storage. If you do something like this, you probably want to have a list of users with data and allow people to switch between them, the idea being that if people are not comfortable with users doing that from the UI, then this app doesn’t have enough security for them.</p><p>With a setup like this you’d only need to require a password when you sync the data (to get a token or cookie for use with auth) and you’d want to delete the token or cookie when the person signs out.</p><h4>Encrypted local database, key not saved</h4><p>The idea here is that you use something like <a href="https://github.com/calvinmetcalf/crypto-pouch">crypto-pouch</a> to encrypt the database locally with a key derived from the user’s password, and you don’t save the key (and never ever save the user’s password). The advantage here is that the safety is pretty intuitive: Is the tab open and signed in? Then they have access (you’d also probably want to do an inactive timeout). The big downside here is that it requires the user to constantly reenter their password which means they are likely to either choose a weak password, save the password somewhere else, or stop using your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnDvqDl9p1KylzWT9lG4mA.jpeg" /><figcaption>There is a security metaphor in here somewhere</figcaption></figure><p>This method is a legitimate choice for certain types of apps that require high security like Lastpass and Keybase (Lastpass I use and can attest to this; for Keybase I’ve been told this as I’m still on the wait list like a pleb). Unless your app involves cryptographic or other sensitive data (e.g. the Saudi Grindr example) this is probably a bad idea for your app as it’s probably going to turn people off or have them use bad security measures that defeat the purpose.</p><h4>Encrypt local database, key is saved</h4><p>The idea here is that the user enters a password, it’s strengthened into a key used to decrypt the database, and that derived key is stored in local storage until the user logs off. With a properly strengthened password, this should be approximately as secure as a normal app (it does allow for offline password cracking attempts, though that is only a threat if a user picks a very easy password or the app author does not have a difficult enough work factor for strengthening the password, as finding good documentation on what appropriate work factors are is hard; this is something to bear in mind). Which means that intuitively this is more or less the same security level as standard ways of logging in: if you’re logged in, people can mess with your stuff; if you’re logged out, they can’t.</p><p>This is not supported by crypto-pouch yet, but I’m <a href="https://github.com/calvinmetcalf/crypto-pouch/pull/38">working on a pull</a>.</p><h4>End-to-end encryption</h4><p>For apps that require high security, not only can the data can be locally encrypted but also encrypted on the server leaving you, the app developer, with no way to decrypt the data. This has advantages for the user — they know you the developer can’t snoop on their sensitive business documents — and has advantages for you the developer — your liability is limited should you be hacked as all the hacker will get is the encrypted data, not plain text data (see the<a href="http://arstechnica.com/security/2015/06/hack-of-cloud-based-lastpass-exposes-encrypted-master-passwords/"> blase reaction</a> when Lastpass, a company that practices very good security, got hacked).</p><p>That being said, there are some pretty steep challenges, the biggest being that it is impossible to do proper end-to-end encryption and have normal password resets. This is a deal breaker in most circumstances and should be; for most apps I personally use, me forgetting the password is a far greater threat than my data being viewed by an employee of the developer or my data getting leaked. In many apps the threat is of impersonation, not leaking of data (e.g. Twitter and Facebook); the exception to this is apps primarily dedicated to storage (e.g. Lastpass or Dropbox), but even then the competing threats of forgetting your password and data being leaked need to be balanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRIXk71hVTK8lPhwMNrUtw.jpeg" /><figcaption>another shiba, primarily to break up the wall of text</figcaption></figure><p>The next challenge is double edged, it means that the app developer can’t read your data. But reading your data is one way developers improve apps, to see if people are using features or not and seeing if people are using the feature as intended. With big data you get things like the way google mines your Gmail account to remind you about upcoming flights, which on one hand is creepy but on the other is damn convenient. There is no right answer here, and this particular question isn’t restricted to end to end encryption. <a href="https://twitter.com/juliansimioni">Julian Simioni</a> from <a href="https://mapzen.com/">Mapzen</a> talked in a different session about the struggle they have in developing their geocoder and balancing not spying on their users with using machine learning to improve the geocoder. (The quick version of geocoders is just that 90% of addresses are easy but the last 10% are all weird things like addresses in <a href="http://stevemorse.org/census/changes/QueensFormat.htm">Queens</a> and <a href="https://en.wikipedia.org/wiki/Japanese_addressing_system">Japan</a>, the various points of interest that often have many different names, and the creative ways people misspell things).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m466ZWe13ae9dlOB7kvAaQ.jpeg" /><figcaption>Picture of my cats, no relevance, I just like the picture</figcaption></figure><p>The last issue to think about is supporting users from shared computers with online-first version of the app; if your app has a lot of data then decryption client side may be slow. Plus when on a hostile computer (aka one at the library which might have some malware) having a key of some sort in memory the entire time the app is open is much more vulnerable then a password which is only remembered locally briefly when getting a token.</p><p>Currently crypto-pouch doesn’t support end-to-end encryption as it saves the salt for deriving the encryption key locally and doesn’t support accessing the documents sometimes encrypted (for syncing) but sometimes decrypted (for using the app), but there is nothing preventing it from doing so in the future.</p><h4>Two-factor authentication</h4><p><a href="https://twofactorauth.org/">Two-factor authentication</a> can be used with Offline First apps, but not necessarily how you’d think. Two-factor auth can’t be used for offline apps when actually offline, but they can be used to authorize synchronization. The fact that two-factor auth can’t be used offline is a bit unintuitive to some people, but here goes…</p><p>A password can be used to prove that you are who you say you are; this is how a password is used when you log into Facebook and how an Offline First app uses your password when it syncs to the server. A password may also be used to derive the encryption key of a file. While both processes use key derivation algorithms on keys and do something with the result, only the local decryption version actually needs the result to proceed. When logging into Facebook, the process that uses the password in the end just returns true or false about whether it was valid. This is because the server side process is trusted so we can believe it if it says this user is okay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*DoWDSz6mZHL5wDbrNHhsVQ.jpeg" /><figcaption>I googled ‘nefarious’ and was not disappointed</figcaption></figure><p>There are a couple different methods of two-factor authentication, but the most common is the kind that gives you a short code that changes every minute or two. The way this works is that you have an algorithm that takes an initial seed and the time rounded to some unit and outputs a code. The client can send in the code it calculated and the server can check it against the one it calculated but some adversary can’t save it and resend it later when it tries to do something nefarious.</p><p>You can’t use two-factor authentication methods like this to decrypt a file because these methods are built around providing a way to show a server you are who you say you are, which doesn’t help you when you are trying to decrypt data which is stored somewhere an untrusted person might get it. What you can use it for is to authorize people who want to sync user data, which would prevent adversaries who steal (or guess) your password but don’t have access to the encrypted data from getting your data, and preventing those same people from modifying or deleting your data.</p><p>In theory somebody could develop (or has developed) a smart card which performs some decryption and encryption on the card and a spec which integrates it with a web app, but (as far as I know) that hasn’t happened (yet).</p><p>You could use some sort of second factor to help derive the local key from the password, but from the app’s perspective the resulting key isn’t all that different from a password, so you could do that without the app having to opt in with a password manager (have I mentioned I like Lastpass?).</p><h3>Wrapping up</h3><p>Writing secure apps is hard in general and even harder in the browser, as documented <a href="https://tonyarcieri.com/whats-wrong-with-webcrypto">by</a> <a href="https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/">others</a>. Additionally, the cryptographic options available for use in browsers is somewhat uneven; there is a <a href="https://www.w3.org/TR/WebCryptoAPI/">native API,</a> but its support is uneven. You have some older, more mature libraries that are super insecure due to not relying on some of the native crypto APIs that have good cross-browser support like the browser function to get random bytes via crypto.getRandomValues (see <a href="https://github.com/digitalbazaar/forge/blob/5f1e1b5a11335de774542bbc7a4447a7dc7556bc/js/prng.js">forge</a> and <a href="https://github.com/bitwiseshiftleft/sjcl/blob/f09fccc04f8bbac78f459819471fdbd90799e9b4/core/random.js">SJCL</a>). These libraries have a tendency to not incorporate<a href="https://github.com/feross/buffer"> widely used high performance buffer options</a> in favor of home grown implementation (see <a href="https://github.com/digitalbazaar/forge/blob/5f1e1b5a11335de774542bbc7a4447a7dc7556bc/js/util.js#L134">forge</a> and <a href="https://github.com/bitwiseshiftleft/sjcl/blob/f09fccc04f8bbac78f459819471fdbd90799e9b4/core/bitArray.js">S</a><a href="https://github.com/bitwiseshiftleft/sjcl/blob/f09fccc04f8bbac78f459819471fdbd90799e9b4/core/codecBytes.js">J</a><a href="https://github.com/bitwiseshiftleft/sjcl/blob/f09fccc04f8bbac78f459819471fdbd90799e9b4/core/codecBase64.js">C</a><a href="https://github.com/bitwiseshiftleft/sjcl/blob/f09fccc04f8bbac78f459819471fdbd90799e9b4/core/codecHex.js">L)</a>. The other options are <a href="https://github.com/calvinmetcalf/native-crypto">less well</a> <a href="https://www.npmjs.com/package/chloride">tested</a> <a href="https://github.com/crypto-browserify/crypto-browserify">libraries</a> with better APIs, but I’m not sure which I’d trust if I was a gay Saudi Arabian. Probably none. I’d just write a <a href="https://twitter.com/shibesbot/media">shiba inu picture app</a> with one and try to hack it until I was sure.</p><p><em>Editor’s Note: This article is part of series of unconference session recaps submitted by the awesome folks who participated in our first ever Offline Camp, a unique tech retreat that brings together the </em><a href="http://offlinefirst.org/"><em>Offline First</em></a><em> community. You can find more coverage of our initial discussions in our </em><a href="http://medium.com/offlinecamp"><em>Medium publication</em></a><em>. To continue the conversation, join us at our </em><a href="http://offlinefirst.org/camp"><em>next event</em></a><em> or </em><a href="https://offlinecamp.typeform.com/to/V8aSWJ"><em>sign up for updates</em></a><em> and cast your vote on where we should host future editions of Offline Camp.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59bf4800e82a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/offline-camp/offline-first-security-59bf4800e82a">Security in Offline First Apps</a> was originally published in <a href="https://medium.com/offline-camp">Offline Camp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>