<?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 Kakamotobi on Medium]]></title>
        <description><![CDATA[Stories by Kakamotobi on Medium]]></description>
        <link>https://medium.com/@daeram.chung?source=rss-bdae4e62d6b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t1G_GKxOU4uRwp0cPg3kIg.jpeg</url>
            <title>Stories by Kakamotobi on Medium</title>
            <link>https://medium.com/@daeram.chung?source=rss-bdae4e62d6b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:48:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daeram.chung/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[Understanding JavaScript Through Philosophy — The Prototype Paradigm]]></title>
            <link>https://medium.com/@daeram.chung/understanding-javascript-through-philosophy-the-prototype-paradigm-79f6021e4f33?source=rss-bdae4e62d6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/79f6021e4f33</guid>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[execution-context]]></category>
            <category><![CDATA[lexical-scope]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Kakamotobi]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 17:44:57 GMT</pubDate>
            <atom:updated>2025-06-20T17:44:57.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding JavaScript Through Philosophy — The Prototype Paradigm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*IrxFmvKcE3GdWFWg58R81A.gif" /></figure><h3>Foreword</h3><p>JavaScript gets a lot of stick for a number of reasons, which is evident through repositories like <a href="https://github.com/denysdovhan/wtfjs">wtfjs</a>. Amidst the (reasonable and relatable) noise, the foundational <em>prototype-based paradigm</em> is drowned. The introduction of the class keyword with the release of ES2015 seemed to have further amplified the confusion around how inheritance works in JavaScript, masking its prototype-based nature behind class-like syntax that resembles traditional <em>class-based object-oriented languages</em>.</p><p>This article aims to explore and better understand the underlying ideas and philosophy of the prototype-based paradigm by comparing it to the class-based paradigm. By doing so, this article will also explore why JavaScript is the way it is — concerning mechanisms like the <em>execution context</em>, <em>lexical scope</em>, <em>hoisting, </em><em>this</em>.</p><p>This article is based on the research paper <a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=30fcb7807ce73f16222761b97e36154f12349efb">Classes vs. Prototypes Some Philosophical and Historical Observations</a> by Antero Taivalsaari. Quotes that are otherwise unspecified are directly from this paper.</p><blockquote>The distinction between class-based and prototype-based systems reflects a longlasting philosophical dispute concerning the representation of <strong>abstractions</strong>.</blockquote><h3>Class-based OOP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkuZt4wvrPnjaX_qAM4nVw.jpeg" /><figcaption><a href="https://en.wikipedia.org/wiki/The_School_of_Athens">Plato and Aristotle in <em>The School of Athens</em> by Raphael</a></figcaption></figure><h4>Plato — Theory of Forms (427 BC E— 348 BCE)</h4><p>Plato’s Theory of Forms makes a distinction between the <strong>world of forms/ideas</strong> and the <strong>physical world</strong> where the concrete entities of those forms are present.</p><p>Class-based languages are based on this idea where a class declaration is a <em>form</em> of which real instances can be created.</p><h4>Aristotle — Classification (384 BCE — 322 BCE)</h4><p>In the pursuit of a complete taxonomy of all natural things, Aristotle declared that things can be categorized based on <strong>fixed and essential properties </strong>pertaining to that particular group.</p><p>By extension, category A can be defined based on category B if category A has at least all of the properties of category B. In class-based languages, a class inherits properties and methods from its superclass if it has one, and it can also have its own set of properties and methods.</p><p>The premise with Aristotle’s Classification is that there is a single perfect taxonomy that works. However, in truth, such classification approach is flawed and prone to subjectivity. We don’t have to jog down our memory for long to remember having to redefine classes that we thought were appropriate at the time. This approach of predetermining the exact characteristics of a particular concept is especially difficult to maintain when requirements change, which they so often do.</p><h3>Prototype-based OOP</h3><h4>Ludwig Wittgenstein — Family Resemblance (1953)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*3I8hRaX5Y0ks8a2vMX_q4A.jpeg" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Ludwig-Wittgenstein-portrait.jpg">Ludwig Wittgenstein</a></figcaption></figure><p>In his book <em>Philosophical Investigations</em>, Wittgenstein criticized traditional classification claiming that concepts like games have no clear-cut definition in terms of shared properties. Some games are about winning or losing, while others (Ex: ring-around-the-rosy) are not. The same goes for art. Whether something can be called “art” is still a hotly debated and controversial topic.</p><p>Instead, Wittgenstein proposed the idea of <em>family resemblance — </em><strong>members of a category can have overlapping similarities without having common features</strong>. Take a look at the <a href="https://www.palaces-of-europe.com/spanish-habsburg-family-tree.html">Habsburg family</a>. A lot of the members of the Habsburg family share the infamous Habsburg jaw but it is not a common feature to all family members.</p><p>Therefore, Wittgenstein claimed that <strong>meaning is determined by family resemblances (representative features) and not by definition (common features)</strong>.</p><h4>Eleanor Rosch — Prototype Theory (1978)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1y9T1Bun42EFt9ufzlVhbw.jpeg" /><figcaption><a href="https://en.wikipedia.org/wiki/Eleanor_Rosch">Eleanor Rosch</a></figcaption></figure><p>Rosch took Wittgenstein’s ideas further to establish the <em>prototype theory </em>in her book <em>Cognition and Categorization</em>. Through experiments, she demonstrated that when we categorize things, we adopt a <em>graded structure</em> where things are graded in order of similarity. That means, <strong>some members of a category are more representative than others belonging to the same category</strong>. These representative members are called <strong><em>prototypes</em></strong>.</p><blockquote>In short, prototypes appear to be just those members of a category that most reflect the redundancy structure of the category as a whole.</blockquote><blockquote>Eleanor Rosch in Cognition and Categorization</blockquote><p>In other words, the member with the highest similarity becomes the prototype of that category — building up on Wittgenstein’s idea of <em>family resemblance</em>.</p><h3>Java (Class-based) vs JavaScript (Prototype-based)</h3><p>Let’s see the two approaches of abstractions in code.</p><h4>Java</h4><p>The below code depicts Aristotelian ideology of an attempt at a single correct taxonomy based on shared properties, and instances of a class always having an identical set of properties.</p><pre>// --Plato&#39;s Idea/Form (reference type that exists in code but not in heap memory)-- //<br>// Base Class<br>class Dog {<br>  int numLegs = 4;<br>  int numEars = 2;<br>  String build = &quot;medium&quot;;<br><br>  void speak() {<br>    System.out.println(&quot;Woof!&quot;);<br>  }<br>}<br><br>// Subclass of Dog<br>class LabradorRetriever extends Dog {<br>  @Override<br>  void speak() {<br>    System.out.println(&quot;Woof! I am a Labrador Retriever!&quot;);<br>  }<br>}<br><br>// Subclass of Dog<br>class Vizsla extends Dog {<br>  Vizsla() {<br>    this.build = &quot;slim&quot;;<br>  }<br><br>  @Override<br>  void speak() {<br>    System.out.println(&quot;Woof! I am a Vizsla!&quot;);<br>  }<br>}<br><br>// Subclass of Vizsla<br>class Clifford extends Vizsla {<br>  @Override<br>  void speak() {<br>    System.out.println(&quot;Woof! I&#39;m Clifford the Big Red Dog!&quot;);<br>  }<br>}<br><br>// --Real world (instance)-- //<br>public class Main {<br>  public static void main(String[] args) {<br>    Clifford clifford = new Clifford();<br><br>    System.out.println(clifford.numLegs); // 4<br>    System.out.println(clifford.numEars); // 2<br>    System.out.println(clifford.build); // slim<br>    clifford.speak(); // Woof! I&#39;m Clifford the Big Red Dog!<br>  }<br>}</pre><h4>JavaScript</h4><p>The above Java code has been recreated in a prototypical way using JavaScript.</p><pre>// --Prototypical dog (the central category member)-- //<br>function LabradorRetriever() {<br>  this.numLegs = 4;<br>  this.numEars = 2;<br>  this.build = &quot;medium&quot;;<br>  this.bark = function() {<br>    console.log(&quot;Woof!&quot;);<br>  };<br>}<br><br>// The instantiated prototype of the best example of a dog.<br>const labradorRetriever = new LabradorRetriever();<br>labradorRetriever.bark(); // &quot;Woof!&quot;<br><br>// --A different breed of dog (less prototypical)-- //<br>function Vizsla() {<br>  this.build = &quot;slim&quot;;<br>}<br>// Vizsla instances should inherit from the prototypical instance(labradorRetriever)<br>Object.setPrototypeOf(Vizsla.prototype, labradorRetriever); // a prototype is an actual object<br>console.log(Vizsla.prototype); // LabradorRetriever {}<br><br>// --Example-- //<br>const clifford = new Vizsla();<br>clifford.bark = function() {<br>  console.log(&quot;Woof! I&#39;m Clifford the Big Red Dog!&quot;);<br>}<br><br>console.log(clifford);<br>// Vizsla { build: &#39;slim&#39;, bark: ƒ }<br>  // bark: ƒ ()<br>  // build: &quot;slim&quot;<br>  // [[Prototype]]: LabradorRetriever<br>    // constructor: ƒ Vizsla()<br>    // [[Prototype]]: LabradorRetriever<br>      // bark: ƒ ()<br>      // build: &quot;medium&quot;<br>      // numEars: 2<br>      // numLegs: 4<br>      // [[Prototype]]: Object<br><br>// Inherited from the prototype (labradorRetriever)<br>console.log(clifford.numLegs); // 4<br>console.log(clifford.numEars); // 2<br>console.log(clifford.build); // slim<br>// Inherited from the prototype (labradorRetriever) but overriden<br>clifford.bark(); // &quot;Woof! I&#39;m Clifford the Big Red Dog!&quot;</pre><p><strong>The Prototype Chain</strong></p><ul><li>.prototype — a property only accessible on constructor functions, which is used as the blueprint object for objects constructed by said function. For example, const labradorRetriever = new LabradorRetriever() will set labradorRetriever.__proto__ to point to LabradorRetriever.prototype.</li><li>.__proto__ (deprecated) — a property on all objects, pointing to the object’s prototype (i.e. what it inherits from). It is the object’s actual internal link to its prototype, forming the prototype chain. Object.getPrototypeOf() should be used instead.</li></ul><pre>// labradorRetriever.__proto__ is a link to LabradorRetriever.prototype<br>console.log(LabradorRetriever.prototype); // ƒ () { [native code] }<br>console.log(labradorRetriever.__proto__); // {}<br>console.log(labradorRetriever.__proto__ === LabradorRetriever.prototype); // true<br><br>// Vizsla.prototype is a link to LabradorRetriever<br>console.log(Vizsla.prototype); // LabradorRetriever {}<br>console.log(Vizsla.prototype.__proto__); // LabradorRetriever {numLegs: 4, numEars: 2, build: &#39;medium&#39;, bark: ƒ} // the actual labradorRetriever object<br>console.log(Vizsla.prototype.__proto__ === labradorRetriever); // true<br><br>// clifford.__proto__ is a link to Vizsla.prototype<br>console.log(clifford.__proto__); // LabradorRetriever {}<br>console.log(clifford.__proto__ === Vizsla.prototype); // true<br><br>// clifford.__proto__.__proto__ is a link to labradorRetriever<br>console.log(clifford.__proto__.__proto__); // LabradorRetriever { numLegs: 4, numEars: 2, build: &#39;medium&#39;, bark: ƒ } // the actual labradorRetriever object<br>console.log(clifford.__proto__.__proto__ === Vizsla.prototype.__proto__); // true<br>console.log(clifford.__proto__.__proto__ === labradorRetriever); // true<br><br>// clifford.__proto__.__proto__.__proto__ is a link to LabradorRetriever.prototype<br>console.log(clifford.__proto__.__proto__.__proto__); // {}<br>console.log(clifford.__proto__.__proto__.__proto__ === labradorRetriever.__proto__); // true<br>console.log(clifford.__proto__.__proto__.__proto__ === LabradorRetriever.prototype); // true</pre><pre>// The prototype chain<br>clifford<br>  ↓ __proto__<br>Vizsla.prototype<br>  ↓ __proto__<br>labradorRetriever<br>  ↓ __proto__<br>LabradorRetriever.prototype<br>  ↓ __proto__<br>Object.prototype<br>  ↓ __proto__<br>null</pre><h4>Implications</h4><p>Prototype-based OOP provides more flexibility than Class-based OOP.</p><p>We can add/remove methods and variables at the individual object level in prototype-based OOP. This diminishes the need to invest a lot of time to determine a proper classification before continuing.</p><p>Object creation in prototype-based languages takes place by copying, and inheritance is replaced by some other, less class-centered mechanism. We saw JavaScript’s prototype chaining mechanism in the above code.</p><p>In prototype-based OOP, the focus is not to classify but to exploit alikeness.</p><p><strong>So, does that mean prototype-based languages overcome the limitations of class-based languages?</strong></p><blockquote>Unfortunately, this is not really the case. Most prototype-based languages of today are motivated by relatively technical matters. For instance, prototypes are commonly used for reaching better reusability through increased sharing of properties and more dynamic bindings of objects, or for providing better support for experimental programming [UnS87]. In contrast, they do not usually take into account the conceptual modeling side, let alone pay any attention to the philosophical basis that underlies object-oriented programming. In a way, thus far the developers of prototype-based object-oriented programming languages seem to have been even more ignorant to these underlying conceptual and philosophical issues than, e.g., the Scandinavian inventors of the class-based object-oriented paradigm (see, e.g. [BDM73, Knu88]).</blockquote><p>In retrospect, traditional Aristotelian classification (i.e. determining shared properties) seems to be more intuitive when it comes to designing an abstraction. I found this to be the case especially when using the class syntactic sugar in JavaScript.</p><h3>JavaScript Mechanisms</h3><p>Let’s return back to JavaScript. In order to understand why some of its mechanisms(<em>execution context, lexical scope, hoisting</em>) exist, it may be worthwhile to explore them through philosophical observations as well.</p><p>Credit for this section goes to this <a href="https://medium.com/@limsungmook/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EB%8A%94-%EC%99%9C-%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85%EC%9D%84-%EC%84%A0%ED%83%9D%ED%96%88%EC%9D%84%EA%B9%8C-997f985adb42">article</a> by Sungmook Lim.</p><h4>Ludwig Wittgenstein — The Use Theory of Meaning</h4><p>When it comes to “meaning”, Wittgenstein has more to say on the matter. In his paper <em>Philosophical Investigations</em>, Wittgenstein explains how words get their meanings.</p><blockquote>Words have meaning only in the stream of life.</blockquote><blockquote>Wittgenstein</blockquote><p>In other words, <strong><em>meaning</em> is determined based on <em>use</em></strong>. A word’s meaning is not derived from its reference to an object or a mental image, but from how it is employed in sentences.</p><p>For example, “Pizza!” could mean “I see pizza”, “Give me pizza”, “Heads up! There’s a pizza flying at you”. The same goes for sarcasm.</p><p>The situation and <em>context</em> matters.</p><h4>Rosch on Context — building up on Wittgenstein’s Use Theory of Meaning</h4><p>When criticizing traditional classification, Rosch mentioned that the outcome of the classification also <strong>depends on the person doing the classification</strong>.</p><p>For example, when asking an ordinary person to give a number, integers are typically given — implying integers are representative of numbers. However, someone with a strong mathematical background could easily give non-integer constants like <em>π</em> or <em>e</em>.</p><h4>JavaScript — Lexical Environment, Execution Context, Hoisting</h4><p>In JavaScript, the value/meaning of a variable is determined based on its <strong>lexical environment</strong> and <strong>execution context</strong>. Therefore, the value is determined only after referring all declarations (<strong>hoisting</strong>) in the particular execution context.</p><p><strong>Hoisting is essentially when all declarations in the lexical scope (the surrounding environment in which a declaration is being used in) are “brought to the top” upon creating an execution context.</strong></p><pre>var name = &#39;Kakamotobi&#39;;<br><br>startTheDay(); // Execution Context created (declarations within are hoisted)<br><br>function startTheDay() {<br> var name = &#39;Truman&#39;;<br><br> function sayHello() {<br>  console.log(name); // Scope Chaining to find the nearest `name` occurs<br> }<br><br> // Execution Context created (declarations within are hoisted)<br> // If `sayHello` has a declaration of `name` in it, it will have priority<br> sayHello();<br>}</pre><pre>// Execution Context Stack<br><br>- Execution: sayHello<br>  - LexicalEnv: null<br>  - Outer: startTheDay<br>- Execution: startTheDay<br>  - LexicalEnv: name, sayHello<br>  - Outer: global<br>- Global Execution<br>  - Lexical Env: name, startTheDay</pre><p>The foundation and core idea of Prototype Theory, prototype-based languages like JavaScript are based on, is that <strong>things have meaning within a particular context</strong>.</p><p>Execution context, lexical scope, and hoisting exist in JavaScript in order to implement this foundation.</p><h4>JavaScript — this</h4><p>Since the use of the word determines its meaning, it also means that <strong>the meaning depends on <em>where</em> it was said and <em>who</em> said it</strong>.</p><p>The value of this depends on how the function — in which this was used — is invoked (runtime binding) instead of how the function was defined. It points to the <em>context</em> through which the function was invoked. Just ask yourself, who invoked the function and what context is this code running in?</p><pre>window.name = &quot;Wittgenstein&quot;;<br><br>const Kakamotobi = {<br>  name: &quot;Kakamotobi&quot;,<br>  sayHello() {<br>    console.log(&quot;this: &quot;, this);<br>    console.log(`Hello, I&#39;m ${this.name}!`);<br>  }<br>}<br><br>function sayHello() {<br>  console.log(&quot;this: &quot;, this);<br>  console.log(`Hello, I&#39;m ${this.name}!`);<br>  console.log(&quot;top-level sayHello&quot;);<br>}<br><br>sayHello();<br>// this: Window {window: Window, self: Window, document: document, name: &#39;World&#39;, location: Location, …}<br>// Hello, I&#39;m Wittgenstein!<br>// top-level sayHello<br><br>Kakamotobi.sayHello();<br>// this: {name: &#39;Kakamotobi&#39;, sayHello: ƒ}<br>// Hello, I&#39;m Kakamotobi!<br><br>sayHello.call(Kakamotobi);<br>// this: {name: &#39;Kakamotobi&#39;, sayHello: ƒ}<br>// Hello, I&#39;m Kakamotobi!<br>// top-level sayHello &lt;-- the global sayHello has been invoked but in the context of `Kakamotobi`</pre><p>But of course, there are exceptions — arrow functions. Read more <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">here</a>.</p><h3>Afterword</h3><p>Yes, JavaScript was created in a rush back in 1995 and is still quite often misunderstood due to it being a “mess” at times. But it is worthwhile to explore the foundational philosophy in order to better understand the language — the client-side programming language that currently comprises 98.8% of websites.</p><h3>References</h3><p><a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=30fcb7807ce73f16222761b97e36154f12349efb">Classes vs. Prototypes Some Philosophical and Historical Observations — Antero Taivalsaari</a></p><p><a href="https://static1.squarespace.com/static/54889e73e4b0a2c1f9891289/t/564b61a4e4b04eca59c4d232/1447780772744/Ludwig.Wittgenstein.-.Philosophical.Investigations.pdf">Philosophical Investigations — Ludwig Wittgenstein</a></p><p><a href="https://www.cs.rice.edu/~vo9/recognition/2016/slides/lecture07/CognitionAndCategorization.pdf">Cognition and Categorization — Eleanor Rosch, Barbara Lloyd</a></p><p><a href="https://www.academia.edu/90826370/The_Use_Theory_of_Meaning_A_Reading_of_Wittgensteins_Philosophical_Investigations">The Use Theory of Meaning — Anil Kumar</a></p><p><a href="https://library.fes.de/libalt/journals/swetsfulltext/10296094.pdf">Wittgenstein and his Philosophy of Beginnings and Beginnings and Beginnings — John Shotter</a></p><p><a href="https://medium.com/@limsungmook/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EB%8A%94-%EC%99%9C-%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85%EC%9D%84-%EC%84%A0%ED%83%9D%ED%96%88%EC%9D%84%EA%B9%8C-997f985adb42">자바스크립트는 왜 프로토타입을 선택했을까 — Sungmook Lim</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this — JavaScript | MDN</a></p><p><a href="https://w3techs.com/technologies/details/cp-javascript">Usage Statistics of JavaScript as Client-side Programming Language on Websites, June 2025</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79f6021e4f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FCM Service Worker + Vite]]></title>
            <link>https://medium.com/@daeram.chung/fcm-service-worker-vite-8deccfc23fe2?source=rss-bdae4e62d6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8deccfc23fe2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[fcm]]></category>
            <dc:creator><![CDATA[Kakamotobi]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 09:49:38 GMT</pubDate>
            <atom:updated>2024-04-11T09:56:21.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*_LO0Q971Tee4LQ6kQ7DlGg.png" /></figure><p>Recently, I was implementing an alert feature using FCM in a Vite + React project.</p><p>My objective was to <strong>not expose the FCM API keys in the source code</strong> directly and make it work in both <strong>dev mode</strong> and <strong>build</strong>.</p><p>You can learn more about how FCM works <a href="https://firebase.google.com/docs/cloud-messaging/js/client">here</a>, and Vite’s characteristics <a href="https://vitejs.dev/guide/">here</a>.</p><h3>Attempt 1</h3><p>Since the FCM client SDK looks for a firebase-messaging-sw.js service worker file in the root level of the project, I naturally placed this file in the public folder.</p><pre>// public/firebase-messaging-sw.js<br><br>if (typeof importScripts === &quot;function&quot;) {<br>  importScripts(&quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js&quot;);<br>  importScripts(<br>    &quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js&quot;<br>  );<br><br>  const firebaseApp = firebase.initializeApp({<br>    apiKey: process.env.VITE_FCM_API_KEY,<br>    authDomain: process.env.VITE_FCM_AUTH_DOMAIN,<br>    projectId: process.env.VITE_FCM_PROJECT_ID,<br>    storageBucket: process.env.VITE_FCM_STORAGE_BUCKET,<br>    messagingSenderId: process.env.VITE_FCM_MESSAGING_SENDER_ID,<br>    appId: process.env.VITE_FCM_APP_ID,<br>    measurementId: process.env.VITE_FCM_MEASUREMENT_ID,<br>  });<br><br>  firebase.messaging(firebaseApp);<br><br>  self.addEventListener(&quot;install&quot;, () =&gt; {<br>    console.log(&quot;installed SW!&quot;);<br>  });<br>}</pre><p>However, import.meta.env or process.env is inaccessible here because service workers run in a different context to the main application. So, I created a custom Vite plugin with the help of the dotenv package. Upon bundling, this plugin simply finds the firebase-messaging-sw.js file and uses regex to replace “process.env.xyz” strings with its corresponding environment value.</p><pre>// config/vitePlugins.ts<br><br>import &quot;dotenv/config&quot;;<br><br>export function fcmSwEnvPlugin() {<br>  return {<br>    name: &quot;rollup-plugin-fcm-sw-env&quot;,<br>    transform(code: string, id: string) {<br>      if (id.endsWith(&quot;/firebase-messaging-sw.js&quot;)) {<br>        // Replace process.env variables with their actual values<br>        return code.replace(<br>          new RegExp(`process.env.(\\w+)`, &quot;g&quot;),<br>          (_, varName) =&gt; `&quot;${process.env[varName]}&quot;`<br>        );<br>      }<br>      return null;<br>    },<br>  };<br>}</pre><p>In <strong>dev mode</strong>, this worked in running the service worker but since it manipulates the file itself, the service worker file would end up containing hard-coded env values, which I would end up having to revert before pushing to the repo (terrible DX).</p><p>Also, when <strong>building for prod</strong>, Vite outputs contents in public as-is to dist. This means that the custom plugin doesn’t apply. So, the built service worker file would for example literally contain the string &quot;process.env.VITE_FCM_API_KEY”, which obviously doesn’t work. I could also have created a node script that does something similar to the above custom plugin and do &quot;build&quot;: &quot;node -env-file=.env scripts/fcmSw.js &amp;&amp; tsc &amp;&amp; vite build. But this would create a new file every time, which is suboptimal.</p><h3>Attempt 2</h3><p>I moved the service worker file into the src folder. Under src, Vite is able to treat this file as a module, allowing the use of import.meta.env to access environment variables. So, there is no need for the custom plugin in Attempt 1.</p><pre>// src/firebase-messaging-sw.js<br><br>if (typeof importScripts === &quot;function&quot;) {<br>  importScripts(&quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js&quot;);<br>  importScripts(<br>    &quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js&quot;<br>  );<br>  <br>  const firebaseApp = firebase.initializeApp({<br>    apiKey: import.meta.env.VITE_FCM_API_KEY,<br>    authDomain: import.meta.env.VITE_FCM_AUTH_DOMAIN,<br>    projectId: import.meta.env.VITE_FCM_PROJECT_ID,<br>    storageBucket: import.meta.env.VITE_FCM_STORAGE_BUCKET,<br>    messagingSenderId: import.meta.env.VITE_FCM_MESSAGING_SENDER_ID,<br>    appId: import.meta.env.VITE_FCM_APP_ID,<br>    measurementId: import.meta.env.VITE_FCM_MEASUREMENT_ID,<br>  });<br>  <br>  firebase.messaging(firebaseApp);<br><br>  self.addEventListener(&quot;install&quot;, () =&gt; {<br>    // eslint-disable-next-line no-console<br>    console.log(&quot;installed SW!&quot;);<br>  });<br>}</pre><p>Now, when <strong>building for prod</strong>, the service worker file ends up getting bundled together with the main application code and not in the root level where it should be. This was easily solvable by declaring two entry points and outputs in Vite config. So build is fine.</p><pre>// vite.config.ts<br><br>import react from &quot;@vitejs/plugin-react&quot;;<br>import { defineConfig } from &quot;vite&quot;;<br>import tsconfigPaths from &quot;vite-tsconfig-paths&quot;;<br><br>export default defineConfig({<br>  plugins: [react(), tsconfigPaths()],<br>  build: {<br>    target: &quot;es2022&quot;,<br>    rollupOptions: {<br>      input: {<br>        &quot;main&quot;: &quot;./index.html&quot;,<br>        &quot;firebase-messaging-sw&quot;: &quot;./src/firebase-messaging-sw.js&quot;,<br>      },<br>      output: {<br>        entryFileNames: (chunkInfo) =&gt; {<br>          return chunkInfo.name === &quot;firebase-messaging-sw&quot;<br>            ? &quot;[name].js&quot; // Output service worker in root<br>            : &quot;assets/[name]-[hash].js&quot;; // Others in `assets/`<br>        },<br>      },<br>    },<br>  },<br>});</pre><p>However, in <strong>dev mode</strong>, there is now an issue with the service worker path. The FCM client SDK attempts GET /firebase-messaging-sw.js. But now it’s being served in /src/firebase-messaging-sw.js, leading to a 404 Error.</p><p>To tackle this, I tried using Vite’s server.proxy config to proxy GET /firebase-messaging-sw.js to /src/firebase-messaging-sw.js. But this resulted in the error: Uncaught SyntaxError: Cannot use &#39;import.meta&#39; outside a module (at firebase-messaging-sw.js:1:8).</p><h3>Solution</h3><p>I ended up with a solution that combines and improves on Attempt 1 and Attempt 2.</p><p>The <strong>prod build</strong> remains unchanged as Attempt 2.</p><p>For <strong>dev mode</strong>, I created a custom plugin that uses the fs node module to read the service worker file, replace the “import.meta.xyz” strings to their corresponding values, and then writes a separate file public/firebase-messaging-sw.js. This file solely exists for dev purposes so I made sure to only run the plugin in dev mode and added it to .gitignore.</p><p><em>p.s. reading the file using node directly instead of rollup allows us to avoid tree-shaking. Otherwise, we would have to manually import the service worker file somewhere in the main application to avoid tree-shaking of the service worker file.</em></p><p><strong>The final code:</strong></p><pre>// vite.config.ts<br><br>import react from &quot;@vitejs/plugin-react&quot;;<br>import { defineConfig } from &quot;vite&quot;;<br>import tsconfigPaths from &quot;vite-tsconfig-paths&quot;;<br>import { fcmSwEnvPlugin } from &quot;./config/vitePlugins&quot;;<br><br>export default defineConfig(({ command }) =&gt; {<br>  if (command === &quot;serve&quot;) {<br>    return {<br>      plugins: [react(), tsconfigPaths(), fcmSwEnvPlugin()],<br>    };<br>  } else {<br>    // command === &#39;build&#39;<br>    return {<br>      plugins: [react(), tsconfigPaths()],<br>      build: {<br>        target: &quot;es2022&quot;,<br>        rollupOptions: {<br>          input: {<br>            &quot;main&quot;: &quot;./index.html&quot;,<br>            &quot;firebase-messaging-sw&quot;: &quot;./src/firebase-messaging-sw.js&quot;,<br>          },<br>          output: {<br>            entryFileNames: (chunkInfo) =&gt; {<br>              return chunkInfo.name === &quot;firebase-messaging-sw&quot;<br>                ? &quot;[name].js&quot; // Output service worker in root<br>                : &quot;assets/[name]-[hash].js&quot;; // Others in `assets/`<br>            },<br>          },<br>        },<br>      },<br>    };<br>  }<br>});</pre><pre>// config/vitePlugins.ts<br><br>import &quot;dotenv/config&quot;;<br>import fs from &quot;fs&quot;;<br>import path from &quot;path&quot;;<br>import { fileURLToPath } from &quot;url&quot;;<br><br>export function fcmSwEnvPlugin() {<br>  const __filename = fileURLToPath(import.meta.url);<br>  const __dirname = path.dirname(__filename);<br><br>  const srcDir = path.resolve(__dirname, &quot;../src&quot;);<br>  const fcmSwCode = fs.readFileSync(<br>    `${srcDir}/firebase-messaging-sw.js`,<br>    &quot;utf8&quot;<br>  );<br><br>  const transformedCode = fcmSwCode.replace(<br>    new RegExp(`import.meta.env.(\\w+)`, &quot;g&quot;),<br>    (_, varName) =&gt; `&quot;${process.env[varName]}&quot;`<br>  );<br>  const finalCode =<br>    &quot;// IMPORTANT: This file only exists for dev mode purposes. Do not modify this file. Any changes should be made in `src/firebase-messaging-sw.js`.\n\n&quot; +<br>    transformedCode;<br><br>  const outputPath = path.resolve(&quot;public&quot;, &quot;./firebase-messaging-sw.js&quot;);<br>  fs.writeFileSync(outputPath, finalCode);<br><br>  return {<br>    name: &quot;rollup-plugin-fcm-sw-env&quot;,<br>  };<br>}</pre><pre>// src/firebase-messaging-sw.js<br><br>if (typeof importScripts === &quot;function&quot;) {<br>  importScripts(&quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js&quot;);<br>  importScripts(<br>    &quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js&quot;<br>  );<br><br>  const firebaseApp = firebase.initializeApp({<br>    apiKey: import.meta.env.VITE_FCM_API_KEY,<br>    authDomain: import.meta.env.VITE_FCM_AUTH_DOMAIN,<br>    projectId: import.meta.env.VITE_FCM_PROJECT_ID,<br>    storageBucket: import.meta.env.VITE_FCM_STORAGE_BUCKET,<br>    messagingSenderId: import.meta.env.VITE_FCM_MESSAGING_SENDER_ID,<br>    appId: import.meta.env.VITE_FCM_APP_ID,<br>    measurementId: import.meta.env.VITE_FCM_MEASUREMENT_ID,<br>  });<br><br>  firebase.messaging(firebaseApp);<br><br>  self.addEventListener(&quot;install&quot;, () =&gt; {<br>    console.log(&quot;installed SW!&quot;);<br>  });<br>}</pre><pre>// .gitignore<br><br># FCM (this file is only used for dev mode purposes)<br>public/firebase-messaging-sw.js</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8deccfc23fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array ft. V8]]></title>
            <link>https://medium.com/@daeram.chung/array-ft-v8-a2ad2ee4b6af?source=rss-bdae4e62d6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2ad2ee4b6af</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[v8]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kakamotobi]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 07:24:37 GMT</pubDate>
            <atom:updated>2024-02-25T07:24:37.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*IZglYn68e4wgAGhnkLM2-Q.png" /></figure><h3>Table of Contents</h3><ul><li><a href="#c9af">Array</a><br>- <a href="#8e49">Array Big O</a></li><li><a href="#02c9">Arrays in JS ft. V8</a><br>- <a href="#d21e">JS Array Big O</a><br>- <a href="#9f58">JS Array Internals in V8</a></li><li><a href="#0770">Reference</a></li></ul><h3>Array</h3><p>A collection of items, which can each be identified by their index.</p><p>Items in an array are of the same size and type and are <strong>contiguous</strong> in terms of memory address (making them dense), which allows the use of indices for random access at time complexity of O(1).</p><pre>Target Item&#39;s Memory Address = <br>  Start of the Array&#39;s Memory Address +<br>  Index * Item Size in Bytes</pre><p>For example, if the array’s memory address starts at 1000, and each item is 8 bytes in size, the fifth item’s memory address is 1000 + 4 * 8 = 1040.</p><h4>Array Big O</h4><p>An “array” is just a data structure that has to meet the below Big O requirements. The specific implementation of it in a language/engine can differ.</p><ul><li>Access: O(1)<br>- Random access through indices.</li><li>Search: O(n)</li><li>Append: O(1)</li><li>Prepend: O(n)<br>- Items need to be shifted to keep the array contiguous.</li><li>Insert: O(n)<br>- Items need to be shifted to keep the array contiguous.</li><li>Delete: O(n)<br>- Items need to be shifted to keep the array contiguous.</li></ul><h3>Arrays in JS ft. V8</h3><p>A JavaScript array is a bit different from the “traditional” array.</p><p>Executing the below command reveals that a JS array is implemented using an ordered map, where the keys are the indices starting from 0. It also has a length property.</p><pre>Object.getOwnPropertyDescriptors([1,2,3]);</pre><pre>{<br>  0: { value: 1, writable: true, enumerable: true, configurable: true },<br>  1: { value: 2, writable: true, enumerable: true, configurable: true },<br>  2: { value: 3, writable: true, enumerable: true, configurable: true },<br>  length: { value: 3, writable: true, enumerable: false, configurable: false }<br>}</pre><ul><li><strong>Since a map is used underneath, items do not have to be the same size or type. They also do not need to be contiguous (allowing them to be sparse)</strong>.</li><li>Items are located by a key and not by an offset.</li></ul><h4>JS Array Big O</h4><ul><li>Access: O(1)<br>- Can be slower than a traditional array since it uses a map (indices are property keys).</li><li>Search: O(n)</li><li>Append: Amortized O(1)<br>- Resizing the array may be needed.</li><li>Prepend: O(n)<br>- Array.prototype.unshift reassigns all the indices.</li><li>Insert: O(1) or O(n)<br>- O(1) if the index is not already occupied.<br>- O(n) if the index is already occupied. Array.prototype.splice reassigns indices.</li><li>Delete: O(1) or O(n)<br>- O(1) if only removing the value.<br>- O(n) if also reassigning indices using Array.prototype.splice.</li></ul><h4>JS Array Internals in V8</h4><p>Let’s take a look at how V8 manages array memory location.</p><p>In the terminal, open up a node REPL using node --allow-natives-syntax.</p><ul><li>--allow-natives-syntax allows us to use internal V8 functionalities, which are invalid JS, such as %DebugPrint() from within JS.</li></ul><p><strong>Empty Array</strong></p><pre>&gt; const arr = []; // []<br>&gt; %DebugPrint(arr);</pre><pre>DebugPrint: 0x2e72c5501e41: [JSArray]<br> ...<br> - elements: 0x2e72d0d01329 &lt;FixedArray[0]&gt; [PACKED_SMI_ELEMENTS]<br> - length: 0<br> ...</pre><ul><li>0x2e72d0d01329 is the memory address of the internal data structure representing the array.</li><li>&lt;FixedArray[0]&gt; indicates this structure is a FixedArray with 0 elements.<br>- These are just types of data structures that are used by V8 internally for optimization purposes.</li><li>[PACKED_SMI_ELEMENTS] indicates the type of the elements in the array.<br>- PACKED refers to whether the array is dense or sparse.<br>- SMI stands for small integer (there are more types that are used internally).<br>- There are more types and they are used by V8 internally for optimization purposes.</li><li>V8 makes optimizations based on an array’s size, the types of elements, etc.</li></ul><p><strong>Small and Packed Array</strong></p><p>Example 1</p><pre>&gt; const arr = [0]; // [0]<br>&gt; %DebugPrint(arr);</pre><pre>DebugPrint: 0x335162b960a1: [JSArray] in OldSpace<br> ...<br> - elements: 0x335162b8b879 &lt;FixedArray[1]&gt; [PACKED_SMI_ELEMENTS (COW)]<br> - length: 1<br> ...<br> - elements: 0x1d151964b879 &lt;FixedArray[1]&gt; {<br>           0: 0<br> }<br> ...</pre><p>Example 2</p><pre>&gt; const arr = [];<br>&gt; arr[0] = 0; // or `arr.push(0)` // [0]<br>&gt; %DebugPrint(arr);</pre><pre>DebugPrint: 0x205177214bf1: [JSArray] in OldSpace<br> ...<br> - elements: 0x0c8ad3a92351 &lt;FixedArray[17]&gt; [PACKED_SMI_ELEMENTS]<br> - length: 1<br> ...<br> - elements: 0x0c8ad3a92351 &lt;FixedArray[17]&gt; {<br>           0: 0<br>        1-16: 0x0ec1133c1689 &lt;the_hole&gt;<br> }<br> ...</pre><ul><li>arr starts off as &lt;FixedArray[0]&gt; [PACKED_SMI_ELEMENTS] but then, after doing arr[0] = 0, the array’s type becomes &lt;FixedArray[17]&gt;.</li><li>It seems V8 gave some extra space despite adding just one element into an empty array.</li></ul><p><strong>Small and Holey Array</strong></p><pre>&gt; const arr = [];<br>&gt; arr[1023] = 1023; // [&lt;1023 empty items&gt;, 1023]<br>&gt; %DebugPrint(arr);</pre><pre>DebugPrint: 0x2e72c5509331: [JSArray]<br> ...<br> - elements: 0x2e72c5511131 &lt;FixedArray[1552]&gt; [HOLEY_SMI_ELEMENTS]<br> - length: 1024<br> ...<br> - elements: 0x2e72c5511131 &lt;FixedArray[1552]&gt; {<br>      0-1022: 0x2e72d0d01689 &lt;the_hole&gt;<br>        1023: 1023<br>   1024-1551: 0x2e72d0d01689 &lt;the_hole&gt;<br> }<br> ...</pre><ul><li>A relatively small array that is sparse has a type of FixedArray with HOLEY_ELEMENTS.</li><li>We can also see that V8 allocated some extra memory space again (for indices 1024–1551).</li></ul><p><strong>Large and Packed Array</strong></p><pre>&gt; const arr = [];<br>&gt; for (let i = 0; i &lt;= 1024; i++) arr[i] = i; // [0, 1, 2, ..., 1024]<br>&gt; %DebugPrint(arr);</pre><pre>DebugPrint: 0x2e721ad45039: [JSArray] in OldSpace<br> ...<br> - elements: 0x2e72e1741131 &lt;FixedArray[1289]&gt; [PACKED_SMI_ELEMENTS]<br> - length: 1025<br> ...<br> - elements: 0x2e72e1741131 &lt;FixedArray[1289]&gt; {<br>           0: 0<br>           1: 1<br>           ...<br>        1024: 1024<br>   1025-1288: 0x2e72d0d01689 &lt;the_hole&gt;<br> }<br> ...</pre><ul><li>A dense array remains a FixedArray even if the the array gets large.</li></ul><p><strong>Large and Very Holey Array</strong></p><pre>&gt; const arr = [];<br>&gt; arr[1024] = 1024; // [&lt;1024 empty items&gt;, 1024]<br>&gt; %DebugPrint(arr);</pre><pre>DebugPrint: 0x2e72c5509359: [JSArray]<br> ...<br> - elements: 0x2e72c55095c9 &lt;NumberDictionary[16]&gt; [DICTIONARY_ELEMENTS]<br> - length: 1025<br> ...<br> - elements: 0x2e72c55095c9 &lt;NumberDictionary[16]&gt; {<br>   - max_number_key: 1024<br>   1024: 1024 (data, dict_index: 0, attrs: [WEC])<br> }<br> ...</pre><ul><li>It seems when the array is large enough but more importantly, the array is “very holey”, V8 transitioned from a FixedArray to a NumberDictionary.</li></ul><p><strong>Large and Kind of Holey Array</strong></p><pre>&gt; const arr = [];<br>&gt; for (let i = 0; i &lt;= 1024; i++) {<br>    if (i % 5 === 0) {<br>      arr[i] = i<br>    }<br>  } // [0, &lt;4 empty items&gt;, 5, &lt;4 empty items&gt;, 10, ... 1020, &lt;4 empty items&gt;]<br>&gt; %DebugPrint(arr);</pre><pre>DebugPrint: 0x3824826a0d71: [JSArray] in OldSpace<br> ...<br> - elements: 0x17eade611131 &lt;FixedArray[1472]&gt; [HOLEY_SMI_ELEMENTS]<br> - length: 1021<br> ...<br> - elements: 0x17eade611131 &lt;FixedArray[1472]&gt; {<br>           0: 0<br>         1-4: 0x2f773fb41689 &lt;the_hole&gt;<br>           5: 5<br>         6-9: 0x2f773fb41689 &lt;the_hole&gt;<br>          10: 10<br>           ...<br>   1016-1019: 0x2f773fb41689 &lt;the_hole&gt;<br>        1020: 1020<br>   1021-1471: 0x2f773fb41689 &lt;the_hole&gt;<br> }<br> ...</pre><ul><li>On the other hand, when the array is large but it is only “kind of holey”, it remains a FixedArray.</li></ul><h3>Reference</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fm9cTaYI95Zc%3Fstart%3D132%26feature%3Doembed%26start%3D132&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dm9cTaYI95Zc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fm9cTaYI95Zc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/65a1e65628f624e331f00256a246e4e9/href">https://medium.com/media/65a1e65628f624e331f00256a246e4e9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2ad2ee4b6af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auth Series 2: Auth Attacks and Mitigations]]></title>
            <link>https://medium.com/@daeram.chung/auth-series-2-auth-attacks-and-mitigations-08271bbd2f41?source=rss-bdae4e62d6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/08271bbd2f41</guid>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Kakamotobi]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 15:43:28 GMT</pubDate>
            <atom:updated>2024-02-22T16:36:30.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*5K3ItlBfJ__0n8sCtDuJwg.gif" /></figure><h3>Table of Contents</h3><ul><li><a href="#5024">Before Reading</a></li><li><a href="#6bf9">Common Types of Attacks</a><br>- <a href="#22f6">Cross-Site Scripting(XSS) Attacks</a><br>- <a href="#bc44">Cross-Site Request Forgery(CSRF) Attacks</a></li><li><a href="#8106">Storing Tokens for Token-based Authentication</a><br>- <a href="#edc6">LocalStorage and Authorization Header</a><br>- <a href="#ebf6">Cookies</a><br>- <a href="#a079">Verdict</a></li><li><a href="#63a8">OIDC Attack Mitigations</a><br>- <a href="#f0a5">Authorization Code Grant Type</a><br>- <a href="#d12a">Authorization Code Interception Attack ft. Proof Key for Code Exchange(PKCE)</a><br>- <a href="#2eb6">CSRF Attack ft. </a><a href="#2eb6">state</a><br>- <a href="#1ecf">ID Token Validity and Authorization Code Injection Attack ft. </a><a href="#1ecf">nonce</a><br>- <a href="#ccaf">Full Picture</a></li><li><a href="#4029">Wrapping Up</a></li><li><a href="#52f2">References</a></li></ul><h3>Before Reading</h3><p><em>This article merely provides some starting points in auth attack mitigation. It is not intended to diagnose and consider every nooks and crannies. There is no once and for all prevention as it also depends on the particular case, and as such, this article is inadequate.</em></p><h3>Common Types of Attacks</h3><h4>Cross-Site Scripting(XSS) Attacks</h4><p><strong>An injection of malicious script into the source code of the trusted web application, which the user/browser receives and executes unknowingly.</strong></p><p>It originally referred to stealing data cross-site. Now, it refers to injection of any content.</p><p><strong>XSS Attack Objective:</strong></p><ul><li>Stealing sensitive information (Ex: cookies, tokens, any information retained by the browser and used in that site).</li><li>Altering the UI to trick users into unwanted actions.</li><li>Injecting malware in the website.</li></ul><p><strong>Some Ways to Initiate XSS Attacks:</strong></p><ul><li>A sketchy package that a developer unknowingly installed in node_modules — directly in the source code to begin with (Ex: typosquatting).</li><li>A developer knowingly includes malicious script in the source code (Ex: corporate spy).</li><li>The website includes third-party content that is malicious (Ex: ads, widgets).</li><li>An attacker may attempt to upload malicious script into input fields in the hopes that the server doesn’t validate the input and when the server serves that resource to the browser to be displayed, the malicious script gets executed by the browser.</li><li>The user’s computer/browser is hacked to begin with — allowing the attacker to run whatever script they want.</li></ul><p><strong>Mitigations</strong></p><p>The objective in XSS mitigation revolves around <strong>preventing insertion and execution of malicious content</strong>. Therefore, all variables (Ex: user input) in a web application should be <strong>sanitized and validated</strong> — especially ones that are responded back to the user.</p><ul><li>Output Encoding<br>- Use to safely display the exact data that the user types in.<br>- There are various output encodings since browsers parses HTML, CSS, JS, URLs differently.</li><li>HTML Sanitization<br>- Strip dangerous HTML from a variable and return a safe HTML string.<br>- Use in cases such as WYSIWYG editors where output encoding breaks intended functionality of the application.</li></ul><p>More information on XSS types <a href="https://owasp.org/www-community/Types_of_Cross-Site_Scripting">here</a>.<br>More information on XSS prevention <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html">here</a>.</p><h4>Cross-Site Request Forgery(CSRF) Attacks</h4><p><strong>An attack where a user is unknowingly forced to execute unwanted actions on a web application that they are currently authenticated.</strong></p><p>Browser requests usually include credentials (Ex: session data, token). Therefore, the web application cannot distinguish between a legitimate request intended by the user and the forged request.</p><p><strong>CSRF Attack Objective:</strong></p><ul><li><strong>The CSRF attacker cannot view the response to the forged request. The attacker’s objective is to simply send a forged request by taking advantage of the user’s authentication status</strong> such as changing authentication details, make a transaction, etc.</li><li><strong>In the case of login CSRF, a non-authenticated user is forced to log in to the attacker’s account on the web application</strong>. Thereby, the user may unknowingly add private information (Ex: address, credit card information) to that account. The attacker can access this by simply logging in to their account.</li></ul><p><strong>Some Ways to Initiate CSRF Attacks:</strong></p><ul><li>Build an exploit URL or script. Then, trick the victim into executing the action with social engineering.</li><li><strong>Example 1</strong><br>- Exploit URL: GET http://mybank.com/transfer?receivingAcc=attackerAcc&amp;amount=9999<br>- An email with an HTML content that has a link connected to the exploit URL (&lt;a href=&quot;<a href="http://mybank.com/transfer">http://mybank.com/transfer</a>?receivingAcc=attackerAcc&amp;amount=9999&quot;&gt;Your AWS bill is skyrocketing! Check your bills right now!&lt;/a&gt;). If the victim clicks on this, they unknowingly send this transfer request to mybank.com’s server.</li><li><strong>Example 2</strong><br>- Exploit URL: POST http://mybank.com/transfer , where receivingAcc and amount are sent in the body.<br>- A form tag with hidden inputs disguised as a link, which when clicked, sends the forged transfer request to mybank.com.</li></ul><pre>&lt;form&gt;<br>  &lt;input type=&quot;hidden&quot; name=&quot;receivingAcc&quot; value=&quot;attackerAcc&quot; /&gt;<br>  &lt;input type=&quot;hidden&quot; name=&quot;amount&quot; value=&quot;9999&quot; /&gt;<br>  &lt;button type=&quot;submit&quot;&gt;Your AWS bill is skyrocketing! Check your bills right now!&lt;/button&gt;<br>&lt;/form&gt;</pre><p><strong>Mitigation</strong></p><ul><li>Use CSRF tokens (whether built-in in the framework or self-implemented if not provided)to all state changing requests and validate them on the server.<br>- By generating CSRF tokens once per user session or per request, you can minimize the time range in which attackers can exploit a stolen token.</li><li>For stateful applications (i.e. server-side session storage), use the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#synchronizer-token-pattern">synchronizer token pattern</a>.</li><li>For stateless applications (i.e. no server-side session storage), use <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#alternative-using-a-double-submit-cookie-pattern">double submit cookies</a>.</li></ul><p><em>Note</em></p><ul><li><em>Successful XSS attacks can undermine CSRF mitigations since these injected scripts can access the user’s session and cookies, allowing them to bypass the CSRF protections. For example, the stolen CSRF token can be embedded into a forged request, thereby deceiving the server as a valid request.</em></li></ul><p>More information on CSRF prevention <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html">here</a>.</p><h3>Storing Tokens for Token-based Authentication</h3><p>Auth tokens need to be stored somewhere in the user’s device in order to persist user login status.</p><p>The controversial topic of where to store auth tokens can be tricky since each client-side storage option (Ex: LocalStorage, Cookies) has its vulnerabilities and considerations.</p><h4>LocalStorage ft. Authorization Header</h4><p>The combination of LocalStorage and Authorization Header involves storing the Access Token and Refresh Token in LocalStorage, and including the Access Token in the Authorization Header in requests using the Bearer auth scheme.</p><p>LocalStorage is a storage API that persists even when the user closes the browser — allowing persistent authentication (as long as the token is valid). It is sandboxed so that one website cannot access that of another website. Even subdomains of the same domain have sandboxed storage.</p><p>However, since <strong>LocalStorage can be read and manipulated by JavaScript, it is completely vulnerable to successful XSS attacks</strong>. Once an attacker successfully injects a malicious script, the attacker is able to steal the stored tokens (localStorage.getItem()). They can also load malicious data into these entries (localStorage.setItem()). Additionally, a malicious person with access to the victim’s device can easily view these items. Therefore, it is advised to not store sensitive information in LocalStorage.</p><h4>Cookies</h4><p>The use of Cookies often seems to be overlooked in token-based authentication as they are prevalently used in traditional session-based authentications.</p><p>A Cookie is merely another HTTP header that is received from the Server and automatically sent back on subsequent requests to the Server.</p><p>Using Cookies with appropriate flags can help mitigate the risk of token theft.</p><ul><li>HttpOnly<br>- Blocks JavaScript from accessing the Cookie, in effect, mitigating XSS attacks that attempt to steal the token.</li><li>Secure<br>- The Cookie is sent to the Server only when the request has been made on HTTPS, preventing MitM attacks.</li></ul><p>With the HttpOnly and Secure flags, a successful XSS attacker is not able to steal the token but they are still able to send requests disguised as the authenticated user. They can just send a forged request to the server since the Cookie is sent automatically. This means that the victim is still vulnerable to a CSRF attack.</p><ul><li>SameSite=strict<br>- The browser will only send the Cookie for same-site requests (requests originating from the same site that set the Cookie). This provides some protection against CSRF attacks and limits the attacker to onsite attacks as they cannot send the Cookie to another website.</li></ul><h4>Verdict</h4><p>Since the Access Token grants permission for state changes, the risk and consequence of exposing it is grave. Therefore, it seems wise to use Cookies with appropriate flags as the means of storage/transport as opposed to storing it in LocalStorage.</p><p>Concerning Refresh Tokens, the consequence of exposing it is less grave (although it should not be disregarded). Storing Refresh Tokens in LocalStorage and using the Authorization Header to send it to the Server could be acceptable. As mentioned above, the main issue with LocalStorage is that XSS could steal the Token. This stolen Refresh Token can be exploited to do what the Refresh Token can do: extend the victim’s login session. However, the same can be done even if the Refresh Token is stored in Cookies with the HttpOnly flag as well.</p><h3>OIDC Attack Mitigations</h3><p>When it comes to <a href="https://medium.com/@daeram.chung/auth-series-1-basics-of-auth-e2720e6c916a#7003">OAuth</a> and <a href="https://medium.com/@daeram.chung/auth-series-1-basics-of-auth-e2720e6c916a#2767">OIDC</a>, there are also some security vulnerabilities and measures to consider. I will only go over OIDC (the Authorization Code Grant flow in particular) but it also generally applies to OAuth.</p><h4>Authorization Code Grant Type</h4><p>Let’s go over the Authorization Code Grant type first. Upon a user providing successful credentials, the OpenID Provider responds an Authorization Code. This Auth Code is then exchanged for Access and ID Tokens. <strong>This code exchange adds an extra layer of security since it is done via a backchannel between your Server application and the OpenID Provider.</strong> In other words, the Tokens only travel directly between your Server and the OpenID Provider.</p><p>Below is an illustration of the Authorization Code Grant type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4FNGoDDwbBZpKRXPe5t5g.png" /><figcaption><a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1">https://datatracker.ietf.org/doc/html/rfc6749#section-4.1</a></figcaption></figure><h4>Authorization Code Interception Attack ft. Proof Key for Code Exchange(PKCE)</h4><p>But before the actual exchange for tokens, your Server application uses the browser as an intermediary to receive the Auth Code once the user provides successful credentials. This potentially leaves the Auth Code vulnerable to interception.</p><p><strong>Authorization Code Interception Attack refers to an attacker stealing an Auth Code, which they can then attempt to exchange it for tokens.</strong></p><p>For an Authorization Code Interception Attack to work, the following preconditions have to be met:</p><ul><li>The attacker registers a malicious app on the victim’s device and a custom URI scheme used by a target application. The OS must allow multiple applications to register the same custom URI scheme.</li><li>The Authorization Code Grant type is used.</li><li>The attacker has access to the client_id and client_secret.</li><li>The malicious app is able to observe only the responses from the authorization endpoint (code_challenge_method=plain mitigates this) OR the malicious app is able to observe both requests and responses to the authorization endpoint (code_challenge_method=S256 mitigates this).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*NU5W4XhRFBvvRMDThp4ZCQ.png" /><figcaption><a href="https://datatracker.ietf.org/doc/html/rfc7636">https://datatracker.ietf.org/doc/html/rfc7636</a></figcaption></figure><ul><li>Step (1) occurs over a secure API that cannot be intercepted.</li><li>Step (2) and Step (3) occurs over TLS, as required by OAuth, and cannot be intercepted.</li><li>In Step (4) the requester received the Auth Code.<br>- This is where a malicious app that was successfully registered may be able to intercept the Auth Code.</li><li>The attacker then proceeds to exchange the stolen Auth Code for tokens in Steps (5) and (6).</li></ul><p>The objective in mitigating Authorization Code Interception Attacks is to <strong>verify whether the User Agent that is requesting to exchange it for tokens is indeed the same User Agent that requested the Auth Code in the first place</strong>.</p><p>This is where <strong>PKCE</strong> comes in. <strong>PKCE addresses the question of whether a request to exchange an Auth Code for tokens is legitimate or not. </strong>The flow goes as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*UIMIlZn1hDB4mccX0A5pQA.png" /><figcaption><a href="https://datatracker.ietf.org/doc/html/rfc7636#section-1.1">https://datatracker.ietf.org/doc/html/rfc7636#section-1.1</a></figcaption></figure><ul><li>The OpenID Client (your server application) generates a random unique secret called the <strong>Code Verifier</strong>, and a one-way hashed version of it called the <strong>Code Challenge</strong>.<br>- The Code Verifier is unique for every individual authorization request.</li><li>The OpenID Client includes the Code Challenge in the request for the Authorization Code.</li><li>The OpenID Client includes the Code Verifier in the request to exchange the Auth Code for Tokens.</li><li>The OpenID Provider <strong>verifies the Code Verifier against the Code Challenge that it received before to check if the User Agents that initiated these two requests are the same</strong>. Only then, the OpenID Provider can be confident in issuing the tokens.</li></ul><p><strong>This works since the attacker would not know this unique one-time Code Verifier sent over TLS (cannot be intercepted).</strong></p><p><em>The OpenID Client generates the Code Verifier and Code Challenge, and the OpenID Provider verifies.</em></p><h4>CSRF Attack ft. `state`</h4><p>As mentioned <a href="#bc44">above</a>, CSRF attacks attempt to make a victim unknowingly perform some action by taking advantage of the victim’s authentication state.</p><p>The objective in mitigating CSRF attacks in the context of authentication is to <strong>bind the authentication request sent by the OpenID Client with the authentication response sent by the OpenID Provider, in effect creating a short-lived “session”, which the OpenID Client can protect itself.</strong></p><p>The <strong>state parameter</strong>, a.k.a. CSRF Token, is a random unique string that should only be used once. The flow goes as follows:</p><ul><li>The OpenID Client generates the state value and includes it in the request for the Authorization Code.</li><li>The OpenID Provider includes that state value in the Redirect URI as a parameter.</li><li>The OpenID Client <strong>verifies that the </strong><strong>state value that it received is indeed the same as the one that it had sent</strong>.<br>- If the state value is different, it is an unsolicited authentication response that was not initiated by the victim, or the OpenID Provider’s response has been tampered with.</li></ul><p><em>The OpenID Client generates and verifies the </em><em>state parameter.</em></p><h4>ID Token Validity and Authorization Code Injection Attack ft. `nonce`</h4><p>The <strong>nonce parameter</strong> is optional but adds an extra layer of protection. It is a string value that <strong>binds the ID Token with the authentication request and helps mitigate Authorization Code Injection Attacks against the OpenID Client (not the OpenID Provider)</strong>.</p><p>The flow goes as follows:</p><ul><li>The OpenID Client generates the nonce value and includes it in the request for the Authorization Code.</li><li>The OpenID Provider later includes that nonce value in the ID Token as a claim.</li><li>The OpenID Client <strong>verifies that the </strong><strong>nonce value that is in the ID Token is indeed the same as the one that it had sent.</strong><br>- The OpenID Client should not use the ID Token before checking the nonce value.</li></ul><p><strong>ID Token Validity</strong></p><ul><li>Is the received ID Token indeed a response to the specific authentication request that was made?</li><li>If the nonce value is different, the ID Token may be a result of an unsolicited authentication request or may have been tampered with. Hence, the ID Token (and the Access Token) should be deemed invalid and rejected.</li></ul><p><strong>Authorization Code Injection Attack</strong></p><ul><li><strong>Authorization Code Injection Attack refers to an attacker attempting to inject a stolen Auth Code into their own session with the OpenID Client</strong>. The objective is to associate their session at the OpenID Client with the victim’s resources/identity to gain access to the victim’s resources.</li><li>Since a nonce value is unique to each authentication request, <strong>if an attacker injected an Auth Code in the authentication response, the </strong><strong>nonce values in the OpenID Client session (attacker’s </strong><strong>nonce value) and the ID Token (victim’s </strong><strong>nonce value since victim’s Auth Code was used) will not match</strong>.<br>- This assumes that the attacker is not able to get hold of the nonce value on the victim’s device where the attacker had stolen the Auth Code.</li><li>If the nonce value is different, the OpenID Client will disregard both the ID Token and Access Token, and abort the authentication process.</li></ul><p><strong>This works since the attacker would not be able to forge the </strong><strong>nonce value.</strong></p><p><em>The OpenID Client generates and verifies the </em><em>nonce value.</em></p><p><strong>nonce vs PKCE</strong></p><p>Can nonce be used instead of PKCE? No, because the moment the protection occurs is different. Without PKCE, an attacker with a stolen Auth Code can exchange it for tokens. They don’t have to care for the nonce value since that happens once the tokens are already issued. With PKCE, an attacker would have to get hold of the Code Verifier (and the hashing algorithm used to hash the Code Challenge) before tokens are even issued. nonce is checked by the OpenID Client as the “last layer of extra protection” after the tokens have already been issued.</p><h4>Full Picture</h4><p>Below is an illustration adopting all three layers (PKCE, state, nonce) of security over OIDC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*xS2PNfBEFci-H12Dgjvtzw.png" /></figure><h3>Wrapping Up</h3><p>Web security vulnerabilities are very much interconnected and handling just one does not guarantee overall security of your application. Therefore, it is important to implement multiple layers of protection in order to mitigate attacks as much as possible.</p><h3>References</h3><ul><li><a href="https://owasp.org/www-community/attacks/xss/">Cross Site Scripting (XSS) | OWASP Foundation</a></li><li><a href="https://owasp.org/www-community/attacks/csrf">Cross Site Request Forgery (CSRF) | OWASP Foundation</a></li><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html?source=post_page-----943fb23239ca--------------------------------#local-storage">HTML5 Security - OWASP Cheat Sheet Series</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc6265">RFC 6265: HTTP State Management Mechanism</a></li><li><a href="https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-11">OAuth 2.0 Security Best Current Practice</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc6819#section-4.4.1.8">RFC 6819: OAuth 2.0 Threat Model and Security Considerations</a></li><li><a href="https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth">OpenID Connect Core 1.0 incorporating errata set 2</a></li><li><a href="https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#section-4.5">OAuth 2.0 Security Best Current Practice</a></li><li><a href="https://auth0.com/docs/secure/attack-protection/state-parameters">Prevent Attacks and Redirect Users with OAuth 2.0 State Parameters</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08271bbd2f41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auth Series 1: Basics of Auth]]></title>
            <link>https://medium.com/@daeram.chung/auth-series-1-basics-of-auth-e2720e6c916a?source=rss-bdae4e62d6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2720e6c916a</guid>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Kakamotobi]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 14:32:34 GMT</pubDate>
            <atom:updated>2024-02-15T16:37:28.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*yLIH3YSjM96twUHa3DWtdA.jpeg" /></figure><h3>Table of Contents</h3><ul><li><a href="#ddbb">Before Reading</a></li><li><a href="#20b4">Prerequisites</a><br>- <a href="#91de">HTTP is Stateless</a><br>- <a href="#c90c">Authentication vs Authorization</a></li><li><a href="#68d6">Authentication</a><br>- <a href="#547a">Session-based Authentication</a><br>- <a href="#7cd5">Token-based Authentication</a></li><li><a href="#7003">Authorization — OAuth2.0</a></li><li><a href="#2767">Authentication — OpenID Connect</a></li><li><a href="#0067">References</a></li></ul><h3>Before Reading</h3><ul><li><em>The terms used in this article (and in the programming world in general) and what they refer to really depend on the involved parties. So try to keep the context in mind! For example, “client” could mean User-Agent (Ex: browser) or an OAuth Client.</em></li></ul><h3>Prerequisites</h3><h4>HTTP is Stateless</h4><p>HTTP is stateless since every single request that a Server receives is independent from one another. In other words, a single HTTP connection starts with a Request and immediately ends with a Response. So, the Server doesn’t remember the client.</p><h4>Authentication vs Authorization</h4><p>Authentication and Authorization have fundamentally different objectives.</p><p><strong>Authentication:</strong> The process of verifying whether or not a user is in fact who they claim to be.</p><p><strong>Authorization:</strong> The process of verifying whether or not a user has access to what they are trying to access, and thereby delegate this access.</p><p><strong>Opinion</strong></p><ul><li>I think we tend to confuse between Authentication and Authorization because both involve providing credentials to verify yourself as the user.</li><li>But strictly speaking, verifying yourself to login to a particular application is Authentication. And, verifying yourself to allow a third-party to access a particular resource or enable some action on behalf of you is Authorization.<br>- Authentication — “I am verifying that I am the rightful owner of this account.”<br>- Authorization — “I am verifying that I am the rightful owner of this account (and I am allowing this third-party application access to my resources).”</li></ul><h3>Authentication</h3><p>As mentioned <a href="#91de">above</a>, HTTP is stateless.</p><p>This raises the question: <strong>How do you allow stateful sessions in a stateless protocol? In other words, how do we maintain a user’s login state?</strong></p><p>In order to maintain a user’s login state, there needs to be a way for the client to identify itself and the server to verify that the client is indeed logged in on every request.</p><p>There are two main ways to achieve this: <strong>Session-based Authentication </strong>and <strong>Token-based Authentication</strong>.</p><h4>Session-based Authentication</h4><p>Session-based Authentication is the more traditional method that was used prior to the introduction of tokens.</p><p>The term “Session” should not be mistaken for something fancy. It just refers to a sort of timeframe between a Client and Server.</p><p><strong>In Session-based Authentication, a user is associated with a unique Session (includes a unique ID, time of login, expiration, etc.) after successful authentication. This Session essentially represents the user’s login state, and is maintained by the Server. Thanks to this, we now have a stateful session between the Client and Server.</strong></p><p>The specifics can be different per implementation but the general flow goes as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28b1yxADm07EIoj6qk2N-A.png" /></figure><ol><li>The User submits their credentials to the Server.</li><li>The Server validates the credentials. If successful, the server creates and stores a Session corresponding to the Client in the database. Then, it sends the unique Session ID to the Client via a Cookie.</li><li>Subsequent requests from the Client to the Server will automatically include this Cookie.</li><li>The Server validates the Session ID in the Cookie against its Session database and responds accordingly.</li></ol><ul><li><strong>Notes</strong><br>- Session-based Authentication is not limited to be implemented by use of Cookies but it is the most widely used approach to transport the Session ID between Client and Server.<br>- Maintaining Sessions in the DB can be a bottleneck.</li></ul><h4>Token-based Authentication</h4><p><strong>Token-based Authentication refers to the use of encrypted security tokens, which are commonly JSON Web Tokens(JWTs) containing the necessary claims (information) to verify a User’s login state including the issuer, user ID, expiry.</strong></p><p>Tokens are stateless and self-contained. Therefore, a DB to manage them is not required. However, the process of revoking a token would ultimately require storing some sort of value in a DB.</p><p>The general flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXatW_ISu90fcRrLNldtfg.png" /></figure><ol><li>The User submits their credentials to the Server.</li><li>The Server validates the credentials. If successful, the Server creates a Token. Then, it sends a response with this Token to the Client.</li><li>The Client securely stores the Token and includes it in subsequent requests to the Server.</li><li>The Server validates the Token and responds accordingly.</li></ol><ul><li><strong>Notes</strong><br>- There are a few different means of transport/storage of Tokens, which is hotly debated for security reasons. For example, you could use Cookies or a combination of LocalStorage and Authorization Header (more on this in the next article).<br>- In token-based authentication, the Server usually responds with two tokens: Access Token and Refresh Token. The Access Token is essentially your validation to access resources. The Refresh Token is used to “refresh”/renew the Access Token for a more seamless user experience.<br>- Do not mix up between JWT and OAuth. JWT is merely a token format and OAuth is an authorization protocol that may use JWTs.</li></ul><h3>Authorization — OAuth 2.0</h3><p>Nowadays, it is rare to come across any service that does not provide login through third-parties (Ex: Google, GitHub).</p><blockquote>The OAuth 2.0 authorization framework enables a third-party<br> application to obtain limited access to an HTTP service, either on<br> behalf of a resource owner by orchestrating an approval interaction<br> between the resource owner and the HTTP service, or by allowing the<br> third-party application to obtain access on its own behalf. | <a href="https://datatracker.ietf.org/doc/html/rfc6749">RFC6749</a></blockquote><p>OAuth, which stands for Open Authorization, is a <strong>token-based <em>authorization</em> protocol</strong>. It guides the delegation of access to a user’s resources on the OAuth Provider to a third-party application without having to expose the credentials to the third-party application. As of publishing this article, OAuth 2.0 is the most recent protocol.</p><h4>The Abstract Protocol Flow</h4><p>Below is an overall illustration of how the protocol works; whereby the steps A — F are in order.</p><ul><li><strong>Client:</strong> Third-Party Application (Ex: your application)</li><li><strong>Resource Owner:</strong> User</li><li><strong>Authorization Server:</strong> OAuth Provider(Ex: Google)’s authorization endpoints</li><li><strong>Resource Server:</strong> OAuth Provider’s resource endpoints</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Nm0aqdvKPNpfAePjl0ZvA.png" /><figcaption><a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.2">https://datatracker.ietf.org/doc/html/rfc6749#section-1.2</a></figcaption></figure><h4>OAuth and Authorization Code Grant Type</h4><p>There are a few authorization grant types. But I will only go over the Authorization Code Grant type. Check <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4">Section 4 of RFC 6749</a> to see other grant types.</p><p>The Authorization Code Grant type is a redirection-based flow, where an Authorization Code is used to issue Access and Refresh Tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBqOaR5Lj64urwW54Q9Ujg.png" /><figcaption><a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1">https://datatracker.ietf.org/doc/html/rfc6749#section-4.1</a></figcaption></figure><ul><li><strong>Notes<br>- </strong>There are lots of security implications to consider but we’ll take a look at them in the next article.</li></ul><h4>Opinion</h4><p>Although OAuth 2.0 is a protocol designed to delegate access of a user’s resources on the OAuth Provider to a third-party, through successful delegation, third-party applications could technically infer that the user verified themselves to be who they claim to be (pseudo authentication?). Therefore, by minimizing the scope of the OAuth (Ex: just the user’s email), third-party applications could use the OAuth 2.0 protocol to sign users in to their application.</p><h3>Authentication — OpenID Connect</h3><blockquote>OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It enables Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner. | <a href="https://openid.net/specs/openid-connect-core-1_0.html">Final: OpenID Connect Core 1.0 incorporating errata set 2</a></blockquote><p><strong>OpenID Connect(OIDC) is an identity layer on top of OAuth 2.0 dedicated to <em>authentication</em></strong>. In contrast, the OAuth 2.0 protocol does not define standard methods to provide identity information.</p><p>You can check the list of standard Claims that can be requested in the OIDC specification <a href="https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">here</a>. Note that other custom Claims may be used in conjunction with the standard Claims.</p><h4>The Abstract Flow</h4><p>Below is an overall illustration of how this identity layer works.</p><ul><li><strong>RP:</strong> Relying Party (the OpenID Client / Third-Party Application)</li><li><strong>OP:</strong> OpenID Provider</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*VdiTHPT5VZfyqI3GzyRHtg.png" /><figcaption><a href="https://openid.net/specs/openid-connect-core-1_0.html#Overview">https://openid.net/specs/openid-connect-core-1_0.html#Overview</a></figcaption></figure><ul><li>Step 3, `AuthN Response`, includes an ID Token and usually an Access Token. This ID Token is a JWT that contains claims including meta data and identity information depending on the scope that you’ve set (Ex: name, email, picture) about the user.</li><li>Steps 4 represents an optional request using the Access Token to access more claims about the user.</li></ul><h4>OIDC and Authorization Code Grant Type</h4><p>Since OIDC is based on top of OAuth 2.0, it can adopt the different grant flows as well. But likewise, I will only go over the Authorization Code Grant type.</p><p>OIDC over Authorization Code Grant type is essentially identical to the above illustrated <a href="#7150">diagram</a>. But instead of exchanging the Authorization Code for Access and Refresh Tokens, it receives ID and Access Tokens.</p><h3>Continue reading on Auth Attacks and Mitigations in the next series:</h3><p><a href="https://medium.com/@daeram.chung/auth-series-2-auth-attacks-and-mitigations-08271bbd2f41">Auth Series 2: Auth Attacks and Mitigations</a></p><h3>References</h3><ul><li><a href="https://auth0.com/docs/manage-users/cookies">Cookies</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc7519">RFC 7519: JSON Web Token (JWT)</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc6749">RFC 6749: The OAuth 2.0 Authorization Framework</a></li><li><a href="https://openid.net/specs/openid-connect-core-1_0.html">OpenID Connect Core 1.0 incorporating errata set 2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2720e6c916a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just-In-Time(JIT) Compiler]]></title>
            <link>https://medium.com/@daeram.chung/just-in-time-jit-compiler-3bd18b5be585?source=rss-bdae4e62d6b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd18b5be585</guid>
            <category><![CDATA[jit]]></category>
            <category><![CDATA[interpreters]]></category>
            <category><![CDATA[v8]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Kakamotobi]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 15:12:33 GMT</pubDate>
            <atom:updated>2023-10-30T06:37:10.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*x_E-YGbrF49Im_JIEe-paw.gif" /></figure><h3>Background</h3><p>Compiler, interpreter, JIT compiler (and more!). These are all different ways to translate code written in a particular language into a target language.</p><h3>Prerequisites</h3><h4>What is a Compiler?</h4><p>A compiler takes the source code (high level language) of a program and entirely converts it into machine code before the program actually runs.</p><ul><li>Source Code (high level language) → Compiler → Executable Machine Code</li></ul><h4>What is an Interpreter?</h4><p>An interpreter runs the program by going through the source code line by line and converting it into machine code on the fly before moving on to the next line.</p><ul><li>Source Code (high level language) Line/Chunk → Interpreter → Machine Code → Execution → Source Code Line/Chunk → …</li></ul><h4>Note</h4><p>You might have heard things like “JavaScript is a JIT compiled language”, etc.</p><p>This can be misleading because it makes it sound as though JavaScript, the programming language, is JIT compiled inherently.</p><p>Any given programming language can be implemented to be compiled, interpreted, JIT compiled, etc. It is up to the individual implementations of the language to use whichever approach.</p><p>In the modern era, most major JavaScript implementations such as the V8 engine, SpiderMonkey, JavaScriptCore make use of JIT compilers.</p><h3>JIT Compiler</h3><p>So, what is a JIT compiler?</p><p>Unlike a static compiler where the complete translation is done before the program runs, a JIT compiler translates while the program runs. In other words, a JIT compiler is part of the runtime environment.</p><p>You might think, “Isn’t that just an interpreter”?</p><p>To be more precise, a JIT compiler<strong> “compiles” during execution of a program at runtime</strong>.</p><p><strong>A JIT compiler starts running a program as an interpreter would. However, the key difference is that, while interpreting the program, the JIT compiler observes the executions and make appropriate optimizations based on those observations (compilation part).</strong></p><p>An example of an optimization could be the JIT compiler observing that a certain function is being called frequently, and therefore may decide to compile that function. The JIT compiler could make this decision by weighing the performance gained from compiling this function as compared to the overhead of compiling the function.</p><p>Usually, a JIT compiler works with an Intermediate Representation (bytecode, which is easier to work with) of the source code instead of translating the actual source code written in a high level language into machine code.</p><p>So, a simplified process of a JIT compiler goes like this:</p><ul><li>Byte Code Line/Chunk → JIT Compiler → Machine Code → Execution → Possible Optimization → Byte Code Line/Chunk → …</li></ul><p>We can see that JIT compilation is essentially combining both worlds of the traditional compilation and interpretation approaches. The key points are <strong>dynamic analysis and optimization during runtime</strong>.</p><h4>Interpreter vs JIT Compiler Performance</h4><p>Let’s take a look at a JIT compiler’s optimization by comparing it to an interpreted-only version in JavaScript.</p><p><strong>Let’s begin with the interpreted version.</strong></p><p><em>V8, by default, uses a JIT compiler. However, it provides a JIT-less mode to opt out of its JIT compiler (the TurboFan optimizing compiler), effectively running the code only through an interpreter (the Ignition interpreter).</em></p><p>In this code, we use a for loop to invoke the add function 1000 times and then print out how many milliseconds the program took to execute.</p><pre>// index.js<br><br>const start = performance.now();<br><br>function add(x, y) {<br>  return x + y;<br>}<br><br>function run() {<br>  let a = 0;<br><br>  for (let i = 0; i &lt; 1000; i++) {<br>    a += add(1, 2);<br>  }<br><br>  console.log(a);<br>}<br><br>run();<br><br>const end = performance.now();<br>console.log(`${end - start}ms`);</pre><p>Execute the program:</p><pre>node --jitless index.js</pre><p>Result:</p><pre>3000<br>4.26829206943512ms</pre><p><strong>Now, let’s execute the same code but using the JIT compiler.</strong></p><p>Execute the program:</p><pre>node index.js</pre><p>Result:</p><pre>3000<br>3.669834017753601ms</pre><p>The JIT compiled version took approximately 3.7ms as compared to 4.3ms in the interpreted version.</p><p>Basically, what happened is that the JIT compiler identified the multiple add function invocations as “hot code” (code that is executed frequently), and optimized it by compiling it for henceforth use.</p><p><strong>Let’s try increasing the number of for loop iterations to 1000000.</strong></p><pre>// interpreted version<br><br>3000000<br>49.223832964897156ms</pre><pre>// jit compiled version<br><br>3000000<br>5.808459043502808ms</pre><p>We can see that as we increase the number of add function calls, the performance gain of the JIT compiler becomes evidently clear as compared to the interpreted version.</p><h3>Conclusion</h3><p>To reiterate, a JIT compiler starts off interpreting the code, dynamically analyze the executions, and potentially optimize the performance of henceforth executions by compiling it (i.e. allocate memory) at runtime.</p><p>Of course, this doesn’t mean that a JIT compiler is always going to be faster than an interpreter in executing the same program. This will depend on a lot of other factors including the code itself, the processor running the code, the particular implementation of the interpreter or JIT compiler, and more.</p><h3>References</h3><p><a href="https://www.youtube.com/watch?v=d7KHAVaX_Rs">Just In Time (JIT) Compilers — Computerphile — YouTube</a></p><p><a href="https://v8.dev/blog/jitless">JIT-less V8 — V8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd18b5be585" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>