<?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 Phakorn Kiong on Medium]]></title>
        <description><![CDATA[Stories by Phakorn Kiong on Medium]]></description>
        <link>https://medium.com/@PhakornKiong?source=rss-d98716de5277------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k_nTJj7P1z2calCpQT-1VQ.jpeg</url>
            <title>Stories by Phakorn Kiong on Medium</title>
            <link>https://medium.com/@PhakornKiong?source=rss-d98716de5277------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:43:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@PhakornKiong/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[My Naive implementation of no-code/low-code tool]]></title>
            <link>https://medium.com/@PhakornKiong/my-naive-implementation-of-no-code-low-code-tool-253e678f2456?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/253e678f2456</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[temporal]]></category>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[no-code]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 02:31:43 GMT</pubDate>
            <atom:updated>2023-03-31T13:10:59.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTy-EYFiKQh1AXWgoTWJhQ.jpeg" /></figure><p>In recent years, the popularity of no-code/low-code tools has skyrocketed, with more and more individuals and organizations looking for ways to simplify their development processes.</p><p>As a software engineer, I am intrigued by these tools and have been exploring their inner workings. In this article, I want to share my learning and provide a naive implementation of such tools.</p><p>The main characteristic of no-code/low-code tools is custom Domain Specific Language (DSL). Most tools have their own schema, of which it provides information of how the workflow should be run.</p><p>Following is an example of workflow in n8n that backup n8n workflows to google drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sC3uv3PZkkUWVx0bS_KuCw.png" /><figcaption><a href="https://n8n.io/workflows/1150-backup-n8n-workflows-to-google-drive/">https://n8n.io/workflows/1150-backup-n8n-workflows-to-google-drive/</a></figcaption></figure><p>In a workflow, each action can be represented as a node in a graph, with each node having its own input, output, and execution logic. Nodes that are connected indicate that data will be passed between them.</p><p>I recently came across an open-source tool called Temporal, which is focused on providing first-class support for workflows in a distributed environment. By managing the execution of workflows and activities, Temporal simplifies the development process and makes it easier for developers to build fault-tolerant and scalable applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxGvZzCFRnBqiFlOQP1-Dw.png" /><figcaption>Temporal UI</figcaption></figure><p>At its core, Temporal consists of two important concepts: activities and workflows. Activities are units of work such as calling an external API or running a database query, while workflows are a series of coordinated activities that form a business process. Workflows manage the state and execution of activities, providing a powerful framework for building scalable and fault-tolerant distributed applications.</p><p>Temporal seems to be the perfect tool for my experiments in writing a naive implementation of no-code/low-code application.</p><p>The primary goal of this implementation is to establish a straightforward domain-specific language (DSL) using YAML to accurately define workflows and activities in Temporal. We will use encore.dev as framework.</p><p>The YAML DSL structure for our workflow consists of nodes representing actions, while connections indicate the sequence of workflow execution.</p><pre>name: my-workflow<br>description: This is an example workflow.<br><br>nodes:<br>  - name: SampleActivity1<br>    type: activity<br>    input:<br>      main:<br>        - SA1Value1<br>        - SA1Value2<br>  - name: SampleActivity2<br>    type: activity<br>  - name: SampleActivity3<br>    type: activity<br>  - name: SampleActivity4<br>    type: activity<br><br>connections:<br>  - from: SampleActivity1<br>    to:<br>      - SampleActivity2<br>      - SampleActivity3<br>      - SampleActivity4<br>  - from: SampleActivity2<br>    to:<br>      - SampleActivity3<br>  - from: SampleActivity4<br>    to:<br>      - SampleActivity2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-LyLuSGQb73epUjBTFWNQ.png" /><figcaption>Visualizing workflow yaml</figcaption></figure><p>The assumption made here is that the graph representing the workflow should always be a Directed-Acyclic Graph. Using topological sort, we can accurately determine the sequence of execution.</p><p>Firstly, we define each activity. Currently, it is doing simple logging and returning some strings as output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nwEhs1DDJSIfVTG7I47NQ.png" /></figure><p>Next, we need to define how to parse our DSL YAML as a struct in go. yaml.Unmarshal from the official library comes in handy here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdtA-j4yhQyRQu_kfd6U9w.png" /></figure><p>Lastly, we need to be able to define a workflow in runtime based on the WorkflowData struct. Topo-sort is used to determine the order of execution. It’s also assumed that the output of each activity is passed as input to the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vH0cP8E9jt43ZvsAmpI-pg.png" /></figure><p>To keep it simple, the engine will parse the YAML file during startup, register the workflow with Temporal, and execute it immediately. We can check execution logs of activities to verify that the workflow is running correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzaLMRND8jmJB6r1zb9e_A.png" /><figcaption>Application Logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHy65EiZSemd0RO_Q4wXKA.png" /><figcaption>Output Activities in Temporal UI</figcaption></figure><p>The code is available on <a href="https://github.com/PhakornKiong/TemporalDSL/tree/31-mar">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=253e678f2456" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySejahtera is a Perfectly Good App With No Exploits]]></title>
            <link>https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-7e7cc52c8f06?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e7cc52c8f06</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[mysejahtera]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Sat, 06 Nov 2021 14:35:35 GMT</pubDate>
            <atom:updated>2023-03-15T13:12:23.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*lInp4Uq-ET1Ipjcx.jpg" /><figcaption>Image from MalaysiaKini — <a href="https://www.malaysiakini.com/news/589720">Source</a></figcaption></figure><h3>MySejahtera is a Perfectly Good App With No Exploits — Quarantine Ver</h3><p>Part 1 — <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-c75c1643d2ff">MySejahtera is a Perfectly Good App With No Exploits</a></p><p>Part 2 — <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-part-2-dba10a428d07">MySejahtera is a Perfectly Good App With No Exploits — Part 2</a></p><p>Final — <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-final-dual-fix-ver-7963f3d5c16a">MySejahtera is a Perfectly Good App With No Exploits — Final (Dual Fix Ver )</a></p><p>The series was supposed to be over, I promised myself to stop looking for more exploits with “MySejahtera”. But trust me, this exploit came to me, and it is kinda <strong>BIG</strong>.</p><p>So I was travelling back to Malaysia via flight. While being processed by personnel from the Ministry of Health (The frontliners), all travellers were asked to open “MySejahtera” or use a QR Code scanner to scan the typical “MySejahtera QR Code”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*wh285R4lJQpI33AqreHcnQ.png" /><figcaption>The Port-of-Entry QR Code</figcaption></figure><p>The QR Code links to something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*_2w5R-oRm9m_4WDkGxWzKw.png" /></figure><p>Nothing out of the ordinary, just the usual information about yourself, mode of transportation and vaccination status.</p><p>Once checked in, the travellers were then asked to line up to show the frontline our documents (Like pre-departure PCR, whether you&#39;re going to home quarantine) and get our lovely pink tag (denoting we’re “Person Under Surveillance” aka “Under Quarantine).</p><p>The interesting thing I noticed is, there are no computers, the frontliners did not use any gadgets. But my status in “MySejahtera” had turned from the usual “Low Risk No Symptom” to “Person Under Surveillance (PUS)”.</p><p>I did play around with the QR Code check-in APIs before, there is no validation on the server-side, you can submit check-in to locations that don’t exist.</p><p>I quickly open up the link and check what are the APIs call made during the submission. The call was made to</p><blockquote><a href="https://mysejahtera.malaysia.gov.my/clockinTraveller">https://mysejahtera.malaysia.gov.my/clockinTraveller</a></blockquote><p>with the following schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1d64f55dddc410b2fbbe2d1d667a9d9/href">https://medium.com/media/e1d64f55dddc410b2fbbe2d1d667a9d9/href</a></iframe><p>The name , contact , userStatus and tenant seems interesting, my wild guess is that:</p><ul><li>name is the name registered in “MySejahtera”</li><li>contact is either the phone number or email address used to register for “MySejahtera”</li><li>userStatus could be a enum of status that exists on server-side</li><li>tenant is the unique id for the check-in location</li></ul><p>I created a few dummy “MySejahtera” account using email to test if this particular API call change the status on the app. After a couple of minutes of tinkering, Tadaa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvzzq0JV2WTjNYQI2RImLw.gif" /><figcaption>Without Quarantine Order</figcaption></figure><p>The worse thing about this? There is absolutely <strong>ZERO </strong>server-side validation. Forget about the schema we talked about earlier, just send contact and it will work. And as we know, contact can be in the form of phone numbers, some bad actor could’ve just enumerated the number so everyone become “PUS”</p><p>A simple server-side validation and admin portal where authorised personnel approve the change of status would’ve avoided this exploit.</p><p>Benefits of being “PUS”? You can legitimately tell your boss you can’t go to the office for the next 7 days😎.</p><p>Now, everyone can become “PUS” like me with a simple curl .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d39e6188198d7c22e52ff60e3bfcd19f/href">https://medium.com/media/d39e6188198d7c22e52ff60e3bfcd19f/href</a></iframe><p>Update 1: Apparently tenant and createDate will trigger “Home Surveillance Order”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzVjcZjbqifh7xZClfGl7g.gif" /></figure><p>Update 2: The endpoint had been taken down. While checking the qrscan page.</p><blockquote><a href="https://mysejahtera.malaysia.gov.my/qrscan/">https://mysejahtera.malaysia.gov.my/qrscan/</a></blockquote><p>The TRAVELLER and TRAVEL_QUARANTINE endpoint was always there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*eqN5pqAi8m4bs4EaP5hEsQ.png" /></figure><p>In theory, one does not need to get the QR Code at the port of entry. Just simply call</p><p><a href="https://mysejahtera.malaysia.gov.my/qrscan/?formType=TRAVELLER">https://mysejahtera.malaysia.gov.my/qrscan/?formType=TRAVELLER</a></p><p>and within the JS code, you will be able to know the exact API that was used for this exploit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*3vzVMjhOxw2LXJudnC84yA.png" /></figure><p>As of 7/11/2021, /clockinTraveller and clockinTravellerQuarantine had been removed and will return NOT FOUND 404 . But you will be able to get the successful check-in page as that was just a render on Frontend which doesn’t depend on a successful response from the backend.</p><p>As reported in the news<br><a href="https://malaysia.news.yahoo.com/complaints-health-ministry-says-sorry-014832037.html">https://malaysia.news.yahoo.com/complaints-health-ministry-says-sorry-014832037.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7cc52c8f06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySejahtera is a Perfectly Good App With No Exploits — Final (Dual Fix Ver )]]></title>
            <link>https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-final-dual-fix-ver-7963f3d5c16a?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/7963f3d5c16a</guid>
            <category><![CDATA[mysejahtera]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 02:30:06 GMT</pubDate>
            <atom:updated>2021-10-24T13:50:43.572Z</atom:updated>
            <content:encoded><![CDATA[<h3>MySejahtera is a Perfectly Good App With No Exploits — Final (Dual Fix Ver )</h3><p>Part 1 — <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-c75c1643d2ff">MySejahtera is a Perfectly Good App With No Exploits</a></p><p>Part 2 — <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-part-2-dba10a428d07">MySejahtera is a Perfectly Good App With No Exploits — Part 2</a></p><blockquote>KUALA LUMPUR, Oct 21 — Health Minister Khairy Jamaluddin today said that the ministry is conducting a “dual-fix” method to address the issue of unsolicited one-time passwords (OTP) and spam emails being sent out from the MySejahtera system, to the public, whose details are registered with the app. — <a href="https://www.malaymail.com/news/malaysia/2021/10/21/khairy-moh-fixing-mysejahtera-improving-safety-after-reports-of-unsolicited/2015050">Malay Mail</a></blockquote><p>With “Dual-Fix”, can we expect all the public API endpoints to be secure now? We’ll have to find that out for ourselves.</p><p>This time around, I thought the better entry point would be from the “MySejahtera” app itself since my brief manual test gave me a hint of what could go wrong given their solid track record.</p><p>Our final play starts with <strong>Man In The Middle Attack (MITM)</strong>. The idea is to route all HTTPS traffic to a proxy and have a self-signed CA certificate installed into the android emulator. <a href="https://httptoolkit.tech/">HTTP Toolkit</a> makes everything easy via the ADB command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBQKmQq6ITKZerU45J_n3A.png" /></figure><p>However, I found out that “MySejahtera” app implements SSL-Pinning, which increases the difficulty of the attack by ensuring that communications are only possible with the dedicated trustful servers. Of course, we can use <a href="https://frida.re/">Frida </a>or <a href="https://github.com/sensepost/objection">Objection </a>to tinker around with the app, but I doubt it&#39;s worth the effort.</p><p>On the verge of giving up, I got the idea that the early version of “MySejahtera” app might not have SSL-Pinning. It&#39;s an idea worth exploring. I quickly get MySejahtera v1.0.9 apk from <a href="https://apkfun.com/down_MySejahtera.25786792.html">APKFun</a>. Install it into the android emulator and proxy the traffic via <a href="https://portswigger.net/burp">Burp Suite</a>.</p><p>Tadaa! My hunch was correct, SSL-Pinning was not implemented in the early version of the app (For obvious reason, since the app was probably rushed to production).</p><p>I found out that the “Reset Password” HTTP endpoint is actually not protected (solid consistency on security here) and is available at https://mysejahtera.malaysia.gov.my/register/forgotPassword?locale=en_US</p><p>It is a POST request that requires emailOrUserName field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvLxl9VGjOrojpckyOJ3gw.png" /><figcaption>Sending ForgetPassword Request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pdvutwr_t3cW0_sq59K-CQ.png" /><figcaption>Successful Request</figcaption></figure><p>Now, you can easily run the following curl command to trigger resetPasswordLink SMS to any phone number or email address that had registered with “MySejahtera”. Just update the emailOrUserName field to an appropriate value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/095c7a96c141258ef7afa7242ad0a80e/href">https://medium.com/media/095c7a96c141258ef7afa7242ad0a80e/href</a></iframe><p>My next strategy is to de-compile the apk to look at the source code (extremely messed up version). After getting “MySejahtera” apk from <a href="https://www.apkmirror.com/">APKMirror</a>, I use Apktool to decompile by running.</p><p>apktool d mysejahtera.apk</p><p>which gives the following folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*QmolZwtVwkvW3FvlCT2G3g.jpeg" /></figure><p>The code is pretty messed up for readability due to minification and bundling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4nGzj4v8VK-IZNgdEAMOA.png" /><figcaption>main.js from the decompiled apk</figcaption></figure><p>We can use tools like <a href="https://codebeautify.org/jsviewer">codebeautify</a> to beautify the minified code and increase the readability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6xJclD63MCDw4waxpJ_8w.png" /></figure><p>The first thing I did is to confirm if there is any change in the baseURL as compared to the previous two articles. A quick search with https:// keywords is good enough to point us right back to main.js .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*sBcze3TatKZuDrvScoFCFA.jpeg" /></figure><p>With the help of codebeautify, we now know that there are two domain names:</p><ol><li>https://covid-19malaysia.kpisoft.com</li><li>https://mysejahtera.malaysia.gov.my</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*yZTQTnVJiWYnU6XOGDC-ug.jpeg" /><figcaption>we’ll see much more of `devLink` too</figcaption></figure><p>Using the semi-guess method, let&#39;s continue to look for some endpoint by searching around. I started the search with /api and saw two functions, resendOTP() and resendEmailOTP() . Looking at the concatenation of the URL , we can kind of guess what is e. It is either contactNumber or email .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*lEQ5WtgKGJvMRiIumdb-KQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*zdvW8tbeR4zlQLPCVrCJrg.jpeg" /></figure><p>While testing out, the /register/api/mobileApp/resendOtp endpoint does work and will send OTP to any number without any authentication or rate-limiting. However, it seems to get taken down at the time of writing and now return 403 Forbidden . Bravo to the dev for trying to fix the vulnerable endpoint.</p><p>The /register/api/mobileApp/resendEmailOtp endpoint is still live, but it is not as vulnerable since there is nothing much one can do with sending OTP to random emails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*2PbGR5iJRXqL2_hlpHeAvg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*WT2TQY3ttr3bRzXzGICPmQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*JxIPFnjgCL7EhGu5Itn6mw.jpeg" /><figcaption>Actual `registerNewUser()` function call</figcaption></figure><p>The next interesting function I found is the registerNewUser() function. With a little digging, we’re able to identify what is being passed to registerNewUser() . It is taking a javascript object with contactNumber and countryCode field.</p><p>That is the same payload as the endpoint in discovered <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-part-2-dba10a428d07">Part 2</a> (It got fixed with the implementation of reCAPTCHA ).</p><p>So its POSTMAN time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPFi0-vnCS-4eGSs1lt4bA.png" /></figure><p>The result is the same with <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-part-2-dba10a428d07">Part 2</a>, now you’re able to send OTP to any phone number that has yet to register in MySejahtera</p><p>The issue with the above endpoint:</p><ol><li>As usual, no Rate-Limit, no Authentication Token required. The door is open to everyone!</li><li>There is a difference in behaviour between the two baseURL , “MySejahtera” URL will explicitly tell you that the number had been registered and give you 200 OK , while the “KPISoft” has inconsistent behaviour. My wild guess is that it is the old URL that is used in early 2020 and got desynced as “MySejahtera” URL got live.</li><li>A bad actor could use this to filter which phone number had been used to register “MySejahtera”. If it is not registered, an OTP will be sent.</li><li>Who is paying for the OTP ?</li></ol><p>In conclusion, the APIs exploit throughout the series fit the description of some of the <a href="https://owasp.org/www-project-api-security/">OWASP API Security Top 10</a></p><ul><li><strong>API2:2019 Broken User Authentication</strong></li><li><strong>API4:2019 Lack of Resources &amp; Rate Limiting</strong></li><li><strong>API9:2019 Improper Assets Management</strong></li><li><strong>API10:2019 Insufficient Logging &amp; Monitoring</strong></li></ul><p><strong>Proudly </strong>brought to you by:</p><figure><img alt="Look at Title" src="https://cdn-images-1.medium.com/max/960/1*s52Jyfse1uZxjoRRQLX16g.jpeg" /></figure><p>The information above is valid as of 22 October 2021. I should probably resign from this series too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7963f3d5c16a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySejahtera is a Perfectly Good App With No Exploits — Part 2]]></title>
            <link>https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-part-2-dba10a428d07?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/dba10a428d07</guid>
            <category><![CDATA[mysejahtera]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 12:49:53 GMT</pubDate>
            <atom:updated>2021-10-19T17:46:11.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcXqwX112WOQwzy-y7BC3A.png" /></figure><h3>MySejahtera is a Perfectly Good App With No Exploits — Part 2</h3><p>Part 1 — <a href="https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-c75c1643d2ff">MySejahtera is a Perfectly Good App With No Exploits</a></p><p>MySejahtera App, according to National Security Council (NSC), had been developed by a seasoned local company that had made it globally.</p><blockquote>This company is among local companies which had succeeded in expanding at the global level. The applications developed by this company are also used by Fortune 500 listed companies. Even though this company has expanded globally, KPISoft’s main management team is still based in Malaysia — <a href="https://www.malaymail.com/news/malaysia/2020/07/01/nsc-says-mysejahtera-app-developers-a-malaysian-company-that-made-waves-int/1880601">Malay Mail</a></blockquote><p>I doubt so. While checking some other endpoint, I noticed that reCAPTCHA is indeed implemented for some of the workflow (registration and sign up).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*iTeKxF5U-NvpAnvx4uUGoA.png" /><figcaption>Register Page for MySejahtera Check-In</figcaption></figure><p>Above is the registration page for the extension of “ MySejahtera” known as “MySejahtera Check-In”. “MySejahtera Check-In” helps businesses in implementing SOPs to fight COVID-19 on the ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*QkvSADgkOQkSCABc8m-3fQ.png" /><figcaption>OTP for Phone Number Verification</figcaption></figure><p>So far it is looking good right? There is reCAPTCHA implemented, which would avoid the same mistake that happens with the exploits in Part 1. So let’s look at the Chrome Developer Tools and intercept the HTTP call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*u2k0lKUsGFbCg0g4-642FQ.png" /></figure><p>The POST request endpoint is</p><blockquote><a href="https://mysejahtera.malaysia.gov.my/checkin/registerPhone">https://mysejahtera.malaysia.gov.my/checkin/registerPhone</a> (Register)</blockquote><p>and</p><blockquote><a href="https://mysejahtera.malaysia.gov.my/checkin/validatePhone?withOtp=true">https://mysejahtera.malaysia.gov.my/checkin/validatePhone?withOtp=true</a> (Login with OTP)</blockquote><p>The request requires 3 fields, countryCode , contactNumber and g-recaptcha-response . The use of reCAPTCHA protects the endpoint from replay attacks as each token is valid for<strong> two minutes</strong> and <strong>can only be verified once</strong>. Great!</p><p>To my surprise, g-recaptcha-response the token was not needed for this endpoint! Why bother implementing it if backend is not going to verify the token.</p><p>We can call the endpoint with just countryCode and contactNumber , and an OTP will be sent to the phone number. There are two types of response:</p><ol><li>Phone Number had already registered, No OTP will be sent (Use Login with OTP endpoint instead if you want to send OTP)</li><li>Phone Number yet to be registered, OTP will be sent</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OvP4gm_LeKYcz8AeIhnvg.png" /></figure><p>The issue with this exploit:</p><ol><li>As usual, no Rate-Limit, no Authentication Token required. The door is open to everyone!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*cS-Vv4ZvmU53Auq8EDjryQ.gif" /><figcaption>Load Test FTW</figcaption></figure><p>2. A bad actor could use this to filter which phone number had been used to register “MySejahtera Check-In”, which are all business phone numbers. With some creative social engineering, one can do wonders.</p><p>3. Paying the cost of all the OTPs sent. While I’m not sure which provider is used for this service, it is usually charged based on total volume. Below is a screenshot from <a href="https://www.twilio.com/sms/pricing/my">Twilio</a> pricing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxZidQMP3o46nKo-fTpItw.png" /></figure><p>If you’re curious, following is the curl command you can use to call the API Endpoint. Change the contactNumber and test it out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac26c0cfbb46799019734f621db26f74/href">https://medium.com/media/ac26c0cfbb46799019734f621db26f74/href</a></iframe><p>The information above is valid as of 17 October 2021.</p><p>Update 1: I’ve been sending OTP to myself for over 15 hours at random intervals. The worst thing of all? OTP code never changes.</p><p>Update 2: As of 20 October, reCAPTCHA had verification had been implemented on the backend. So considered the exploit patched.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dba10a428d07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySejahtera is a Perfectly Good App With No Exploits]]></title>
            <link>https://medium.com/@PhakornKiong/mysejahtera-is-a-perfectly-good-app-with-no-exploits-c75c1643d2ff?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/c75c1643d2ff</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[mysejahtera]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Sat, 16 Oct 2021 19:21:46 GMT</pubDate>
            <atom:updated>2023-03-15T13:02:46.333Z</atom:updated>
            <content:encoded><![CDATA[<p>To those that are unfamiliar with “MySejahtera”, the official description of the app is as follows:</p><blockquote>MySejahtera is an application developed by the Government of Malaysia to assist in monitoring COVID-19 outbreak in the country by empowering users to assess their health risk against COVID-19. This application also provides the Ministry of Health (MOH) with the necessary information to plan for early and effective countermeasures.</blockquote><p>While I only have brief experience with the app for about 2 months when I was in Malaysia last year, I would say the app had achieved its objective given the time used to develop the app.</p><p>My issue started when I get to know that those who received the COVID-19 vaccine overseas can apply for a digital certificate via the “MySejahtera” helpdesk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*5sj1WamJGDW1BvjoHuHTFw.png" /></figure><p>I followed the instruction and was led to the following address (web app).</p><blockquote><a href="https://mysejahtera.malaysia.gov.my/help_en/">https://mysejahtera.malaysia.gov.my/help_en/</a></blockquote><p>I have to fill in the relevant information, like vaccination date, batch number etc. Everything seems to works fine till it doesn’t. I got this cryptic error that says my file is not a PDF file when I try to submit my request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*6f8eqzGXaMSnQ0pFTDKQhg.jpeg" /></figure><p>Initially, I thought there was something wrong with my browser, so I switched to Edge, and it got the same error. There were a couple of complaints in the Facebook group as well, where most users end up submit screenshots of their vaccination certificate.</p><p>Putting on my detective’s hat, I opened up the good old Chrome Developer Tools and dig through the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*5Pt7qsPGBvx8Cd_jCyv3Tw.png" /></figure><p>Okay, so now we know that validateAndSubmitVaccinationOverseasRequest() function is called when submit button is clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*euCzMC4SOWAXgzXcMYDaCA.png" /></figure><p>validateAndSubmitVaccinationOverseasRequest() then calls validateUploadFile() to validate the file type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*LEQ6IVp8PYVNfVuQScdq6Q.png" /></figure><p>So validateUploadFile() is checking the file type by checking the extension(suffix) part of the file name, which is what I’ll do for client-side validation as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*ZiYyVm6zZ--qT0ttZfg1Ng.png" /></figure><p>And to my horror, the culprit is actually in the fileExtArr array that string of the allowed extension. So someone might have forgotten to add that “pdf” string. No biggie, a silly mistake like this happens once in a while.</p><p>Not till I realize that the developer might not have fully tested the feature that is being shipped. A simple unit test would’ve captured this way before it got to production. I’ve submitted a description of the error through the helpdesk for them to fix it.</p><h3>What&#39;s Next?</h3><p>What to do while waiting for the fix? Can I submit it directly through the API endpoint?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU3T85ENGCp2smTWg4EE3w.jpeg" /></figure><p>The answer is yes, it is a POST request and the endpoint is</p><blockquote><a href="https://mysejahtera.malaysia.gov.my/register/v2/rest/contactSupport">https://mysejahtera.malaysia.gov.my/register/v2/rest/contactSupport</a></blockquote><p>Not the most obvious way to identify a resource per RESTful API, but I can live with this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*zJnNYHwITgfDCXcOgKw-jQ.png" /></figure><p>A simple post request, and viola! I’ve successfully submitted my request!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*0q0A0crw8YHz1kbprx5cKw.png" /></figure><p>There are a few quirks I found out.</p><p>1. All information filled in the request is stored in content as an HTML string and it gets sent back as an email. It doesn’t make sense why the developer would do this as it creates more overhead (albeit small) for the HTTP call. It is also harder to parse this as compared to a key-value pair solution (I guess they didn’t even use this information in their backend at all).</p><p>2. You can use this endpoint to “send an email on behalf of MySejahtera”. Imagine a malicious attempt to scare people using this exploit?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihQVqt-KqCSVSAeZG2UPuA.png" /><figcaption>Time to rickroll</figcaption></figure><p>3. No Authentication token is required to make the call. Only Content-Type header is required.</p><p>4. There is no rate limit imposed on the endpoint. I hope they did implement some mechanism to ignore such requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*W4wdJGugqDtoY3MhgOvPTQ.gif" /><figcaption>Load Test FTW!</figcaption></figure><p>If you’re curious, following is the curl command you can use to call the API Endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c456af50e9dbaa6851e90a1e6153ce1/href">https://medium.com/media/6c456af50e9dbaa6851e90a1e6153ce1/href</a></iframe><p>The information above is valid as of 16 October 2021.</p><p>Update 1: As of 18 October 2021, reCAPTCHA had been added to submit page, but PDF error remains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*G5OnqL72EXzcy3qIk5bvBg.png" /><figcaption>Got time to add reCAPTCHA but no time to add “pdf” to array?</figcaption></figure><p>Also as reported in the news</p><p><a href="https://malaysia.news.yahoo.com/glitch-malaysia-covid-tracing-app-081032072.html">https://malaysia.news.yahoo.com/glitch-malaysia-covid-tracing-app-081032072.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c75c1643d2ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Encryption Feature  in pdf-lib]]></title>
            <link>https://medium.com/aia-sg-techblog/implementing-encryption-feature-in-pdf-lib-112091bce9af?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/112091bce9af</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[portable-document-format]]></category>
            <category><![CDATA[pdf-password]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 05:26:42 GMT</pubDate>
            <atom:updated>2021-08-15T05:28:47.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Encryption Feature in pdf-lib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxpH6Ie5DI-uRuTz15Xf3A.jpeg" /></figure><p>At work, a requirement to password protect existing PDF files came up. I was tasked with adding this feature to our existing backend that uses Express.</p><p>I thought it would be a straightforward task to implement it since there are probably plenty of libraries in NPM that are capable of this functionality.</p><p>For the sake of simplicity, password protection and encryption is used interchangeably in this article.</p><p>After half a day of searching, I realize that not many libraries support modifying existing PDF files, let alone encryption features. The notable candidate is <a href="https://github.com/chunyenHuang/hummusRecipe">hummusRecipe</a> (Mostly written in C/C++). However, it does not support output as Buffer (as of this writing). In the end, I have to save the encrypted PDF file to the local disk and load it back as a Buffer (Extremely inefficient).</p><p>My next preferred candidate is <a href="https://github.com/Hopding/pdf-lib">pdf-lib</a>. The library provides many useful PDF modification features and works with all JavaScript environments. However, the encryption feature is not yet available in this library.</p><p>So I thought to myself, can I implement this feature?</p><p>To get started, I started reading the PDF Specification file to understand the overall structure of a PDF file. I’ve written a short article <a href="https://medium.com/aia-sg-techblog/basic-structure-of-portable-document-format-pdf-79db682579c9">here</a>.</p><h3>Encryption in PDF Specification</h3><p>A Conforming Reader determines if a PDF file is encrypted by first looking at Encrypt entry in Trailer dictionary. If it exists, then the file is encrypted and the Conforming Reader will go through the decryption routine to extract the content before rendering the file.</p><p>Following is an example of Trailer dictionary of an encrypted PDF file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd27b82334d8dfcc7ea6377edaeafcc7/href">https://medium.com/media/bd27b82334d8dfcc7ea6377edaeafcc7/href</a></iframe><p>The Encrypt entry is referencing to Indirect Objects with object number 7 and generation number 0 . This object is known as Encryption dictionary and contains all encryption-related information.</p><p>Following is an example of anEncryption dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4596abc0b35b83cada680e2326af4a42/href">https://medium.com/media/4596abc0b35b83cada680e2326af4a42/href</a></iframe><p>It might seem very complicated, but let’s go through each of the entries in the dictionary to understand what it meant.</p><ul><li>/Filter — Identifies the security handler for the document. /Standard means the <strong><em>“Standard password-based security handler” </em></strong>is used.</li><li>/V — Specify the algorithm to be used in encrypting and decrypting the document.</li><li>/Length — Length of the encryption key</li><li>/CF — A dictionary whose keys is crypt filter names and whose values is the corresponding crypt filter dictionary (Only meaningful for PDF 1.5 and above)</li><li>/StmF — Name of the crypt filter to be used by default when decrypting streams in the document</li><li>/StrF — Name of the crypt filter to be used by default when decrypting all strings in the document</li></ul><p>The following field is only used if /Filter is /Standard</p><ul><li>/R — Number specifying revision of the standard security handler</li><li>/O — 32-byte string, based on both owner and user passwords. Used in computing the encryption key and determining whether a valid owner password was entered</li><li>/U — 32-byte string, based on user password. Used in determining whether a valid owner or user password was entered</li><li>/P — A set of permission flags will be permitted when the document is opened with user password. We will get back to this in the latter part of the article.</li></ul><p>A <strong>security handler</strong> is a software module that implements various aspects of the encryption process and controls access to the contents of the encrypted document. While the PDF Standard specify a <strong><em>“Standard password-based security handler”</em></strong> that all Conforming Reader must support, a custom security handler could be added by Conforming Reader to enhance the security of encrypted PDF File.</p><p><strong>Crypt filters </strong>provide finer granularity control over encryption within a PDF file (Only for PDF 1.5 and above with a value of /V entry equal to 4). For example, you could define different encryption mechanisms for <strong>streams </strong>( /StmF ) and <strong>strings </strong>( /StrF ) using different<strong> crypt filters </strong>defined in /CF of Encryption dictionary. There is a couple of entry in <strong>crypt filters </strong>that we should understand, as follow:</p><ul><li>/CFM — Define the method used by conforming reader to decrypt data. Can be None , V2 or AESV2 . The value V2 uses RC4 algorithm while AESV2 uses AES algorithm in <strong>Cipher Block Chaining (CBC) </strong>mode with 16-byte block size.</li><li>/AuthEvent — Define the event used to trigger authorization to access the encryption key used by this filter. Either DocOpen or EFOpen .The value DocOpen means authorization will be required when a document is opened, while EFOpen means authorization will be required when accessing embedded files. Default to DocOpen .</li><li>/Length — The bit length of the encryption key. Multiple of 8 in the range of 40 to 128.</li></ul><p>Furthermore, <strong>crypt filters </strong>do support public-key security handlers implementation (Not the scope of this article).</p><p>For sake of simplicity, the article will focus on the <strong><em>“Standard password-based security handler” </em></strong>and the algorithm used in conjunction with the <strong>crypt filter </strong>shown in the example above.</p><p>The encryption of data in a PDF file is based on the use of an <strong>encryption key</strong> computed by the <strong>security handler. </strong>While we could define our custom <strong>security handler</strong> with a different mechanism to compute the <strong>encryption key</strong>, the process of <strong>encrypting </strong>the data never changes (Follow <em>“</em><strong><em>Algorithm 1: Encryption of data using the RC4 or AES algorithms”</em> </strong>defined in the specification).</p><p>The next question would be, how do we compute the <strong>encryption key</strong> following the <strong>standard security handler </strong>in PDF specification?</p><p>The process to compute <strong>encryption key </strong>is described in <em>“</em><strong><em>Algorithm 2: Computing an encryption key”</em> </strong>of the PDF specification. It requires two inputs that have to be computed beforehand, namely O and ID entry in the Encryption dictionary.</p><p>Computation of U and O entry follows steps of padding (to ensure consistent length), MD5 hashing and RC4 encryption function.</p><p>U entry is computed using either <strong><em>“Algorithm 4: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 2)”</em></strong> or <strong><em>“Algorithm 5: Computing the encryption dictionary’s U (user password) value (Security handlers of revision 3 or greater)”</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd486f8625f00d2ee7b976468b2dea9e/href">https://medium.com/media/bd486f8625f00d2ee7b976468b2dea9e/href</a></iframe><p>O entry is computed using <strong><em>“Algorithm 3: Computing the encryption dictionary’s O (owner password) value”</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de402c45d605d0547597e1ca87dfc680/href">https://medium.com/media/de402c45d605d0547597e1ca87dfc680/href</a></iframe><p>PDF specification does not define how ID entry should be computed. However, since it is also used as a unique file identifier, we could pass the Info entry from the Trailer dictionary into an MD5 Hash to generate the required byte-strings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7908d24dd9bf3e7ca5793e8e44732e4/href">https://medium.com/media/a7908d24dd9bf3e7ca5793e8e44732e4/href</a></iframe><p>(Fun fact: No matter how ID entry is computed, it will not cause encryption or decryption to fail, as long as it is the constant)</p><p>Once we have all the ingredients, we could compute the <strong>encryption key</strong> as follow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c1e8bc65f348f0ac6e6d2ca99a9af0b/href">https://medium.com/media/0c1e8bc65f348f0ac6e6d2ca99a9af0b/href</a></iframe><p>With the computed <strong>encryption key</strong>, an <strong>encryption function</strong> (encrypt the actual data in PDF file) can be created for use by the PDFWriter (Code that saves the PDF in binary format).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb20f630ae939f0de0ca2375a9f9012f/href">https://medium.com/media/cb20f630ae939f0de0ca2375a9f9012f/href</a></iframe><h3>Permission Flag</h3><p>Coming back to the /P entry in the Encryption dictionary, it is also known as <strong>user access permission</strong>. It is an unsigned 32-bit integer containing a set of flags specifying which access permission shall be granted when a document is opened with user passwords. Only bit positions 3, 4, 5, 6, 9, 10, 11 and 12 is meaningful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*4A5pQhl6RN2D3ulJ_uTR3Q.png" /><figcaption>Extracted from PDF 32000–1:2008 (Table 22 — User Access Permission)</figcaption></figure><p>In the example above, the /P entry has a value -3896 in decimal format, which is equivalent to 1111000011001000 , since only bit position 4 is set , the user would be able to modify the file but not print.</p><p>With all the above steps in place, all that is left is to plug the code in and ensure that the <strong>encryption function </strong>is run at the right place for the right data in the PDFWriter of pdf-lib . Many thanks to the security module of <a href="https://github.com/foliojs/pdfkit">pdfkit</a> for the code on <strong>encryption </strong>algorithm.</p><p>Link to the Pull-Request for the Encryption Feature for pdf-lib below.</p><p><a href="https://github.com/Hopding/pdf-lib/pull/917">Feature: Document Encryption by PhakornKiong · Pull Request #917 · Hopding/pdf-lib</a></p><h3>Useful Reference​</h3><ol><li><a href="https://www.oreilly.com/library/view/developing-with-pdf/9781449327903/ch01.html">Developing with PDF by Leonard Rosenthol (Chapter 1. PDF Syntax)</a></li><li><a href="https://github.com/Hopding/pdf-lib/blob/master/pdf_specification.pdf">PDF 32000–1:2008</a></li></ol><p>​</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=112091bce9af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/implementing-encryption-feature-in-pdf-lib-112091bce9af">Implementing Encryption Feature  in pdf-lib</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Structure of Portable Document Format (PDF)]]></title>
            <link>https://medium.com/aia-sg-techblog/basic-structure-of-portable-document-format-pdf-79db682579c9?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/79db682579c9</guid>
            <category><![CDATA[portable-document-format]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Tue, 10 Aug 2021 15:44:23 GMT</pubDate>
            <atom:updated>2021-09-01T02:52:51.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*NTh0r2vd4fZ0_zYmryVciA.jpeg" /><figcaption>Image Credit: <a href="https://www.techradar.com/in/best/best-pdf-reader-for-mac">https://www.techradar.com/in/best/best-pdf-reader-for-mac</a></figcaption></figure><p>Portable Document Format (PDF) is the go-to standard when you want to ensure your document looked exactly the same everywhere, regardless of which device opened the file.</p><p>PDF had been standardized as ISO-32000 in 2008. The PDF specification that is used to write this article is available <a href="https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf">here</a>.</p><p>Before we begin, let’s clarify some of the terms that will be used in this article</p><ul><li>Objects — It is not the objects in the OOP sense, but the basic data type of the PDF standard. There are 9 types of objects (null, boolean, integer, real, name, string, array, dictionary and stream)</li><li>Dictionary — A key-value pair object that is unordered. They are denoted by &lt;&lt; and &gt;&gt; at the beginning and the end.</li><li>Indirect Objects — Objects that are referred to by reference</li><li>Direct Objects — Objects that appear inline and are obtained directly</li><li>Conforming Reader — Application that parses a PDF file according to the PDF Standard</li></ul><p>To follow along with the article, you could open a PDF file using a text editor and try to view the structure of the PDF file.</p><h3>Structure of PDF File</h3><p>For Simplicity, a PDF file is made up of 4 parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*BxBU-T_HNc1_A82SdtpeLA.png" /><figcaption>Overall Structure of PDF File</figcaption></figure><h3>Header</h3><p>The first line of the PDF file is a Header . This denotes the version of the PDF file with the following format</p><ul><li>%PDF- followed by the version number in the form of 1.N</li></ul><p>However, beginning with PDF 1.4 , the Version entry in the document’s catalog dictionary (Within Root entry of Trailer ), if present, will be used instead of the Header.</p><p>Furthermore, if a PDF File contains binary data (Most likely to have, as most modern PDF File contains stream object of some sort), the Header line shall be immediately followed by a line containing at least four binary characters (character codes of 128 or greater) like following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cbf6658e6c53712e553be21012878e9/href">https://medium.com/media/3cbf6658e6c53712e553be21012878e9/href</a></iframe><h3>Body</h3><p>Body of a PDF File consist of Indirect Objects representing the contents of a document. Indirect Objects starts with a unique object identifier that allows other objects to refer to it. The identifier is made up of the following</p><ul><li>Object Number (Positive Integer, can be in any arbitrary order)</li><li>Generation Number (Non-negative Integer)</li></ul><p>The Indirect Objects can be referred to from elsewhere by an Indirect Reference which consist of Object Number, Generation Number and keyword R (For example 4 0 R).</p><p>After the identifier is the keyword obj (start of the object) and endobj (end of the object), anything in between is a key-value pair that describes the object.</p><p>Following is a simple example of an Indirect Objects</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ec90ce2539700ee33480def25fe3c50/href">https://medium.com/media/7ec90ce2539700ee33480def25fe3c50/href</a></iframe><p>Simply put, Body of a PDF file is a tree of objects linked together, ultimately coming down to the Root Object (Defined by Root entry in Trailer, is a catalog dictionary)</p><h3>Cross-Reference Table</h3><p>Basically, a table that contains a list of byte offset pointing to the indirect objects . Conforming reader uses Cross-Reference Table as a lookup table to access certain objects quickly when needed.</p><p>The format for entries in Cross-Reference Table can be summarized as follows:</p><ul><li>In the following format nnnnnnnnnn ggggg n eol, a total of 20 bytes</li><li>nnnnnnnnnn is a 10-digit byte offset in the decoded stream</li><li>ggggg 5-digit generation number</li><li>n keyword for in-use entry or f keyword for free entry</li><li>eol 2 character end-of-line sequence (Like CR LF)</li></ul><p>Cross-Reference Table always start with a special entry 0000000000 65535 f that never changes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/496ee291b009404606c68a1c02c42a7c/href">https://medium.com/media/496ee291b009404606c68a1c02c42a7c/href</a></iframe><h3>Trailer</h3><p>Trailer shows the location of Cross-Reference Table and certain special objects. A conforming reader always read a PDF file from its end, hence it will be able to access Cross-Reference Table and others Indirect Objects quickly without parsing the entire file.</p><p>The Trailer is basically another key-value pair Dictionary with the following format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18ffe16f6f4190e9c330374460f173f2/href">https://medium.com/media/18ffe16f6f4190e9c330374460f173f2/href</a></iframe><p>Following is an example of a Trailer dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f929c16ec1586eacfdae7957f949ed11/href">https://medium.com/media/f929c16ec1586eacfdae7957f949ed11/href</a></iframe><p>The Trailer dictionary has the following keys:</p><ul><li>/Size — Total number of entries in Cross-Reference Table</li><li>/Prev — Only used if there is more than one Cross-Reference Table . It is the byte offset in the decoded stream from the beginning of the file to the beginning of the previous Cross-Reference Section</li><li>/Root — Catalog dictionary for the PDF (Can be a dictionary or indirect reference )</li><li>/Encrypt — Encryption dictionary, if exists, the PDF file is encrypted (Can be a dictionary or indirect reference )</li><li>/Info — Information dictionary containing general information on the file. (Must be indirect reference )</li><li>/ID — Array of two byte-strings constituting a file identifier. (If Encrypt entry exists, then this entry is <strong>required </strong>and shall be direct objects )</li></ul><h3><strong>Conclusion</strong></h3><p>Looking at the overall structure of a PDF file, we can see that the PDF standard is somewhat complicated, with plenty of consideration on being quick and memory efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79db682579c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/basic-structure-of-portable-document-format-pdf-79db682579c9">Basic Structure of Portable Document Format (PDF)</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Cloud Skill Challenge is a Perfectly Balanced Challenge]]></title>
            <link>https://medium.com/aia-sg-techblog/microsoft-cloud-skill-challenge-is-a-perfectly-balanced-challenge-da401b12786e?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/da401b12786e</guid>
            <category><![CDATA[microsoft-cloud-services]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[microsoft-learn]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 09:07:24 GMT</pubDate>
            <atom:updated>2021-06-24T12:35:49.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image by Kurtis Beaver @ https://dribbble.com/shots/7174817-Microsoft-Learn" src="https://cdn-images-1.medium.com/max/1024/1*wZmCNKkFuale7F55YSHASw.jpeg" /><figcaption>Image by Kurtis Beaver @ <a href="https://dribbble.com/shots/7174817-Microsoft-Learn">https://dribbble.com/shots/7174817-Microsoft-Learn</a></figcaption></figure><p>I’ve just received an email from Microsoft that there is an ongoing Cloud Skill Challenge for Singapore this morning. As a beginner in Azure Platform, I think this is a good initiative to incentivize myself to learn more through the Microsoft Learn platforms.</p><p>The rules are pretty simple, Top 3 winners will walk away with <strong>Surface Go 2</strong>. A decent prize I would say. Winners are decided by the total XP (experience points) gained over the duration of the challenge.</p><p>It is about 2 weeks into the challenge. I quickly signed up and went to see how is the top learner doing. To my horror, the top 2 learners are sitting at over <strong>3,000,000 XP</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*PEzMxpuQQV_k2uCqEAmXPg.jpeg" /></figure><p>For those unfamiliar with Microsoft Learn, you can get about 100XP to 300XP for completing a unit of learning. Each unit would take 5 minutes to 30 minutes, depending on the complexity of the unit itself. My arithmetic sense told me something fishy is going on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*vlRhlnh4-SKa6GVtYgJaHg.gif" /></figure><p>After a few minutes of searching, I found out that Microsoft does expose their catalogue API at <a href="https://docs.microsoft.com/en-us/learn/support/catalog-api">https://docs.microsoft.com/en-us/learn/support/catalog-api</a></p><p>The response from the above API gives us complete information of all learning paths and modules that exists on Microsoft Learn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48e6c0895a1e8643a9ff5a163c0039b3/href">https://medium.com/media/48e6c0895a1e8643a9ff5a163c0039b3/href</a></iframe><p>By tinkering with the developer console of my browser, I found out the API required needed to do the job. Before going into the gist of this exploration, let us review some terminology on Microsoft Learn.</p><p><strong>Unit: </strong>Smallest unit in Microsoft Learn. You gain XP for completing each unit.</p><p><strong>Module: </strong>A module comprises multiple units. You unlock an achievement for completing each module.</p><p><strong>Learning Path: </strong>A learning path comprises multiple modules. You gain a trophy for completing each learning path.</p><p>The endpoint to complete a unit is (via PUT request) <a href="https://docs.microsoft.com/api/progress/units/$%7BUnit%7D">https://docs.microsoft.com/api/progress/units/${Unit}</a>. This endpoint requires Bearer Token, which is easily extracted via developer console or via Microsoft Graph API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*6tj_Z2fUplduFJqdak_qfw.jpeg" /><figcaption>Extract Bearer Token</figcaption></figure><p>To get the unit name, we would need to extract information of all unit from either the module or learning path.</p><p>I found out that the following endpoint returns the following information:</p><p><a href="https://docs.microsoft.com/api/hierarchy/paths/$%7BLearningPath%7D">https://docs.microsoft.com/api/hierarchy/paths/${LearningPath}</a></p><p>Combining the three API and some JSON wrangling, the rest is to call the complete API with some delay to avoid getting rate-limited by the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*7aEjlNPZWOms6C0nFqxXsw.jpeg" /></figure><p>Some units could not be completed due to the existence of the “Knowledge Check” section. This requires the PUT request to include the answer to those question.</p><p>The entire process took no more than 30 minutes, just think about it. While I appreciate Microsoft for putting in the effort to advocate a culture of learning, there is much to be done on the Cloud Skill Challenge.</p><p>As an afterthought, exposing your entire API to the public requires much consideration as it might lead to unforeseen usage such as this exercise.</p><p>I’ve pushed the code with detailed instruction of this exercise to <a href="https://github.com/PhakornKiong/mscloud-challenge-expoilt">Github</a>.</p><p>PS: There is more than <strong>19,000</strong> <strong>unit </strong>of learning available on Microsoft Learn (For FREE!), it is indeed a great resource for self-paced learning.</p><p>Disclaimer: Try this at your own risk, most likely we’re violating the T&amp;C of the platform &amp; the challenge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da401b12786e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/microsoft-cloud-skill-challenge-is-a-perfectly-balanced-challenge-da401b12786e">Microsoft Cloud Skill Challenge is a Perfectly Balanced Challenge</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Node.js Event Loop Visualizer]]></title>
            <link>https://medium.com/aia-sg-techblog/building-a-node-js-event-loop-visualizer-1c6ec900ee5c?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c6ec900ee5c</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 09:25:26 GMT</pubDate>
            <atom:updated>2021-06-24T12:34:19.727Z</atom:updated>
            <content:encoded><![CDATA[<p>Try the Live demo <a href="https://node-event-loop.herokuapp.com/">here</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dBI9XVxadT6LRvK9" /></figure><p>While reading how Event Loop works for JavaScript &amp; Node.js, I’ve come across this great <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">explanation of JavaScript’s Event Loop by Philip Roberts</a>. He had made a great visualizer called <a href="http://latentflip.com/loupe">Loupe</a>. However, I couldn’t find any similar visualizer that supports Node.js API like setImmediate() or process.nextTick().</p><p>So why not build one, I thought to myself.</p><h3>Overall Architecture</h3><p>Not to reinvent the wheel, The project is based on the closest visualizer I could find, <a href="https://github.com/Hopding/js-visualizer-9000-server">js-visualizer-9000</a>. There are two components to this project, frontend and backend. The frontend is responsible for submitting code and replaying the list of event from the backend. The frontend is pretty much complete thanks to Dillion&#39;s work. We&#39;ll be focusing on the backend side of the project. The core of the application is how we&#39;re instrumenting the execution of code.</p><p>The flow of the program can be seen from the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*lv_OQFLaY4XfPSeUrI8-uQ.png" /></figure><p>There are several steps required after we get the code from the frontend.</p><ol><li>Create New Worker using Node.js Worker threads API</li></ol><ul><li>This allows running the submitted code in an independent execution thread, preventing malicious code from crashing the server.</li></ul><p>2. Transform Code &amp; Inject Tracerusing Babel</p><ul><li>We’ll inject Tracer to instrument function call &amp; prevent infinite loop.</li></ul><p>3. Run Transformed Code using vm module and async-hooks enabled</p><ul><li>The vm module enables compiling and running of the transformed code.</li><li>async-hooks is enabled to instrument flow of asynchronous function, read more <a href="https://nodejs.org/api/async_hooks.html">here</a></li></ul><p>4. Listen to Events Broadcast from worker</p><p>5. Collect &amp; Reduce Events</p><ul><li>Reduce the broadcasted events into a consistent format for the frontend to replay the events</li></ul><h3>Instrumenting Execution of Code</h3><p>We’re using two tools to instrument the execution flow of code:</p><h3>Tracer Function</h3><p>The purpose of Tracer is to broadcast event as it occurs. The event is then used by the frontend to replay and visualize the execution flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/451bfed60fc4e6b0467221ce28211e96/href">https://medium.com/media/451bfed60fc4e6b0467221ce28211e96/href</a></iframe><p>To use Tracer to broadcast the event, we need to inject our Tracer to call the correct method at the right place.</p><p>So how could we use the Tracer to instrument the code? The answer to this is by using plugins support from Babel.</p><p>First, we’ll transform the code submitted from the frontend into Abstract Syntax Tree(AST), then we&#39;ll traverse the AST to look for the marker to inject our code. To understand how this is possible, read <a href="https://medium.com/aia-sg-techblog/understanding-how-babel-works-d6ca363bce1e?source=your_stories_page-------------------------------------">here</a>.</p><p>Using the custom babel plugin written, the code will be transformed as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42606ec4e399327247b2c3af572204ba/href">https://medium.com/media/42606ec4e399327247b2c3af572204ba/href</a></iframe><p>Tracer does come with a feature that will limit the loop to the time limit set by TIMEOUT_MILLIS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77cf48379f57a3c7d63019d1291a8281/href">https://medium.com/media/77cf48379f57a3c7d63019d1291a8281/href</a></iframe><h3>Async-Hooks</h3><p>By using async-hooks, we&#39;re able to spy on the stage of an asynchronous operation, which is the whole point of this visualizer. There is a total of five hook that is supported by the API, as follow:</p><ol><li>init</li><li>before</li><li>after</li><li>destroy</li><li>promiseResolve</li></ol><p>Example of the hook registered for promiseResolve as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dae6df8256cf2c330c16a93509d82444/href">https://medium.com/media/dae6df8256cf2c330c16a93509d82444/href</a></iframe><p>We broadcast events as it occurs by calling postEvent()</p><p>For more information on how async-hooks work, read <a href="https://blog.insiderattack.net/understanding-async-resources-with-async-hooks-3416de574f30">here</a>.</p><h3>Conclusion</h3><p>We’ve successfully built a visualizer for Node.js Event Loop, the live demo available <a href="https://node-event-loop.herokuapp.com/">here</a>. <a href="https://github.com/PhakornKiong/Node-EventLoop-Visualizer-Client">Frontend </a>&amp; <a href="https://github.com/PhakornKiong/Node-EventLoop-Visualizer-Server">Backend </a>code is pushed to Github if you would like to learn more about the implementation.</p><p>This project has been made possible by prior work from <a href="https://github.com/Hopding">Andrew Dillon</a> &amp; <a href="https://github.com/latentflip">Philip Roberts</a>.</p><h3>Useful Reference:</h3><p><a href="http://alltom.com/pages/instrumenting-javascript/#">Instrumenting Javascript by Tom Lieber</a></p><p><a href="https://blog.insiderattack.net/event-loop-and-the-big-picture-nodejs-event-loop-part-1-1cb67a182810">Node.js Event Loop by Deepal Jayasekara</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c6ec900ee5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/building-a-node-js-event-loop-visualizer-1c6ec900ee5c">Building a Node.js Event Loop Visualizer</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding how Babel Works]]></title>
            <link>https://medium.com/aia-sg-techblog/understanding-how-babel-works-d6ca363bce1e?source=rss-d98716de5277------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ca363bce1e</guid>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[babeljs]]></category>
            <category><![CDATA[code-transformation]]></category>
            <dc:creator><![CDATA[Phakorn Kiong]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 06:30:47 GMT</pubDate>
            <atom:updated>2021-06-24T12:53:10.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53_gRWwIh1_Ja9dZPhiw_Q.jpeg" /><figcaption>Source: <a href="https://github.com/babel/logo/blob/master/babel.svg">https://github.com/babel/logo/</a></figcaption></figure><p>One of the more interesting I’ve done recently is learning how to modify JavaScript code programmatically using Babel. Babel is a JavaScript transpiler, best known for transpiling ES5+ code into a backwards-compatible version of JavaScript that can run in any browser.</p><p><strong><em>What is a transpiler?</em></strong></p><p>Transpilers are also known as source-to-source compilers. They are tools that read source code written in one programming language and produce equivalent code in another language. Transpilers enables languages like TypeScript and CoffeeScript to exists, which is the syntactic sugar of JavaScript. There are basically three main steps for a transpiler to be able to do what seems like a magical feature.</p><ol><li><strong>Lexical Analysis (Tokenization)</strong> — Source Code to Token</li><li><strong>Syntax Analysis (Parsing)</strong> — Token to Abstract Syntax Tree</li><li><strong>Code Generation</strong> — Abstract Syntax Tree to Source Code</li></ol><p><strong><em>Lexical Analysis (Tokenization)</em></strong></p><p>During this step, the lexical analyzer (let’s call it <em>a tokenizer</em>) converts code in the form of strings into an array of tokens using defined rules. Tokenizer will scan the code, character by character, and when it encounters a symbol or whitespace, it decides whether a word is completed and finally give it a type and value. However, resulting tokens does not explain how things fit together. It represents merely the components of the input.</p><p>Babel does not export its tokenizer as part of the package (Its functionality is grouped with @babel/parser, however <a href="https://esprima.org/">ESPRIMA</a> provide a simple to use tokenizer that can be used to visualize the result of tokenization. The resulting information is helpful for syntax analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b6fefd651d0e50e5c3156895e19c288/href">https://medium.com/media/2b6fefd651d0e50e5c3156895e19c288/href</a></iframe><p><strong><em>Syntax Analysis (Parsing)</em></strong></p><p>In this step, the tokens produced will be converted into an Abstract Syntax Tree (AST).</p><blockquote><em>AST is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.</em></blockquote><p>AST is useful in representing <em>abstract</em> structure (does not represent every detail appearing in real syntax) of source code. AST can be used to compile code to different languages, transpile code (what babel does), perform static analysis of code, generate source code and more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e40f4be2e7ca3b70e2b42b164642c21/href">https://medium.com/media/3e40f4be2e7ca3b70e2b42b164642c21/href</a></iframe><p>The code above will generate the following AST. There are many <em>parsers</em> available to generate AST, which will have some minor differences in taste. You may try the AST viewer <a href="https://astexplorer.net/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*u1kjHBljUWSXS4TfbvdlKg.png" /></figure><p><strong><em>Code Generation</em></strong></p><p>During this step, the modified AST will be used to generate the final code to be used. In the context of Babel, this is provided via @babel/generator</p><h3>Babel</h3><p>Putting the three steps together, we’re able to manipulate code with confidence by modifying the AST using Babel.</p><p>In the following example, we’re looking to change the variable keyword n into x, the flow of the transformation is as follow:</p><ol><li>@babel/parser provides a parse method that converts source code into an AST.</li><li>@babel/traverse provide us with a way to get to the node that we&#39;re interested in using a pattern known as visitor. We&#39;re defining an object literal which implements a visitor property that consists of an object of methods named to match the node it should process (typing is based on @babel/types). In this example, we&#39;re looking for Identifier node, and the function will visit both Identifier once ( n and y). However, in real-world code where multiple visitor and plugins are used, there are chances that a node might get visited more than once (although rare, it happens). So there should be some checks done to skip the transformation.</li><li>@babel/generator turns the modified AST back into code.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dba6359843cc1fb584cee0f2387d878d/href">https://medium.com/media/dba6359843cc1fb584cee0f2387d878d/href</a></iframe><p>All in all, we can see that Babel had taken care of all the three steps for us so we can focus on transforming AST according to our requirements. For the common use-cases of Babel, we can easily mix and match the published <a href="https://babeljs.io/docs/en/plugins/">plugins</a> to get what we want.</p><h3>Traversing the AST with Babel</h3><p>To traverse AST, we simply define an object literal with methods defined for accepting particular node types in a tree (typing is based on @babel/types). For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e752122a2844e8ecd454fdea57c13c39/href">https://medium.com/media/e752122a2844e8ecd454fdea57c13c39/href</a></iframe><p>The code above is a simple visitor that during traversal, will call the Identifier() method for every Identifier visited. We can also use aliases as visitor nodes (for example Function is an alias for FunctionDeclaration, FunctionExpression, ArrowFunctionExpression, ObjectMethod and ClassMethod)</p><p>While traversing an AST to transform the source code, you should be aware of the traversal sequence. You may run the following code and compare the output with <a href="https://astexplorer.net/">AST Explorer</a> to visualize the flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a49fea0cf655104ce5027d7339928a/href">https://medium.com/media/55a49fea0cf655104ce5027d7339928a/href</a></iframe><p>The path we get during traversal is an object representation of the link between nodes. Imagine the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d24275ed6f34d5185fa9ab1a2e2a4555/href">https://medium.com/media/d24275ed6f34d5185fa9ab1a2e2a4555/href</a></iframe><p>We know that the code above has FunctionDeclaration and Identifier node. If we choose to represent Identifier as a path, we will get something like the snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54c1c4750f414d09a075f82e8a483d7d/href">https://medium.com/media/54c1c4750f414d09a075f82e8a483d7d/href</a></iframe><p>Babel does provide additional metadata and methods to make AST transformation easier. In summary, paths are a reactive representation of a node position in the tree, with additional information appended. Whenever you call a method that modifies the tree, Babel manages everything and update the information. Babel makes working with AST very straightforward.</p><h3>State</h3><p>We need to be extremely careful about state during AST transformation. Let&#39;s take the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5afd8868377a9b8c0849fa3b86c202d/href">https://medium.com/media/e5afd8868377a9b8c0849fa3b86c202d/href</a></iframe><p>Assuming we want to rename foo into baz inside the add function, we could do a hacky transformation like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab3310fa655713b5bf2215c799474351/href">https://medium.com/media/ab3310fa655713b5bf2215c799474351/href</a></iframe><p>The above transformation should work. We’re changing the param inside FunctionDeclaration and the name inside Identifier. The transformed source code we get is actually like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f201cf0dc68a947b63c51c1ca3800b72/href">https://medium.com/media/f201cf0dc68a947b63c51c1ca3800b72/href</a></iframe><p>But why? This is because we’re modifying every Identifier with the same name as foo. This is due to the state of AST, and it is likely to happen if you&#39;re working with a big codebase.</p><p>How could we avoid the above? We could do a recursive traverse inside the FunctionDeclaration to eliminate polluting the global state</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d5f8c9f39c251bc051217c941f0aa1e/href">https://medium.com/media/8d5f8c9f39c251bc051217c941f0aa1e/href</a></iframe><p>The solution above is a very naïve example, actual transformation logic in real-world cases should have more checks to ensure transformation only occurs on the node that you’re interested in.</p><h3>Scope</h3><p>Note that JavaScript implements <a href="https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_vs._dynamic_scoping">lexical scoping</a>. We can imagine this like a tree structure where every nested node has its scope. Code within a deeper scope can use a reference from a higher scope and create a reference of the same name without modifying it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7e544d0a277c1d47949a927d722904c/href">https://medium.com/media/c7e544d0a277c1d47949a927d722904c/href</a></iframe><p>When transforming a complex AST, we should be wary of the scope to avoid breaking existing code. Let’s look at the next example and identify the issue with the transformation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32aac78f9a75a8371b1bcbfd48fbb6b7/href">https://medium.com/media/32aac78f9a75a8371b1bcbfd48fbb6b7/href</a></iframe><p>Assume we would like to transform the first param of add function from foo to x. We could easily reuse the logic from the previous example to do the transformation. However, we would end up with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afb9238a3342eac091728c61032e229/href">https://medium.com/media/2afb9238a3342eac091728c61032e229/href</a></iframe><p>At first, it seems that the transformation is correct. However, the add function refers to x and y from the global scope. Based on the current transformation, the variable x no longer refers to the one in the global scope. In a large codebase, we wouldn&#39;t even notice this error as it is almost impossible to keep track of closure and scoping.</p><p>Nonetheless, let’s try to solve the example above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f53d17dd827b1804ef739311f0689e43/href">https://medium.com/media/f53d17dd827b1804ef739311f0689e43/href</a></iframe><p>Although the code above is not perfect, it shows how complex and difficult it is to deal with scope during transformation. We have to keep track of all the binding and reference while figuring out if there is a conflict in the identifier name. We&#39;re in luck as Babel provide many useful methods that we could use inside path.scope (You may refer to <a href="https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md#scope">here</a>).</p><p>With the power of Babel, we could simplify it down to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef78e292b8f248e6e3cdc63a40f2f69/href">https://medium.com/media/cef78e292b8f248e6e3cdc63a40f2f69/href</a></iframe><p>The next natural question would be, what are the use cases of Babel. Following is some example that you might be interested in:</p><ul><li>Create custom syntax using Babel syntax plugins — <a href="https://lihautan.com/creating-custom-javascript-syntax-with-babel/">Great tutorial by Tan Li Hau</a></li><li>Transform source code across the entire application (let&#39;s say transforming all old-fashioned antonymous function with arrow functions)</li><li>Create custom linter using Babel transform plugins</li></ul><p>At last, have fun with Babel!</p><h4>Useful Reference</h4><p><a href="https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md">Babel Plugin Handbook by Jamie Kyle</a></p><p><a href="https://juejin.cn/post/6844903956905197576">Babel in Depth — Architecture &amp; Use Cases (Mandarin) by 荒山</a></p><p><a href="https://astexplorer.net/">AST Explorer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ca363bce1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/understanding-how-babel-works-d6ca363bce1e">Understanding how Babel Works</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>