<?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 Ganesh B on Medium]]></title>
        <description><![CDATA[Stories by Ganesh B on Medium]]></description>
        <link>https://medium.com/@ganeshkbhat?source=rss-935bd349918c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dukzc61NHpFXvvqYNRGTEQ.jpeg</url>
            <title>Stories by Ganesh B on Medium</title>
            <link>https://medium.com/@ganeshkbhat?source=rss-935bd349918c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 18 Jun 2026 12:35:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ganeshkbhat/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[Toying with the idea of browser storage and cyber security]]></title>
            <link>https://ganeshkbhat.medium.com/toying-with-the-idea-of-storage-security-9fdd65707d6e?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fdd65707d6e</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 04:17:23 GMT</pubDate>
            <atom:updated>2024-03-08T07:51:41.227Z</atom:updated>
            <content:encoded><![CDATA[<p>This is for developers but written for non IT and people using the internet without any knowledge of IT and Internet Security</p><p>There are abundant of resources in the community which talk about hacking, server security-protection, and underground criminal white-blue collar activities; and cyber organized crime.</p><p>First,</p><blockquote>have you been ever toying with the idea of security — <strong>Dont ever. Controlled Production never exists</strong>. Let us repeat “Controlled Production Environment Never Exists”.</blockquote><p>Second,</p><blockquote>let us come clean on ethics that there is nothing called as “<strong>ethical hacker</strong>”, unless the ethical hacker is your company’s server admin doing the positive, good, beneficial non-criminal work.</blockquote><p>Third,</p><blockquote>While the concept of crime and laws may change country to country, you do not need laws to comprehend and decipher insanity, abuse, and try to prove that something is wrongfully crossing the ethical borders and ethical limits of activities.</blockquote><blockquote>If it pains - there is and was a hurt.</blockquote><p><em>Just because there is no law for a cyber crime activity it may not mean (cyber crime) something is right. It may be, can be, and will be accommodated into other available laws in every part of the world where laws are followed.</em></p><p><strong>[1] </strong>Having said it, open your browser’s developer tools. If you a novice, right click on your browser and click the “inspect” link.</p><p>You will see the web page’s developer tools open up.</p><p><strong>[2] </strong>Click on the “<strong>Application</strong>” Tab [<em>check first and second image</em>] in the developer tools. You will see list of storage sections [<em>check second image</em>].</p><p>This method of opening the developer fools is probably the same in the <strong>MS Edge</strong> and <strong>Chrome Browser</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ocix62yx_GGNgEimeg_TLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmjn8IkWL1rCBXc0_I49gg.png" /></figure><p>Click on every tab option of Storage —<strong> <em>localStorage, Session Storage, Web SQL, IndexDB, Cookies, Private State Tokens, Shared Storage, Cache Storage</em></strong>.</p><p>You are visiting a website that stores data can be hacked (simple as that), IF (AGAIN IF), you are able to</p><p><strong>[a]</strong> <em>read any text</em>,</p><p><strong>[b]</strong> <em>comprehend any of it</em>, and</p><p><strong>[c]</strong> <em>figure out what it is used for and how</em></p><p>A hacker with better tech skills may be someone who will do it easier, and will take the cookie and the cake.</p><p><strong>Following content is to address the developer community.</strong></p><p>Even if you are a non-developer, you can continue. You will understand what I am writing below. I will be very simple for you to understand every word (atleast most of it), including the code that is written or presented.</p><p><strong><em>[1]</em></strong><em> For critical — sensitive data : encrypt-decrypt content</em></p><p><strong><em>[2]</em></strong><em> For non-critical — non-sensitive data : encrypt-decrypt content as much as possible</em></p><p><strong><em>[3]</em></strong><em> For frequently used data : encrypt-decrypt content as much as possible, probably, with following options — not </em><strong><em>rules*</em></strong><em>.</em></p><p><em>** If the frequently used data is not of a very big size (and has to be stored in the indexdb/ localstorage) consider storage as encrypted format.</em></p><p><em>** If working with data try using the data from the memory using probably memcache or just plain simple memory? Probably consider a simple solution to persist it during crucial interval times or using internal application controls</em></p><p><em>There is a definite cost to encrypt-decrypt but it is worth the time used. A definite logical trade off.</em></p><blockquote><strong><em>rules*</em></strong><em>: </em>There are no rules for better cyber security other than lower end minimal security baselines</blockquote><p>Let me now introduce a nodejs package <strong>hasher-apis</strong> that addresses Crypto usable in a simple manner.</p><ul><li><a href="https://www.npmjs.com/package/hasher-apis">hasher-apis</a></li><li><a href="https://github.com/ganeshkbhat/apis-hasher">GitHub - ganeshkbhat/apis-hasher: Simple and flexible implementation Crypto Module functions to hash/ encrypt/ decrypt content and get SHA or other algorithm hashes of text or any data</a></li></ul><p>The secure storage of data can be as simple as</p><pre>let secure = require(&quot;hasher-apis&quot;);<br>let hash = secure.hashContent(data, salt);<br>// .hashContent(data, salt, algorithm, keyAlgorithm, digest, options)<br>let dehashed = secure.dehashContent(hash, salt);<br>// .dehashContent(data, salt, algorithm, keyAlgorithm, digest, options)</pre><p>What stops you from using this? I am presuming at this moment, probably, <strong>99% plus (or most of the websites including most fortune 500 applications — websites) of the website do not encrypt their browser data storage</strong>.</p><p>Update:</p><p>To ease the use of a encrypter and decrypter function, you can use the following package as a proof of concept for the same. It is browser compatible and nodejs environment compatible as well.</p><p><a href="https://www.npmjs.com/package/safecookies">safecookies — npm (npmjs.com)</a></p><p><a href="https://github.com/ganeshkbhat/safe-cookies.git">GitHub - ganeshkbhat/safe-cookies: Wrap most of the cookie libraries with a safer encrypt - decrypt function - should work with most libraries</a></p><pre><br>import pkg from &quot;safecookie&quot;;<br>const { encrypt, decrypt, cryptoencrypt, cryptodecrypt, getKeyFromPassword } = pkg;<br><br>let key = getKeyFromPassword(&quot;password&quot;, &quot;testsalt&quot;);<br>let yourFnThatReturnsValue = (v) =&gt; { console.log(v.toString(&quot;base64&quot;)); return v; }<br><br>// <br>// USAGE:<br>//  <br>//    encrypt(yourfunc, key_generated, value_arg_index, cryptoencrypt) <br>//<br>//    encrypt(yourFnThatReturnsValue, key, 0, cryptoencrypt) <br>// <br>// if the value to be encrypted is argument index 0 then use 0 <br>//      else use the index of the value argument<br>// <br>// if the value to be encrypted is argument index 1 then use 1 <br>//      else use the index of the value argument<br>// <br>//      yourfunc(value) =======&gt; index is 0<br>//      yourfunc(something, value) ========&gt; index is 1<br>// <br><br>let cryptedfn = encrypt(yourFnThatReturnsValue, key, 0, cryptoencrypt) <br>let cryptedtext = cryptedfn(&quot;Testing new crypter&quot;); <br>console.log(cryptedtext.toString(&quot;base64&quot;));<br><br>let decryptedfn = decrypt(yourFnThatReturnsValue, key, 0, cryptodecrypt)<br>let decryptedtext = decryptedfn(cryptedtext);<br>console.log(decryptedtext.toString());</pre><p>It is irrespective of the fact whether</p><p><strong>[a]</strong> the data is used by only their own site or not,</p><p><strong>[b]</strong> the data is a cross domain single sign on shared cookie or not</p><p><strong>[c]</strong> what ever kind of data the site is being used for</p><p><em>Encrypt-Decrypt local Storage, Session Storage, Web SQL, IndexDB, Cookies, Private State Tokens, Shared Storage, Cache Storage where possible.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fdd65707d6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[School Math Economics: Bad Non-inclusive, Non-comprehensive ‘per capita’ Income & ‘Inflation’…]]></title>
            <link>https://ganeshkbhat.medium.com/bad-non-inclusive-non-comprehensive-per-capita-income-inflation-calculation-methods-and-cb3a6ff64fda?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb3a6ff64fda</guid>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Sun, 08 Oct 2023 12:58:54 GMT</pubDate>
            <atom:updated>2024-07-22T11:56:06.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>School Math Economics: Bad Non-inclusive, Non-comprehensive ‘per capita’ Income &amp; ‘Inflation’ calculation Methods and Economic Standardizations</h3><blockquote>SUBJECT: The per capita income and inflation calculation [and data] are bad. Please be inclusive, non-selective, realistic in sampling of data for such calculations</blockquote><p>The basics of individual income [<em>per capita</em> income] and economic/ financial policies go sour and bad when percolation of monetary incentives do not seep to the individual levels as incomes affecting and effecting expenditures leading to bad baselines [<em>income baselines, expenditures, pricing policies, inflation, public policies, farse quality of living standards</em>] data.</p><p>This bad intensive <em>hybrid [estimation : guess-timation] technique</em> is well apart from the fact that “<em>RBI rates, Other financial pointers, Industrial production and related Pricings, Agricultural commodities, Commodities, Stock market Capitalization, EXIM, and FDI</em>” pointers have been “<em>considered to be instrumental in deciding</em>” related economic policies and strategies for the nation.</p><p>While most of the above mentioned pointers greatly impact the life basics [<em>Electronic and Telecommunication/ Communication, Transportation, Energy, Petroleum (including Kitchen Gas, Petrol, and allied), Financial services, and many other essentials industries, retail (including processed foods)</em>], the mentioned life basics pointers have generally been ignored for many financial pointers [<em>including inflation, pricing, per capita, and related macro and micro economic policies at state and center level</em>]; apart from agricultural and basic market commodities.</p><blockquote>The US <strong>inflation</strong> pointers are derived from and with using more than 80000 items for calculations.</blockquote><blockquote>The <strong>inflation </strong>derivations in India may need to be inclusive, comprehensive, non-selective, and/ or realistic.</blockquote><blockquote>The <strong>per-capita</strong> income derivations may need to be comprehensive and inclusive.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*lGAh1Mpr7HsBcLGCI4dXKw.jpeg" /><figcaption>Consumer Price Index (CPI): What It Is and How It’s Used: <a href="https://www.investopedia.com/terms/c/consumerpriceindex.asp">https://www.investopedia.com/terms/c/consumerpriceindex.asp</a></figcaption></figure><p>We <em>do not have a guidelines or associate policies to measure, monitor, curb, and risk mitigate pricing [inflationary] levels</em> of “all the other” life essentials we use along with [already calculation accommodated] essentials used for determining pricing [<em>inflationary</em>] levels. <em>Electronic and Telecommunications, Banking, Energy, Petrol, and Retailing</em> is yet not considered an essential. Or are they <em>really [and genuinely]</em>?</p><blockquote>India’s per capita income is approximately ₹2 lakh ($2500) in FY23.</blockquote><p>Well, is it really the average income of the nation, the individual, or the family? I am yet to figure out.</p><p>REFERENCES:</p><blockquote>How do you calculate <strong>per capita [per capita income]</strong>? Per capita is calculated by dividing the attribute of interest (such as income) by the number of people living in the area of interest. Per capita income is equal to the total income in that area divided by the number of people living in that area. Per capita income for a nation is calculated by dividing the country’s national income by its population. Per capita income includes all individuals, not just adults of working age.</blockquote><blockquote><strong>Inflation</strong> is a decrease in the purchasing power of money, reflected in a general increase in the prices of goods and services in an economy. Inflation can occur when prices rise due to increases in production costs, such as raw materials and wages. A surge in demand for products and services can cause inflation as consumers are willing to pay more for the product. A few factors impacting inflation are Demand-pull, Cost-push, Increased money supply, Devaluation, Rising wages, Monetary and fiscal policies.</blockquote><p>eBook: <a href="https://drive.google.com/file/d/1ttrx4B797d-61QnH0o6ZvP__5jdofrLI/view?usp=sharing">Finance Management [pointers using inflation]</a> or <a href="https://www.linkedin.com/posts/projectmanagementinformation_financial-and-strategic-management-activity-7116895875561328640-wklT?utm_source=share&amp;utm_medium=member_desktop">Linkedin Project Management Post Link</a></p><blockquote>A recommended change in the inclusive-ness, comprehensiveness in the data used for the pointers of per-capita/ inflation will see serious changes in baselines in your `base wages`, `planning commission recommendations`, `RBI recommendations and decisions`, and long term visions in the financial policies, and probably in your `next budget`.</blockquote><blockquote>Per capita income, Inflation, Stock Market, increased FDI inflows are not the true picture of the quality and standard of living of the nation.</blockquote><p>Mitigate, Mitigate, Mitigate.</p><p>Again, the per-capita or incomes of <em>lower [, lower-middle] class income families</em> in the “<em>lower end of the sigmoid curves</em>” may not be really the “<em>genuine, authentic, dependable</em>” financial data case [<em>Data which is free of selective [non-inclusion] bias, skewed data collection, and planning process of baselines nor good pointers for financial policies</em>].</p><p>I do not consider per-capita income or inflation as a financial policy pointer as a serious budgeting factor is not true either. No finance auditor gives away to this; unless…</p><blockquote>This skewness of data used for the per-capita and inflation pointers are critically true, especially, for the case of `individual incomes` and `inflation` pointers that relate to many `of and in` the unorganized sectors, many in sectors like retail, “micro” or “petty finances” [organized or unorganized] financial services, individual businesses, lower end SME businesses, and other essential service businesses. Well, yes, atleast at the moment.</blockquote><p>Some other questions that make up for the greater challenges to these pointers to be better reference points are:</p><blockquote>[A] Is per-capita income genuinely the right pointer case with right standard deviations that is being `accounted` for with all appropriations OR is this a skewed sample data used for pointer generation?</blockquote><blockquote>[B] Is the financial data collection sources, their calculations of per-capita and inflationreally authentic and not a not skewed or selective [bias] data sampling case?</blockquote><blockquote>[C] Does the entire India file taxes* irrespective of income source*?</blockquote><blockquote>[D] Do you expect a INR 10000 [15000] per month or below salaried labourer to file taxes?</blockquote><blockquote>[E] Is there a consideration of one member earning families in all sections of the society?</blockquote><blockquote>[F] Are the Employed, Partly Employed, Not Employed assumed [and right] into the data set? What is the source of the data set? Is it ethically and legally collected?</blockquote><blockquote>[G] Is Financial Data collected from the Banking, Financial filings not abusive or non-abusiveto the Financial Privacy ofIndividualsand Entities? There is no such individual comprehensive financial privacy protection policy nor a anti-abuse policy. More, the Data Privacy Policy Model is non-comprehensive, non-inclusive in (to) all sections in the victims, auditors [protectors of law], perpetuators, and the beneficiaries after a legal case.</blockquote><p><em>[*, C] — including “all tax free” agriculture-ists [agriculture income source]</em></p><p>The baselines of `<em>per-capita</em>` [incomes] and `<em>inflation</em>` pointers go wrong, absolutely wrong, with the <em>`lower end of sigmoid curve`</em> becoming critical without any appropriate standard deviations ever being considered for most financial and upliftment policies; whether an organization nor the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_aEsjeshlxRNNM3gEzsl-A.png" /><figcaption>X Axis Incomes, Y Axis Numbers - Approximations or Guesstimations of Realistic [Red] VS Currently Calculated [Black]</figcaption></figure><p>While this [per-capita income pointer] is definitely the average pointer, it does not warranty that the `<em>in the data sets</em>` of `<em>lower end of sigmoid curve</em>` incomes are genuinely a part of average (or plus) incomes. This [per-capita income pointer] is part of a genuine major problem that `affects and effects` fair standard [quality] of living based incomes and essential’s based expenditures. But…</p><blockquote>Do you really have a good standard of living?</blockquote><blockquote>Where does the capital oozing in expenditures go?</blockquote><blockquote>Is that monitored by the government comprehensively?</blockquote><p>Anything not accepted as the problem, not tracked, not monitored cannot be changed. This is NOT sarcasm.</p><p><em>Ethical Percolation, Ethical Percolation, Ethical Percolation.</em></p><p><em>Fair Inclusion, Fair Inclusion, Fair Inclusion.</em></p><p>Do not block - It is not just courtesy, It is also the Law!</p><p>Free or Financial Infusions or SOPsto the masses or industries (majorly) may not be a long term effective solution to eradicating poverty nor changing of baselines of incomes, nor quality standard of living. Free or financial infusions are a definite effective short term policy or decision and, yes, it can be a industry [economy] saviour many times.</p><p>I did not say <em>Free or Financial Infusions or SOPs</em> may not be needed based on the economic situation. What I meant is a financially sound entity does not need free. Free then becomes the cream for the financially sound. Free and Financial Infusions frequently, as a `need`, along with non-inclusiveness and non-comprehensiveness may be a bad strategy and a real deterrent over a long term. <em>It may not be a </em><em>sustainable financial stability decision(&#39;s) over a period of time or long term; especially when it can become a </em><em>dependency or may become an </em><em>expectation or </em><em>the expected</em>.</p><blockquote>A recommendation of introduction of filing taxes by the entire country irrespective of income tax slab.</blockquote><p>While this recommendation may not be a promotion of business of the financial and financial services industry, assistance to file taxes by the `<em>unprivileged</em>` can be made available using already available state resources like <em>National Banks like SBI or Aadhaar Centers, etc</em>. While initial thrust may be great like `minimal charge filings support` it <em>can be removed when the baselines change</em> or <em>can be made commercially viable source of income generation to the governments</em>. There may be many other useful recommendations that may and will come by if there are genuine debates on this. My recommendations on support and need based on economic upliftment have been clean as mentioned before.</p><blockquote>There is a need of Comprehensive, Inclusive Accountability and Responsibility model of Data Privacy Bill that includes victims, auditors, perpetuators, and government alike for `accountability and responsibility` (apart from `beneficiaries of proceedings` to be inclusive and comprehensive) on data privacy pointers, policies, bills, and rules for data collection from the governance even for finance department intents and larger intents.</blockquote><blockquote>The data privacy accountability and responsibility in [, for, by] the government or government associated entities for its end users or end beneficiaries of an governance activity and government [associated, public sector] entity now exists in the EU; even if in a lower form. The government and government services is for the people.</blockquote><p>The above mitigates many lapses and issues related to data privacy. <em>There is a need for accommodations of lapses and their mitigations across planning, execution, and implementation in entirety is needed and important including Planning, the Bills, and the Laws of the Land</em>. We all are humans and that is why we need the courts, policing, and the governance . This is a need based citation not a recommendation. My 17 year’s story in one recommendation, and yours…?</p><p>However, wrong data, or biased data, or wrong [incomplete, selective] sampling data may be a bigger deterrent to fix real problems or take the right decisions on budgeting. More, <em>the baseline pointers that lead to better financial decision making, pricing, and references to Pricing, Inflation, Incomes data are references not the solution by itself</em>.</p><p>You do not even have a good standard deviations of <em>lower-upper ends of sigmoids</em> for Per Capita Income and other financial pointers.</p><blockquote>How will the budgeting for organizations be right; leave away public policies?</blockquote><blockquote>How are the budgetings based on?</blockquote><blockquote>Have the budgeting basis been dependable or benefited a “few” in the real sense. Upper middle classes and below?</blockquote><p>I, I, I, I, I, I, I does not help all. It is not the nation’s need nor some omkar.</p><blockquote>Well, a Covid Emergency lockdown is not 1977 emergency lockdown. The needs, issues, decisions, affects, effects, policies do not match up apple to apple.</blockquote><p>You may not agree, of course, macro-economics is all about situational decision making and right ethical leadership; without breaching laws with whims and fancies.</p><p><em>Adding a point of note to avoid misinterpretation:</em></p><blockquote><strong>It is very important to keep finances and budgeting out of divisive planning and policies even if they may play a important role in your </strong><strong>Visions, Policies, Planning, Budgeting; owing to pro-, anti-, balanced- socialistic economic policies. Social factors play an important role in economics, viz-a-viz, the foundations of economics are people, who are social.</strong></blockquote><p>I have other half of the document that has not been published here that will go as a complaint. However, until then, pass the goodie… but let me know — to whome, to where, and how.</p><p>Many a times, accept the reality. The grass can be [and IS] greener on the other side.</p><p>I do not think CSs, CAs, Auditors, Financial Departments, RBI not understand this nor that this is a financial discovery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb3a6ff64fda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ExpressJS Series: True After Middlewares for ExpressJS]]></title>
            <link>https://ganeshkbhat.medium.com/expressjs-series-true-after-middlewares-for-expressjs-5c919f4e0d87?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c919f4e0d87</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[before-and-after]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 03:58:36 GMT</pubDate>
            <atom:updated>2023-03-11T03:23:33.624Z</atom:updated>
            <content:encoded><![CDATA[<p>After middlewares are basically a function of set of function that executes after all your business logic has been wrapped or finished.</p><p>This is a follow up article for</p><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-how-can-i-implement-before-and-after-middlewares-13da90892d72">ExpressJS Series: How can I implement before and after middlewares?</a></p><ol><li>While, I write this ExpressJS monkey patch article, let me change my dictionary a little and call the aftermiddlewares in this <a href="https://medium.com/@ganeshsurfs/expressjs-series-how-can-i-implement-before-and-after-middlewares-13da90892d72">ExpressJS aftermiddlewares</a> article to be “<strong><em>pseudo — aftermiddlewares</em></strong>”. I call them “<strong><em>pseudo aftermiddlewares</em></strong>” since they are executed when all the business logic has been performed but the aftermiddlewares are <em>executed “before” the response from the server is sent</em>.</li><li>A true aftermiddleware should execute or run after the response has been sent so that some clean up actions or after need activities can be performed; irrespective of what response was sent to the HTTP client.</li></ol><p>Now let us implement a “<strong><em>true aftermiddleware</em></strong>” in ExpressJS.</p><p>While ExpressJS does not have true after middlewares that executes after the response has been sent, you may modify this <strong><em>res.send</em></strong> function using a patch like below to achieve the feature of true after middlewares that executes or runs after the response has been sent by the server.</p><p>The same result of after middlewares execution can be achieved for <strong><em>res.sendFile</em></strong>, <strong><em>res.json</em></strong>, <strong><em>res.jsonp</em></strong> functions.</p><p>The real expressjs response functions can be found in the link:</p><p><a href="https://raw.githubusercontent.com/expressjs/express/master/lib/response.js">https://raw.githubusercontent.com/expressjs/express/master/lib/response.js</a></p><p>This is how the <strong><em>“original” res.send </em></strong>function looks like:</p><pre>/**<br> * Send a response.<br> *<br> * Examples:<br> *<br> *     res.send(Buffer.from(&#39;wahoo&#39;));<br> *     res.send({ some: &#39;json&#39; });<br> *     res.send(&#39;&lt;p&gt;some html&lt;/p&gt;&#39;);<br> *<br> * @param {string|number|boolean|object|Buffer} body<br> * @public<br> */<br><br>// Line 111<br>res.send = function send(body) {<br>  var chunk = body;<br><br>// ...<br>// ...<br>// ...<br><br>// Line 235<br>  return this;<br>}</pre><p>This is how the “original” <strong><em>res.send</em></strong> function should be <strong>patched</strong>:</p><pre>/**<br> * Send a response.<br> *<br> * Examples:<br> *<br> *     res.send(Buffer.from(&#39;wahoo&#39;));<br> *     res.send({ some: &#39;json&#39; });<br> *     res.send(&#39;&lt;p&gt;some html&lt;/p&gt;&#39;);<br> *<br> * @param {string|number|boolean|object|Buffer} body<br> * @public<br> */<br><br>// Line 111<br>res.send = function send(body, callback = (response, ...args) =&gt; { console.log(&quot;Testing aftermiddlewares with my actions&quot;, Date.now()); }, ...args) {<br>  var chunk = body;<br><br>// ...<br>// ...<br>// ...<br><br>// Add to Line 234<br>  ((callback, response, ...args) =&gt; { callback(response, ...args) })(callback, this, ...args);<br><br>// Line 235<br>  return this;<br>}</pre><p>This is how the <strong><em>complete/ full “patched” res.send</em></strong> function should look like after being patched:</p><pre>//<br>// Note the changed parts<br>// Line 111<br>// Function send(body) was changed to send(body, callback, ...args)<br>//<br>// function send(body) {<br>//<br>// function send(body, callback = (response, timer, ...args) =&gt; { console.log(&quot;Testing aftermiddlewares&quot;, timer || Date.now()); }, ...args) {<br>//<br><br>res.send = function send(body, callback = (response, ...args) =&gt; { console.log(&quot;Testing aftermiddlewares&quot;, Date.now()); }, ...args) {<br>  var chunk = body;<br>  var encoding;<br>  var req = this.req;<br>  var type;<br><br>  // settings<br>  var app = this.app;<br><br>  // allow status / body<br>  if (arguments.length === 2) {<br>    // res.send(body, status) backwards compat<br>    if (typeof arguments[0] !== &#39;number&#39; &amp;&amp; typeof arguments[1] === &#39;number&#39;) {<br>      deprecate(&#39;res.send(body, status): Use res.status(status).send(body) instead&#39;);<br>      this.statusCode = arguments[1];<br>    } else {<br>      deprecate(&#39;res.send(status, body): Use res.status(status).send(body) instead&#39;);<br>      this.statusCode = arguments[0];<br>      chunk = arguments[1];<br>    }<br>  }<br><br>  // disambiguate res.send(status) and res.send(status, num)<br>  if (typeof chunk === &#39;number&#39; &amp;&amp; arguments.length === 1) {<br>    // res.send(status) will set status message as text string<br>    if (!this.get(&#39;Content-Type&#39;)) {<br>      this.type(&#39;txt&#39;);<br>    }<br><br>    deprecate(&#39;res.send(status): Use res.sendStatus(status) instead&#39;);<br>    this.statusCode = chunk;<br>    chunk = statuses.message[chunk]<br>  }<br><br>  switch (typeof chunk) {<br>    // string defaulting to html<br>    case &#39;string&#39;:<br>      if (!this.get(&#39;Content-Type&#39;)) {<br>        this.type(&#39;html&#39;);<br>      }<br>      break;<br>    case &#39;boolean&#39;:<br>    case &#39;number&#39;:<br>    case &#39;object&#39;:<br>      if (chunk === null) {<br>        chunk = &#39;&#39;;<br>      } else if (Buffer.isBuffer(chunk)) {<br>        if (!this.get(&#39;Content-Type&#39;)) {<br>          this.type(&#39;bin&#39;);<br>        }<br>      } else {<br>        return this.json(chunk);<br>      }<br>      break;<br>  }<br><br>  // write strings in utf-8<br>  if (typeof chunk === &#39;string&#39;) {<br>    encoding = &#39;utf8&#39;;<br>    type = this.get(&#39;Content-Type&#39;);<br><br>    // reflect this in content-type<br>    if (typeof type === &#39;string&#39;) {<br>      this.set(&#39;Content-Type&#39;, setCharset(type, &#39;utf-8&#39;));<br>    }<br>  }<br><br>  // determine if ETag should be generated<br>  var etagFn = app.get(&#39;etag fn&#39;)<br>  var generateETag = !this.get(&#39;ETag&#39;) &amp;&amp; typeof etagFn === &#39;function&#39;<br><br>  // populate Content-Length<br>  var len<br>  if (chunk !== undefined) {<br>    if (Buffer.isBuffer(chunk)) {<br>      // get length of Buffer<br>      len = chunk.length<br>    } else if (!generateETag &amp;&amp; chunk.length &lt; 1000) {<br>      // just calculate length when no ETag + small chunk<br>      len = Buffer.byteLength(chunk, encoding)<br>    } else {<br>      // convert chunk to Buffer and calculate<br>      chunk = Buffer.from(chunk, encoding)<br>      encoding = undefined;<br>      len = chunk.length<br>    }<br><br>    this.set(&#39;Content-Length&#39;, len);<br>  }<br><br>  // populate ETag<br>  var etag;<br>  if (generateETag &amp;&amp; len !== undefined) {<br>    if ((etag = etagFn(chunk, encoding))) {<br>      this.set(&#39;ETag&#39;, etag);<br>    }<br>  }<br><br>  // freshness<br>  if (req.fresh) this.statusCode = 304;<br><br>  // strip irrelevant headers<br>  if (204 === this.statusCode || 304 === this.statusCode) {<br>    this.removeHeader(&#39;Content-Type&#39;);<br>    this.removeHeader(&#39;Content-Length&#39;);<br>    this.removeHeader(&#39;Transfer-Encoding&#39;);<br>    chunk = &#39;&#39;;<br>  }<br><br>  // alter headers for 205<br>  if (this.statusCode === 205) {<br>    this.set(&#39;Content-Length&#39;, &#39;0&#39;)<br>    this.removeHeader(&#39;Transfer-Encoding&#39;)<br>    chunk = &#39;&#39;<br>  }<br><br>  // this.set(&quot;server-time&quot;, Date.now().toString());<br><br>  if (req.method === &#39;HEAD&#39;) {<br>    // skip body for HEAD<br>    this.end();<br>  } else {<br>    // respond<br>    this.end(chunk, encoding);<br>  }<br><br>//<br>// Line 234<br>// Add following line<br>//<br>  ((callback, response, ...args) =&gt; { callback(response, ...args) })(callback, this, ...args);<br><br>  return this;<br>};</pre><p><strong>Update:</strong></p><p>When talking to the expressjs team for the above pull request, they also mentioned that you can run a callback after the response has been sent like this below. I was not aware of this nor had I seen this in lot or most of the codes ever, so I wanted you all to know this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ced615ba36f79d3aef3b4237023a7e7/href">https://medium.com/media/4ced615ba36f79d3aef3b4237023a7e7/href</a></iframe><p>Again, for a “<em>partial (pseudo) before and after middlewares</em>” that is executed or run before the response is sent, use this article in this link:</p><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-how-can-i-implement-before-and-after-middlewares-13da90892d72">https://medium.com/@ganeshsurfs/expressjs-series-how-can-i-implement-before-and-after-middlewares-13da90892d72</a></p><p>Happy Coding and after middlewares. Run your true DevOps like workflow activities behind a HTTP/S server using a HTTP based REST/ GraphQL.</p><p>This <a href="https://medium.com/@ganeshsurfs/expressjs-series-how-can-i-implement-before-and-after-middlewares-13da90892d72">before and after middlewares ExpressJS article</a> cover what I call a <strong><em>pseudo aftermiddlewares</em></strong>. It uses the following design:</p><p><em>Request -&gt; Before Middleware -&gt; APILogic -&gt; After Middleware -&gt; Response</em></p><p>However, this article provides implementation of <strong><em>true after middlewares</em></strong>. It follows following design:</p><p><em>Request -&gt; Before Middleware -&gt; APILogic -&gt; Response -&gt; After Middleware</em></p><p>To summarize:</p><p>This application pattern of using middlewares both before and after helps you with better code segregation for responsibilities, response manipulation (removal of clutter in such cases), cleaner code, and more importantly allowing you to do something after the response has been created or sent; whatever, the scenario.</p><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">ExpressJS Series All Blogs</a>: <a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c919f4e0d87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Node.js and JS: The love affair of PHP scripts integration from all languages]]></title>
            <link>https://ganeshkbhat.medium.com/exploring-node-js-and-js-the-love-affair-of-php-scripts-integration-from-all-languages-d7e01640b89f?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7e01640b89f</guid>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[phpcgijs]]></category>
            <category><![CDATA[execute]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 05:18:34 GMT</pubDate>
            <atom:updated>2022-11-28T05:25:13.592Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you trying to integrate PHP scripts to your node.js application? This blog and library may fit your needs well.</p><p><strong>BACKGROUND:</strong></p><p>The love affair of PHP developers trying to integrate and/ or run PHP Scripts into all languages has been an interesting one.</p><p>Well, did someone just say all languages have been trying to have an affair of trying to integrate and/ or run their languages in other stacks? Yes. They have been.</p><p>As expected, many love affairs fail without appropriate love and care.</p><p><em>On a lighter note</em>: C/ C++ has been a leader integrator and does the job well. But no one knows to work that out that weeeeell enough. Java does not care, it does it all. Python is looking AI/ML. Nodejs/ Javascript looks to be everywhere.</p><p><strong>PHPCGIJS:</strong></p><p>Let me introduce a new javascript/ node.js library in the npmjs environment — <a href="https://www.npmjs.com/package/phpcgijs">phpcgijs</a>.</p><p>The library takes two core routes while integrating other scripts like PHP into node.js — run the script via shell to get a stdout response, or proxy response from an PHP web application server.</p><p>Can running a PHP Script be as simple as</p><pre>const express = require(&quot;express&quot;);<br>const php = require(&quot;phpcgijs&quot;);<br>const path = require(&quot;path&quot;);<br>var app = express();<br>//<br>// Express Route<br>//<br>// app.use(<br>//         &quot;/&quot;,<br>//         php.cgi(<br>//                 path_to_phpscript,<br>//                { <br>//                   cgi_path: &quot;path_to_/usr/bin/_php_cgi_executable&quot;,<br>//                   options: { &quot;-c&quot;: &quot;path_to_php.ini_file&quot; } <br>//                }<br>//          )<br>//        );<br>//<br>app.use(&quot;/&quot;, php.cgi(p, { path.join(&quot;test/php&quot;), cgi_path: &quot;/usr/bin/&quot;, options: { &quot;-c&quot;: &quot;/etc/php.ini&quot; } }));<br>app.use(&quot;/phpdynamic&quot;, php.cgi( &quot;/path/to/phpscript.php&quot;, { &quot;cgi_path&quot;:&quot;to/php/cgi/path/php-cgi&quot;, &quot;options&quot;: {&quot;-c&quot;: &quot;/to/php/ini/path/php.ini&quot;} } ));<br>// Listen Express Server<br>app.listen(9090, &quot;127.0.0.1&quot;);</pre><p>Yes. With the <em>phpcgijs</em> library, it is as simple as this.</p><p>The <em>phpcgijs</em> library comes with multiple features that can run PHP Scripts in <em>multiple architecture modes/ routes to capture and integrate the script responses</em> as per your needs.</p><p>Either (a) use the stdout/ file serve responses into your node.js express middleware/ application, (b) use your php web application server’s response into your webserver using a proxy, (c) use the cgi executable’s stdout responses into your application/ server</p><ol><li>Express Middleware</li></ol><p><em>use the stdout responses into your node.js express middleware application</em></p><pre>require(&quot;phpcgijs&quot;).cgi()</pre><p>2. Running PHP Script as a file via the shell</p><pre>require(&quot;phpcgijs&quot;).cgijs.cgiServe()</pre><p>3. Remote Proxy</p><p><em>use your php web application response into your application/ server using a proxy of a PHP web application server</em></p><pre>require(&quot;phpcgijs&quot;).cgijs.proxy();</pre><p>4. Process Execute</p><p><em>use the executable stdout responses directly into your application/ server</em></p><pre>require(&quot;phpcgijs&quot;).cgijs.process();</pre><p>A sample usage of the cgi express middleware can be seen as follows:</p><pre>const express = require(&quot;express&quot;);<br>const php = require(&quot;phpcgijs&quot;);<br>const path = require(&quot;path&quot;);<br>var app = express();<br>//<br>// Express Route<br>//<br>// app.use(<br>//         &quot;/&quot;,<br>//         php.cgi(<br>//                 path_to_phpscript,<br>//                { <br>//                   cgi_path: &quot;path_to_/usr/bin/_php_cgi_executable&quot;,<br>//                   options: { &quot;-c&quot;: &quot;path_to_php.ini_file&quot; } <br>//                }<br>//          )<br>//        );<br>//<br>app.use(&quot;/&quot;, php.cgi(p, { path.join(&quot;test/php&quot;), cgi_path: &quot;/usr/bin/&quot;, options: { &quot;-c&quot;: &quot;/etc/php.ini&quot; } }));<br>app.use(&quot;/phpdynamic&quot;, php.cgi( &quot;/path/to/phpscript.php&quot;, { &quot;cgi_path&quot;:&quot;to/php/cgi/path/php-cgi&quot;, &quot;options&quot;: {&quot;-c&quot;: &quot;/to/php/ini/path/php.ini&quot;} } ));<br>// Listen Express Server<br>app.listen(9090, &quot;127.0.0.1&quot;);</pre><p>A sample usage of the proxy module can be seen as follows:</p><pre>const express = require(&#39;express&#39;);<br>const URL = require(&#39;url&#39;);<br>const fs = require(&#39;fs&#39;);<br>const os = require(&#39;os&#39;);<br>const path = require(&quot;path&quot;);<br>const cgijs = require(&quot;cgijs&quot;);<br><br>var app = express();<br>const ostype = os.type();<br>var configuration;<br><br>if (ostype === &quot;Linux&quot;) {<br>    configuration = JSON.parse(fs.readFileSync(&#39;./demo/demo-app/config-linux.json&#39;));<br>} else if (ostype === &quot;Windows_NT&quot;) {<br>    configuration = JSON.parse(fs.readFileSync(&#39;./demo/demo-app/config-win.json&#39;));<br>} else if (ostype === &quot;Darwin&quot;) {<br>    configuration = JSON.parse(fs.readFileSync(&#39;./demo/demo-app/config-mac.json&#39;));<br>}<br><br>let php = configuration.php.script.path;<br>let sport = 9090, shost = &#39;127.0.0.1&#39;;<br><br>let config = {<br>    &quot;options&quot;: {<br>        &quot;target&quot;: {<br>            &quot;protocol&quot;: &quot;http:&quot;,<br>            &quot;host&quot;: &quot;127.0.0.1&quot;,<br>            &quot;port&quot;: 9001,<br>            &quot;pfx&quot;: null,<br>            &quot;passphrase&quot;: &quot;&quot;<br>        },<br>        &quot;ws&quot;: false,<br>        &quot;secure&quot;: false,<br>        &quot;xfwd&quot;: true,<br>        &quot;toProxy&quot;: true,<br>        &quot;prependPath&quot;: true,<br>        &quot;ignorePath&quot;: false,<br>        &quot;changeOrigin&quot;: false,<br>        &quot;preserveHeaderKeyCase&quot;: true,<br>        &quot;auth&quot;: &quot;:&quot;,<br>        &quot;hostRewrite&quot;: true,<br>        &quot;protocolRewrite&quot;: null,<br>        &quot;cookieDomainRewrite&quot;: false,<br>        &quot;cookiePathRewrite&quot;: false,<br>        &quot;headers&quot;: {},<br>        &quot;proxyTimeout&quot;: 10000,<br>        &quot;timeout&quot;: 10000,<br>        &quot;selfHandleResponse&quot;: false,<br>        &quot;buffer&quot;: null,<br>        &quot;ssl&quot;: {<br>            &quot;key&quot;: null,<br>            &quot;cert&quot;: null<br>        }<br>    },<br>    &quot;listenPort&quot;: 8001,<br>    &quot;stream&quot;: false,<br>    &quot;modify&quot;: false,<br>    &quot;runtime&quot;: false<br>};<br><br>function remoteWebProxy(port) {<br>    var remoteproxy = express();<br>    remoteproxy.use(&quot;/sub&quot;, function (req, res, next) { res.status(200).send(&quot;Path //sub&quot;); });<br>    remoteproxy.use(&quot;/&quot;, function (req, res, next) { res.status(200).send(&quot;Path //&quot;); });<br>    let srv = remoteproxy.listen(port);<br>    return { proxy: remoteproxy, server: srv };<br>}<br><br>var remoteProxy = remoteWebProxy(configuration.options.target.port);<br><br>function proxyHandler(handler, configuration) {<br>    handler.proxy.setup(&quot;proxyone&quot;, configuration, {})<br>    let proxy = handler.proxy.serve(&quot;proxyone&quot;);<br>    return function (req, res, next) {<br>        proxy.proxy.web(req, res)<br>    }<br>}<br><br>let h = cgijs.proxy();<br>app.use(&quot;/proxyone&quot;, proxyHandler(h, config));<br><br>app.use(&quot;*&quot;, (req, res) =&gt; res.send(&quot;Testing Server&quot;));<br><br>app.listen(sport, shost, function () {<br>    console.log(`Server listening at ${sport}!`);<br>});</pre><p>A sample usage of the process execute method can be seen as follows:</p><pre>const obj = require(&quot;phpcgijs&quot;).cgijs.process();<br><br>var proc = obj.process.executeProcess(<br>    {<br>        name: &quot;phptest&quot;, exe: &quot;php-cgi&quot;, os: &quot;win32&quot;, <br>        // options in child_process.exec(command, options) <br>        options: {<br>            stdio: &#39;inherit&#39;,<br>            shell: true<br>        },<br>        // COMMAND .cmds list to execute<br>        cmds: { &quot;generic&quot;: { usage: &quot;&quot;, args: [&quot;./www/php/index.php&quot;] } },<br>        other: {<br>            osPaths: { conf: &quot;&quot;, exe: &quot;&quot; },<br>            executetype: &quot;&quot;,<br>            // COMMAND .cmds to execute in the above list<br>            command: &quot;generic&quot;,<br>            serverType: &quot;&quot;<br>        }<br>    },<br>    (error, stdout, stderr) =&gt; {<br>        // EXEC STDOUT STDERR HANDLER FUNCTION<br>        console.log(&quot;CB: Callback function Invoking for dataHandler&quot;);<br>        console.log(&quot;CB: Stdout: &quot;, stdout);<br>        console.log(&quot;CB: Stderr: &quot;, stderr);<br>        console.log(&quot;CB: Error: &quot;, error);<br>    },<br>    (options, prc) =&gt; {<br>        // EXIT HANDLER FUNCTION<br>        console.log(&quot;Exit Handler options for cleanup handler&quot;, options);<br>        console.log(&quot;Exit Handler process&quot;, prc.pid);<br>    },<br>    (data, code) =&gt; {<br>        // CALLBACK FUNCTION <br>        console.log(&quot;CB: Callback function Invoking for handler&quot;);<br>    }<br>);</pre><p>I will cover each of the modules in detail in the upcoming blogs.</p><p>While these architectures look very easy, there have been issues when working and capturing the executable’s shell output which is the most dependable if what you are trying to integrate is a script or a file (and not really a web application).</p><p>The PHPCGIJS npmjs package is going through an architectural overhaul that</p><p>(a) makes use of <em>lesser</em> dependencies,</p><p>(b) works with multiple protocols of <em>proxy</em>’ing including <em>http</em>, <em>https</em>, <em>websockets</em>, <em>udp</em>, <em>tcp</em>, <em>sockets (socks)</em></p><p>(c) making the file module <em>phpcgijs.cgijs.file</em> module’s <em>.cgiServe </em>execution tailored to <em>PHP and other</em> scripts.</p><p>(d) making the process module work with the <em>phpcgijs.cgijs.process</em> <em>phpcgijs.cgijs.file</em> module’s <em>child_process.exec</em>, <em>child_process.fork</em>, <em>child_process.spawn </em>execution tailored to <em>PHP and other</em> scripts/ executables/ processes.</p><p>(e) more testing of code and real use cases</p><p>However, if you are interested to use, or have questions, or want to contribute, you can connect with me here or by raising an issue in the following repositories:</p><p><a href="https://www.npmjs.com/package/phpcgijs">PHPCGIJS</a></p><p><a href="https://github.com/cgi-js/node-php-cgi">GitHub - cgi-js/node-php-cgi: Run and Execute PHP, JS, Ruby, Python 2, Python 3, ASPX, JSP, and CGI in CGI mode / Shell mode / nodejs server using node.js npm package / module phpcgijs: npm install phpcgijs --save</a></p><p><a href="https://www.npmjs.com/package/cgijs">CGIJS</a></p><p><a href="https://github.com/cgi-js/cgi-js">GitHub - cgi-js/cgi-js: Run cgi / interpreted script files that supports command line execution, or connect to cgi / other server proxies : npm install cgijs --save</a></p><p>I am looking for any feedback and feature request under the earth for this library to ease and unblock any of your language integration needs in this problem area. I am looking to make <em>phpcgijs</em> and <em>cgijs</em> a one stop package for multiple tech stack integration.</p><p><strong>Note</strong>: The library is in active development and is platform/ framework agnostic/ independant.</p><p>I am also blogging about Expressjs along with Nodejs.</p><p><a href="https://medium.com/@ganeshsurfs">https://medium.com/@ganeshsurfs</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7e01640b89f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Node.js and JS: Developer Maths and Dechiphering Primes and working with basic utilities]]></title>
            <link>https://ganeshkbhat.medium.com/developer-maths-dechiphering-primes-and-working-with-basic-utilities-478d548618b?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/478d548618b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 08:02:38 GMT</pubDate>
            <atom:updated>2022-11-28T05:21:24.765Z</atom:updated>
            <content:encoded><![CDATA[<p>Calculate, work with primes or check primes in a very fast way possible.</p><p><strong>Background</strong>:</p><p>Basic mathematics were never so interesting for me. As for that matter even history classes. I was too busy with my friends and childhood. But as I started choosing my profession and proceeded in life, I had to go back to history, math, chemistry, and biology as much as I hated studying them.</p><p>Having said that: Let children enjoy childhood with studies and play like they should; without stress and with the right focus of what makes them successful in your geolocation (important).</p><p><strong>Context:</strong></p><p>Dechiphering primes is something I never thought I would write about. There were so few libraries and a little need of the same in normal development work. Anything needed as a math library needed is freely available on the internet. No need to work on algorithms, especially, in the current age of AI/ML. The experts, both commercial and opensource teams, have done the work for you. Your need is to implement them.</p><p>But then I was asked to write a prime number check in one of my historical interviews and I wrote this library for you all.</p><p>Fast Prime:</p><p><a href="https://www.npmjs.com/package/fast-prime">fast-prime</a> is a library that is written in <a href="https://www.npmjs.com/package/fast-prime-client">Javascript</a> (for browsers), <a href="https://www.npmjs.com/package/fast-prime">Nodejs</a>, <a href="https://pypi.org/project/fast-prime/">Python</a>, <a href="https://github.com/ganeshkbhat/fastprimenumbers/tree/main/java">Java</a>, <a href="https://github.com/ganeshkbhat/fastprimenumbers/tree/main/typescript">Typescript</a>, <a href="https://github.com/ganeshkbhat/fastprimenumbers/tree/main/php">PHP</a>. I intend to write it for Go, and C/C++ as well.</p><p>You can find the repository here: <a href="https://github.com/ganeshkbhat/fastprimenumbers">https://github.com/ganeshkbhat/fastprimenumbers</a></p><p>It has three basic implementations —</p><ol><li>Conventional Iteration,</li><li>Square root (AKS - Mersenne primes - Fermat&#39;s little theorem) Iteration,</li><li>Fast, innovative, and new implementation — fast-prime.</li></ol><p>Check this code out. This may be the fastest prime calculations, checks, and implementation as of 11th March 2022 based on the number of iterations and the way it checks for primes or generates primes. If someone testifies the performance checks, I will add/submit this for a publication — on a serious note. Help invited.</p><p>The library and code only has a <a href="https://github.com/ganeshkbhat/fastprimenumbers/blob/main/LICENSE">special give me credit and notify me proprietory license</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3ed06064b32f880fbdb4c64e0594987/href">https://medium.com/media/d3ed06064b32f880fbdb4c64e0594987/href</a></iframe><p>Here are the complete codebase and the package repository.</p><ul><li><a href="https://github.com/ganeshkbhat/fastprimenumbers/blob/main/nodejs/src/node/primes_alternate.js">fastprimenumbers/primes_alternate.js at main · ganeshkbhat/fastprimenumbers</a></li><li><a href="https://github.com/ganeshkbhat/fastprimenumbers/blob/main/nodejs/src/node/primes.js">fastprimenumbers/primes.js at main · ganeshkbhat/fastprimenumbers</a></li></ul><p>The package allows you to:</p><ol><li>check is a number is prime (in different ways — Conventional Iteration, Square root (AKS — Mersenne primes — Fermat’s little theorem) Iteration, and Fast innovative — fast-prime),</li><li>generate a single or range or counts of prime,</li><li>generate summation and factorials of range/ count of primes</li><li>has a generator function for primes generation,</li><li>random primes generation, and</li><li>pre-calculated primes (&lt; 10000, &lt; 100000, &lt; 1000000).</li></ol><p>I am also blogging about Expressjs along with Nodejs.</p><p><a href="https://medium.com/@ganeshsurfs">https://medium.com/@ganeshsurfs</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478d548618b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Node.js and JS: Checking is a package is a CommonJS script/module or a ESM module]]></title>
            <link>https://ganeshkbhat.medium.com/exploring-node-js-and-js-checking-is-a-package-is-a-commonjs-script-module-or-a-esm-module-2847c456d93f?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2847c456d93f</guid>
            <category><![CDATA[esm]]></category>
            <category><![CDATA[commonjs]]></category>
            <category><![CDATA[check]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[check-esm]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Sun, 30 Oct 2022 02:35:05 GMT</pubDate>
            <atom:updated>2023-09-23T02:31:07.654Z</atom:updated>
            <content:encoded><![CDATA[<p>Many a times finding whether a code is commonjs script, commonjs module, or esm module makes or breaks your code. Be in a surprise if you find yourself in that situation. And, the situation is common.</p><p>I am writing this, right now, near a spiritual place where “some” people are worshiping for money; rather than for peace and solace.</p><p>Let not — not being able to find out whether a code is commonjs script, commonjs module, or esm module be a solace.</p><p>There are a few ways you can check (as of 30thSeptember 2022) whether a code is a commonjs script, commonjs module, esm module:</p><ol><li>Package.json —key type used as “type” : “module”</li><li>File extension — whether .js, .cjs, .mjs</li><li>Check if require object is globally present</li><li>Check if import is supported</li><li>Check the version of Node.js you are using</li></ol><p>While doing all the checks above can be cumbersome, I am introducing a module called check-esm (<a href="https://www.npmjs.com/package/check-esm">https://www.npmjs.com/package/check-esm</a>) that does all the jobs above for you in one simple function “_isESCode”.</p><p>Let us look at how to use it:</p><ol><li>Install the package <a href="https://www.npmjs.com/package/check-esm">https://www.npmjs.com/package/check-esm</a> using the command “npm i check-esm” in your package</li><li>Use the functions in the following code examples as a demo.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9130b9bcc1b7f96fe6abad9dd80888a7/href">https://medium.com/media/9130b9bcc1b7f96fe6abad9dd80888a7/href</a></iframe><p>How difficult was that? Please let a feedback, or pull request, or an issue in the github repository here: <a href="https://github.com/ganeshkbhat/isesm">https://github.com/ganeshkbhat/isesm</a> or <a href="https://www.npmjs.com/package/check-esm">https://www.npmjs.com/package/check-esm</a></p><p>There are other script APIs you may wish to explore that includes the following:</p><p>_checkModuleImports, _requiresObject, _requireRegex, _importRegex, _importESRegex, _importRegexExtended, _isESMFileExtension, _isESMCodeBase, _isCJSCodeBase, _isESCode, _isModuleInPackageJson</p><p>The APIs have now been updated in the newer version to have normalized naming as below:</p><p>checkModuleImports, requiresObject, requireRegex, importRegex, importESRegex, importRegexExtended, isESMFileExtension, isNodeCompatibleFileExtension, isESMCodeBase, isCJSCodeBase, isModuleInPackageJson, isESCode</p><p>I am also blogging about Expressjs along with Nodejs.</p><p><a href="https://medium.com/@ganeshsurfs">https://medium.com/@ganeshsurfs</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2847c456d93f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ExpressJS Series: Managing json configuration based express server]]></title>
            <link>https://ganeshkbhat.medium.com/expressjs-series-managing-json-configuration-based-express-server-dc2f88caf58f?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc2f88caf58f</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[json-schema]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Tue, 10 May 2022 11:09:57 GMT</pubDate>
            <atom:updated>2022-05-10T11:36:24.600Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a Express application or for that matter any other framework’s application creation can be a daunting task. It should not be so now. Reason: Many people now use pre-made templates, template automation scripts, pre-made files to create a logic structure for app, etc.</p><p>Most times, it may bloat the application size and that may not be a real side effect that you may need. Let us look at another way of working with the application. This concept may not be completely new. But, probably, technology variation of the <em>Donot Repeat Yourself (DRY) principle</em>.</p><p>I call this a “configuration based application route generation”. You call it what you want. The routes can be created in simple JSON file or as a JSON Object in a JS file. Let us have a look at what I have been working with since sometime now and I found it to be simple to work with.</p><p>Please take a look at the <em>config.json</em>, <em>index.js</em> files below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e0ee57ef9f461f69496a506f2c0b0a/href">https://medium.com/media/45e0ee57ef9f461f69496a506f2c0b0a/href</a></iframe><p>Please feel free to add your own parameters to <em>config.json</em> like for overriding response functions, etc.</p><p>Please feel free to make changes to <em>index.js</em> as per need to manage your <em>middlewares/ callbackHandler</em> functions and their import ways based on project structure or other requirements. Probably, manipulate it for adding callback or middleware functions imported from some folder mentioned in config.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4ae94957a133966866974792e0d1e1/href">https://medium.com/media/af4ae94957a133966866974792e0d1e1/href</a></iframe><p>Well, you can also automate function template’s (like above) creation and config file generation using a cli javascript script. Take a try at it.</p><p>To summarize:</p><p>This application routing technique makes it easy to implement just route handlers and route specific middlewares in an easier way without having to handle multiple changes in your applications’ routing, controller, middleware, and/or configuration system.</p><p>A simple addition of the route handler, middlewares, route method, and path suffices the creation of an entire new routing for the application without a lot of efforts. This process is easier automated “than” other modes of automation or code creation automation.</p><p>Did I say simplest “serverless” model?</p><p>Now, lets go RAD on REST APIs and GraphQL APIs.</p><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">ExpressJS Series All Blogs</a>: <a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc2f88caf58f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ExpressJS Series: How can I implement before and after middlewares?]]></title>
            <link>https://ganeshkbhat.medium.com/expressjs-series-how-can-i-implement-before-and-after-middlewares-13da90892d72?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/13da90892d72</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 12:44:15 GMT</pubDate>
            <atom:updated>2023-02-25T04:12:52.742Z</atom:updated>
            <content:encoded><![CDATA[<p>It is a great concept that you can implement middlewares in ExpressJS. A lot of frameworks have been using this idea, copied from ExpressJS, since. ExpressJS is basically a <a href="https://docs.zendframework.com/zend-expressive/v3/cookbook/double-pass-middleware/">double pass middleware</a>. “Double pass middleware receives both the request and a response in addition to the handler, and passes both the request and response to the handler when invoking it”. Below is a normal implement of our ExpressJS function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97d0dc8ab1625207004c42459148543/href">https://medium.com/media/c97d0dc8ab1625207004c42459148543/href</a></iframe><p>Triggering a middleware before the response is great. However, there are scenarios where you might want logging after response has been completed. You can achieve this in the responseHandler or by adding a afterMiddleware after our responseHandler in the ExpressJS route implementation. Lets look at the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcc4065a7a296b0363500c96b577a686/href">https://medium.com/media/dcc4065a7a296b0363500c96b577a686/href</a></iframe><p>Note:</p><p>Trying to manipulate the response or headers in the afterMiddleware function will fetch us an application error — warning us that the response has been sent to the client.</p><p>However, there are a lot of scenarios where you might want to either manipulate the response after the responseHandler has been triggered, or you might want to perform other tasks after the response has been created. These may include advanced logging for analytics before response is sent, response validation, response sanitation, or just ACL based response manipulation.</p><p>It is important to note that when you use .send() function in ExpressJS, you cannot manipulate the headers nor the response. It is possible to do other activities (other than header or response manipulation) after the response is sent. This may be anything from logging, triggering schedulers, emailing, or some pub-sub action. However, again the headers nor the response can be manipulated since the response has been sent to the client already.</p><p>This creates a couple of use cases. May be once the response has been created, you might want to check if the response object variables or data to be sent is actually valid, authorised, and if not you may want to restrict it or remove that response data. Second, you may just want to log it off somewhere for analytics purposes, response sanitation, or just ACL based response manipulation, or just initiate a pub-sub application’s action after the response has been created/”supposedly” sent.</p><p>Lets create the code that will behave so. Instead of using the .send() we will create a .send() manipulator function called .response (function) attached to the ExpressJS response object that will allow us to trigger after middlewares (after responseHandler function trigger) in our ExpressJS application. Once all the after response middlewares have been triggered, we will use a final handler function that will take the pre-created response / after-middlewares-manipulated response and send it to the client. Lets look at the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f0de69be600a54a505e33f38493a867/href">https://medium.com/media/3f0de69be600a54a505e33f38493a867/href</a></iframe><p>If you notice, the beforeAfterInjection function is the one that allows us to use a .response(obj) function. This is one of the most important functions and is always triggered first in the middleware list. The signification of the function is that it separates the logic of storing the response from the actual response handler function.</p><p>The next middleware in the implementation is the beforeMiddleware function which is a normal middleware that we have all been using before in ExpressJS.</p><p>Then comes a quite important middleware implementation where our application’s response handler resides. Notice that we have not used the responseHandler directly but we have actually wrapped this in a wrapper function that triggers the responseHandler function and then calls next() to pass the triggers to then next middleware — actually our after middlewares implementation — afterMiddleware. Do notice here that our implementation of afterMiddleware does not come at the cost of sending the response to the client. The response is yet stored in the request object as a req.res property rather than being sent to client. This afterMiddleware implementation allows us to do ACL checks, validation, sanitation, and all that you can think of in a cleaner and single-responsibility fashion from within the application. Instead of a single function taking care of all the work in the responseHandler, we are now delegating the tasks to other middlewares.</p><p>But, again, what happens if I use the .send() function instead of .response() function created by us to manipulate the framework for this kind of pattern? Well, actually, the response will be sent to the client even though the afterMiddleware is triggered. This can be nasty if you have business logic that needs the response to client to be held back for manipulation in the after middlewares. A .send() implementation instead of .response() implementation in this case results in an “application error” when trying to manipulate the response or headers; warning us that the response has been sent to the client. However, there may be cases where you might not need the response to the client to be held back; like say logging or sending a email trigger, etc. Such cases, you can actually use the .send() trigger of ExpressJS. The client will receive the response faster (rather on time) without having to worry about delays due to your application’s after response action’s logic. Lets have a look at such implementation below, again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/920a641ebee3f4343c62e701ae2230ff/href">https://medium.com/media/920a641ebee3f4343c62e701ae2230ff/href</a></iframe><p>Now, you have a choice to for your implementation — using this application pattern or all other ways that you have implemented your business logic after the response has been created. However, testing can be a challenge like it is for your normal responseHandlers which needs a request, response, and next arguments to be passed while testing. You may be better off on performing API end tests in such cases, or segregating common logic from your middlewares to test. Choose one that you like, is more testable, or one that fits your needs more.</p><p>For a <strong><em>true aftermiddleware implementation</em></strong> in ExpressJS for <strong><em>usage in devops or workflow automation use cases</em></strong> use this link:</p><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-true-after-middlewares-for-expressjs-5c919f4e0d87">ExpressJS Series: True After Middlewares for ExpressJS</a></p><p>This article cover what I call a <em>pseudo aftermiddlewares</em>. It uses the following design:</p><p><em>Request -&gt; Before Middleware -&gt; APILogic -&gt; After Middleware -&gt; Response</em></p><p>However, <a href="https://medium.com/@ganeshsurfs/expressjs-series-true-after-middlewares-for-expressjs-5c919f4e0d87">this link</a> provides implementation of <a href="https://medium.com/@ganeshsurfs/expressjs-series-true-after-middlewares-for-expressjs-5c919f4e0d87"><em>true aftermiddlewares</em></a>. It follows following design:</p><p><em>Request -&gt; Before Middleware -&gt; APILogic -&gt; Response -&gt; After Middleware</em></p><p>To summarize:</p><p>This application pattern of using middlewares both before and after helps you with better code segregation for responsibilities, response manipulation (removal of clutter in such cases), cleaner code, and more importantly allowing you to do something after the response has been created or sent; whatever, the scenario.</p><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">ExpressJS Series All Blogs</a>: <a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13da90892d72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ExpressJS Series: What I need to know about serving a response?]]></title>
            <link>https://ganeshkbhat.medium.com/expressjs-series-what-i-need-to-know-about-serving-a-response-b8964a0ff13?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8964a0ff13</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[learning-and-development]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Wed, 03 Oct 2018 03:20:24 GMT</pubDate>
            <atom:updated>2018-10-04T08:07:19.296Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@ganeshsurfs/expressjs-series-applying-standard-security-to-expressjs-server-16e1a00c1c4f">previous post</a>, we set up the basic secure for our ExpressJS Server. Before we start delving into details of an application development, we will also understand how to serve responses/files from our server.</p><p>There are three different types of application responses that serve some content:</p><ol><li>Static Application (serving static assets like HTML, CSS, etc)</li><li>Template based application (dynamic pages processed and responses served as pages by the application)</li><li>REST / SOAP based Server application responses with a client either HTML or an Single Page Application</li></ol><p>All the three are used today in the market extensively, depending on project needs. The way to serve responses from an ExpressJS application is also the same. This is apart from the fact that project structure, application architecture, coding patterns, testing and its ways, and deployment “may” differ for all the three ways of serving a response from the server.</p><p>Let us take the first, Static responses. These are response where where static files like HTML, CSS, Images, fonts, etc are served. One of the job’s of the server is that it serves static content. Now, this may be an entire site or just some assets of your application or site.</p><p>NodeJS and the ExpressJS framework by default does not expose any folder publicly. You have to do it explicitly. Let us do it.</p><p>ExpressJS provides a method called as <strong>.<em>static</em></strong> that allows you to expose a static folder publicly. You can apply this as an middleware later.</p><p>Usage:</p><blockquote>express.static(root, [options])</blockquote><p>Let us create a folder called as <em>public</em> and put any file called <em>styles.css</em> in it. Second, let us create a folder <em>client</em> and then <em>assets</em> within it. Finally, let us add the middleware that servers the static folder. Take a look at the code snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17f46946c16910f1a04065795af74497/href">https://medium.com/media/17f46946c16910f1a04065795af74497/href</a></iframe><p>We see that there are three ways of serving :</p><ol><li>Same name exposed: The <em>public</em> folder inside our project folder <em>basicsrv</em> is served with the same name publicly.</li><li>Different name exposed with relative path: The ‘<em>client/assets</em>’ folder in line 12 is exposed as <em>/assets</em> publicly. <em>This allows us to keep the system path names hidden (if not all secure)</em>.</li><li>Different name exposed with complete path: The ‘<em>client/assets</em>’ folder in line 20 is exposed as <em>/assets</em> publicly. But this time it <em>uses the complete path of the OS rather than a relative path</em>.</li></ol><p>A point to note is that response object <em>res </em>in the route handler also provides us an option to send files. You can use the method <strong><em>.sendFile</em></strong> in the res object after the .<strong><em>status</em></strong> method like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1206321ffb9ab76922551cacfdb2f3a5/href">https://medium.com/media/1206321ffb9ab76922551cacfdb2f3a5/href</a></iframe><p>That is all to serving static files and responses from the application.</p><p>There are two other ways of sending a response to the client.</p><ol><li>We have looked at one way before by means of sending a JSON file using the <strong>.<em>send</em></strong> method. The <strong><em>.send</em></strong> method applies for not just sending response as JSON but also for XML.</li><li>But, for a template engine based response you have to use the <strong><em>.render</em></strong> method. This has to be in the route handler after we set the view folder and templating engine details using the <strong><em>.set</em></strong> method of express app.</li></ol><p>Before setting the template engine to our app, let us have a look at the code below for sending json/xml type responses:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8896433a0e23f055dc09b0111cb54875/href">https://medium.com/media/8896433a0e23f055dc09b0111cb54875/href</a></iframe><p>Dont forget to install xml2js to send xml as a response.</p><blockquote>npm install -S xml2js</blockquote><p>To send a dynamic template engine based response, we will have to add a middleware informing our ExpressJS Application that we are going to use a specific templating engine. Commonly used <a href="https://github.com/expressjs/express/wiki#template-engines">templating engines</a> are <a href="https://www.npmjs.com/package/jade">Jade</a> (now pug), <a href="https://www.npmjs.com/package/pug">Pug</a>, <a href="https://www.npmjs.com/package/ejs">ejs</a>, <a href="https://www.npmjs.com/package/mustache">Mustache</a>, etc.</p><p><a href="https://expressjs.com/en/guide/using-template-engines.html">ExpressJS uses Pug/Jade</a> as the default. If you are coming from other backend programming languages then you might like <em>ejs</em> since it used variable binding based templates. However, if you like <em>HAML</em>, then <em>Pug/Jade</em> is for you.</p><p>Lets install pug.</p><blockquote>npm install pug -S</blockquote><p>Now, lets create a <em>view</em> folder in the <em>basicsrv</em> folder and inform express about what templating engine we are going to use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a503c08ecb7ee1260747ed38bdb6124c/href">https://medium.com/media/a503c08ecb7ee1260747ed38bdb6124c/href</a></iframe><p>Lets create the template file called as <em>views/index.pug</em> as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/304b4b21a6048848844c3230f7aa8ae5/href">https://medium.com/media/304b4b21a6048848844c3230f7aa8ae5/href</a></iframe><p>Add this code in your file, and run the file. The try accessing the path <a href="http://127.0.0.1:9001/template"><em>http://127.0.0.1:9001/template</em></a> . You will see the template rendered. If you wish to change the templating engine to something else then you will have to set your new templating engine in the ExpressJS application.</p><p>Thats it. We covered the bare bone basics of ExpressJS.</p><p>To summarize, along the post we touched:</p><ul><li>Rendering files from a static pulic folder in three different ways.</li><li>Sending JSON, and XML response.</li><li>Sending a server processed html page processed from a pug template</li></ul><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">ExpressJS Series All Blogs</a>: <a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8964a0ff13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ExpressJS Series: Applying standard security to ExpressJS Server]]></title>
            <link>https://ganeshkbhat.medium.com/expressjs-series-applying-standard-security-to-expressjs-server-16e1a00c1c4f?source=rss-935bd349918c------2</link>
            <guid isPermaLink="false">https://medium.com/p/16e1a00c1c4f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[learning-and-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Ganesh B]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 13:58:13 GMT</pubDate>
            <atom:updated>2018-10-04T03:32:50.872Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@ganeshsurfs/expressjs-series-understanding-the-request-from-the-client-with-the-help-of-middlewares-a50960c4239f">previous post</a>, we used body-parser library to understand the request and parse the request body. We worked with library internals of working with parsing. I intend to touch real life use cases later, once we understand ExpressJS Framework better.</p><p>In this post, we will focus on applying Content Security Policy, Cross Site Scripting, Cross Site Request Forgery, and Rate limit safe guards. All this will be done in a very simple manner with just few libraries and few code lines additions.</p><ol><li><a href="https://github.com/helmetjs/helmet">helmet</a></li><li><a href="https://www.npmjs.com/package/express-rate-limit">express-rate-limit</a> or/and <a href="https://www.npmjs.com/package/express-brute">express-brute</a> or/and <a href="https://github.com/animir/node-rate-limiter-flexible">node-rqate-limiter-flexible</a></li><li><a href="https://www.npmjs.com/package/cors">cors</a></li><li><a href="http://expressjs.com/en/resources/middleware.html">Others</a></li></ol><p>If you are overwhelmed by the incomplete details above and what we are trying to achieve, have a quick look at the <a href="https://expressjs.com/en/advanced/best-practice-security.html">security best practices brief in the ExpressJS documentation</a> before starting.</p><ol><li>CSP, CORS: Have you ever wondered what would happen if your site was open to requests from everyone and people start hacking attacks?</li><li>Sanitization, CSRF, XSS: What if someone fills a form or comment and enters a (creepy) javascript snippet in a post of forum hosted on your site which gets displayed/loaded (because your did not sanitise for safety of HTML before rendering it in the forum post or comment)?</li><li>Sanitization, XSS, CSRF: What happens if that creepy javascript posted in a unsanitized (uncleaned) document rendering starts capturing security tokens off cookies, taking off localstorage data, or just starts putting unending popping messages from that external script?</li><li>Sanitization, XSS, CSRF: What if, that creepy javascript posted in a unsanitized (uncleaned) document rendering loads a heavy unnecessary javascript files, image, file, or infected file from a third party location?</li><li>Sanitization, CSRF: What if, they save your site’s form and start sending form submits from local system? What if, this process gets automated by the hacker?</li><li>Secure Protocol: What if, the hacker intercepted your client’s insecure requests during login or form submits or browsing in general?</li><li>CORS, Rate Limiting, DDOS: What if, just to be noticed after hacking failure, they start annoying your server with huge amount of requests your server is not able to handle?</li><li>CORS, Rate Limiting, DDOS: What if, they keep a automated agent or spider that makes constant 1Million or X requests every hour consistently for next one month or perennially? More, if your server is able to handle those requests, wont your cloud billing or resources get blocked or wasted?</li><li>CORS, Rate Limiting, DDOS, CSRF, Targeted Vulnerability Attacks: What if, such requests are brute force (and automated request randomizer) attacks targeted at a very important section of the application because the hacker knows the vulnerabilities of the server or the application’s functioning (development vulnerability)?</li></ol><p>There are more that we have not spoken about. The hacker never has the best interest and intentions for you. A protector safeguards by risk mitigation, not by teaching a lesson through cyber crimes. As an developer or an infrastructure or an security professional, you owe a lot of accountability, responsibility, and risk mitigation to your users and organisation to safeguarding their assets from hacks; and incase things go wrong then your response to it.</p><p>These packages address the risk mitigation part of security. They help you set up a bare basic standard protection against known vulnerabilities (in the least tedious manner).</p><p>Note that <em>all these packages are ExpressJS middlewares. You can either apply them to all routes or a single route/group of routes based on need and security strictness.</em></p><p><strong>HELMET</strong></p><p>Helmet is a middleware that clubs many libraries together to give a comprehensive support against a few common attacks/known vulnerabilities. It may not cover all the use cases but it is one of the best packages I have seen that implements protection against these issues. With just few lines, it gives you a set of default security implemented for your server. This makes the ExpressJS server more secure out of the box.</p><p>Let use install it in our project:</p><blockquote>npm install helmet -S</blockquote><p>Let us add helmet() as a middleware. Look at the code in Line3 and Line 8:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67277bd84db1e59a402f37e7f2d29a4f/href">https://medium.com/media/67277bd84db1e59a402f37e7f2d29a4f/href</a></iframe><p>It adds default security using libraries below (<a href="https://github.com/helmetjs/helmet#how-it-works">read more here</a>) by default:</p><blockquote><a href="https://helmetjs.github.io/docs/csp/">contentSecurityPolicy</a> for setting Content Security Policy (CSP) <br><a href="https://helmetjs.github.io/docs/expect-ct/">expectCt</a> for handling Certificate Transparency <br><a href="https://helmetjs.github.io/docs/dns-prefetch-control">dnsPrefetchControl</a> controls browser DNS prefetching ✓<br><a href="https://helmetjs.github.io/docs/frameguard/">frameguard</a> to prevent clickjacking ✓<br><a href="https://helmetjs.github.io/docs/hide-powered-by">hidePoweredBy</a> to remove the X-Powered-By header ✓<br><a href="https://helmetjs.github.io/docs/hpkp/">hpkp</a> for HTTP Public Key Pinning <br><a href="https://helmetjs.github.io/docs/hsts/">hsts</a> for HTTP Strict Transport Security ✓<br><a href="https://helmetjs.github.io/docs/ienoopen">ieNoOpen</a> sets X-Download-Options for IE8+ ✓<br><a href="https://helmetjs.github.io/docs/nocache/">noCache</a> to disable client-side caching <br><a href="https://helmetjs.github.io/docs/dont-sniff-mimetype">noSniff</a> to keep clients from sniffing the MIME type ✓<br><a href="https://helmetjs.github.io/docs/referrer-policy">referrerPolicy</a> to hide the Referer header <br><a href="https://helmetjs.github.io/docs/xss-filter">xssFilter</a> adds some small XSS protections ✓</blockquote><p>I recommend you to add Content Security Policy (CSP) for your contents in your application by means of configurations like the code below (<em>change based on your needs</em>). The below code can be quite a standard but might need tweaks based on your requirement.</p><blockquote>npm install helmet-csp -S</blockquote><p>Change code like in lines below:</p><blockquote>Lines 4, 12–26, 46–53</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06be3a11d18a0decfef2cf2836630b8e/href">https://medium.com/media/06be3a11d18a0decfef2cf2836630b8e/href</a></iframe><p>Whenever there is a violation, it will report to <em>/report-violation</em> using HTTP request by modern browsers. Read more about CSP in the <a href="https://helmetjs.github.io/docs/csp/">Helmet CSP documentation here</a>.</p><p><strong>CORS</strong></p><p>Let us implement Cross Origin Resource Sharing support using <a href="https://github.com/expressjs/cors">CORS</a> npm package:</p><blockquote>npm install cors -S</blockquote><p>Add the support as in lines 30–36 below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcc0b7a84e188dba16517af9ca7c6059/href">https://medium.com/media/bcc0b7a84e188dba16517af9ca7c6059/href</a></iframe><p>You can also use a logic instead of the origin option to enable whitelist identification for domains or IPs like below (taken from ExpressJS documentation and replacing line 31–34 above):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dca4ea31435e0bc0c01dbc55a991b9cd/href">https://medium.com/media/dca4ea31435e0bc0c01dbc55a991b9cd/href</a></iframe><p>More, this whitelist may be a dynamic one coming from a database rather than just hard coded. The above is just an example of how it works.</p><p><strong>CROSS SITE REQUEST FORGERY (CSURF)</strong></p><p>If you have a lot of forms in your site or application, it will be wise to set up not just a captcha but also CSRF protection. You do not want forms being submitted from a external site or from a local machine when you are not expecting any (for security or resource utilisation purposes).</p><p>You can do that with <a href="https://www.npmjs.com/package/csurf">csurf</a> package. The package allows you to create a token using <em>req.csrfToken()</em> method; and then validating the token when a form request is made from the client. The <a href="http://expressjs.com/en/resources/middleware/csurf.html">documentation</a> for the module resides <a href="http://expressjs.com/en/resources/middleware/csurf.html">here</a>. I will not be implementing the csurf module now but will do that when we work on forms and use this package along with multer module.</p><p><strong>EXPRESS RATE LIMIT</strong></p><p>I definitely dont want DDOS — huge number of persistent attacks on my system. I dont wish my server to get choked, crashed, or be hacked by a randomizer. Let us install the express-rate-limit package using the command below:</p><blockquote>npm install -S express-rate-limit</blockquote><p>Changed lines 6, 39–47</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13bb5457c25930998bbb0b747c1d569c/href">https://medium.com/media/13bb5457c25930998bbb0b747c1d569c/href</a></iframe><p>Our ExpressJS Server implementation now has a simple standard security configuration implementation for:</p><p>Cross Origin Resource Sharing (CORS), Content Security Policies (CSP), Cross Site Scripting (XSS), Rate Limiting, No sniff for MIME Sniffing, Click jacking (frameguard), Hiding the Application Server for targeted attacks (X-Powered-By), Upgrading HTTP requests to HTTPS.</p><p>We will build on this. But for now, it is definitely a basic safeguard. These configurations and implementations do not guarantee <em>“no hack attacks”</em> from culprits but ensures you are ready atleast with the basic safeguards.</p><p><em>Note: Two other important aspects to ensure safety of your servers are</em></p><ul><li><em>strong server/infrastructure access plus logging policy (for risk mitigation, and post risk occurrence postmortems/response), and</em></li><li><em>organisational data security policy for associated or non-associated actors to avoid human errors.</em></li></ul><p><em>The last one is the cause of majority of cyber crimes.</em></p><p>A lot of concepts are associated with this post; and it is sanely not possible to cover all in a single post. Once we understand how to serve files and send a response from our ExpressJS server in the next posts, we will start touching these one by one; possibly each might require multiple posts. Do leave comments if you have a specific need/information to be covered.</p><p>In the next post we will understand how to serve a response (files, json, xml, etc) from the application/server.</p><p>What I need to know about serving a response: <a href="https://medium.com/@ganeshsurfs/expressjs-series-what-i-need-to-know-about-serving-a-response-b8964a0ff13">https://medium.com/@ganeshsurfs/expressjs-series-what-i-need-to-know-about-serving-a-response-b8964a0ff13</a></p><p><a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">ExpressJS Series All Blogs</a>: <a href="https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b">https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b</a></p><p>Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16e1a00c1c4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>