<?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 notachraf on Medium]]></title>
        <description><![CDATA[Stories by notachraf on Medium]]></description>
        <link>https://medium.com/@not.achraf?source=rss-7e72e8a460c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oC9IA4KxyAJY1jtnSJm0yg.png</url>
            <title>Stories by notachraf on Medium</title>
            <link>https://medium.com/@not.achraf?source=rss-7e72e8a460c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:52:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@not.achraf/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[ Create your OWN intrusive javascript blocker script ]]></title>
            <link>https://medium.com/ovrsea/create-your-own-intrusive-javascript-blocker-script-e058cfc79707?source=rss-7e72e8a460c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e058cfc79707</guid>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[webdev]]></category>
            <dc:creator><![CDATA[notachraf]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 10:49:44 GMT</pubDate>
            <atom:updated>2023-12-26T10:55:12.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*TBHWPNukEwcAtuwz.png" /><figcaption>The comment on my previous article</figcaption></figure><p>Recently, one of the comments on my previous article about sharing a state between windows asked me how can one go about not sharing informations about the screen to websites.</p><p>Well you can disable javascript, but nobody want that…</p><p>Another way is to make them not able to access it , but how ?</p><p>Well the solution is to use a concept I wanted to talk about : Proxies ! <br> Stick around to find out how we’re gonna do this using JS and a user script injector ( like TamperMonkey for Chrome )</p><blockquote><strong><em>Disclaimer</em></strong><em> <br> This is in no way a reliable way to assert that no website will be able to access screen information.<br> Using this on a website may break the website if the property hidden are crucial to the normal behavior of the website<br> This is educational content only.</em></blockquote><h3>Proxies</h3><p>Proxies are basically a way to intercept write/read instruction to a Javascript Object.</p><p>Imagine a Person object, that has a name</p><pre>type Person {<br>    name: string<br>}<br><br>const person: Person = {<br>    name: &quot;Achraf&quot;,<br>}</pre><p>Without a proxy, trying to get the name will of course just give back the name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*pQXHn-fvquLT2low.png" /><figcaption>Without a proxy</figcaption></figure><p>But using a proxy will help us intercept this get instruction, and modify it however we want</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*iAmqqZCE7BX4s0DF.png" /><figcaption>With a proxy</figcaption></figure><p>Okay that sounds exactly like something we’d want !</p><h3>Simple example</h3><p>We’ll try to make a simple anonymizer for an object that has a name</p><pre>const authorAnonym = new Proxy(author, {<br>    get(originalObject, propertyName){<br>        if (propertyName === &quot;name&quot;){<br>            return &quot;*******&quot;<br>        }<br>        return originalObject[propertyName]<br>    }<br>})<br><br>console.log(&quot;Original Name&quot;, author.name);<br>console.log(&quot;Proxied Name&quot;, authorAnonym.name);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/0*cZ7wihui1dFq_ZNR.png" /><figcaption>The result</figcaption></figure><p><em>Btw you can override more than just the </em><em>get method but also </em><em>set, </em><em>has, etc. </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"><em>More Info Here</em></a></p><p>Okay that’s good, but for our original purpose ( hide window properties) this wont work, as even if we create a anonimizedWindow the website will just use the original window</p><p>And….you’re right. We can’t use a proxy to replace the window as the window object is not replaceable , but that’s okay, we’ll replace other information, like the screen</p><h3>Let’s start writing our Script</h3><pre>window.screenX = 0<br>window.screenY = 0 <br>window.devicePixelRatio = 0</pre><p>We can start easy by overriding some information like the position of the tab on the monitor</p><p>Now let’s make default screen properties we want to override, like for example availWidth and availHeight which are the enough to give away our monitor size</p><pre>const overridenProperties: Partial&lt;Screen&gt; = {<br>    availHeight: 0,<br>    availWidth: 0,<br>    pixelDepth: 10,<br>}<br><br>const screenProxy = new Proxy(window.screen, {<br>    get(screen, propertyName){<br>        return overridenProperties[propertyName] ?? screen[propertyName]<br>    }<br>})<br><br>window.screen = screenProxy</pre><p>and with that, we are basically done, let’s test it on a small test website that displays information in a div</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*mPcP_iLk9O5mGTCY.png" /><figcaption>Here on the left is the website without the tamperMonkey script running and on the right with the script running !</figcaption></figure><p><a href="https://gist.github.com/achrafl0/079ed803d83c6c1736481ce5364073fb">The whole sourcecode can be found here</a></p><blockquote><em>This was tested on Chrome only, maybe it doesn’t work on Mozilla, if you have, please share it in the comments !</em></blockquote><h3>Conclusion</h3><p>Proxies are a great way to intercept read/write operation on an object, they are used for multiple reasons ( mocking dependencies, singleton pattern, caching, etc. )<br> If you have ideas on how to use them or personal anecdotes involving proxies, feel free to share them !</p><p><a href="https://notachraf.substack.com/">Subscribe to my Newsletter ( for free ! )</a></p><p>Hope you had fun reading this article , if you liked it , you can share it to your friends, you can also subscribe to my new newsletter ( first exclusive post dropping 2nd of January, don’t miss it ! )<br><a href="https://notachraf.substack.com/">It’s right here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*r7THXg_lU1JeU69F" /></figure><p><em>Originally published at </em><a href="https://dev.to/notachraf/create-your-own-intrusive-javascript-blocker-script-1cbc"><em>https://dev.to</em></a><em> on December 26, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e058cfc79707" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ovrsea/create-your-own-intrusive-javascript-blocker-script-e058cfc79707">🛑 Create your OWN intrusive javascript blocker script 🛑</a> was originally published in <a href="https://medium.com/ovrsea">OVRSEA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharing a state between windows without a server]]></title>
            <link>https://medium.com/ovrsea/sharing-a-state-between-windows-without-a-server-6d5c1716cbc8?source=rss-7e72e8a460c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d5c1716cbc8</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[notachraf]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 15:21:53 GMT</pubDate>
            <atom:updated>2024-01-11T09:47:33.187Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you found this article helpful, intersting or just fun, you can share it to your friends/coworkers/community </em>❤️️<em><br></em><a href="https://notachraf.substack.com/"><em>You can also subscribe to my newsletter</em></a><em> !</em></p><p>Recently, there was a gif trending on social networks displaying an <a href="https://twitter.com/_nonfigurativ_/status/1727322594570027343">amazing piece of art made by Bjorn Staal</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vCKb_XLed3eD9y4h-yjdKQ.gif" /><figcaption>Bjorn Staal art piece</figcaption></figure><p>I wanted to recreate it, but lacking the 3D skills for the sphere, particles, and physics, I aimed to understand how to make a window react to the position of another window.</p><p>Essentially, sharing a state between multiple windows, which I find to be one of the coolest aspects of Bjorn’s project! <br>Unable to find a good article or tutorial on the topic, I decided to share my findings with you.</p><blockquote>Let’s attempt to create a simplified Proof of Concept (POC) based on Bjorn’s work!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KJHO9DmEDcTISWuCcvDpMQ.gif" /><figcaption>What we’ll try to create ( ofc it’s way less sexy than Bjorn’s work )</figcaption></figure><p>The first thing I did was to list all the ways I know for sharing information between multiple clients:</p><h3>Duh: A server</h3><p>Obviously, having a server (either with polling or websockets) would simplify the problem. However, since Bjorn achieved his result without using a server, this was out of the question.</p><h3>Local Storage</h3><p>Local Storage is essentially a browser key-value store, commonly used for persisting information between browser sessions. While typically used for storing Auth Tokens or Redirect URLs, it can store anything serializable. <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">You can learn more about it here</a>.</p><p>I recently discovered some fun APIs of Local Storage, including the <em>`storage`</em> event, which fires whenever the Local Storage is changed by another session of the same website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otw7fDvd-XFjj9yVBxn5zg.png" /><figcaption>How the storage event works ( simplified of course )</figcaption></figure><p>We can leverage this by storing the state of each window in the local storage. Whenever a window changes its state, other windows will be updated via the storage event.</p><p>This was my initial idea, and it seems to be the solution Bjorn chose, as he shared his LocalStorage manager code along with an example of using it with threeJs <a href="https://github.com/bgstaal/multipleWindow3dScene">here</a>.</p><p>But once I found out that there was code solving this problem, I wanted to see if there was another way… and spoiler alert: Yes, there is!</p><h3>Shared Workers</h3><p>Behind this flashy terminology is a fascinating concept — the concept of WebWorkers.</p><p>In simple terms, a worker is essentially a second script running on another thread. While they don’t have access to the DOM as they exist outside the HTML Document, they can still communicate with your main script. <br>They are mostly used to offload the main script by handling background jobs, such as pre-fetching information or handling less critical tasks like streaming logs and polling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izcnWc_p13m8pZy5d49mVw.png" /><figcaption>Simplified explanation of the mechanisms of communication between a script and a worker</figcaption></figure><p>Shared workers are a special kind of WebWorkers that can communicate with multiple instances of the same script, making them interesting for our use case! Okay, let’s dive right into the code!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7ObCM2OjojgfFP57ankyw.png" /><figcaption>Shared workers can send information to multiple sessions of the same script</figcaption></figure><h4>Setting up the worker</h4><p>As mentioned, workers are a “second script” with their own entry points. Depending on your setup (TypeScript, bundler, development server), you may need to tweak your tsconfig, add directives, or use specific import syntax.</p><p>I can’t cover all the possible ways to use a web worker, but you can find the informations on MDN or the internet. <br>If needed, I’d happily do a prequel to this article detailing all the ways to set them up!</p><p>In my case, I’m using Vite and TypeScript, so I need a `worker.ts` file and installing the `@types/sharedworker` as a dev dependency. We can create our connection in our main script using this syntax:</p><pre>new SharedWorker(new URL(&quot;worker.ts&quot;, import.meta.url));</pre><p>Basically, we need to:</p><ul><li>Identify each window</li><li>Keep track of all window states</li><li>Alert other windows to redraw once a window changes its state</li></ul><p>Our state will be quite simple:</p><pre>type WindowState = {<br>  screenX: number; // window.screenX<br>  screenY: number; // window.screenY<br>  width: number; // window.innerWidth<br>  height: number; // window.innerHeight<br>};</pre><p>The most crucial information is, of course, window.screenX and window.screenY as they tell us where the window is relative to the top-left corner of your monitor.</p><p>We’ll have two types of messages:</p><ul><li>Each window, whenever it changes its state, will publish a windowStateChangedmessage with its new state.</li><li>The worker will send updates to all other windows to alert them that one of them has changed. The worker will send a syncmessage with the state of all windows.</li></ul><p>We can start with a plain worker looking a bit like this:</p><pre>// worker.ts <br>let windows: { windowState: WindowState; id: number; port: MessagePort }[] = [];<br><br>onconnect = ({ ports }) =&gt; {<br>  const port = ports[0];<br><br>  port.onmessage = function (event: MessageEvent&lt;WorkerMessage&gt;) {<br>    console.log(&quot;We&#39;ll do something&quot;);<br>  };<br>};</pre><p>And our basic connection to the SharedWorker will look something like this. I have some basic functions that will generate an id, and calculate the current window state, also I did some typing on the kind of Message that we can use called WorkerMessage:</p><pre>// main.ts<br>import { WorkerMessage } from &quot;./types&quot;;<br>import {<br>  generateId,<br>  getCurrentWindowState,<br>} from &quot;./windowState&quot;;<br><br>const sharedWorker = new SharedWorker(new URL(&quot;worker.ts&quot;, import.meta.url));<br>let currentWindow = getCurrentWindowState();<br>let id = generateId();</pre><p>Once we start the application, we should alert the worker that there is a new window, so we send immediately a message:</p><pre>// main.ts <br>sharedWorker.port.postMessage({<br>  action: &quot;windowStateChanged&quot;,<br>  payload: {<br>    id,<br>    newWindow: currentWindow,<br>  },<br>} satisfies WorkerMessage);</pre><p>We can listen to this message on our worker side and change the onmessage accordingly. Basically, once the worker receives the windowStateChanged message, either it&#39;s a new window, and we append it to the state, or it&#39;s an old one that changed. Then we should alert everybody that the state has changed:</p><pre>// worker.ts<br>port.onmessage = function (event: MessageEvent&lt;WorkerMessage&gt;) {<br>  const msg = event.data;<br>  switch (msg.action) {<br>    case &quot;windowStateChanged&quot;: {<br>      const { id, newWindow } = msg.payload;<br>      const oldWindowIndex = windows.findIndex((w) =&gt; w.id === id);<br>      if (oldWindowIndex !== -1) {<br>        // old one changed<br>        windows[oldWindowIndex].windowState = newWindow;<br>      } else {<br>        // new window <br>        windows.push({ id, windowState: newWindow, port });<br>      }<br>      windows.forEach((w) =&gt;<br>        // send sync here <br>      );<br>      break;<br>    }<br>  }<br>};</pre><p>To send the sync, I actually need a bit of a hack, because the “port” property cannot be serialized, so I stringify it and parse it back. Because I’m lazy and I don’t just map the windows to a more serializable array:</p><pre>w.port.postMessage({<br>  action: &quot;sync&quot;,<br>  payload: { allWindows: JSON.parse(JSON.stringify(windows)) },<br>} satisfies WorkerMessage);</pre><p>Now it’s time to draw stuff!</p><h3>The Fun Part : Drawing !</h3><p>Of course, we won’t be doing complicated 3D spheres : we’ll just draw a circle in the center of each window and a line linking between the spheres!</p><p>I’ll be using the basic 2D Context of the HTML Canvas to draw, but you can use whatever you want. To draw a circle, it’s pretty simple:</p><pre>const drawCenterCircle = (ctx: CanvasRenderingContext2D, center: Coordinates) =&gt; {<br>  const { x, y } = center;<br>  ctx.strokeStyle = &quot;#eeeeee&quot;;<br>  ctx.lineWidth = 10;<br>  ctx.beginPath();<br>  ctx.arc(x, y, 100, 0, Math.PI * 2, false);<br>  ctx.stroke();<br>  ctx.closePath();<br>};</pre><p>And to draw the lines, we need to do a bit of math (I promise, it’s not a lot 🤓) by converting the relative position of the center of another window to coordinates on our current window. <br>Basically, we are changing bases. I do this using this bit of math. First, we will change the base to have coordinates on the monitor and offset that by the current window screenX/screenY</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zg_z1aZxUE1WP-uOk1owdw.png" /><figcaption>Basically we are looking for the target position after base change</figcaption></figure><pre>const baseChange = ({<br>  currentWindowOffset,<br>  targetWindowOffset,<br>  targetPosition,<br>}: {<br>  currentWindowOffset: Coordinates;<br>  targetWindowOffset: Coordinates;<br>  targetPosition: Coordinates;<br>}) =&gt; {<br>  const monitorCoordinate = {<br>    x: targetPosition.x + targetWindowOffset.x,<br>    y: targetPosition.y + targetWindowOffset.y,<br>  };<br><br>  const currentWindowCoordinate = {<br>    x: monitorCoordinate.x - currentWindowOffset.x,<br>    y: monitorCoordinate.y - currentWindowOffset.y,<br>  };<br><br>  return currentWindowCoordinate;<br>};</pre><p>And as you know, now we have two points on the same relative coordinates system, we can now draw the line !</p><pre>const drawConnectingLine = ({<br>  ctx,<br>  hostWindow,<br>  targetWindow,<br>}: {<br>  ctx: CanvasRenderingContext2D;<br>  hostWindow: WindowState;<br>  targetWindow: WindowState;<br>}) =&gt; {<br>  ctx.strokeStyle = &quot;#ff0000&quot;;<br>  ctx.lineCap = &quot;round&quot;;<br>  const currentWindowOffset: Coordinates = {<br>    x: hostWindow.screenX,<br>    y: hostWindow.screenY,<br>  };<br>  const targetWindowOffset: Coordinates = {<br>    x: targetWindow.screenX,<br>    y: targetWindow.screenY,<br>  };<br><br>  const origin = getWindowCenter(hostWindow);<br>  const target = getWindowCenter(targetWindow);<br><br>  const targetWithBaseChange = baseChange({<br>    currentWindowOffset,<br>    targetWindowOffset,<br>    targetPosition: target,<br>  });<br><br>  ctx.strokeStyle = &quot;#ff0000&quot;;<br>  ctx.lineCap = &quot;round&quot;;<br>  ctx.beginPath();<br>  ctx.moveTo(origin.x, origin.y);<br>  ctx.lineTo(targetWithBaseChange.x, targetWithBaseChange.y);<br>  ctx.stroke();<br>  ctx.closePath();<br>};</pre><p>And now, we just need to react to state changes.</p><pre>// main.ts<br>sharedWorker.port.onmessage = (event: MessageEvent&lt;WorkerMessage&gt;) =&gt; {<br>    const msg = event.data;<br>    switch (msg.action) {<br>      case &quot;sync&quot;: {<br>        const windows = msg.payload.allWindows;<br>        ctx.reset();<br>        drawMainCircle(ctx, center);<br>        windows<br>          .forEach(({ windowState: targetWindow }) =&gt; {<br>            drawConnectingLine({<br>              ctx,<br>              hostWindow: currentWindow,<br>              targetWindow,<br>            });<br>          });<br>      }<br>    }<br>};</pre><p>And as a final step, we just need to periodically check if our window changed and send a message if that’s the case</p><pre>  setInterval(() =&gt; {<br>    const newWindow = getCurrentWindowState();<br>    if (<br>      didWindowChange({<br>        newWindow,<br>        oldWindow: currentWindow,<br>      })<br>    ) {<br>      sharedWorker.port.postMessage({<br>        action: &quot;windowStateChanged&quot;,<br>        payload: {<br>          id,<br>          newWindow,<br>        },<br>      } satisfies WorkerMessage);<br>      currentWindow = newWindow;<br>    }<br>  }, 100);</pre><p><a href="https://github.com/achrafl0/multi-window-article">You can find the whole code for this on this repository</a>. I actually made it a bit more abstract as I did a lot of experiments with it, but the gist of it is the same.</p><p>And if you run it on multiple windows, hopefully, you can get the same thing as this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KJHO9DmEDcTISWuCcvDpMQ.gif" /></figure><p>Thanks for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d5c1716cbc8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ovrsea/sharing-a-state-between-windows-without-a-server-6d5c1716cbc8">Sharing a state between windows without a server</a> was originally published in <a href="https://medium.com/ovrsea">OVRSEA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Context Isolation in NodeJS and why you should know about it]]></title>
            <link>https://medium.com/ovrsea/asynchronous-context-isolation-in-nodejs-and-why-you-should-know-about-it-1b9b03c2fb2d?source=rss-7e72e8a460c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b9b03c2fb2d</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[notachraf]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 17:10:21 GMT</pubDate>
            <atom:updated>2023-07-12T17:10:21.915Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Sharing Resources in an Asynchronous Environment with AsyncLocalStorage</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAkCY4PKYO5YVsrUbAOPoA.jpeg" /><figcaption>“In the tapestry of life, context weaves the threads that give meaning and depth to our experiences.” — ChatGPT</figcaption></figure><h3>TL;DR :</h3><p>- Having a shared resource in an asynchronous function can lead to inconsistency <br>- You can avoid those problems by using <a href="https://nodejs.org/api/async_context.html#new-asynclocalstorage">Async Local Storage</a> (<em>available in Node13+, stable in Node16+)</em></p><h3>A bit of … context</h3><p>Back in January 2023, I was working on an internal context logger for <a href="https://www.ovrsea.com/">OVRSEA</a>. It was inspired by the Mapped Diagnostic Context concept found in popular loggers like Log4j, where you can set a variable in the context at any point to have it in subsequent logs.</p><pre>import {logger} from &quot;@ovrsea/ovrlogger&quot;<br>const sendMessage = async (userId: string) =&gt; {<br>   logger.setContext(&quot;user&quot;, userId)<br>   logger.info(&quot;Trying to send a message&quot;) <br>   // This will log : <br>   // INFO: Trying to send a message, userId: &quot;achraf&quot;<br>   <br>   // * some computations<br>   logger.info(&quot;Sent the message successfully&quot;) <br>   // This will log :<br>   // INFO: Trying to send a message, userId: &quot;achraf&quot;<br>}</pre><p>If we had deeply nested calls to the logger, it will still have the userId logged ! <br>And it was working quite well for a lot of case….until it didn’t.</p><h3>The fall</h3><p>One time, while investigating the logs of a document service, I noticed that the document IDs shown did not correspond to the URL of the document. <br>But, there was no sign of a bug in the document service when examining the data, and no bugs were reported.</p><pre>INFO: Uploading document, documentId: 222<br>INFO: Uploaded document to /111.pdf, documentId: 222<br>INFO: Uploading document, documentId: 222<br>INFO: Uploading document to /222, documentId: 333 // WTF ?<br>INFO: Uploading document, documentId: 333<br>INFO: Uploading document to /333, documentId: 111</pre><p>The code associated with the logs was:</p><pre>export const uploadDocuments = (documentIds: string[]) =&gt; {<br>   await Promise.all(documentsIds.map((documentId) =&gt; {<br>     logger.setContext(&quot;documentId&quot;, documentId)<br>     logger.info(&quot;Uploading document&quot;)<br>     const url = await determineUrl(documentId)<br>     // more work<br>     logger.info(`Uploaded document to ${url}`)<br>   }))<br>}</pre><p>So even If I didn’t want to believe it, the logger was sending untrustworthy logs. <strong>That’s worst than no logs !</strong></p><p>So I made a Minimal Reproducible Example to try to understand what was happening.</p><h3>Minimal Reproducible Example</h3><p>I didn’t want to make actual HTTP requests or Database queries, so I simulated the asynchronous behavior with a handy function calledrandomDelay which <strong>adds a random delay</strong></p><pre>const randomDelay = (delayInSeconds: number) =&gt; {<br>   return new Promise((resolve) =&gt; {<br>     setTimeout(resolve, delayInSeconds * Math.random() * 1000);<br>   });<br>};</pre><p>I also needed a minimal, naive logger with context capabilities, as I knew this was the faulty part.</p><pre>const buildLogger = () =&gt; {<br>   const context: Record&lt;string, any&gt; = {};<br>   const logger = {<br>     log: (…args: any[]) =&gt; console.log(…args, context),<br>     setContext: (key: string, value: any) =&gt; {<br>       context[key] = value;<br>     },<br>   };<br>   return logger<br>  }<br>const logger = buildLogger();</pre><p>It’s a builder that creates a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closure</a> to utilize the context in logs, allowing for multiple loggers with uncorrelated contexts. <br>Additionally, I replicated the actual asynchronous code with a fake mutation for testing purposes.</p><pre>const mutation = async ({ documentId }: { documentId: number }) =&gt; {<br>   logger.setContext(&quot;documentId&quot;, documentId);<br>   logger.log(`Before async, true documentId = ${documentId}`)<br>   await randomDelay(2);<br>   logger.log(`After async, true documentId = ${documentId}`)<br>};<br><br>const uploadMultipleDocuments = async () =&gt; {<br>   const documentsIds = [111, 222, 333]<br>   await Promise.all(<br>     documentsIds.map(async (documentId) =&gt; {<br>       await mutation({ documentId });<br>     })<br>   );<br>};</pre><p>Putting all of this together, we have a similar function to the actual code that sent inconsistent logs.</p><pre>const randomDelay = (delayInSeconds: number) =&gt; {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(resolve, delayInSeconds * Math.random() * 1000);<br>  });<br>};<br><br>const buildLogger = () =&gt; {<br> const context: Record&lt;string, any&gt; = {};<br> const logger = {<br>   log: (...args: any[]) =&gt; console.log(...args, context),<br>   setContext: (key: string, value: any) =&gt; {<br>     context[key] = value;<br>   },<br> };<br> return logger<br>}<br><br>const logger = buildLogger();<br><br>const mutation = async ({ documentId }: { documentId: number }) =&gt; {<br>  logger.setContext(&quot;documentId&quot;, documentId);<br>  logger.log(`Before async, true documentId = ${documentId}`)<br>  await randomDelay(2);<br>  logger.log(`After async, true documentId = ${documentId}`)<br>};<br><br>const uploadMultipleDocuments = async () =&gt; {<br>  const documentsIds = [111, 222, 333]<br>  await Promise.all(<br>    documentsIds.map(async (documentId) =&gt; {<br>      await mutation({ documentId });<br>    })<br>  );<br>};</pre><p>Okay, we’re all set! Let’s call this function and hopefully, we can figure out what’s going on. Hopefully, it’s not a real bug in the document service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIFeGBysKF_x6u2RgT6vOw.png" /><figcaption>Results of the MRE</figcaption></figure><p>Hmmm… well, it’s definitely the logger. <br>Before the asynchronous call, it seems correct, but once we start the asynchronous call, we never update the context, so the context will just stay at the last set value. <br><strong>That’s no good.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAuddjqiZ7-Hi-vw-1_HhA.png" /><figcaption>A simplified illustration on what’s exactly going on</figcaption></figure><p>The issue with this was that I realized any context set at the HTTP Request level (such as adding the targeted resource by the request to the context) was also at risk of being corrupted by parallel requests.</p><p><strong>Therefore, we couldn’t set a context at the top level and expect it to be present in every log within nested function calls.</strong></p><h3>The firefighting</h3><p>I tried to solve the issue in a naive way, but unfortunately, I couldn’t find a solution that didn’t negatively impact the developer experience, which is not ideal.</p><p>Since the logger wasn’t used everywhere, there was still room for improvement and fixing it. The solution I opted for was advocating for building a different logger in each asynchronous context.</p><p>While it did the job, I didn’t want to invest more time into it as the workaround wasn’t too burdensome.</p><p>However, this approach greatly limits the potential of the logger, as an ideal logger would have <strong>context isolation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qS0eWPT5d5abW5r7BMa45A.png" /><figcaption>Context Isolation — Ideal Logger</figcaption></figure><h3>The Rise</h3><p>While working on another issue, I realized that I was essentially facing the same problem but in a different form.</p><blockquote>I needed a value to be associated with the user request, and simply passing down the value from the top level to every part of the code where it was needed was not a feasible option.</blockquote><p>So, I decided to revisit the logger and search online for potential solutions to this problem. After all, I couldn’t be the only one facing this issue!</p><p>As it turned out, I wasn’t alone.</p><p>Some incredibly intelligent individuals had implemented async_hooks to track the lifecycle of various asynchronous resources. While exploring the Node.js documentation for async_hooks, I stumbled upon something that appeared to be the solution to my problem: <a href="http://While working on another issue, I realized that I was essentially facing the same problem but in a different form. I needed a value to be associated with the user request, and simply passing down the value from the top level to every part of the code where it was needed was not a feasible option. So, I decided to revisit the logger and search online for potential solutions to this problem. After all, I couldn&#39;t be the only one facing this issue!  As it turned out, I wasn&#39;t alone. Some incredibly intelligent individuals had implemented async_hooks to track the lifecycle of various asynchronous resources. While exploring the Node.js documentation for async_hooks, I stumbled upon something that appeared to be the solution to my problem: Async Local Storage.">Async Local Storage.</a></p><p>It’s a class that provides helpers to insure that our context is there when we need it and to insure it’s correct !</p><ul><li>Set something as a local context : asyncLocalStorage.enterWith(context)</li><li>Retrieve the current context : asyncLocalStorage.getStore()</li><li>Run an asynchronous function within a specific context: asyncLocalStorage.run(context, fn)</li></ul><blockquote>Using run is crucial. Attempting to call the other functions outside this scope will result in undefined stores</blockquote><p>Now that we have all the necessary tools, we can modify the logger!</p><p>To transform the Minimal Reproducible Example into a Proof of Concept, we first need to do is initialize the Async Local Storage.</p><pre>import { AsyncLocalStorage } from &quot;async_hooks&quot;;<br>type Context = Record&lt;string, any&gt;;<br>const asyncLocalStorage = new AsyncLocalStorage&lt;Context&gt;();</pre><p>Then we need to change our logger to use the store</p><pre>const buildLogger = () =&gt; {<br> // we no longer need a closure actually<br>  const logger = {<br>    log: (...args: any[]) =&gt; {<br>      console.log(...args, asyncLocalStorage.getStore());<br>    },<br>    setContext: (key: string, value: any) =&gt; {<br>      const oldContext = asyncLocalStorage.getStore() ?? {};<br>      oldContext[key] = value;<br>      asyncLocalStorage.enterWith(oldContext);<br>    },<br>  };<br><br>  return logger;<br>};</pre><p>We also need to initialize the context at the top level. To accomplish this, I created a small wrapper helper function that allows us to wrap our mutation in the asyncLocalStorage.run() scope. This ensures that the context is properly set and available throughout the execution.</p><pre>const withAsyncContext =<br>  &lt;T, F extends (...args: any[]) =&gt; Promise&lt;T&gt;&gt;(fn: F) =&gt;<br>  (...args: Parameters&lt;F&gt;): Promise&lt;T&gt; =&gt; {<br>    return asyncLocalStorage.run({}, async () =&gt; {<br>      const result = await fn(...args);<br><br>      return result;<br>    });<br>  };<br><br></pre><p>It’s simply a curried function that takes another function as an argument, runs it inside the scope of asyncLocalStorage.run(), and returns the result. <br>Let&#39;s put all of this together:</p><pre>import { AsyncLocalStorage } from &quot;async_hooks&quot;;<br><br>type Context = Record&lt;string, any&gt;;<br>const asyncLocalStorage = new AsyncLocalStorage&lt;Context&gt;();<br><br>const randomDelay = (delayInSeconds: number) =&gt; {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(resolve, delayInSeconds * Math.random() * 1000);<br>  });<br>};<br><br>const buildLogger = () =&gt; {<br>  const logger = {<br>    log: (...args: any[]) =&gt; {<br>      console.log(...args, asyncLocalStorage.getStore());<br>    },<br>    setContext: (key: string, value: any) =&gt; {<br>      const oldContext = asyncLocalStorage.getStore() ?? {};<br><br>      oldContext[key] = value;<br>      asyncLocalStorage.enterWith(oldContext);<br>    },<br>  };<br><br>  return logger;<br>};<br><br>const logger = buildLogger();<br><br>const withAsyncContext =<br>  &lt;T, F extends (...args: any[]) =&gt; Promise&lt;T&gt;&gt;(fn: F) =&gt;<br>  (...args: Parameters&lt;F&gt;): Promise&lt;T&gt; =&gt; {<br>    return asyncLocalStorage.run({}, async () =&gt; {<br>      const result = await fn(...args);<br><br>      return result;<br>    });<br>  };<br><br>const mutation = async ({ documentId }: { documentId: number }) =&gt; {<br>  logger.setContext(&quot;documentId&quot;, documentId);<br><br>  logger.log(`Before async, true documentId = ${documentId}`);<br>  await randomDelay(2);<br>  logger.log(`After async, true documentId = ${documentId}`);<br>};<br><br>const uploadMultipleDocuments = async () =&gt; {<br>  const documentsIds = [111, 222, 333];<br><br>  await Promise.all(<br>    documentsIds.map(async (documentId) =&gt; {<br>      await withAsyncContext(mutation)({ documentId });<br>    })<br>  );<br>};</pre><blockquote>This example is primarily intended for demonstration purposes. In practical scenarios, the withAsyncContext function would likely serve as middleware within an HTTP server or as a wrapper for the top-level handler of a serverless function.</blockquote><p>Okay, it’s now time test it !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTR2VWaHV2Z2KTGNKBHD9g.png" /><figcaption>Reliable logs due to AsyncLocalStorage</figcaption></figure><p>That’s exactly what we’d expect ! That’s perfect for us !</p><h3>Conclusion</h3><p>Logging can be a challenging task since it primarily serves as a message to our future selves when we encounter bugs during debugging. To be considerate to our future selves, it is crucial to provide sufficient context in our logs to aid in bug resolution. However, achieving this can be tricky in asynchronous functions. Thankfully, by leveraging AsyncLocalStorage, we can bind the context to our scope and generate reliable logs.</p><p>Thank you for joining me on this journey through the peculiar yet fascinating aspects of Node.js. I hope the insights shared here prove valuable for your projects. <br>If you do something cool using <strong>AsyncLocalStorage</strong>, I’d be curious to hear about it. <br>Feel free to reach out and share your experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b9b03c2fb2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ovrsea/asynchronous-context-isolation-in-nodejs-and-why-you-should-know-about-it-1b9b03c2fb2d">Asynchronous Context Isolation in NodeJS and why you should know about it</a> was originally published in <a href="https://medium.com/ovrsea">OVRSEA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOP : Of CORS it works like that !]]></title>
            <link>https://medium.com/ovrsea/sop-of-cors-it-works-like-that-1aeb2209ffb7?source=rss-7e72e8a460c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aeb2209ffb7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[notachraf]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 08:50:37 GMT</pubDate>
            <atom:updated>2023-07-10T08:50:37.961Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>SOP : Of CORS it works like that !</h3><p>Most of web developers encounter at one point or another some errors about CORS in the console, of course, we look it up on Google, other devs tell us to just put a line in our backend, and then it’s all good from there …. Or is it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mn-lLqX9BQX4PWayg_ng3w.png" /><figcaption>Typical CORS error when trying to make HTTP request</figcaption></figure><p>What really happens when we add that magical StackOverflow one liner in our server</p><pre>response.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)</pre><p>And how does it affect our security?</p><p>If we try to understand CORS, we find soon enough that we also need to understand SOP. And in this article we’ll try to understand how both of them work!</p><h4>TL;DR</h4><p>SOP and CORS are web security mechanisms that prevent unauthorised access to resources from different origins.</p><p>- <strong>Origin</strong>: Web content’s <strong>origin</strong> is defined by the s<em>cheme </em>(protocol), <em>hostname</em> (domain), and <em>port</em> of the <a href="https://developer.mozilla.org/en-US/docs/Glossary/URL">URL</a> used to access it. Two objects have the same origin only when the scheme, hostname, and port all match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH_YvOEfXk1DXYnevX5D2Q.png" /></figure><ul><li><strong>SOP</strong>: Same Origin Policy : SOP restricts web resources from being accessed across different origins</li><li><strong>CORS</strong>: Cross Origin Ressources Sharing : Allows web resources to be accessed across different origins with appropriate permissions.</li></ul><h4>Definitions</h4><p>For the purpose of this introductory article, certain definitions are required, even though they may not be entirely precise and can be improved upon. <br>However, they adequately serve the intended scope of this article:</p><p>- <strong>Web Resource</strong> : A web resource is basically any resource that is the target of a web request.<br>- <strong>Origin</strong> : Origin is just a fancy word to talk about a tuple defined by the scheme, hostname, and port of a URL. <br>If two URLs have the same scheme, hostname, and port, they are considered to be from the same<strong> </strong><a href="https://url.spec.whatwg.org/#concept-url-origin"><strong>origin</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUn0ONS-Yn-wbRSQBRGIFg.png" /><figcaption>For example, comparing <a href="https://ovrsea.com/">https://ovrsea.com:443</a> to other urls</figcaption></figure><h3><strong>Same-Origin Policy (SOP)</strong></h3><p>The Same-Origin Policy is a web security mechanism implemented on the <strong>browser side</strong> that restricts access to web resources</p><p>The purpose of SOP is to prevent malicious scripts from accessing sensitive resources by restricting them to only access resources from the same origin. This is because web browsers have the unfortunate tendency to send cookies and other informations to their corresponding origin on each request, which is quiet handy for all legit use cases, but can become problematic if a malicious person try to use this fact.</p><p>For example, imagine if client of https://bank.comvisits the malicious website https://evilWebsite.comwith the same browser he use to connect to his bank. And imagine that the evil website integrates malicious HTTP calls to https://bank.com</p><p>If there was no security mechanism, the malicious website will be able to just go ahead and read confidential banking information on behalf of the user, which is not good :</p><ul><li>User connects to https://bank.com</li><li>User visits htttps://evilWebsite.com</li><li>evilWebsite.com makes requests to confidential data in https://bank.com</li><li>The browser sees a request to https://bank.com so he joins the cookies in the request</li><li>The bank server responds with the confidential data, and because there is no SOP, it’s forwarded to the evil website 😈.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12BnV-bzwLKGPvTOq3BEfA.png" /></figure><p>But because of the Same-Origin Policy, the malicious website cannot directly access the user’s banking information since <em>bank.com</em> and <em>evilwebsite.com </em>have different <strong>origins</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnZmrq48U_UK9aO_MS7niQ.png" /></figure><p>However, SOP only prevents the malicious website from reading the answer, not making it. So, the malicious website can still make the request to the bank domain on behalf of the user, but it cannot read the response due to SOP.</p><p>That would need a different kind of protection to Cross Site Request Forgery, which may be the subject of a next article 👀.</p><p>In this exemple, the attacker makes the request to bank.com/pay?to=evil&amp;amount=5000and assuming it doesn’t need any kind of authentification or verification more than the cookies, the request will succeed. <br>Hopefully, most banks and websites will actually have CSRF protection and Multi Factor Authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVS5idT24y5fBuNidvUpKw.png" /><figcaption>Here the request actually happens, and not blocked by the browser, it’s the responsibility of the bank’s server to stop it</figcaption></figure><p>One common misconception is to believe that the SOP prohibits <strong>all </strong>cross-origin requests. If that were the case, content delivery networks (CDNs) and even the web would be worthless since it would be impossible to use images from other origins, or using javascript packages.</p><pre>&lt;img href=&quot;https://gravatar.com/my-avatar.com&quot; /&gt;<br>Or <br>&lt;script src=&quot;https://unpkg.com/htmx.org@1.9.2&quot;&gt;&lt;/script&gt;</pre><p><em>This is actually permitted in browsers with SOP !</em></p><p>Moreover, the SOP does not prohibit origins from contacting one another or sending and receiving requests (such as submitting forms), they only prohibit the website from <strong><em>reading</em></strong> the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ef8vO5EtpiQgGtOM2BUMQ.png" /><figcaption>Ovrsea.com can embed an image from cdn.ovrsea.com, but not read it’s content if not explicitly allowed to, the user will be able to see the image ( of course if it’s available )</figcaption></figure><p>But even with this set of rules, it is still too strict for some legitimate usage. For our case, our frontend https://ovrsea.comwill be able to make the HTTP Request to https://api.ovrsea.combut will not be able to read the answer ( as they don’t have the same origin )</p><p>But thankfully, there is a way to allow us to tell the browser to chill out a bit : by using <strong>CORS</strong> !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0kZEzorI8jStHN9d4TVzg.png" /></figure><h4><strong>Cross-Origin Resource Sharing (CORS)</strong></h4><p>Cross-Origin Resource Sharing is a web security mechanism that allows resources to be accessed from different origins if it is explicitly allowed to!</p><p>CORS works by adding HTTP headers ( one of them is the famous Access-Control-Allow-Origin) to responses that indicate which cross origin is allowed to access a particular resource.</p><p>For example, if a web page from <a href="https://ovrsea.com/">https://ovrsea.com</a> wants to access an API from https://api.ovrsea.com, the API should tell the browser:</p><blockquote>Hey it’s cool , ovrsea.com is a safe site for me, you can send him my data</blockquote><p>And to do that technically the server of the api will set the header to allow for https://ovrsea.com:</p><pre>Access-Control-Allow-Origin: &#39;&lt;https://ovrsea.com&gt;&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NONr1PSzCHzbWCTN3NXcRQ.png" /></figure><p>So now, we understand a bit more about what happens when we set <strong><em>”Access-Control-Allow-Origin”: “*”</em></strong> : <br>It means that everybody is able to request the origin and read from it ! <br>So if that’s not your intended purpose, you better restrict it !</p><blockquote>By the way, if you ever wondered about the utility of the `<strong><em>OPTIONS</em></strong>` method request you see before making the actual request in your network inspector, well it’s because of <strong>CORS</strong>. It’s a <strong>preflight</strong> request that precedes the actual request, to ask the other origin if it’s okay to proceed with the actual request, or if it should be aborted. <br>So in the case of simple CSRF attacks like the one we saw before, the server would see that “evilWebsite.com” is trying to send money, and they will block it. But for it to actually fail, the bank server should not have <strong><em>”Access-Control-Allow-Origin”: “*”</em></strong> !</blockquote><p>There is also other headers that may be interesting to use that are more detailed <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#cors">here</a></p><h4>Conclusion</h4><p>SOP will restrict how we can share resources by limiting the readability of the resources, and CORS will relax those restriction to allow us to access them if they are explicitly allowed to !</p><p>But those protections and mechanisms are only implemented on <strong>the browser side</strong>, this doesn’t block requests made by other means like <strong>`curl`</strong>, <strong>`wget`</strong>, and any other request made by non browsers, so it shouldn’t be used as a way to restrict access to a backend, this should be done by other tools and mechanisms !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aeb2209ffb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ovrsea/sop-of-cors-it-works-like-that-1aeb2209ffb7">SOP : Of CORS it works like that !</a> was originally published in <a href="https://medium.com/ovrsea">OVRSEA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>