<?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 Uday Kiran Jayanthi on Medium]]></title>
        <description><![CDATA[Stories by Uday Kiran Jayanthi on Medium]]></description>
        <link>https://medium.com/@udaykiranjayanthi?source=rss-8f6685e49dd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lV2uyvjL_6kaFF0aGSnPGA.jpeg</url>
            <title>Stories by Uday Kiran Jayanthi on Medium</title>
            <link>https://medium.com/@udaykiranjayanthi?source=rss-8f6685e49dd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:04:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@udaykiranjayanthi/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[tRPC: Building Better APIs, Faster (The Type-Safe Advantage)]]></title>
            <link>https://medium.com/@udaykiranjayanthi/trpc-building-better-apis-faster-the-type-safe-advantage-76836db4e6f0?source=rss-8f6685e49dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/76836db4e6f0</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[trpc]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Uday Kiran Jayanthi]]></dc:creator>
            <pubDate>Sun, 05 May 2024 08:32:56 GMT</pubDate>
            <atom:updated>2024-05-06T05:07:29.199Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlV29sdk7w4Y-nPuEsl6fA.png" /><figcaption>tRPC blog by Uday Kiran Jayanthi</figcaption></figure><p>To set the context, in this blog post, we’ll dig into tRPC, a powerful tool for building robust and type-safe APIs. We’ll explore how tRPC streamlines development for full-stack TypeScript projects. Let’s get started.</p><h4><strong>The Struggles of REST API Integration</strong></h4><p>REST APIs dominate web development due to thier simplicity and inherent flexibility, scaling well for countless applications. But web developers are all too familiar with the frustrations of integrating with REST APIs. It’s a constant loop of switching between your code editor and the network tab in your browser to debug issues. The backend team builds the APIs and shares documentation, but this process is riddled with manual effort. Misunderstandings about API structure, endpoint formats, and payload formats are common between teams. Even simple human errors, like misspelling URLs or misinterpreting JSON data, can lead to errors within your application.</p><h4><strong>Why Does This Happen?</strong></h4><p>The core issue lies in the inherent assumptions of REST APIs. The frontend team assumes the backend will provide data in a specific format, and the backend team assumes the frontend understands how to interpret it. This reliance on assumptions creates vulnerabilities.</p><p>During development, even if you believe you understand the payload format, mistakes can be made when sending requests or reading responses. These mistakes often manifest as bugs later on. As your product grows and features evolve, request and response payloads change, making it even harder to maintain clear communication between teams about these updates.</p><h4><strong>Limitations of Current Solutions</strong></h4><p>While GraphQL offers an alternative solution by allowing you to request data in a specific format solving the over/under fetching problem of REST, it has its limitations. The frontend defines its data expectations through a schema. However, if the backend team renames fields or restructures the data, the frontend schema can break. Even with proper communication, human error when reading the payload can still introduce bugs that only surface when the application is running.</p><p>The bigger problem goes beyond communication. Current workflows fail to identify integration issues during the development or build stages. These critical problems remain hidden until the application is running, causing delays and headaches as developers struggle to fix bugs.</p><p>Say hello to tRPC, a powerful solution for building end-to-end, type-safe APIs that streamlines development and reduces errors.</p><h3><strong>What is tRPC?</strong></h3><p>RPC is short for “Remote Procedure Call”. It is a way of calling functions on one computer (the server) from another computer (the client). With traditional HTTP/REST APIs, you call a URL and get a response. With RPC, you call a function and get a response.</p><p>tRPC (TypeScript Remote Procedure Call) is one implementation of RPC, designed for TypeScript monorepos.</p><p>So instead of hitting HTTP endpoints, we call functions (called procedures) on the server to send or receive data. You might think about how we can call functions on the server with HTTP calls. If you inspect the network traffic of a tRPC app, you’ll see that it’s fairly standard HTTP requests and responses, but you don’t need to think about the implementation details while writing your application code. You just call functions from your code, and tRPC takes care of everything else. You don’t need to worry about HTTP methods, endpoints, etc. Just call the functions with the required arguments.</p><h4><strong>Constraints:</strong></h4><ul><li><strong>Only Typescript:</strong> To ensure type safety, tRPC works with typescript only, so both backend and frontend should exist on typescript. You might use frameworks of your choice like React, Angular, Vanilla, Node, Express, etc. But they should be on typescript. You can’t be flexible with tRPC to use other programming languages.</li><li><strong>Monorepo:</strong> Both your backend and frontend code should be on the same repo to export and import the types. As tRPC ensures type safety by communicating the changes made on backend to the frontend by exporting the application schema as a Type.</li></ul><h4><strong>Terminology:</strong></h4><p>Before going into the implementation, let’s understand some basic terminology in tRPC.</p><ul><li><strong>Procedure:</strong> A procedure is an API endpoint (typically a function) which will be called from the client side to send or retrieve data. There are three types of procedures namely query, mutation, and subscription.</li><li><strong>Query:</strong> A procedure to get some data from the server.</li><li><strong>Mutation:</strong> A procedure to create, update, or delete data on the server.</li><li><strong>Subscription:</strong> A procedure that creates a persistent connection and listens to changes. This is for web sockets. This is not supported in HTTP server.</li><li><strong>Router:</strong> A collection of procedures (and/or other routers) under a shared namespace. Router is basically an Object wrapping and handling all endpoints.</li><li><strong>Context:</strong> Stuff that every procedure can access. Commonly used for things like session state and database connections. The createContext() function is called for each request and the result is propagated to all resolvers. <a href="https://trpc.io/docs/server/context">Read more</a></li><li><strong>Validation:</strong> It is a layer on procedures to ensure the type safety of input and output payloads.</li><li><strong>Middleware:</strong> A function that can run code before and after a procedure. Can modify context. Generally used to add common layers like authorization and authentication before executing the procedure.</li></ul><h4><strong>How does tRPC work?</strong></h4><p>Please refer to the below image for high-level architecture of tRPC implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*McQRatUbkQ_NHrZ_" /><figcaption>tRPC high-level architecture</figcaption></figure><p>To get started, keep both your frontend and backend code base on the same repository. Something like this.</p><pre>|-- repo/<br>    |-- client/<br>    |   |--node_modules/<br>    |   |--src/<br>    |   |--index.ts<br>    |   |--package.json<br>    |-- server/<br>    |   |--node_modules/<br>    |   |--src/<br>    |   |--index.ts<br>    |   |--package.json</pre><p>Naming and directory structure could be anything of your choice. But they should be on the same repo to share types.</p><p>Here I am not going to explain the entire implementation using tRPC. For that, you can refer to the official documentation here <a href="https://trpc.io/docs">https://trpc.io/docs</a> . Here I am only gonna cover the high-level overview and basic implementation of it.</p><h3>Coding</h3><p>Start by creating typescript node project on backend and frontend. You can use frameworks of your choice like React, Next, Express, Vanilla JS, etc.</p><p><strong>Server:</strong></p><ul><li>Install @trpc/server package with yarn or npm</li><li>Create tRPC instance</li></ul><pre>/* server/trpc.ts */<br><br>import { initTRPC } from &#39;@trpc/server&#39;;<br> <br>/**<br> * Initialization of tRPC backend<br> * Should be done only once per backend!<br> */<br>const t = initTRPC.create();<br> <br>/**<br> * Export reusable router and procedure helpers<br> * that can be used throughout the router<br> */<br>export const router = t.router;<br>export const publicProcedure = t.procedure;</pre><ul><li>Create a router with a query procedure and export the type of your router object.</li></ul><pre>/* server/index.ts */<br>import { db } from &#39;./db&#39;;<br>import { publicProcedure, router } from &#39;./trpc&#39;;<br> <br>const appRouter = router({<br>  userList: publicProcedure<br>    .query(async () =&gt; {<br>      // Retrieve users from a datasource, this is an imaginary database<br>      const users = await db.user.findMany();<br>      return users;<br>    }),<br>});<br><br>// Export type router type signature,<br>// NOT the router itself.<br>export type AppRouter = typeof appRouter;</pre><ul><li>Let’s add input parser to validate procedure inputs. To implement the userById procedure, we need to accept input from the client. tRPC lets you define input parsers to validate and parse the input. You can define your own input parser or use a validation library of your choice, like zod, yup, or superstruct.</li></ul><pre>import { z } from &#39;zod&#39;;<br> <br>const appRouter = router({<br>  // ...<br>  userById: publicProcedure<br>    .input(z.string())<br>    .query(async (opts) =&gt; {<br>      const { input } = opts;<br>      // Retrieve the user with the given ID<br>      const user = await db.user.findById(input);<br>      return user;<br>    }),<br>});</pre><ul><li>Let’s add a mutation procedure.</li></ul><pre>const appRouter = router({<br>  // ...<br>  userCreate: publicProcedure<br>    .input(<br>      z.object({<br>        name: z.string(),<br>        email: z.string(),<br>        age: z.number(),<br>      })<br>    )<br>    .mutation(async (opts) =&gt; {<br>      const { input } = opts;<br>      // Create a new user in the database<br>      const user = await db.user.create(input);<br>      return user;<br>    }),<br>});</pre><ul><li>You can add output parser for output validation in the same way but using .output() function. But this is optional as tRPC automatically infers the return type of your procedure. But If you want to avoid any mismatch of data inside your procedure you can add output validation.</li></ul><pre>const appRouter = router({<br>  // ...<br>  userById: publicProcedure<br>    .input(z.string())<br>    .output(<br>      z.object({<br>        id: z.string(),<br>        name: z.string(),<br>        email: z.string(),<br>        age: z.number(),<br>      })<br>    )<br>    .query(async (opts) =&gt; {<br>      const { input } = opts;<br>      // Retrieve the user with the given ID<br>      const user = await db.user.findById(input);<br>      return user;<br>    }),<br>});</pre><ul><li>Let’s start serving the API. Now that we have defined our router, we can serve it. tRPC has many adapters so you can use any backend framework of your choice. To keep it simple, we’ll use the standalone adapter.</li></ul><pre>import { createHTTPServer } from &#39;@trpc/server/adapters/standalone&#39;;<br> <br>const appRouter = router({<br>  // ...<br>});<br> <br>const server = createHTTPServer({<br>  router: appRouter,<br>});<br> <br>server.listen(8000);</pre><p>Hurray.. now our server is running. Let’s start calling the APIs from client.</p><p><strong>Client:</strong></p><ul><li>Install @trpc/client package with yarn or npm</li><li>Create tRPC client instance</li></ul><pre>/* client/trpc.ts */<br>import { createTRPCClient, httpLink } from &#39;@trpc/client&#39;;<br>import type { AppRouter } from &#39;../server&#39;;<br>//     👆 **type-only** import<br> <br>// Pass AppRouter as generic here. 👇 This lets the `trpc` object know<br>// what procedures are available on the server and their input/output types.<br>export const trpcClient = createTRPCClient&lt;AppRouter&gt;({<br>  links: [<br>    httpLink({<br>      url: &#39;http://localhost:8000&#39;,<br>    }),<br>  ],<br>});</pre><ul><li>Now you are pretty much end-to-end tRPC implementation. Now you can start calling your APIs in your code using this tRPC.</li></ul><pre>/* client/trpc.ts */<br>import { trpcClient } from &quot;./trpc&quot;;<br><br>const user = await trpcClient.userById.query(&#39;1&#39;);<br> <br>const createdUser = await trpcClient.userCreate.mutate({ <br>  name: &#39;uday&#39;,<br>  email: &#39;udaykiranjayanthi099@gmail.com&#39;,<br>  age: 23,<br>});</pre><ul><li>That is as simple as that. You may not understand the developer experience while just reading this article. Try it yourself, you’ll experience the joy of working with typesafe APIs.</li></ul><p><em>For a complete implementation example please refer to the Github repo provided at the end.</em></p><p>Let me just show you an example here on vs code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*BYQTOLyvYAdkODjL.gif" /><figcaption>tRPC coding example on VS code</figcaption></figure><h4><strong>HTTP implementation of tRPC:</strong></h4><p>Let’s see underneath the hood how tRPC makes HTTP calls. You don’t have to understand these network calls, but if you are curious to know…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*LJfAxuDPAzmvCcq98z2TAQ.png" /></figure><h4><strong>Advantages:</strong></h4><ul><li><strong>End-to-End Type-Safe APIs:</strong> tRPC enforces strongly-typed API definitions using TypeScript’s powerful type system. You define your API endpoints and their input/output types with simple TypeScript interfaces. <br>The compiler ensures that your code adheres to these definitions, catching errors at build time rather than runtime. This level of type safety empowers you to refactor and extend your APIs confidently.</li><li><strong>Better Communication: </strong>tRPC bridges the client-server communication gap seamlessly. It provides a straightforward way to define API structures with TypeScript types. <br>Both the server and client applications understand the available data and operations, leading to better communication between them.</li><li><strong>No Under/Over Fetching: </strong>With tRPC, you can precisely define the data needed for each API call. There’s no unnecessary fetching of data, reducing network overhead as you don’t have to worry about REST standards. <br>This fine-grained control ensures efficient data transfer between the client and server.</li><li><strong>Auto Suggestions: </strong>tRPC’s strong typing and autocompletion with TypeScript provide real-time feedback during development. <br>As you write code, you’ll receive suggestions and catch potential issues early, improving productivity.</li><li><strong>Simplified Setup:</strong> Setting up tRPC is straightforward. It offers automatic code generation, saving development time and minimizing manual tasks. <br>You can focus on implementing business logic rather than dealing with boilerplate code.</li><li><strong>Faster Development Cycles: </strong>By combining type safety, automatic code generation, and a straightforward API definition process, tRPC streamlines API development. <br>Developers can build robust and scalable APIs more efficiently, resulting in faster development cycles.</li></ul><h4><strong>Disadvantages:</strong></h4><ul><li><strong>Only for TypeScript Projects: </strong>tRPC is tightly integrated with TypeScript. While this provides strong type safety and seamless integration for TypeScript, it also means that tRPC is not suitable for non-TypeScript projects. <br>If your project uses a different language (e.g., JavaScript, Python, Go), you won’t be able to leverage tRPC’s features.</li><li><strong>Disadvantages of Monorepos: </strong>tRPC encourages structuring your codebase as a monorepo, where multiple projects or applications reside within a single repository. However, monorepos come with their own challenges:<br><strong>- Increased Repository Size:</strong> Over time, monorepos can become large, leading to longer clone times and increased storage usage.<br><strong>- More Complex Builds</strong>: Without proper tooling and configurations, build times may increase as the size of the monorepo grows.<br><strong>- Access Control Challenges</strong>: Monorepos provide the same access levels to all engineers involved in a project. There’s no way to restrict access to specific parts of the app, potentially leading to security issues.<br><strong>- Poor Git Performance in Scalable Projects</strong>: As the monorepo grows, Git performance can suffer, especially when working on large-scale projects.</li></ul><h4><strong>Summary:</strong></h4><p>To sum it up, tRPC offers significant advantages over traditional REST or GraphQL APIs, especially in terms of developer experience and type safety. However, it’s important to remember that tRPC isn’t a one-size-fits-all solution. The key takeaway is to make an informed decision based on your project’s current and future requirements. Don’t feel pressured to adopt tRPC simply because it’s trendy. If you’re already in a team where you’re mixing languages or have third-party consumers that you have no control over, you’d better go with GraphQL or REST which is language-agnostic. Weigh the pros and cons carefully to ensure you choose the right tool for the job.</p><h4><strong>References:</strong></h4><p>tRPC provided excellent documentation for all its features and implementation. I took some of the examples here from the same. Please go through the docs here <a href="https://trpc.io/docs">https://trpc.io/docs</a>.</p><p>If you want to refer to the implementation of a full-stack application. You can refer to my git repo below. While features are basic, it provides a solid foundation for applying tRPC to your own projects.</p><p><a href="https://github.com/udaykiranjayanthi/trpc-demo">https://github.com/udaykiranjayanthi/trpc-demo</a></p><p><strong>Implementation details:</strong></p><ul><li><strong>On frontend</strong> it is a React app. I used NextJS but only for frontend just for the app router. For React apps the recommended way to use tRPC is to use it along with ReactQuery (by TanStack). But for learning purposes, I just used the vanilla JS implementation of tRPC. So once you understand the basic concept of it, you’ll get the idea how it works.</li><li><strong>On backend</strong> I used node JS and Express. Express won’t play any major role but I want to show how easy it is to integrate tRPC with existing express apps as it is the most popular choice for node js server applications. The whole implementation remains the same for creating routers and procedures; the only difference is running the server.</li></ul><blockquote>Thanks for reading. Follow me on medium for more content.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76836db4e6f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How TOTPs work?]]></title>
            <link>https://medium.com/@udaykiranjayanthi/how-totps-work-c58cea69a313?source=rss-8f6685e49dd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58cea69a313</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Uday Kiran Jayanthi]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 12:35:37 GMT</pubDate>
            <atom:updated>2024-04-19T04:49:34.881Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Understanding TOTP: Securing Your Digital Identity</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T40CRBufLqFpVti9nXZcIg.jpeg" /></figure><p>In today’s interconnected digital landscape, security is paramount. With the increasing prevalence of cyber threats, it’s essential to adopt robust measures to protect sensitive information. Time-Based One-Time Password (TOTP) emerges as a powerful solution in this endeavor, offering enhanced security for online accounts and transactions. In this blog post, we’ll delve into the why, how, challenges, and uses of TOTP.</p><h3>Introduction to TOTP</h3><p>Two-factor authentication (2FA) has become common these days, acknowledging that the traditional method of user authentication via ID and password is not secure enough in today’s tech world. Software applications have thus turned to 2FA to bolster security on their services.</p><p>While several methods exist for enabling 2FA, one of the most robust is Time-Based One-Time Passwords (TOTPs). Unlike OTPs sent via SMS or email, TOTPs offer a higher level of security and convenience.</p><h3>How TOTP Works</h3><p>Time-based one-time passwords are typically six-digit codes that expire after 30 seconds. Users are prompted to input this code after validating their password, following which the server verifies the TOTP.</p><p>Apps like Google Authenticator and Authy facilitate the setup process, allowing users to scan a QR code generated by the application. What’s intriguing is that TOTPs can be generated even when the device is offline, and they remain valid when submitted on the website or app, without any network calls or synchronization.</p><p>This is possible due to the shared secret key and synchronized time between the user’s device (authenticator app) and the server. Both entities generate OTPs by hashing using the same HMAC algorithm with the shared secret key and current time as input.</p><h3>TOTP Generation and Validation</h3><p>TOTP generation and validation involve several key components:</p><ol><li><strong>Random Shared Key</strong>: The server generates a random key and shares it with the user via a setup QR code. Both parties store this key. The user saves it in their chosen authentication app (e.g., Google Authenticator), while the server links it to the user’s identity and possibly their device.</li><li><strong>Agreement on HMAC Algorithm</strong>: Both server and client agree on the Hash-based Message Authentication Code (HMAC) algorithm to be used.</li><li><strong>Ability to Obtain Current Time</strong>: Both server and user’s device have the capability to obtain the current time in Unix time.</li><li><strong>Additional Parameters</strong>: Parameters like the number of digits for OTP and the time period the OTP should be valid are considered.</li></ol><p>Secret key will be generated and shared by the server, both the server and user’s device will have the ability to get current time and the rest of the parameters are optional. If not provided, these are the defaults that the industry has agreed on:</p><ol><li>HMAC algorithm is SHA1</li><li>Time step size is 30 seconds</li><li>TOTP length is six digits</li></ol><p>At a minimum, the QR code contains this string:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*DJ6k-OEWPbszkrkc" /></figure><pre>otpauth://totp/Gupshup:uday.jayanthi%40gupshup.io?secret=4JCAVIMRQJBTEGNJS3T3BC4P6AXKCWNU&amp;issuer=Gupshup</pre><p>But you can customize the parameters like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*ma4M4l5Nhll3CJxv" /></figure><pre>otpauth://totp/Gupshup:uday.jayanthi%40gupshup.io?secret=4JCAVIMRQJBTEGNJS3T3BC4P6AXKCWNU&amp;issuer=Gupshup&amp;algorithm=SHA1&amp;digits=6&amp;period=30</pre><p><em>Both the strings result in the same OTP, even though we didn’t specify other parameters. Industry defaults will be applied.</em></p><p>Once the user’s app receives the secret and other information, it generates a new TOTP every 30 seconds by default, without needing to connect to the internet for further information exchange.</p><p>When the user submits the TOTP, the server also generates the TOTP using the same secret and parameters. Both values are then compared, and if they match, the TOTP is considered valid.</p><h3>Time Synchronization Issue</h3><p>Time synchronization is crucial in Time-Based One-Time Password (TOTP) systems because both the server and the user’s device (authenticator app) need to generate OTPs based on the current time. Any deviation in time between the server and the user’s device can lead to authentication failures. Here’s how time synchronization issues occur and how they can be mitigated using time windows:</p><p>Time Synchronization Issue:</p><ol><li><strong>Clock Drift:</strong> The clock on the user’s device and the server may drift over time due to various factors such as hardware differences, software delays, or manual adjustments. Even a small deviation in time can result in OTPs being generated out of sync.</li><li><strong>Network Latency:</strong> The time it takes for data to travel between the user’s device and the server can introduce delays, leading to discrepancies in time synchronization.</li></ol><p><strong>Solution using Time Windows:</strong></p><p>To address time synchronization issues, TOTP systems often employ the concept of time windows. A time window allows for a certain degree of flexibility in OTP validation, accommodating slight differences in time between the server and the user’s device. Here’s how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pFe6aiy9TFo-O61O" /><figcaption>TOTP generation on client and server (Credits: Atlassian)</figcaption></figure><p><strong>Defining Time Window:</strong> Instead of strictly comparing the OTP generated by the user’s device with the expected OTP calculated by the server at the exact current time, a time window is established around the current time.</p><p><strong>Acceptable Tolerance:</strong> The time window typically spans multiple intervals, including the current time interval and adjacent intervals. The size and number of intervals included depend on the acceptable tolerance for time deviation.</p><p><strong>Validation within Time Window:</strong> During authentication, the server validates the user-provided OTP against OTPs generated within the defined time window. If the provided OTP matches any OTP generated within the time window, authentication is deemed successful.</p><p><strong>Adjustable Parameters:</strong> Parameters of the time window, such as its size and the number of intervals, can be tailored based on factors like network latency, anticipated clock drift, and acceptable security risks.</p><p>The parameters of the time window, such as its size and the number of intervals included, can be adjusted based on factors like network latency, expected clock drift, and acceptable security risks. (Despite providing flexibility, time windows maintain security by limiting the window of opportunity for attackers to misuse OTPs.)</p><p>Time synchronization issues can pose challenges in TOTP systems, but employing time windows as a mitigation strategy helps ensure reliable and secure authentication. By defining acceptable tolerances for time deviation and validating OTPs within predefined time windows, TOTP systems can effectively address time synchronization issues while maintaining a balance between security and usability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMtUvCigWNow-XNxVUOqFQ.png" /><figcaption>TOTP implementation between in client and sever</figcaption></figure><h3>Algorithm to Generate TOTP Code</h3><p>To generate a Time-Based One-Time Password (TOTP), you typically need the following parameters:</p><ol><li><strong>Shared Secret Key</strong>: A unique secret key shared between the server and the user’s device (authenticator app).</li><li><strong>Time Step Interval</strong>: The duration of each time step, typically set to 30 seconds.</li><li><strong>Hash Algorithm</strong>: The cryptographic hash algorithm used for OTP generation, commonly HMAC-SHA1 or HMAC-SHA256.</li><li><strong>Number of Digits</strong>: The number of digits in the OTP, often set to 6 or 8.</li></ol><p>Here’s the algorithm to generate a TOTP with the given parameters:</p><p><strong>Calculate the Current Time Step</strong>:</p><ul><li>Divide the current time by the time step interval and round down to the nearest integer.</li><li>This gives you the current time step.</li></ul><p><strong>Format Time Step and Secret Key</strong>:</p><ul><li>Format the timestep and Secret Key in the format HMAC algorithm requires.</li></ul><p><strong>Generate HMAC hash</strong>:</p><ul><li>Use the shared secret key and time step to calculate an HMAC value using the chosen hash algorithm.</li><li>The HMAC value is a cryptographic hash based on the shared secret key and the current time step.</li></ul><p><strong>Extract OTP from HMAC Value</strong>:</p><ul><li>Take the last 4 bits of the HMAC value to determine the starting index (offset).</li><li>Extract a 4-byte (32-bit) chunk from the HMAC value starting at the offset.</li><li>This 4-byte value is used to generate the OTP.</li></ul><p><strong>Convert OTP to Decimal Digits</strong>:</p><ul><li>Take the least significant 31 bits of the extracted 4-byte value.</li><li>Take the modulus of this value with 10^n, where n is the number of digits in the OTP (typically 6 or 8).</li><li>Convert the result to a string representation with leading zeros if necessary.</li><li>This string is the TOTP.</li></ul><p><strong>Return the TOTP</strong>:</p><ul><li>Return the generated TOTP to the user for authentication.</li></ul><p>This algorithm ensures that the generated TOTP is time-based, using the shared secret key and the current time step to calculate a unique OTP that changes over time according to the defined time step interval.</p><h3>Advantages of TOTP</h3><ul><li><strong>Offline Usage</strong>: TOTP does not require an internet connection for OTP generation.</li><li><strong>Time-Sensitive Security</strong>: OTPs are valid only for a short duration, adding an extra layer of security.</li><li><strong>No Dependency on SMS or Network Coverage</strong>: TOTP operates independently of network coverage, reducing vulnerability to attacks.</li><li><strong>Increased Security</strong>: Utilizes strong cryptographic algorithms for OTP generation.</li><li><strong>Cross-Platform Compatibility</strong>: Supported by a wide range of authenticator apps on various platforms.</li><li><strong>User Experience</strong>: Involves scanning a QR code during setup for seamless authentication.</li><li><strong>Cost-Effectiveness</strong>: No additional costs associated with SMS delivery or hardware tokens.</li><li><strong>Scalability</strong>: Easily scaled to accommodate large user bases without significant infrastructure changes.</li></ul><p>TOTP stands as a reliable and convenient method for enhancing security in online authentication, offering a balance between robust protection and user experience.</p><h3>Implement your own TOTP service in Node JS</h3><p>There are plenty of libraries available in all languages to implement TOTP service for your application.</p><p>But if you want to implement your own service on Javascript/Typescript, you can refer to my Github <a href="https://github.com/udaykiranjayanthi/totp-generator-lib">https://github.com/udaykiranjayanthi/totp-generator-lib</a>. This code is also available as npm package if you want to install that in your node project, run this command.</p><pre>npm install totp-generator-lib</pre><p>or</p><pre>yarn add totp-generator-lib</pre><p>Refer to NPM package registry for docs and how to use it. <a href="https://www.npmjs.com/package/totp-generator-lib">https://www.npmjs.com/package/totp-generator-lib</a></p><p>Thanks for reading. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58cea69a313" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>