Skip to content
Browse documentation

A CIDR and firewall allowlist editor with IPv4/IPv6 validation, live subnet host counts, wildcard exposure guards, containment checks and bulk paste.

Used forCloud databases and VPC firewallsEnterprise API key restrictionsWebhook ingress allowlistsCompliance and zero-trust settings

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/ip-allowlist.json

Registered the namespace? Then it’s shadcn add @hairline/ip-allowlist. Set it up

Templates

Need the whole page?

63 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

All 63 templates

Where it’s used

  • Cloud databases and VPC firewalls

    Let engineers manage IPv4 and IPv6 egress blocks with immediate subnet size readouts and redundant-rule detection.

  • Enterprise API key restrictions

    Pair with API keys and Env editor to lock production credentials to known office VPNs and CI runners.

  • Webhook ingress allowlists

    Paste a provider published multi-line CIDR list with # comments straight into the composer to import all ranges at once.

  • Compliance and zero-trust settings

    Set allowWildcard={false} to block 0.0.0.0/0 and ::/0 rules at the UI boundary before submission.

What it handles for you

A firewall allowlist editor has to prevent typos, make subnet blast radius obvious before saving and support pasting dozens of CI ranges cleanly.

Instead of wiring upcustom IP regex inputCIDR host calculatorwildcard exposure bannersubnet containment checker
  1. Strict IPv4, IPv6 and CIDR validation

    Normalises bare IPs to /32 or /128, rejects out-of-range octets and prefixes and recoils gently on invalid or duplicate entries.

  2. Live subnet host-count readout

    Computes exact IPv4 address counts ("1 host", "256 IPs", "65,536 IPs") and IPv6 prefix scopes right inside the composer as you type.

  3. Wildcard /0 exposure guard

    Surfaces an unmistakable amber warning banner whenever 0.0.0.0/0 or ::/0 is active, or blocks wildcard rules completely with allowWildcard={false}.

  4. 32-bit IPv4 subnet containment checks

    Flags narrower IPv4 rules that are already covered by a broader CIDR block in the list ("Covered by 203.0.113.0/24").

  5. One-click Add my IP and bulk paste

    Pass currentIp to add the caller device in one click, or paste newline/comma-separated CIDR lists with # comments to batch import.

  6. Exported network helpers

    Exports parseIpCidr(), ipv4CidrContains() and parseBulkIpList() for shared server/client validation.

Overview

Cloud databases, webhook endpoints and enterprise dashboards all need IP allowlists, yet raw inputs silently accept malformed addresses, hide how wide a /24 or /16 subnet is and let operators accidentally open 0.0.0.0/0 to the entire internet. IpAllowlist validates IPv4, IPv6 and CIDR notation as you type, displays exact live subnet scope ("1 host", "256 IPs", "/48 subnet"), warns immediately on 0.0.0.0/0 or ::/0 wildcard exposure and private RFC 1918 addresses, detects redundant IPv4 rules covered by a broader CIDR block ("Covered by 203.0.113.0/24"), supports one-click Add my IP and parses multi-line or comma-separated CIDR lists with inline # comments.

States

live scope badge
Typing a valid IP or CIDR updates an inline chip showing IP version and exact host count.
wildcard open
Active 0.0.0.0/0 or ::/0 rules display an amber exposure warning banner across the top of the panel.
redundant rule
An IPv4 host or subnet contained inside a broader existing CIDR displays a sky Covered by badge.
bulk paste import
Pasting multiple lines imports all valid non-duplicate CIDRs, preserves # comment labels and confirms with an emerald Imported pill.

Usage

usage.tsx
import { IpAllowlist } from "@/components/ip-allowlist";<IpAllowlist  value={rules}  onChange={setRules}  currentIp={viewerIp}/>

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Works with

Database network settings with strict no-wildcard policy

Pass the viewer IP detected on your server and disable wildcard /0 rules for production clusters.

example.tsx
"use client";import { useState } from "react";import { IpAllowlist, type IpAllowlistEntry } from "@/components/ip-allowlist";export function ClusterNetworkPolicy({ initial, viewerIp }: { initial: IpAllowlistEntry[]; viewerIp?: string }) {  const [rules, setRules] = useState<IpAllowlistEntry[]>(initial);  return (    <IpAllowlist      value={rules}      onChange={setRules}      currentIp={viewerIp}      allowWildcard={false}      maxEntries={25}    />  );}

Props

