<?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 Roman Pylypets on Medium]]></title>
        <description><![CDATA[Stories by Roman Pylypets on Medium]]></description>
        <link>https://medium.com/@romanpylypets?source=rss-f6c3e964442c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*D5kaN3_PdJS4RZp5FneJAQ.jpeg</url>
            <title>Stories by Roman Pylypets on Medium</title>
            <link>https://medium.com/@romanpylypets?source=rss-f6c3e964442c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 23:20:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romanpylypets/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[Tails and trampolines or what is recursion all about]]></title>
            <link>https://medium.com/@romanpylypets/tails-and-trampolines-or-what-is-recursion-all-about-f748b66130c1?source=rss-f6c3e964442c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f748b66130c1</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Roman Pylypets]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 15:42:18 GMT</pubDate>
            <atom:updated>2024-09-21T15:42:18.238Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a few topics we encounter throughout our lives as software developers that we don’t always fully understand. Long, aimless meetings might be one of them, and recursion could be another. While I haven’t yet mastered the art of meetings, recursion is something I’d like to discuss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kXAdb6aoN7dg9mgF" /><figcaption>Photo by <a href="https://unsplash.com/@hautier?utm_source=medium&amp;utm_medium=referral">Christophe Hautier</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is recursion?</h3><p>A function that invokes itself is called a recursive function. It continues to invoke itself multiple times until it reaches a safeguard — a condition inside the function that, instead of invoking itself, returns a value. This causes the entire stack of function calls to resolve, and we get our final result.</p><p>Let’s try using recursion for a simple task. Suppose we need to implement a function that returns the length of a given array. Without recursion, we could implement it like this:</p><pre>function length(arr) {<br>  let count = 0<br>  while (arr[count] !== undefined) {<br>    count++;<br>  }<br>  return count;<br>}</pre><p>It’s straightforward: we check each item and return the count when any item is undefined. For the simplicity, we assume that the array doesn’t include undefined values. Now, how would we implement the same logic using recursion? For example, we could do it like this:</p><pre>function length(arr) {<br>  if (arr[0] === undefined) {<br>    return 0<br>  }<br>  return 1 + length(arr.slice(1))<br>}</pre><p>As with any recursion, we always need a base condition to stop the otherwise endless calls. In this case, if the array is empty, we return 0. Then, we add 1 to the result of the next call to the same function, but this time with a slightly different argument — the array minus its first element. We can visualize this like this:</p><pre>length([1, 2, 3])<br>1 + length([2, 3])<br>1 + 1 + length([3])<br>1 + 1 + 1 + length([])<br>1 + 1 + 1 + 0</pre><h3>When do we use recursion?</h3><p>In this small example, recursion is optional and not a necessity. It doesn’t offer any performance improvements and may even be less efficient in terms of memory usage. However, there are cases where recursion is the better choice. These usually include:</p><ul><li>Traversing nested structures like trees or nested lists</li><li>Divide-and-conquer algorithms that break down a problem into smaller, identical subproblems, e.g., quicksort or binary search</li><li>Generating all possible permutations or combinations, such as finding all arrangements of characters in a string</li></ul><h3>What are the drawbacks of recursion?</h3><p>It’s not surprising that developers are often hesitant to use recursion, as it can be difficult to debug. A missing or incorrect stopping condition can lead to infinite loops, making bug tracking extremely frustrating.<br>However, the most important concern is inefficient memory usage. Recursion consumes memory with each call, as every recursive function invocation adds a new frame to the stack. If the recursion depth is too great, this can result in stack overflow errors.</p><h3>How do we improve the memory usage for recursive functions?</h3><p>One way to make recursive functions more memory-efficient is by using a technique known as tail call optimization (TCO). TCO is a compiler optimization that reuses the same stack frame for all function invocations. However, this optimization can only be applied to recursive functions where the last operation the function performs before returning is the recursive call itself. By reusing the same stack frame, we avoid the ever-growing call stack, reducing the risk of stack overflow errors.</p><p>To better understand this, let’s return to our previous example:</p><pre>function length(arr) {<br>  if (arr[0] === undefined) {<br>    return 0<br>  }<br>  return 1 + length(arr.slice(1))<br>}</pre><p>This function is not tail-call optimized. Let’s examine why. In the last line of the function, rather than simply returning the recursive call, we perform an additional operation: +. As a result, the current stack frame cannot be discarded because it must wait for the recursive call to return before completing the addition.<br>So how do we optimize it? Our goal is to eliminate the unnecessary addition and ensure that the function’s last action is a simple recursive call. We can achieve this by passing the accumulated value as an argument to the function. By reusing default values, the function&#39;s usage remains the same.</p><pre>function length(arr, count = 0) {<br>  if (arr[0] === undefined) {<br>    return count<br>  }<br>  return length(arr.slice(1), count + 1)<br>}</pre><p>In this example, the compiler no longer needs to retain the stack frame for later use and can discard it after each call.</p><p>However, things are rarely that simple. The key point about TCO is that it’s a compiler-level optimization, meaning not all languages support it. Functional languages, such as Haskell or F#, typically have built-in support for this. But what about JavaScript? As usual, it’s more complicated. In theory, the latest specification requires JavaScript engines to support TCO. In practice, the only engine that supposedly supports it is JavaScriptCore in Safari, while V8 and other engines do not.</p><h3>How to optimize without TCO?</h3><p>Fortunately, we can still improve our recursive functions without TCO by using a technique called trampolines. Trampolines aren’t true recursion; they mimic it without increasing the call stack. Let’s take a look at a helper function, trampoline</p><pre>function trampoline(fn) {<br>  return function(...args) {<br>    let result = fn(...args);<br>    while (typeof result === &#39;function&#39;) {<br>      result = result();<br>    }<br>    return result;<br>  };<br>}</pre><p>In this approach, we call our function(e.g. length), which returns another function. We then repeatedly call the returned functions in a loop until we reach the base condition and return a value. By mimicking recursion with loops, we avoid creating separate stack frames and prevent potential stack overflows. However, this also means that our function will need to be a bit more verbose:</p><pre>function length (arr) {<br>  function _length(arr, acc) {<br>    if (arr[0] === undefined) {<br>      return acc;<br>    }<br>    return () =&gt; _length(arr.slice(1), acc + 1);  <br>  }<br>  return trampoline(_length)(arr, 0);<br>}</pre><p>As we can see, there’s still a base condition to stop infinite calls. The key difference is that, instead of returning the result of the self-invocation, we return a function that wraps our self-invoking call. This is then picked up by the while loop in the trampoline utility, which continues calling our functions until we hit the base condition in the first if statement.</p><h3>Does it make any difference?</h3><p>To see if this extra code makes any difference, let’s compare the memory usage of our recursive call and the trampoline version. In this experiment, I first ran the recursive function with TCO optimization (which, as we know, doesn’t work in the JavaScript context). As shown in the screenshot, for an array of length 1000, the stack contains 1000 frames, one for each call.</p><figure><img alt="Multiple stack frames for the recursive function" src="https://cdn-images-1.medium.com/max/503/1*TuDnYmKFu60Uh4nkvp5lHQ.png" /></figure><p>Next, I ran the trampoline code, and as we can see, there are only four stack frames: one for the length and trampoline call, and two for our recursive _length calls. Why two? One is for the initial call before the while loop, and the other is for the &#39;recursive&#39; calls inside the loop.</p><figure><img alt="Stack frames for recursive function via trampoline" src="https://cdn-images-1.medium.com/max/502/1*Hoy2-XpB5if6X3u9lprHXA.png" /></figure><h3>So what have we learned here?</h3><p>Recursion is a powerful tool in our arsenal that we should remember to use wisely. It’s not always the best choice, as with great power comes great responsibility. When we do use it, it’s important to keep in mind that, depending on the use case, we may want to optimize performance using TCO (if the language supports it) or a trampoline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f748b66130c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About web content security]]></title>
            <link>https://medium.com/@romanpylypets/about-web-content-security-eb8d384a31e2?source=rss-f6c3e964442c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8d384a31e2</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[http-headers]]></category>
            <category><![CDATA[content-security-policy]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Roman Pylypets]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 07:01:01 GMT</pubDate>
            <atom:updated>2019-12-09T07:01:01.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wHjJX_SfeX4JyWzA" /><figcaption>Photo by <a href="https://unsplash.com/@kymellis?utm_source=medium&amp;utm_medium=referral">Kym Ellis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Darkness came upon you when least expected… Your customers are reporting seeing weird erotic pictures in your application. Hmm, your bank application definitely shouldn’t do that, right? Oh wait, they are also losing money!? And why is the evil-hacker.com/main.js loading in your application? What can I do? How to protect my application from loading malicious content?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FKFOqUTRI8H26s%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FKFOqUTRI8H26s%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FKFOqUTRI8H26s%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="241" frameborder="0" scrolling="no"><a href="https://medium.com/media/b371afbed89dd8db1fed9d3ce77b3c76/href">https://medium.com/media/b371afbed89dd8db1fed9d3ce77b3c76/href</a></iframe><p>Oh yeah, it was just a dream. But wait, one word suddenly comes to your mind from nowhere — CSP.</p><h3>So what is CSP?</h3><p>Content Security Policy, or CSP, is a set of directives that control what resources can be loaded in your web application. This can be a powerful tool against e.g. XSS attacks, where an attacker makes users load content(js, fonts, styles) from a malicious domain.</p><p>The most common way to use the CSP is through the <strong>Content-Security-Policy </strong>response header for the page document(html file). For example, a CSP header can look like that:</p><pre>Content-Security-Policy: default-src &#39;none&#39;; script-src &#39;self&#39; google-analytics.com; connect-src &#39;self&#39;; img-src &#39;self&#39;; style-src &#39;self&#39;;</pre><p>Apart from setting the header, we can set the policy through the <em>meta</em> tag with <em>http-equiv</em> attribute directly on the page:</p><pre>&lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;&quot;&gt;</pre><p>Meta tags may be used when we don’t have access to the server, so we cannot set headers. However, headers should be the preferred method as the meta tag doesn’t support all CSP directives. Besides, implementation across browsers is more consistent with headers.</p><blockquote>“Em, is this feature supported in my browser?”</blockquote><p>Guess what? Internet Explorer, a.k.a. “what-the-hell browser”, doesn’t support CSP, although we can use <strong>X-Content-Security-Policy </strong>with IE10+. It’s important to keep in mind that this header is considered <strong>deprecated</strong>, and shouldn’t be used together with the CSP header, as it may lead to unexpected behaviour in some browsers.</p><h3>How to use this magical tool?</h3><p>CSP accepts a list of directives separated with semicolon. Directives can accept multiple values separated with space.</p><p>CSP is mainly a tool to white list domains for loading content, so usually the values for the directives would be domain urls e.g. <a href="https://example.com./"><em>https://example.com</em>.</a> Apart from passing the whole domain address, we can allow loading from:</p><ul><li>any subdomain, e.g. <em>*.example.com</em></li><li>specific protocol, e.g. <em>https:</em></li></ul><p>There are also special values:</p><ul><li><strong>* → </strong>allow any url, e.g. <em>script-src *</em></li><li><strong>self → </strong>allow only current origin, e.g. <em>style-src self</em></li><li><strong>none → </strong>don’t allow any origin e.g. <em>script-src none</em></li></ul><p>A comprehensive list of all values can be found <a href="https://content-security-policy.com/#source_list">here</a>.</p><h3>Awesome! How do I white-list origins for my resources?</h3><p>There is a separate directive for most kinds of resources that we want to load:</p><ul><li>script-src</li><li>style-src</li><li>img-src</li><li>font-src</li><li>connect-src (for ajax and web socket requests)</li></ul><p>Let’s take a closer look at some other directives though, that aren’t strictly about a specific resource type.</p><h4>default-src</h4><p>This directive sets the default values for all other directives. E.g. if you don’t set the font-src explicitly, it will fallback to the default-src. There are, however, some directives that do <strong>not </strong>fallback to default-src, so failing to set them is the same as allowing anything to go through:</p><ul><li>base-uri</li><li>form-action</li><li>frame-ancestors</li><li>plugin-types</li><li>report-uri</li><li>sandbox</li></ul><p>This directive can be a good starting point when implementing CSP. Just set it to none and monitor your console. You’ll see what is the current state of your policy, what rules are passing through and what domains you use for loading your resources.</p><p>It’s important to remember that default-src acts as a fallback, meaning that it will have no effect on other directives that are set explicitly. For example, we still need to set ‘self’ explicitly in every directive we use, event if we set it in the default-src:</p><pre>Content-Security-Policy: default-src &#39;self&#39;; form-action &#39;self&#39; cdn.example.com</pre><h4>base-uri</h4><p>This directive restricts what origins can be used in the base element in the document(html page). In a nutshell,<em> &lt;base /&gt; </em>tag sets the, well, base uri for the relative urls in the document, e.g. <em>&lt;img src=”/my-pic.jpg” /&gt;. </em>As far as I can understand, the attack for the <em>&lt;base /&gt;</em> tag is quite limited — e.g. if you have a form with action to a relative url, attacker can exploit it. Although, in this particular case we should use the <strong>form-action</strong> directive. So, if we have</p><pre>Content-Security-Policy: base-uri example.com; form-action api.example.com</pre><p>then forms can post only to the api.example.com, even if the action is a relative url.</p><h4>sandbox</h4><p>This one is a bit different from the others. Instead of blocking a specific resource from loading, it instructs the browser to behave as if the page was loaded inside an <strong>iframe </strong>with the sandbox attribute. This then severely restricts the actions that can be performed on the web page, given us control over what actions we want to allow. For example, we can block popups or scripts. This directive behaves the same way as the sandbox attribute on iframes, and Html5Rocks has a very <a href="https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/">nice article </a>about sandboxing.</p><h4>frame-ancestors</h4><p>This directive specifies what parents can load our page. More specifically, this directive tells browser if <em>iframe, object, embed or applet</em> can insert our application. For example, if a page allows to load any domain through an iframe, and tries to load our page, that has <em>frame-ancestors ‘none’, </em>than the browser will prevent our page from loading in that iframe. It’s similar to the <strong>X-Frame-Options </strong>but takes precedence over it if both are present.</p><h4>report-uri</h4><p>This one sets a uri to which browser will report all violations of CSP policies. The uri has to point to our endpoint that will handle this report, e.g. by saving to our logs and alerting our team.</p><blockquote>It’s that easy? No way!</blockquote><p>Nothing is easy for us, front-end developers 😢. report-uri is now <strong>deprecated </strong>and the new directive <strong>report-to </strong>should be used. There is always a <em>but </em>though. Because not all browsers support report-to at the moment, it is recommended to use both report-uri and report-to directives at the same time. Browsers that support report-to will ignore the report-uri directive.</p><p>report-to is also a bit more complex than report-uri. Instead of url it accepts a group name. What, in the name of all that’s holly, is a group name? Group name is a name of a group defined by another header, <strong>Report-To</strong>. It accepts a list of groups of endpoints and their lifetime. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*BWn2FQv5vkf98R03000_fg.png" /></figure><p>More information about the report-to can be found in the <a href="https://www.w3.org/TR/reporting/#header">w3c docs</a></p><h3>Test before breaking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*0PE6B7db44xPd6Ip.jpg" /></figure><p>Before running to production and feeling proud about ourselves, it can be a good idea to first test our policies with the <strong>Content-Security-Policy-Report-Only </strong>instead. This header will allow all requests to pass, but will report all violations to the report-uri/report-to endpoints. An example of a violation report can be found on <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only#Sample_violation_report">MDN</a></p><p>CSP is among those powerful tools that can significantly improve security of our applications. It can also break our application easily, as it is a very complex instrument that can give us a false feeling of security when set up incorrectly. For example, we can white-list a cdn for loading scripts, and then go for a Friday beer with a clean conscience. However, anyone can upload their scripts to cdns, so we actually allowed any content to be loaded.</p><p>In my opinion, it’s a good idea to start with <em>default-src ‘none’, </em>monitor the console and then create a policy manually or by using one of the many <a href="https://report-uri.com/home/generate">tools</a>. Then, when we feel good about our policy deploy it with <strong>Content-Security-Policy-Report-Only </strong>and once again monitor for a few days if our desire for security didn’t break customers’ desire to do something meaningful with our application. Only after we are pretty sure we are on a good path, deploy the <strong>Content-Security-Policy. </strong>And be prepared for all the evil that is coming your way!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FReQQKxuOg05lm%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FReQQKxuOg05lm%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FReQQKxuOg05lm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="181" frameborder="0" scrolling="no"><a href="https://medium.com/media/a42edb372f23913202ee456382a66305/href">https://medium.com/media/a42edb372f23913202ee456382a66305/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8d384a31e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>