Today I Learned
Introduction
I’ve noticed that the longer I write code, the more I bump into things I “already know” but never really understood. They work, I use them, and then one day a tiny behavior or detail makes me stop and dig deeper. Most of those discoveries never make it past a browser tab or a passing thought — which is a waste, because that’s where the real learning hides.
“Today I Learned” doesn’t always mean brand new. Sometimes it’s something I’ve used for years but never stopped to read the spec, question the behavior, or write it down properly. This series is my way of slowing down just enough to capture those quiet “oh, that’s why” moments — not because they’re groundbreaking, but because they’re worth remembering.
And of course, not everything here comes from experience. Some posts start with me realizing I actually don’t know how something works, then digging until it finally makes sense — and writing it down before I forget again.
Day 0 - Simple css that anyone know
- [CSS]
accent-color
<div> <div> <input type="checkbox" checked /> </div> <div> <input type="radio" checked /> </div> <div> <input type="range" /> </div> <div> <progress></progress> </div></div> input[type="checkbox"], input[type="radio"], input[type="range"], progress { accent-color: #ff5a00; }Browsers that support accent-color currently apply it to the following HTML elements:
<input type="checkbox"><input type="radio"><input type="range"><progress>
- [CSS]
:active,:focus,:focus-visible,:focus-within
<div> <fieldset> <legend>:focus-within</legend> <button>click here then press <strong>Tab</strong></button> <div class="focus-within"> <input type="checkbox" /> <label>focus-within</label> </div> </fieldset></div> .focus-within:focus-within { font-weight: bold; } .focus-within:not(:focus-within) label:after { content: ": false"; } .focus-within:focus-within label:after { content: ": true"; }- The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus. (This includes descendants in shadow trees.)
<div><fieldset> <legend>:active, :focus, :focus-visible</legend> <div class="pseudo_input"> <input type="text" class="pseudo_input-input" placeholder="try me"/> <span class="pseudo_input-span pseudo_input-span--active">active</span> <span class="pseudo_input-span pseudo_input-span--focus">focus</span> <span class="pseudo_input-span pseudo_input-span--focus-visible">focus-visible</span> </div> <div class="pseudo_btn"> <button class="pseudo_btn-btn">click or tab me</button> <span class="pseudo_btn-span pseudo_btn-span--active">active</span> <span class="pseudo_btn-span pseudo_btn-span--focus">focus</span> <span class="pseudo_btn-span pseudo_btn-span--focus-visible">focus-visible</span> </div></fieldset></div> .pseudo_input-span { display: none; } .pseudo_input-input:active ~ .pseudo_input-span--active, .pseudo_input-input:focus ~ .pseudo_input-span--focus, .pseudo_input-input:focus-visible ~ .pseudo_input-span--focus-visible { display: inline-block; } .pseudo_btn-span { display: none; } .pseudo_btn-btn:active ~ .pseudo_btn-span--active, .pseudo_btn-btn:focus ~ .pseudo_btn-span--focus, .pseudo_btn-btn:focus-visible ~ .pseudo_btn-span--focus-visible { display: inline-block; }-
The
:activeCSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, “activation” typically starts when the user presses down the primary mouse button. -
The
:focusCSS pseudo-class represents an element (such as a form input) that has received focus. It is generally triggered when the user clicks or taps on an element or selects it with the keyboard’skbk>Tab key. -
The
:focus-visiblepseudo-class applies while an element matches the:focuspseudo-class and the UA (User Agent) determines via heuristics that the focus should be made evident on the element. (Many browsers show a “focus ring” by default in this case.) -
The difference between
:focusand:focus-visiblelies in intent, not capability. Both target elements that currently have focus, but:focus-visibleactivates only when the browser determines the user needs a visible cue—usually when navigating with a keyboard or assistive technology. In contrast,:focustriggers for any focused element, regardless of how it was reached. This means:focusis best for behavior and logic (like showing a dropdown when an input gains focus), while:focus-visibleis for visual indicators that help non-mouse users track their position without cluttering the interface for pointer
Day 1
(2.2) TCP - Key TCP Concepts
-
TCP provides a reliable, in-order, byte-stream service to applications.
-
The application byte-stream is conveyed over the network via TCP segments, with each TCP segment sent as an Internet Protocol (IP) datagram.
-
TCP reliability consists of detecting packet losses (via sequence numbers) and errors (via per-segment checksums), as well as correction via retransmission.
-
TCP supports unicast delivery of data. There are anycast applications that can successfully use TCP without modifications, though there is some risk of instability due to changes of lower-layer forwarding behavior [46].
-
TCP is connection oriented, though it does not inherently include a liveness detection capability.
-
Data flow is supported bidirectionally over TCP connections, though applications are free to send data only unidirectionally, if they so choose.
-
TCP uses port numbers to identify application services and to multiplex distinct flows between hosts.
(3.3.1) TCP - Key Connection State Variables
Every active TCP connection has one TCB, which is a record in memory holding all the current state for that connection. It includes:
- Local + remote IP + port
- Buffers (send, receive, retransmit)
- Sequence number tracking (the heart of reliability)
- Control flags (urgent data, window size, etc.) When the connection closes, the TCB is destroyed — so no TCB means no connection.
TCB has 3 group of variable
- S(SND.*): end-side variables These describe what we’ve sent, what’s been ACKed, and what we can send next. In another words, outgoing (transmit) side of the state machine.
- R(RCV.*): eceive-side variables These track what we’ve received, what we’re expecting next, and how much room we have left. This group governs incoming data handling.
- C(SEG.*): urrent Segment variables When a new TCP segment arrives, the implementation temporarily extracts its key header fields into these variables. These describe the current incoming packet during processing — they’re ephemeral, updated per segment.
(3.3.2) TCP - State Machine Overview
A connection progresses through a series of states during its lifetime. The states are:
- Connection establishment (the 3-way handshake)
| State | Who | Meaning || ---------------- | ------ | -------------------------------------------------------------- || **LISTEN** | server | Waiting for someone to knock (a SYN). || **SYN-SENT** | client | Sent SYN, waiting for SYN+ACK from the server. || **SYN-RECEIVED** | server | Got SYN, sent SYN+ACK, now waiting for the client’s final ACK. || **ESTABLISHED** | both | 3-way handshake complete — ready to exchange data. |- Data transfer
| State | Meaning || --------------- | ------------------------------------------------------- || **ESTABLISHED** | Active communication. Data can flow in both directions. |- Connection teardown (graceful close)
| State | Who | Meaning || -------------- | -------------- | ------------------------------------------------------------------------------------------------ || **FIN-WAIT-1** | active closer | Sent FIN; waiting for ACK (and possibly FIN from the other side). || **FIN-WAIT-2** | active closer | Got ACK for our FIN; now just waiting for the peer’s FIN. || **CLOSE-WAIT** | passive closer | Got peer’s FIN; waiting for the app to call `close()`. || **CLOSING** | rare | Both sides sent FIN at nearly the same time; waiting for ACK. || **LAST-ACK** | passive closer | Sent our FIN after receiving peer’s FIN; waiting for ACK of our FIN. || **TIME-WAIT** | active closer | After both sides done, wait 2×MSL to ensure all stray packets have died before reusing the port. || **CLOSED** | — | TCB removed, connection fully gone. |Transitions happen because of events. These fall into three categories:
| Event Type | Examples || --------------------- | --------------------------------------------------------------------------- || **User actions** | `OPEN` (connect), `SEND`, `RECEIVE`, `CLOSE`, `ABORT`, `STATUS`. || **Incoming segments** | TCP flags like `SYN`, `ACK`, `FIN`, or `RST`. || **Timers / timeouts** | Retransmission timeout, delayed ACK timeout, 2×MSL timeout (for TIME-WAIT). |HTML - <dialog/>
Features:
- Enable/Disable background interaction
- Builtin backdrop
- Tab focus stays inside the dialog.
- Close and return value by integrate with
<form method="dialog"> - Handles ARIA roles and focus management by default.
- Keyboard support: ESC key closes it automatically when modal.
<button id="open-modal">Open Modal (blocks background)</button><button id="open-nonmodal">Open Non-modal (background clickable)</button><dialog id="modalDialog"><h3>Modal Dialog</h3><p> This one <b>blocks background</b> and traps focus inside.</p><button id="close-modal">Close</button></dialog><dialog id="nonModalDialog"><h3>Non-modal Dialog</h3><p>You can still click buttons in the background.</p><button id="close-nonmodal">Close</button></dialog><button id="open-form">Open Form Dialog</button><dialog id="formDialog"><form method="dialog"> <h3>Choose your favorite color</h3> <button value="red">Red</button> <button value="blue">Blue</button> <button value="cancel">Cancel</button></form></dialog><p id="chosen"></p>body {font-family: system-ui, sans-serif;display: flex;flex-direction: column;align-items: center;gap: 1rem;margin-top: 2rem;}dialog {border: none;border-radius: 8px;padding: 1.5rem 2rem;box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);}/_ Built-in backdrop customization _/dialog::backdrop {background: rgba(0, 0, 0, 0.6);backdrop-filter: blur(2px);}button {margin: 0.25rem;padding: 0.5rem 1rem;}// Modal: background interaction disabledconst modal = document.getElementById("modalDialog");document.getElementById("open-modal").onclick = () => modal.showModal();document.getElementById("close-modal").onclick = () => modal.close();
// Non-modal: background still clickableconst nonModal = document.getElementById("nonModalDialog");document.getElementById("open-nonmodal").onclick = () => nonModal.show();document.getElementById("close-nonmodal").onclick = () => nonModal.close();
// Form dialog with return valueconst formDialog = document.getElementById("formDialog");const chosen = document.getElementById("chosen");document.getElementById("open-form").onclick = () => formDialog.showModal();
formDialog.addEventListener("close", () => {chosen.textContent =formDialog.returnValue === "cancel"? "You cancelled the dialog.": "You chose: " + formDialog.returnValue;});Day 2 - TCP (continue)
(3.4) Sequence Numbers
1. Every byte has a sequence number.
TCP doesn’t number packets — it numbers bytes. Each byte sent has a unique sequence number.
2. Acknowledgments are cumulative.
When the receiver sends ACK = X, it indicates that all octets up to but not including X have been received.
3. Sequence number space is finite.
Sequence numbers go from 0 to 232−1 and then wrap around. All comparisons (e.g., is this ACK valid?) use modulo 232 arithmetic to handle wraparound safely.
4. Control flags also consume sequence space.
- SYN counts as one byte before any data.
- FIN counts as one byte after all data. This ensures SYN and FIN are acknowledged exactly once and can be retransmitted safely.
5. Why sequence number design matters
Every TCP byte on the wire has a sequence number. These numbers let each endpoint know which data is new, which is duplicate, and how to reorder or acknowledge what it receives. The system only works if each byte range is used once—no confusion between the past and the present.
The problem is that TCP connections can be reused. A new connection might have the same IP and port pair as a recent one (“another incarnation”), while old segments from the first could still be lingering in the network. To prevent those ghosts from being mistaken for live data, TCP relies on two main safeguards:
- TIME-WAIT: holds a closed connection for roughly one Maximum Segment Lifetime (MSL), long enough for stray packets to disappear.
- Initial Sequence Numbers (ISNs): make each new connection’s numbering unique.
Each connection starts with a 32-bit ISN chosen as:
ISN = M + F(localip, localport, remoteip, remoteport, secretkey)M: a fast “clock” that increases roughly every 4 microseconds and wraps around after about 4.55 hoursF(): a pseudorandom function using connection info and a secret key.
This blend ensures two things:
- ISNs grow monotonically so recent ones don’t repeat for several hours.
- Attackers can’t guess the next ISN.
If a host reboots and loses its memory of recent sequence numbers, it faces the same risk of overlap. To stay safe, it’s recommended a brief “quiet time”—roughly one MSL—before sending any new segments. That pause gives any stragglers in the network time to drain. In practice, modern systems skip it because ISN randomization and faster links make collisions nearly impossible, and most reboots take longer than two minutes anyway.
At normal speeds, the 32bit-wide sequence space is large enough that numbers never wrap before all old data drains—roughly four billion bytes per wrap.
But at very high data rates (gigabits per second and beyond), that assumption weakens: a sender could cycle through all sequence numbers in less than one MSL.
To defend against that, TCP timestamps and PAWS (Protection Against Wrapped Sequence numbers) extend the logic. Each segment carries a monotonically increasing timestamp, so even if numeric sequence numbers repeat, the receiver can still tell new data from old.
Together, TIME-WAIT, randomized ISNs, and PAWS keep TCP’s sense of time and identity intact—ensuring that what you receive now truly belongs to the conversation you’re having.
Day 3 - TCP (continue)
(3.5) Establishing a Connection
1. Basic 3WHS for Connection Synchronization
TCP Peer A TCP Peer B1. CLOSED LISTEN2. SYN-SENT --> <SEQ=100><CTL=SYN> --> SYN-RECEIVED3. ESTABLISHED <-- <SEQ=300><ACK=101><CTL=SYN,ACK> <-- SYN-RECEIVED4. ESTABLISHED --> <SEQ=101><ACK=301><CTL=ACK> --> ESTABLISHED5. ESTABLISHED --> <SEQ=101><ACK=301><CTL=ACK><DATA> --> ESTABLISHED-
Line 2: TCP Peer A begins by sending a SYN segment, indicating that it will use sequence numbers starting with SEQ = 100.
-
Line 3: TCP Peer B responds with a SYN and an ACK, acknowledging the SYN it received from Peer A.
- The ACK field = 101, meaning Peer B is now expecting to receive sequence 101, which acknowledges the SYN that occupied sequence 100.
2. Simultaneous Connection Synchronization
Each TCP peer’s connection state cycles from CLOSED to SYN-SENT to SYN-RECEIVED to ESTABLISHED.
TCP Peer A TCP Peer B1. CLOSED CLOSED2. SYN-SENT --> <SEQ=100><CTL=SYN> ...3. SYN-RECEIVED <-- <SEQ=300><CTL=SYN> <-- SYN-SENT4. ... <SEQ=100><CTL=SYN> --> SYN-RECEIVED5. SYN-RECEIVED --> <SEQ=100><ACK=301><CTL=SYN,ACK> ...6. ESTABLISHED <-- <SEQ=300><ACK=101><CTL=SYN,ACK> <-- SYN-RECEIVED7. ... <SEQ=100><ACK=301><CTL=SYN,ACK> --> ESTABLISHED2.1. Notes
- A TCP implementation must track whether a connection entered the SYN-RECEIVED state due to a passive OPEN (server waiting for connections) or an active OPEN (client initiating a connection).
2.2. Purpose of the Three-Way Handshake
The three-way handshake exists mainly to prevent old duplicate connection initiations from causing confusion or unexpected connections.
To handle this, TCP defines a special control message: Reset (RST).
2.3. Reset (RST) Behavior
-
If a TCP peer is in a non-synchronized state (e.g.,
SYN-SENTorSYN-RECEIVED) and receives an acceptable RST, → it returns to LISTEN (or CLOSED if it was actively opening). -
If the TCP peer is in a synchronized state (
ESTABLISHED,FIN-WAIT-1,FIN-WAIT-2,CLOSE-WAIT,CLOSING,LAST-ACK,TIME-WAIT), → it aborts the connection and informs its user.
3. Recovery from Old Duplicate SYN
TCP Peer A TCP Peer B1. CLOSED LISTEN2. SYN-SENT --> <SEQ=100><CTL=SYN> ...3. (duplicate) ... <SEQ=90><CTL=SYN> --> SYN-RECEIVED4. SYN-SENT <-- <SEQ=300><ACK=91><CTL=SYN,ACK> <-- SYN-RECEIVED5. SYN-SENT --> <SEQ=91><CTL=RST> --> LISTEN6. ... <SEQ=100><CTL=SYN> --> SYN-RECEIVED7. ESTABLISHED <-- <SEQ=400><ACK=101><CTL=SYN,ACK> <-- SYN-RECEIVED8. ESTABLISHED --> <SEQ=101><ACK=401><CTL=ACK> --> ESTABLISHED3.1. Explanation
-
Line 3: An old duplicate SYN (with
SEQ=90) arrives at TCP Peer B. Since B cannot distinguish it from a valid new SYN, it responds normally with a SYN+ACK (line 4). -
Line 5: TCP Peer A receives the SYN+ACK, but the ACK field is incorrect (it acknowledges sequence 91, not 101). A detects this mismatch and sends a RST (
SEQ=91) — chosen so it looks valid to B.→ On receiving this RST, TCP Peer B resets the half-open connection and returns to the LISTEN state.
-
Line 6–8: When the original SYN (with
SEQ=100) finally arrives, Peer B treats it as a normal new request. The three-way handshake completes successfully, moving both peers to the ESTABLISHED state.
3.2. Note
If the original SYN (line 6) had arrived before the RST (line 5), a race condition could have occurred — with RSTs sent in both directions as each side misinterpreted the other’s state.
4. Half-Open Connection Discovery
A TCP connection is considered half-open when:
- One peer has closed or aborted the connection without the other peer knowing, or
- The peers have become desynchronized due to a failure or reboot that caused loss of connection state.
When either side attempts to send data on a half-open connection, the other (no longer synchronized) endpoint will respond with a Reset (RST) — forcing both sides to abort and return to a clean state.
Half-open connections are rare but can occur after crashes or unexpected reboots.
TCP Peer A TCP Peer B1. (REBOOT) (send 300,receive 100)2. CLOSED ESTABLISHED3. SYN-SENT --> <SEQ=400><CTL=SYN> --> (??)4. (!!) <-- <SEQ=300><ACK=100><CTL=ACK> <-- ESTABLISHED5. SYN-SENT --> <SEQ=100><CTL=RST> --> (Abort!!)6. SYN-SENT CLOSED7. SYN-SENT --> <SEQ=400><CTL=SYN> --> ...4.1. Explanation
-
Line 1–2: Peer A reboots, losing all record of the existing connection. Meanwhile, Peer B still believes the connection is ESTABLISHED.
-
Line 3: After reboot, Peer A sends a new SYN (
SEQ=400) to start a fresh connection. Peer B, still synchronized, sees this segment as out of window and responds with an ACK=100 (the next sequence it expects). -
Line 4–5: Peer A receives this ACK but realizes it doesn’t match any known state (since A’s memory was wiped). Interpreting it as an invalid acknowledgment, A sends a RST (
SEQ=100) to terminate what it sees as a corrupted session. Peer B receives this RST and aborts the old connection. -
Line 6–7: The stale session is gone. Peer A continues trying to establish a new, clean connection — which now proceeds like a normal three-way handshake.
5. Active Side Causes Half-Open Connection Discovery
TCP Peer A TCP Peer B1. (REBOOT) (send 300,receive 100)2. (??) <-- <SEQ=300><ACK=100><DATA=10><CTL=ACK> <-- ESTABLISHED3. --> <SEQ=100><CTL=RST> --> (ABORT!!)5.1. Explanation
-
Line 1: TCP Peer A reboots, losing all connection state.
-
Line 2: TCP Peer B sends data on the old connection (thinking it’s still ESTABLISHED). Since Peer A has no record of the connection, the segment is unacceptable.
-
Line 3: Peer A responds with a RST, signaling that no such connection exists. Peer B receives the RST, recognizes the problem, and aborts the connection.
6. Old Duplicate SYN Initiates a Reset on Two Passive Sockets
TCP Peer A TCP Peer B1. LISTEN LISTEN2. ... <SEQ=Z><CTL=SYN> --> SYN-RECEIVED3. (??) <-- <SEQ=X><ACK=Z+1><CTL=SYN,ACK> <-- SYN-RECEIVED4. --> <SEQ=Z+1><CTL=RST> --> (return to LISTEN!)5. LISTEN LISTEN6.1. Explanation
-
Line 2: An old duplicate SYN arrives at Peer B, which is in LISTEN. Peer B treats it as a new SYN and moves to SYN-RECEIVED.
-
Line 3: Peer B responds with a SYN+ACK. Peer A sees this segment but the ACK field is not acceptable (it doesn’t match any current connection state), so it sends a RST.
-
Line 4: Peer B receives the RST, interprets it as an indication that the connection is invalid, and returns to LISTEN.
-
Line 5: Both peers are back in LISTEN, ready for a legitimate new connection.
7. Rule of Reset (RST)
A reset (RST) is sent whenever a TCP segment arrives that appears not intended for the current connection.
7.1. CLOSED State
- If the connection does not exist (CLOSED), a reset is sent in response to any incoming segment except another reset.
- This rejects any SYN or other segments that do not match an existing connection.
- Sequence/ACK handling:
- If the incoming segment has the ACK bit set, the RST’s sequence number = incoming ACK.
- Otherwise, the RST sequence = 0, and the ACK field = incoming SEQ + segment length.
- The connection remains CLOSED.
7.2. Non-Synchronized State
- States: LISTEN, SYN-SENT, SYN-RECEIVED.
- Send a reset if:
- The incoming segment acknowledges something not yet sent (unacceptable ACK), or
- The segment’s security level/compartment does not match the requested connection.
- Sequence/ACK handling:
- If the segment has an ACK field, the RST sequence = incoming ACK.
- Otherwise, RST sequence = 0, and ACK = incoming SEQ + segment length.
- The connection remains in the same state.
7.3. Synchronized State
- States: ESTABLISHED, FIN-WAIT-1, FIN-WAIT-2, CLOSE-WAIT, CLOSING, LAST-ACK, TIME-WAIT.
- For any unacceptable segment (out-of-window SEQ or unacceptable ACK):
- Respond with an empty acknowledgment (no user data) containing:
- Send sequence number = current send SEQ
- ACK = next expected receive SEQ
- Connection remains in the same state.
- Respond with an empty acknowledgment (no user data) containing:
- If the segment has a mismatched security level/compartment:
- Send a RST and transition the connection to CLOSED.
- RST sequence = incoming ACK field.
8. Reset (RST) Processing
-
Validation:
- In all states except SYN-SENT, RST segments are validated by their sequence number (SEQ).
- A reset is valid if its SEQ is within the current receive window.
- In SYN-SENT (waiting for SYN-ACK), a RST is valid if its ACK field acknowledges the SYN.
- In all states except SYN-SENT, RST segments are validated by their sequence number (SEQ).
-
State Transitions Upon Receiving a Valid RST:
- LISTEN: Ignore the RST.
- SYN-RECEIVED:
- If previously in LISTEN, return to LISTEN.
- Otherwise, abort the connection → go to CLOSED.
- All other states:
- Abort the connection → go to CLOSED and notify the user.
-
RST with Data:
- TCP implementations SHOULD allow RST segments to carry data.
- This could include diagnostic information explaining the reason for the reset.