value / defaultValue / onChange
IpAllowlistEntry[] / IpAllowlistEntry[] / (v) => void
Controlled or uncontrolled list of { id, cidr, label?, expiresAt? }.
currentIp
string
Optional caller IP address enabling the one-click Add my IP action.
allowWildcard / maxEntries= true / —
boolean / number
Allow or block 0.0.0.0/0 and ::/0 rules, and optionally cap total rule count.
parseIpCidr / ipv4CidrContains / parseBulkIpList
exported utility functions
Validate CIDRs, test IPv4 subnet containment and parse bulk pasted lists outside the component.

Accessibility and motion

  • Bare IPv4 addresses normalise cleanly to /32 and bare IPv6 addresses to /128 so duplicate rules like 1.2.3.4 and 1.2.3.4/32 are caught consistently.
  • All IPv4 subnet containment math runs on unsigned 32-bit integers with zero external dependencies.
  • Under prefers-reduced-motion: reduce, validation recoil is skipped while error text and focus remain unchanged.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Text morph, Number roll, Status button.

Source

"use client";import * as React from "react";import {  AlertTriangle,  Check,  Copy,  Globe,  Info,  LocateFixed,  Plus,  Shield,  Trash2,} from "lucide-react";import {  EASE_OUT,  INTERACTION_FOCUS,  INTERACTION_PRESS,  interactionIcon,  useInteractionReducedMotion,} from "./ui-interaction-motion";import { ConfirmAction } from "./confirm-action";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";import { useRowMotion } from "./use-row-motion";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * IP ALLOWLIST: CIDR & firewall rules editor * *   bitmask   every rule (and the live composer) draws a hairline *             4-octet CIDR prefix bar showing locked network bits *             vs open host bits, making the blast radius difference *             between /32, /24, /16 and /0 immediately legible * *   motion    adding rules or pasting a bulk list glides siblings *             smoothly via useRowMotion; removing a rule stretches *             its trash icon into ConfirmAction ("Remove"), draws *             its check, dissolves the row ghost and glides the *             rest up; counts roll with NumberRoll and pills morph *             with TextMorph * ───────────────────────────────────────────────────────── */export interface IpAllowlistEntry {  id: string;  /** IPv4, IPv6 or CIDR block (e.g. "203.0.113.0/24", "198.51.100.42/32", "2001:db8::/32"). */  cidr: string;  /** Optional human note (e.g. "Office VPN", "GitHub Actions"). */  label?: string;  /** Optional subtle expiry badge (e.g. "7d left"). */  expiresAt?: string;}export interface ParsedCidr {  valid: boolean;  version: 4 | 6 | null;  normalized: string;  prefix: number | null;  hostCountLabel: string;  isWildcard: boolean;  isPrivate: boolean;  error?: string;}export interface IpAllowlistProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange"> {  /** Controlled list of allowlist entries. */  value?: IpAllowlistEntry[];  /** Initial uncontrolled list of allowlist entries. */  defaultValue?: IpAllowlistEntry[];  /** Called whenever entries are added, edited or removed. */  onChange?: (entries: IpAllowlistEntry[]) => void;  /** Caller's detected IP address (from server headers) enabling the one-click "Add my IP" button. */  currentIp?: string;  /** Allow pasting/adding wildcard 0.0.0.0/0 or ::/0 rules with a warning (default true; false blocks wildcards). */  allowWildcard?: boolean;  /** Maximum number of allowlist rules allowed (optional). */  maxEntries?: number;  /** Card header title (default "IP allowlist"). */  title?: string;  /** Opt-in Web Audio cues (from ui-sounds.ts). */  sound?: boolean;}let uidCounter = 1;const nextUid = () => `ip_${uidCounter++}`;function parseIpv4ToUint32(ip: string): number | null {  const parts = ip.split(".");  if (parts.length !== 4) return null;  let num = 0;  for (let i = 0; i < 4; i++) {    const p = parts[i];    if (!/^\d{1,3}$/.test(p)) return null;    if (p.length > 1 && p.startsWith("0")) return null;    const oct = Number(p);    if (oct < 0 || oct > 255) return null;    num = ((num << 8) | oct) >>> 0;  }  return num;}function isPrivateIpv4(u32: number): boolean {  const a = (u32 >>> 24) & 255;  const b = (u32 >>> 16) & 255;  if (a === 10) return true;  if (a === 172 && b >= 16 && b <= 31) return true;  if (a === 192 && b === 168) return true;  if (a === 127) return true;  if (a === 169 && b === 254) return true;  return false;}function isValidIpv6(ip: string): boolean {  if (!ip.includes(":")) return false;  const doubleColons = ip.split("::");  if (doubleColons.length > 2) return false;  const left = doubleColons[0] ? doubleColons[0].split(":") : [];  const right = doubleColons.length === 2 && doubleColons[1] ? doubleColons[1].split(":") : [];  const groups = [...left, ...right];  if (doubleColons.length === 1 && groups.length !== 8) return false;  if (doubleColons.length === 2 && groups.length >= 8) return false;  return groups.every((g) => /^[0-9a-fA-F]{1,4}$/.test(g));}function formatIpv4Count(prefix: number): string {  if (prefix === 0) return "All IPv4 (open)";  if (prefix === 32) return "1 host";  const count = Math.pow(2, 32 - prefix);  if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M IPs`;  return `${count.toLocaleString("en-US")} IPs`;}/** Validate and classify an IPv4, IPv6 or CIDR string. */export function parseIpCidr(raw: string): ParsedCidr {  const trimmed = raw.trim();  if (!trimmed) {    return { valid: false, version: null, normalized: "", prefix: null, hostCountLabel: "", isWildcard: false, isPrivate: false };  }  const slashParts = trimmed.split("/");  if (slashParts.length > 2) {    return {      valid: false,      version: null,      normalized: trimmed,      prefix: null,      hostCountLabel: "",      isWildcard: false,      isPrivate: false,      error: "Multiple slashes in CIDR",    };  }  const host = slashParts[0].trim();  const prefixRaw = slashParts[1]?.trim();  const v4 = parseIpv4ToUint32(host);  if (v4 !== null) {    let prefix = 32;    if (prefixRaw !== undefined) {      if (!/^\d{1,2}$/.test(prefixRaw)) {        return { valid: false, version: 4, normalized: trimmed, prefix: null, hostCountLabel: "", isWildcard: false, isPrivate: false, error: "IPv4 prefix must be 0–32" };      }      prefix = Number(prefixRaw);      if (prefix < 0 || prefix > 32) {        return { valid: false, version: 4, normalized: trimmed, prefix: null, hostCountLabel: "", isWildcard: false, isPrivate: false, error: "IPv4 prefix must be 0–32" };      }    }    return {      valid: true,      version: 4,      normalized: `${host}/${prefix}`,      prefix,      hostCountLabel: formatIpv4Count(prefix),      isWildcard: prefix === 0,      isPrivate: prefix > 0 && isPrivateIpv4(v4),    };  }  if (isValidIpv6(host)) {    let prefix = 128;    if (prefixRaw !== undefined) {      if (!/^\d{1,3}$/.test(prefixRaw)) {        return { valid: false, version: 6, normalized: trimmed, prefix: null, hostCountLabel: "", isWildcard: false, isPrivate: false, error: "IPv6 prefix must be 0–128" };      }      prefix = Number(prefixRaw);      if (prefix < 0 || prefix > 128) {        return { valid: false, version: 6, normalized: trimmed, prefix: null, hostCountLabel: "", isWildcard: false, isPrivate: false, error: "IPv6 prefix must be 0–128" };      }    }    const lower = host.toLowerCase();    const isPrivate = lower === "::1" || lower.startsWith("fc") || lower.startsWith("fd") || lower.startsWith("fe80:");    return {      valid: true,      version: 6,      normalized: `${lower}/${prefix}`,      prefix,      hostCountLabel: prefix === 0 ? "All IPv6 (open)" : prefix === 128 ? "1 host" : `/${prefix} subnet`,      isWildcard: prefix === 0,      isPrivate: prefix > 0 && isPrivate,    };  }  return {    valid: false,    version: null,    normalized: trimmed,    prefix: null,    hostCountLabel: "",    isWildcard: false,    isPrivate: false,    error: "Enter a valid IPv4, IPv6 or CIDR block",  };}/** Check if an IPv4 CIDR `outer` fully contains another IPv4 CIDR `inner`. */export function ipv4CidrContains(outer: string, inner: string): boolean {  const [oHost, oPreStr] = outer.split("/");  const [iHost, iPreStr] = inner.split("/");  const oIp = parseIpv4ToUint32(oHost ?? "");  const iIp = parseIpv4ToUint32(iHost ?? "");  if (oIp === null || iIp === null) return false;  const oPre = oPreStr === undefined ? 32 : Number(oPreStr);  const iPre = iPreStr === undefined ? 32 : Number(iPreStr);  if (!Number.isFinite(oPre) || !Number.isFinite(iPre) || oPre > iPre) return false;  if (oPre === 0) return true;  const mask = (0xffffffff << (32 - oPre)) >>> 0;  return ((oIp & mask) >>> 0) === ((iIp & mask) >>> 0);}/** Parse newline- or comma-separated CIDR blocks (preserving inline `# label` comments). */export function parseBulkIpList(raw: string): Array<{ cidr: string; label?: string }> {  const results: Array<{ cidr: string; label?: string }> = [];  const lines = raw.split(/\r?\n/);  for (const line of lines) {    const trimmed = line.trim();    if (!trimmed || trimmed.startsWith("#")) continue;    const hashIdx = trimmed.indexOf("#");    const main = (hashIdx >= 0 ? trimmed.slice(0, hashIdx) : trimmed).trim();    const comment = hashIdx >= 0 ? trimmed.slice(hashIdx + 1).trim() : undefined;    const tokens = main.split(/[,\s]+/).filter(Boolean);    for (const tok of tokens) {      const parsed = parseIpCidr(tok);      if (parsed.valid) {        results.push({ cidr: parsed.normalized, ...(comment ? { label: comment } : {}) });      }    }  }  return results;}/** Razor-thin 4-segment CIDR prefix specificity meter: full = /32 (/128) locked host, empty/amber = /0 open internet. */function PrefixMaskMeter({  parsed,  reduced,}: {  parsed: ParsedCidr;  reduced: boolean;}) {  if (!parsed.valid || parsed.prefix === null || parsed.version === null) return null;  const totalBits = parsed.version === 4 ? 32 : 128;  const ratio = Math.max(0, Math.min(1, parsed.prefix / totalBits));  const broad = parsed.isWildcard || (parsed.version === 4 && parsed.prefix <= 16);  return (    <div      aria-hidden="true"      title={`/${parsed.prefix} of ${totalBits} network bits locked`}      className="relative hidden h-1.5 w-16 shrink-0 overflow-hidden rounded-full border border-border/75 bg-muted/45 @[420px]:block"    >      {/* 4-octet hairline ticks */}      <span className="absolute inset-y-0 left-1/4 z-10 w-px bg-card/70" />      <span className="absolute inset-y-0 left-1/2 z-10 w-px bg-card/70" />      <span className="absolute inset-y-0 left-3/4 z-10 w-px bg-card/70" />      {parsed.isWildcard ? (        <span className="absolute inset-0 bg-amber-500/80" />      ) : (        <span          className={`absolute inset-y-0 left-0 origin-left ${broad ? "bg-amber-500/80" : "bg-primary/85"}`}          style={{            width: "100%",            transform: `scaleX(${ratio.toFixed(4)})`,            transition: reduced ? "none" : `transform 320ms ${EASE_OUT}, background-color 200ms ${EASE_OUT}`,          }}        />      )}    </div>  );}const DEFAULT_ENTRIES: IpAllowlistEntry[] = [  { id: "ip_init_1", cidr: "203.0.113.0/24", label: "London office VPN" },  { id: "ip_init_2", cidr: "198.51.100.42/32", label: "CI deploy runner" },];export function IpAllowlist({  value: controlledValue,  defaultValue = DEFAULT_ENTRIES,  onChange,  currentIp,  allowWildcard = true,  maxEntries,  title = "IP allowlist",  sound = false,  className = "",  ...props}: IpAllowlistProps) {  const reduced = useInteractionReducedMotion();  const [ownEntries, setOwnEntries] = React.useState<IpAllowlistEntry[]>(defaultValue);  const entries = controlledValue !== undefined ? controlledValue : ownEntries;  const [cidrDraft, setCidrDraft] = React.useState("");  const [labelDraft, setLabelDraft] = React.useState("");  const [formError, setFormError] = React.useState<string | null>(null);  const [lastFormError, setLastFormError] = React.useState("");  const [copiedAll, setCopiedAll] = React.useState(false);  const [importNote, setImportNote] = React.useState<string | null>(null);  const [lastImportNote, setLastImportNote] = React.useState("");  const [liveStatus, setLiveStatus] = React.useState("");  if (formError && formError !== lastFormError) setLastFormError(formError);  if (importNote && importNote !== lastImportNote) setLastImportNote(importNote);  const composerRef = React.useRef<HTMLFormElement | null>(null);  const listRef = React.useRef<HTMLDivElement | null>(null);  const ghostsRef = React.useRef<HTMLDivElement | null>(null);  const copyTimerRef = React.useRef(0);  const noteTimerRef = React.useRef(0);  const rowRanks = React.useMemo(() => new Map(entries.map((e, i) => [e.id, i])), [entries]);  useRowMotion(listRef, { reduced, ranks: rowRanks, ghosts: ghostsRef });  React.useEffect(    () => () => {      window.clearTimeout(copyTimerRef.current);      window.clearTimeout(noteTimerRef.current);    },    [],  );  const commit = React.useCallback(    (next: IpAllowlistEntry[]) => {      if (controlledValue === undefined) setOwnEntries(next);      onChange?.(next);    },    [controlledValue, onChange],  );  const recoilComposer = React.useCallback(() => {    if (reduced || !composerRef.current) return;    const el = composerRef.current;    const start = performance.now();    const duration = 320;    const step = (now: number) => {      const t = Math.min(1, (now - start) / duration);      const x = Math.sin(t * Math.PI * 5) * (1 - t) * 5;      el.style.transform = `translate3d(${x.toFixed(2)}px, 0, 0)`;      if (t < 1) window.requestAnimationFrame(step);      else el.style.transform = "";    };    window.requestAnimationFrame(step);  }, [reduced]);  const parsedDraft = React.useMemo(() => parseIpCidr(cidrDraft), [cidrDraft]);  const analyzed = React.useMemo(() => {    const meta = entries.map((entry) => ({ entry, parsed: parseIpCidr(entry.cidr) }));    return meta.map((item, idx) => {      let coveredBy: string | null = null;      if (item.parsed.valid && item.parsed.version === 4) {        for (let j = 0; j < meta.length; j++) {          if (j === idx) continue;          const other = meta[j];          if (            other.parsed.valid &&            other.parsed.version === 4 &&            other.parsed.normalized !== item.parsed.normalized &&            ipv4CidrContains(other.parsed.normalized, item.parsed.normalized)          ) {            coveredBy = other.parsed.normalized;            break;          }        }      }      return { ...item, coveredBy };    });  }, [entries]);  const hasWildcardEntry = analyzed.some((a) => a.parsed.isWildcard);  const atLimit = maxEntries !== undefined && entries.length >= maxEntries;  const currentIpParsed = React.useMemo(() => (currentIp ? parseIpCidr(currentIp) : null), [currentIp]);  const currentIpAlreadyAdded = Boolean(    currentIpParsed?.valid && analyzed.some((a) => a.parsed.normalized === currentIpParsed.normalized),  );  const showAddMyIp = Boolean(currentIpParsed?.valid && !currentIpAlreadyAdded && !atLimit);  const addSingleEntry = (rawCidr: string, rawLabel?: string) => {    if (atLimit) {      setFormError(`Maximum of ${maxEntries} rules reached`);      recoilComposer();      return;    }    const p = parseIpCidr(rawCidr);    if (!p.valid) {      setFormError(p.error ?? "Invalid IP or CIDR");      recoilComposer();      if (sound) playSound("error", 0.32);      return;    }    if (p.isWildcard && !allowWildcard) {      setFormError("Wildcard rules (0.0.0.0/0 or ::/0) are disabled by policy");      recoilComposer();      if (sound) playSound("error", 0.32);      return;    }    if (analyzed.some((a) => a.parsed.normalized === p.normalized)) {      setFormError(`${p.normalized} is already in the allowlist`);      recoilComposer();      if (sound) playSound("error", 0.32);      return;    }    const nextEntry: IpAllowlistEntry = {      id: nextUid(),      cidr: p.normalized,      ...(rawLabel?.trim() ? { label: rawLabel.trim() } : {}),    };    commit([...entries, nextEntry]);    setCidrDraft("");    setLabelDraft("");    setFormError(null);    setLiveStatus(`Added ${p.normalized}`);    if (sound) playSound("success", 0.32);  };  const handleSubmit = (e: React.FormEvent) => {    e.preventDefault();    addSingleEntry(cidrDraft, labelDraft);  };  const handleBulkPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {    const text = e.clipboardData.getData("text");    if (!text || (!text.includes("\n") && !text.includes(","))) return;    const bulk = parseBulkIpList(text);    if (bulk.length <= 1) return;    e.preventDefault();    const existing = new Set(analyzed.map((a) => a.parsed.normalized));    const additions: IpAllowlistEntry[] = [];    for (const item of bulk) {      const p = parseIpCidr(item.cidr);      if (!p.valid) continue;      if (p.isWildcard && !allowWildcard) continue;      if (existing.has(p.normalized)) continue;      if (maxEntries !== undefined && entries.length + additions.length >= maxEntries) break;      existing.add(p.normalized);      additions.push({ id: nextUid(), cidr: p.normalized, ...(item.label ? { label: item.label } : {}) });    }    if (additions.length === 0) {      setFormError("No new valid CIDR blocks found in clipboard");      recoilComposer();      return;    }    commit([...entries, ...additions]);    setCidrDraft("");    setFormError(null);    const msg = `Imported ${additions.length} rule${additions.length === 1 ? "" : "s"}`;    setImportNote(msg);    setLiveStatus(msg);    if (sound) playSound("success", 0.36);    window.clearTimeout(noteTimerRef.current);    noteTimerRef.current = window.setTimeout(() => setImportNote(null), 3000);  };  const confirmRemove = async (id: string) => {    if (!reduced) {      await new Promise((r) => window.setTimeout(r, 220));    }    commit(entries.filter((e) => e.id !== id));    if (sound) playSound("fold", 0.25);  };  const handleCopyAll = async () => {    if (entries.length === 0) return;    const text = entries.map((e) => (e.label ? `${e.cidr} # ${e.label}` : e.cidr)).join("\n");    try {      await navigator.clipboard?.writeText(text);    } catch {}    setCopiedAll(true);    if (sound) playSound("success", 0.32);    setLiveStatus("Copied allowlist rules");    window.clearTimeout(copyTimerRef.current);    copyTimerRef.current = window.setTimeout(() => setCopiedAll(false), 1800);  };  const composerHint = formError    ? { tone: "error" as const, text: formError }    : parsedDraft.valid && parsedDraft.isWildcard      ? {          tone: "warn" as const,          text: allowWildcard            ? "Warning: /0 opens access to every IP address on the internet."            : "Wildcard /0 blocks are prohibited by policy.",        }      : parsedDraft.valid && parsedDraft.isPrivate        ? { tone: "info" as const, text: "Private / local network address (unreachable from public internet)." }        : null;  return (    <div      role="region"      aria-label={title}      data-rule-count={entries.length}      data-wildcard-open={hasWildcardEntry ? "true" : "false"}      className={`@container flex w-full max-w-[560px] flex-col overflow-hidden rounded-[16px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${className}`}      {...props}    >      {/* Header */}      <div className="flex flex-wrap items-center justify-between gap-2 border-b border-border/80 bg-muted/20 px-4 py-3">        <div className="flex flex-wrap items-center gap-2">          <Shield className="size-4 text-muted-foreground" strokeWidth={1.9} />          <span className="text-[13px] font-medium tracking-[-0.01em] text-foreground">{title}</span>          <span className="inline-flex items-center gap-1 font-mono text-[11px] tabular-nums text-muted-foreground">            <NumberRoll value={entries.length} />            <TextMorph>{entries.length === 1 ? "rule" : "rules"}</TextMorph>          </span>          <span            aria-hidden={!importNote || undefined}            className="grid"            style={{              gridTemplateColumns: importNote ? "1fr" : "0fr",              opacity: importNote ? 1 : 0,              transition: reduced ? "none" : `grid-template-columns 340ms ${EASE_OUT}, opacity 200ms ${EASE_OUT}`,            }}          >            <span className="min-w-0 overflow-hidden">              <span className="inline-flex w-max items-center whitespace-nowrap rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 text-[10.5px] font-medium text-emerald-700 dark:text-emerald-300">                <TextMorph>{importNote ?? lastImportNote}</TextMorph>              </span>            </span>          </span>        </div>        <div className="flex items-center">          <div            className="grid"            inert={!showAddMyIp}            style={{              gridTemplateColumns: showAddMyIp ? "1fr" : "0fr",              opacity: showAddMyIp ? 1 : 0,              transition: reduced ? "none" : `grid-template-columns 320ms ${EASE_OUT}, opacity 200ms ${EASE_OUT}`,            }}          >            <div className="min-w-0 overflow-hidden">              <div className="pr-1.5">                <button                  type="button"                  onClick={() => currentIpParsed?.valid && addSingleEntry(currentIpParsed.normalized, "Current device")}                  className={`inline-flex h-7 w-max cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-[8px] border border-border bg-background px-2 text-[11.5px] font-medium text-foreground hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                >                  <LocateFixed className="size-3 text-muted-foreground" strokeWidth={2} />                  Add my IP                </button>              </div>            </div>          </div>          {entries.length > 0 && (            <button              type="button"              onClick={() => void handleCopyAll()}              className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2 text-[11.5px] font-medium hover:bg-accent ${                copiedAll ? "border-emerald-500/40 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground hover:text-foreground"              } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}            >              <span className="relative flex size-3.5 shrink-0 items-center justify-center">                <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!copiedAll, reduced)}>                  <Copy className="size-3.5" strokeWidth={1.9} />                </span>                <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(copiedAll, reduced)}>                  <Check className="size-3.5" strokeWidth={2.3} />                </span>              </span>              <TextMorph>{copiedAll ? "Copied" : "Copy"}</TextMorph>            </button>          )}        </div>      </div>      {/* Wildcard open-to-internet exposure banner (smooth grid-template-rows fold!) */}      <div        aria-hidden={!hasWildcardEntry || undefined}        className={`grid ${!hasWildcardEntry ? "pointer-events-none" : ""}`}        style={{          gridTemplateRows: hasWildcardEntry ? "1fr" : "0fr",          opacity: hasWildcardEntry ? 1 : 0,          transition: reduced ? "none" : `grid-template-rows 340ms ${EASE_OUT}, opacity 220ms ${EASE_OUT}`,        }}      >        <div className="min-h-0 overflow-clip">          <div            role="alert"            className="flex items-center gap-2 border-b border-amber-500/25 bg-amber-500/[0.08] px-4 py-2 text-[11.5px] text-amber-800 dark:text-amber-200"          >            <AlertTriangle className="size-3.5 shrink-0 text-amber-600 dark:text-amber-400" strokeWidth={2} />            <span>Wildcard rule active: connections are currently open to the entire public internet.</span>          </div>        </div>      </div>      {/* Composer row with live CIDR bitmask scope chip */}      <form ref={composerRef} onSubmit={handleSubmit} className="flex flex-col border-b border-border/80 px-4 py-3">        <div className="flex flex-col gap-2 @[460px]:flex-row @[460px]:items-center">          <div className="relative flex min-w-0 flex-1">            <input              type="text"              spellCheck={false}              autoComplete="off"              disabled={atLimit}              aria-label="IP address or CIDR block"              aria-invalid={Boolean(formError) || undefined}              placeholder="203.0.113.0/24 or 2001:db8::/32"              value={cidrDraft}              onPaste={handleBulkPaste}              onChange={(e) => {                setCidrDraft(e.currentTarget.value);                setFormError(null);              }}              className={`h-9 w-full rounded-[9px] border bg-background pl-2.5 font-mono text-[12.5px] text-foreground placeholder:text-muted-foreground/45 focus:border-foreground/30 focus:outline-none disabled:opacity-50 ${                cidrDraft.trim() ? "pr-28" : "pr-2.5"              } ${                formError ? "border-red-500/55" : "border-border/85"              }`}            />            {cidrDraft.trim() && (              <span                className={`pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 rounded-[5px] px-1.5 py-0.5 font-mono text-[10px] font-medium transition-colors ${                  !parsedDraft.valid                    ? "bg-red-500/12 text-red-600 dark:text-red-400"                    : parsedDraft.isWildcard                      ? "bg-amber-500/15 text-amber-700 dark:text-amber-300"                      : "bg-muted text-muted-foreground"                }`}              >                <TextMorph>{parsedDraft.valid ? `v${parsedDraft.version} · ${parsedDraft.hostCountLabel}` : "Invalid"}</TextMorph>              </span>            )}          </div>          <input            type="text"            disabled={atLimit}            aria-label="Optional rule description"            placeholder="Label (optional)"            value={labelDraft}            onChange={(e) => setLabelDraft(e.currentTarget.value)}            className="h-9 w-full rounded-[9px] border border-border/85 bg-background px-2.5 text-[12.5px] text-foreground placeholder:text-muted-foreground/45 focus:border-foreground/30 focus:outline-none disabled:opacity-50 @[460px]:w-36"          />          <button            type="submit"            disabled={atLimit || !cidrDraft.trim()}            className={`inline-flex h-9 shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-[9px] bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-35 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}          >            <Plus className="size-3.5" strokeWidth={2.2} />            Add          </button>        </div>        {/* Live composer guidance / error fold */}        <div          aria-hidden={!composerHint || undefined}          className={`grid ${!composerHint ? "pointer-events-none" : ""}`}          style={{            gridTemplateRows: composerHint ? "1fr" : "0fr",            opacity: composerHint ? 1 : 0,            transition: reduced ? "none" : `grid-template-rows 260ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,          }}        >          <div className="min-h-0 overflow-hidden">            <div className="pt-2">              {composerHint?.tone === "error" ? (                <p role="alert" className="text-[11.5px] font-medium text-red-600 dark:text-red-400">                  <TextMorph animateWidth={false}>{composerHint.text}</TextMorph>                </p>              ) : composerHint?.tone === "warn" ? (                <p className="inline-flex items-center gap-1.5 text-[11.5px] text-amber-700 dark:text-amber-300">                  <AlertTriangle className="size-3 shrink-0" strokeWidth={2} />                  <span>{composerHint.text}</span>                </p>              ) : composerHint?.tone === "info" ? (                <p className="inline-flex items-center gap-1.5 text-[11.5px] text-muted-foreground">                  <Info className="size-3 shrink-0" strokeWidth={2} />                  <span>{composerHint.text}</span>                </p>              ) : (                <p className="text-[11.5px] text-red-600 dark:text-red-400">{lastFormError}</p>              )}            </div>          </div>        </div>      </form>      {/* Active allowlist rows with additive FLIP glides, detached ghost fade exits & ConfirmAction */}      {analyzed.length === 0 ? (        <div className="flex flex-col items-center justify-center gap-1.5 py-8 text-center">          <Globe className="size-4 text-muted-foreground/55" strokeWidth={1.8} />          <p className="text-[12.5px] font-medium text-foreground">No IP rules configured</p>          <p className="text-[11.5px] text-muted-foreground">Add a single IP, CIDR block or paste a multi-line list above.</p>        </div>      ) : (        <div className="relative">          <div ref={ghostsRef} aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden" />          <div ref={listRef} className="divide-y divide-border/70">            {analyzed.map(({ entry, parsed, coveredBy }) => (              <div                key={entry.id}                data-row-id={entry.id}                data-cidr-row={parsed.normalized || entry.cidr}                data-redundant={coveredBy ? "true" : "false"}                className="flex items-center justify-between gap-3 bg-card px-4 py-2.5"              >                <div className="min-w-0 flex-1">                  <div className="flex flex-wrap items-center gap-1.5">                    <span className="font-mono text-[12.5px] font-medium text-foreground">                      {parsed.valid ? parsed.normalized : entry.cidr}                    </span>                    {parsed.valid && (                      <span                        className={`rounded-[5px] border px-1.5 py-0 font-mono text-[10px] ${                          parsed.isWildcard                            ? "border-amber-500/35 bg-amber-500/12 font-medium text-amber-700 dark:text-amber-300"                            : "border-border/80 bg-muted/40 text-muted-foreground"                        }`}                      >                        {parsed.hostCountLabel}                      </span>                    )}                    {coveredBy && (                      <span className="rounded-[5px] border border-sky-500/30 bg-sky-500/10 px-1.5 py-0 text-[10px] font-medium text-sky-700 dark:text-sky-300">                        Covered by {coveredBy}                      </span>                    )}                    {entry.expiresAt && (                      <span className="rounded-[5px] border border-border/70 px-1.5 py-0 text-[10px] text-muted-foreground">                        {entry.expiresAt}                      </span>                    )}                  </div>                  {entry.label && (                    <p className="mt-0.5 truncate text-[11.5px] text-muted-foreground">{entry.label}</p>                  )}                </div>                <div className="flex shrink-0 items-center gap-2.5">                  <PrefixMaskMeter parsed={parsed} reduced={reduced} />                  <ConfirmAction                    icon={<Trash2 className="size-3.5" strokeWidth={1.9} />}                    label={`Remove ${entry.cidr}`}                    labels={{ idle: "Remove", pending: "Removing", success: "Removed" }}                    tone="danger"                    onConfirm={() => confirmRemove(entry.id)}                  />                </div>              </div>            ))}          </div>        </div>      )}      {/* Footer tip */}      <div className="flex flex-wrap items-center justify-between gap-2 border-t border-border/80 bg-muted/15 px-4 py-2 text-[11px] text-muted-foreground">        <span>Supports IPv4, IPv6 and bulk multi-line paste</span>        {currentIpParsed?.valid && (          <span className="font-mono text-[10.5px]">Your IP: {currentIp}</span>        )}      </div>      <span className="sr-only" role="status" aria-live="polite">        {liveStatus}      </span>    </div>  );}export default IpAllowlist;

Registry item: /r/ip-allowlist.json