Category: software

  • It passed every test, in the wrong place

    It passed every test, in the wrong place

    10 min read

    On the afternoon of 11 October 2026 I ran a script against my OPNsense router’s API from Windows PowerShell 5.1, the PowerShell that comes with Windows. It stopped before it wrote a single line of its own log. The script’s first call to the router comes after that line, so, as far as I can tell, nothing reached the router.

    That was version 2.0. Version 2.4 finished the job at 15:06, 37 minutes after I saved version 2.0. Each version had passed its tests in Claude’s sandbox first. Those tests ran in the wrong place: against a mock router instead of the real one, and under PowerShell 7 instead of Windows PowerShell 5.1. The mock passed all three versions that then failed on the router. Whether the PowerShell difference played a part in failure 1 I do not know. It played none in failure 2, and it broke my test harness later. Three runs failed, each for a different reason. None of them left a change switched on.

    I did this with Claude. I set the rules the script had to follow, created the API key and deleted it afterwards, and ran every version on my own PC against my own router. Claude wrote the script, the mock router it was tested against, and each fix. It tested them under PowerShell 7, the only PowerShell its sandbox had.

    The script, a mock router and a test harness are at the end of this page, under the MIT licence. The script makes a router refuse three common ways around its DNS blocklist: DNS over HTTPS, DNS over TLS or QUIC, and plain DNS sent to another server. This page records the runs and what I would change, and a panel near the end walks through running the script on your own router.

    New to the command line? How to read the boxes

    PS> means: type this in PowerShell on Windows (Start menu → type powershell → Enter). Do not type the PS> itself.

    Each line that starts with PS> is one command. Click that PS> to copy just that line, paste it, press Enter, and wait for it to finish before the next. A box with a Copy button at the top holds one command (or one file), so copy it whole. A dashed box shows what you should see back, or code to read; you do not type it.

    What the script does

    The script applies a DNS fix on an OPNsense 26.7 router. My router’s blocklist only filters devices that ask the router; phones, browsers and some devices ask other servers. The fix involves four objects:

    • an alias, DoH_IPs, that downloads a public list of DNS-over-HTTPS server addresses kept by the Hagezi project (1,434 of them that day);
    • Rule A, which rejects LAN traffic to those addresses on port 443;
    • Rule B, which rejects LAN traffic to any address on port 853, used by DNS over TLS and DNS over QUIC;
    • a NAT redirect that sends any port 53 query aimed past the router back to the router.

    On my router the alias and the redirect rule already existed, and the redirect was switched off. The script cleans the alias, creates the two rules if they are missing, and switches the redirect on. It does not create the redirect rule. The rules cover IPv4 and the LAN interface only; the limits are listed in the step-by-step panel near the end.

    I could have clicked these four objects into place. I scripted it because I wanted the change in a form I could check without changing anything, run again, and switch off in one command.

    The rules it runs under

    1. Three modes. Check reads and reports. Apply makes the change. Rollback switches the two rules and the redirect off and deletes nothing. A command without -Mode runs Check.
    2. Version guard. The script first asks the router what it runs, and stops unless the answer is the 26.7 series.
    3. Backup next. Before it reads or changes any configuration, every run downloads the router’s full configuration into a new file. It refuses to overwrite an existing one.
    4. Test each change. The alias first, then both rules, then the redirect. In version 2.3 a failed test undid everything the run had changed. From version 2.4, if only the redirect fails, only the redirect is switched off, and the rules that passed stay.
    5. No secret in the script. The API key lives in a separate file.

    Thirty-seven minutes

    Started Version Mode What happened Left on the router
    after 14:29 2.0 not logged Stopped before its first log line Nothing
    14:43 2.1 Check Read-only report, complete Nothing
    14:51 2.2 Apply Stopped on its own guard before any save Nothing
    14:56 2.3 Apply Rules worked; redirect test failed; undone Two rules, disabled
    15:04 2.4 Apply Finished at 15:06, every test passed The fix

    Version 2.0 wrote no log, so its time is the minute I saved the file. The other times are from the script’s own logs.

    The order of operations limited the damage. The script checks the version, backs up, and reads before it writes. Failure 1 stopped before any call to the router. Failure 2 stopped before any save, on a guard written for a different problem. Failure 3 happened after changes were made, and that version’s undo switched them off.

    Failure 1: a cause I got wrong

    Version 2.0 took its working folder from a parameter default:

    [string]$WorkDir = $PSScriptRoot

    $PSScriptRoot is the folder the script sits in. The script uses it to build the path for its logs folder, which it creates before it reads the key or calls the router.

    Version 2.1 changed three things. It worked out the folder in the script body, it stopped if that folder did not exist, and it wrapped two counts so that an empty DNS answer counts as zero. Only the folder changes come before the first log line. On the day, Claude and I concluded that Windows PowerShell 5.1 had left $PSScriptRoot empty, and the first drafts of this post said so.

    The test kit for this post checked that, and the conclusion was wrong. On my PC, Windows PowerShell 5.1, started with -File as I start the script, put the folder into $PSScriptRoot in a parameter default. So did PowerShell 7.4.6. I did not test every way of starting a script, so I cannot rule out that some leave it empty. I did not record how I started version 2.0 that afternoon, or the error it showed, so I do not know what stopped it. What the evidence supports is narrower: version 2.0 stopped before its first log line, and so, as far as the evidence shows, before any call to the router. A comment in the published script says the folder can be empty under Windows PowerShell 5.1. That comment repeats my first conclusion; I left the tested file as it was.

    The change in version 2.1 stays. It costs nothing and it works whichever way the script is started:

    if ([string]::IsNullOrWhiteSpace($WorkDir)) {
        if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
        else { $WorkDir = (Get-Location).Path }
    }

    Version 2.1’s Check run at 14:43 completed.

    Failure 2: a mock without the router’s quirks

    To check the alias’s type, version 2.2 called the router’s alias/get_item endpoint. The run log at 14:51:

    14:51:46  Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
    14:51:46  Nothing to undo.
    ...
    14:51:47  STOP: Apply did not complete; changes from this run were undone.

    The alias’s type was not empty. The router’s reply contains entries whose name is an empty string ("":). JSON allows that. PowerShell cannot make an object property with an empty name. Microsoft’s documentation for ConvertFrom-Json says so (the PowerShell 7.4 reference), and offers the -AsHashtable switch for such replies. Windows PowerShell 5.1 does not have that switch. Invoke-RestMethod raised no error. It returned the reply as plain text, and the script read the type from that text as nothing.

    This was not a difference between PowerShell versions. The test kit gives the script a reply with an empty key. Under PowerShell 7.4.6, and on my PC under Windows PowerShell 5.1, Invoke-RestMethod returned it as text, with no error. Version 2.2 passed against the mock because the mock’s reply had no empty keys. The router’s reply had them.

    The guard that stopped the run was written for a different problem: an existing alias of the wrong type. It stopped this run because an empty type is not urltable. Without it, the run would have saved the new URL and then, on undo, written an empty string into the alias.

    The Check run at 14:43 had not caught this. Check read the alias through alias/search_item. Only Apply called get_item.

    Version 2.3 makes two changes. The router’s search_item and search_rule endpoints already return the type and contents, and their replies parsed, so the script reads only through them. And every API call now goes through one helper that refuses a reply it could not parse:

    $r = Invoke-RestMethod @p
    if ($r -is [string]) {
        $t = $r.TrimStart()
        if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
    }

    Failure 3: a redirect tested too soon

    Version 2.3 got further. It cleaned the alias, added both rules and tested them. Then it switched the NAT redirect on and tested it five seconds later:

    14:57:16  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    14:57:17  NAT rule enabled and applied. Verifying...
    14:57:22  Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
    14:57:22  Undoing changes made in this run...

    The test sends two queries to 8.8.8.8: one for example.com and one for an ad domain. The firewall log showed one of the two redirected. The ad domain came back with real addresses, so it was the one not redirected. Thirteen seconds before switching the redirect on, the script’s opening check had sent that same name to 8.8.8.8, to show the bypass was open.

    I have two explanations, and I tested neither. The firewall keeps a state entry for each connection it has seen, and applies a redirect only to new connections. If the second query for the ad domain left my PC from the same source port as the first, it matched the old entry and went out to Google. Or something on my PC answered the repeated question from memory, and the query never left the PC.

    This router’s UDP state timeouts, read from Firewall → Diagnostics → Statistics, are 60 seconds for udp.first and udp.multiple and 30 seconds for udp.single. Version 2.4 waits 70 seconds before testing, and the test passed:

    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.

    The wait outlasts the firewall’s state entries. Whether it also outlasts an answer remembered on the PC depends on how long that answer is kept, which I did not measure. So the result does not tell the two explanations apart. A test with a name not queried earlier, with the firewall’s state table open, would.

    The undo in version 2.3 switched the redirect off, disabled the two new rules and restored the alias’s contents. It did not delete the rules, and it left the alias’s refresh interval at one day. The backup taken after the undo is 4,788 bytes larger than the one before the run. Version 2.4 began by finding the two rules:

    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200

    So “undone” meant “nothing left switched on”, not “the router as it was”. Version 2.4 switched the two existing rules on instead of adding new copies, because it looks rules up by description before creating them.

    What the mock missed, and a second round of tests

    Claude had run each version against its mock before I ran it against the router. By the record of that session, each version ran once normally and once with a forced failure, to check the undo. Versions 2.0 to 2.3 passed against the mock. Against the router, three of the four failed. The mock never ran under Windows PowerShell 5.1, and its replies did not carry the router’s empty keys.

    The script at the end of this page is version 2.5.1, not 2.4. Before publishing, I had Claude review the script again, and version 2.5 fixes what that review found: messages that could describe the router’s state wrongly, stops that were not written to the log, an undo that did not restore the alias’s enabled flag, and runs that could start on a router without the redirect rule or the LAN allow-all rule. It also refuses a router address that does not start with https://, except one on the PC itself, which the test kit uses. Version 2.4 is the one that ran on my router. Version 2.5.1, which differs from 2.5 in its header comments only, has run only against the mock.

    The second round of tests used a new mock, built to misbehave the way a router can, including a reply with an empty key. A harness ran a copy of the script against it once for each of 30 cases. Under PowerShell 7.4.6, all 30 passed.

    The first run under Windows PowerShell 5.1 on my PC failed two cases. The script’s logs showed it had done the right thing; the harness had not. When a PowerShell function returns a list with one item, the caller gets the item itself. PowerShell 7 lets you count and index that item as if it were a list. Windows PowerShell 5.1 does not, for this kind of object. The harness had run only under PowerShell 7. With that fixed, all 30 cases passed under Windows PowerShell 5.1 too, on the published version of the script.

    To check the harness itself, Claude broke the script ten ways, for example by removing the undo, the JSON check or the HTTPS check. Each break made at least one case fail. That check ran under PowerShell 7.4.6 against version 2.5, with an earlier version of the harness.

    What I would take to the next script

    1. Test on the PowerShell that will run the script, and run the tests there too. The harness passed under PowerShell 7 and failed its first run under 5.1.
    2. Build the mock’s replies from real ones. A reply saved from the router’s get_item would have caught failure 2 before the router saw the script.
    3. Make the read-only mode make every read the write mode will make. Here, Check and Apply read the alias through different endpoints.
    4. Treat a string from Invoke-RestMethod as a failure when you expected an object. It does not always raise an error.
    5. After switching on a redirect, wait longer than the firewall’s state timeout, and test with a name you have not queried before.
    6. If the undo disables instead of deleting, make the next run look for what the last one left.
    7. Break the script on purpose to check that the tests can fail.
    8. Keep the API key out of the script and delete it when the work is done. I used the root user’s key. A user with only the privileges the script needs would be better; I have not tried that.
    Run it on your own router, step by step

    Before you start. You need:

    • a Windows PC on the same network as the router. You type in two places: PowerShell on the PC, and the router’s web page in a browser;
    • OPNsense 26.7. The script stops on any other series, because its API paths were read from that series’ own pages;
    • the DNS blocklist switched on, under Services → Unbound DNS → Blocklist (the OPNsense documentation names that page), and your devices asking the router for DNS;
    • a Destination NAT rule that sends DNS queries (port 53) aimed anywhere but the router back to the router, already made, with the description “Redirect non-local DNS to Local”. The script switches it on. It does not build it. The script does not create this rule, this panel does not cover making one, and without it Apply stops. A community how-to on the OPNsense forum shows one way;
    • a LAN rule called “Default allow LAN to any rule”, which OPNsense creates by default. The script checks that its two new rules sit above it.

    Version 2.5.1, the script in this panel, has run only against the mock router in the test kit. Version 2.4 is the one that ran on my router.

    Allow about 20 minutes; the change itself takes about two. The first change to the router is the API key in step 3. The Check run in step 5 changes nothing on it. Apply in step 6 changes it. Step 8 switches the fix off and shows how to restore the whole configuration. Every run saves a backup of the router’s configuration on the PC before it reads the configuration.

    Read the limits next. If one describes your network, the script does not suit it, so do not go on.

    Limits

    • IPv4 only. Rules A and B are created for IPv4, and every test uses an IPv4 address. If your LAN has IPv6, DoH and DoT over IPv6 are neither blocked nor tested. (Interfaces → LAN shows an IPv6 Configuration Type; None means no IPv6.)
    • LAN interface only. Other interfaces and VLANs are not covered.
    • Every LAN host. A Pi-hole or AdGuard Home on the LAN that uses DoH or DoT upstream loses its upstream. If it sends plain DNS to a public server, your redirect rule may catch that too, depending on how the rule is built.
    • Devices that insist on encrypted DNS. A device set to use only an encrypted DNS provider, for example a phone with Private DNS set to a hostname, may lose name lookups on this network once the rules refuse its route. Change that setting on the device.
    • The redirect rule must exist in Firewall → NAT → Destination NAT, with the description “Redirect non-local DNS to Local” or whatever you set in $NatDesc. It is not created or checked for how it is built.
    • The alias is overwritten with the Hagezi URL. The old contents are written to the log.
    • The test domain in $AdTestDomain must be blocked by your router’s blocklist, answered as 0.0.0.0 or with no address, or the redirect test fails.
    • A LAN you trust. The script’s certificate check accepts any certificate presented for the router’s address, so a device on the LAN posing as the router would receive the key. Run it only on a network you control.
    • The wait in $NatWaitSeconds should be longer than your router’s UDP state timeouts.
    • Rollback switches the two rules and the redirect rule off, even if the redirect was on before you first ran Apply. It does not restore the alias.
    1. Open PowerShell and make a folder. Open the Start menu, type powershell and press Enter. A window titled Windows PowerShell opens, and its prompt starts with PS. If the prompt has no PS, you are in Command Prompt: close it and open PowerShell instead, because the commands below work only in PowerShell. Click inside the window. Use the two lines below one at a time: click the PS> to copy a line, paste it (Ctrl + V, or right-click), and press Enter.

      New-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns"
      Set-Location "$env:USERPROFILE\opnsense-dns"

      The first line makes a folder called opnsense-dns inside your user folder and prints a short listing; the second moves PowerShell into it, and the prompt then ends with opnsense-dns>. Each takes under a second. If the first line says the folder exists, go on. Keep this window open, and keep the folder out of OneDrive, Dropbox and shared locations: the backups saved here hold the router’s whole configuration.

    2. Save the script. Scroll to The script, the mock router and the test harness at the end of this page, open opnsense-dns-bypass.ps1 (version 2.5.1), read it, and click Copy. It is 491 lines. It will use your router’s key, so read it before you run it. Windows marks files a browser downloads as coming from the internet; a file written by the command below has no such mark, so Unblock-File is not needed. The command replaces a file of the same name in this folder. In the PowerShell window:

      Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1

      Get-Clipboard reads what you copied and Set-Content writes it to a file; the script is plain ASCII, so that encoding is safe. It takes under a second and prints nothing. Check that all of it arrived:

      (Get-Content .\opnsense-dns-bypass.ps1).Count
      491

      A different number suggests the copy was cut short or changed. Go back to the page, click Copy again and repeat the first command.

    3. Create an API key on the router. In a web browser, type https:// and the address you use for the router’s settings page (for example https://192.168.1.1), and press Enter. The browser may warn that the connection is not private, because the router signs its own certificate. Choose the option that continues to the address (in Chrome: Advanced, then Proceed). Log in with your own router login. Then:

      1. In the menu on the left, click System, then Access, then Users.
      2. Click the pencil (edit) icon at the end of the row of the administrator you log in as.
      3. Find the API keys section in the user’s settings (the OPNsense documentation calls it the ApiKeys tab) and use the button in its grid that creates a key.
      4. The browser downloads a small text file within a few seconds. It has a key= line and a secret= line. The documentation says the secret is generated only once; if the file is lost, make a new key.

      A key acts as the user it belongs to. I used the root user’s key and deleted it afterwards; the root key gives full control of the router. A user limited to the firewall, NAT and backup pages would hold less power, but the script downloads the router’s whole configuration, so that user can still read the password hashes and private keys in it. I have not tried a limited user. If your menu looks different, the OPNsense documentation on local users describes the same step. Do not paste the key file anywhere: the secret in it gives control of the router.

    4. Put the key file in the folder. Back in PowerShell, list the newest text files in your Downloads folder:

      Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTime
      Name                  LastWriteTime
      ----                  -------------
      example_apikey.txt    <date and time>

      If the list is empty, your browser saved the file somewhere else: press Ctrl + J in the browser to see where. Now move the file into the folder under the name the script expects. Replace <file-name>, angle brackets included, with the name from the list:

      Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txt

      It takes under a second and prints nothing. It will not overwrite an apikey.txt already in the folder; if it refuses for that reason, an earlier key file is there. Remove that key on the router (step 8 shows where), run Remove-Item .\apikey.txt, and repeat this step. If it reports an error about the path, the path may still hold <file-name>, or the name may differ from the one in the list. Now check the key file has its two lines. This prints only the word before each =, never the values:

      Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }
      key
      secret

      If you see other words, this is probably not the key file. Download a new key (step 3).

    5. Run Check. It only reads. First tell PowerShell your router’s address. Click the PS> to copy the line, paste it, and do not press Enter yet. Replace <router-ip-address>, angle brackets included, with the numbers of the address from step 3 (for example 192.168.1.1), and leave https:// as it is. Move the cursor with the arrow keys, because a mouse click does not move it in PowerShell; Backspace deletes. Then press Enter. The script stops if the angle brackets are still there.

      $RouterUrl = 'https://<router-ip-address>'

      This remembers the address for this window only. If you close the window, repeat it.

      Now run the script. powershell -ExecutionPolicy Bypass -File starts a fresh Windows PowerShell 5.1 that runs the file. -ExecutionPolicy Bypass on the command line lasts for that one run, and Microsoft’s documentation on execution policies says it is not stored. It does not override a Group Policy set by an employer. Without -Mode the script runs Check.

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      It takes 10 to 60 seconds and changes nothing on the router. It saves a backup of the router’s configuration in the router-backups folder inside opnsense-dns, a log in logs, and runs five live tests. The lines that matter:

      HH:MM:SS  Router reports: OPNsense series 26.7, amd64
      HH:MM:SS  Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes)
      ...
      HH:MM:SS  Router resolves example.com            : True   (want True)
      HH:MM:SS  Router blocks the ad domain (blocklist) : True   (want True)
      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
      HH:MM:SS  Check mode: nothing was changed on the router.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.log

      Both “want True” lines must be True. If “Router blocks the ad domain” is False, your blocklist does not block the test domain and the redirect test in step 6 would fail. Set $AdTestDomain near the top of the script to a domain your blocklist blocks, or switch the blocklist on. If a yellow line starts Apply would stop:, it names a missing rule: the redirect rule or the LAN allow-all rule. Fix that on the router before step 6.

      If something went wrong. The script prints a red line (most contain the word STOP) and changes nothing on the router. What the line says, and what it means:

      • Set -Router to your router’s address: the angle brackets are still in the address from this step.
      • Missing an argument for parameter ‘Router’: probably the address line above was not run in this window. Run it again.
      • -Router must start with https://: the address begins with http://. Use https://.
      • STOP: Key file not found: apikey.txt is not in the opnsense-dns folder. Redo step 4.
      • STOP: Cannot reach the router API with this key: the address is wrong, the key was removed, or the PC is not on the router’s network. Open the address in the browser to test it.
      • STOP: Script was built for OPNsense 26.7: your router runs another series, and the script’s API paths were read from 26.7. Stop here.
      • PowerShell says running scripts is disabled: a policy on your PC blocks scripts, and the command-line option cannot override it. Stop here.
    6. Run Apply. This changes the router. It overwrites the alias DoH_IPs with the Hagezi list address (the old contents go to the log), adds the two reject rules if they are missing, and switches the redirect rule on. Devices on your network that talk to a DNS-over-HTTPS or DNS-over-TLS server directly lose that route; that is the purpose. Run the same command with -Mode Apply added:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Apply

      It takes about two minutes, and up to four if the alias has to download its list first. One line says Waiting 70 s for older DNS states to expire before testing...; wait for it and do not close the window. The last lines should read:

      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
      HH:MM:SS  Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes)
      HH:MM:SS  Apply finished. Expected: router tests True, all three bypass tests False.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.log

      If something went wrong. Apply did not complete; changes from this run were undone: a test failed, and the script switched off what it had changed. Rules it added stay, switched off. It saved a backup of the result. Read the line that starts Problem: for the reason. If any line says UNDO STEP FAILED, restore the “before” backup as step 8 describes. Apply PARTLY finished (in yellow): the alias and the two rules are in place and tested, and the redirect did not pass; the line says whether the redirect was left on or off. To switch the fix off, use step 8.

    7. Check that it worked. Run the Check command from step 5 again:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      Now the three Bypass lines read False and the two Router lines read True. In the router’s web page you can also look at Firewall → Rules (choose LAN in the interface selector), where the two rules Reject DoH to known resolvers (A) and Reject DoT/DoQ 853 from LAN (B) now appear, and at Firewall → NAT → Destination NAT, where Redirect non-local DNS to Local is enabled.

    8. Switch it off, restore if you need to, and remove the key. To switch the fix off, run the command with -Mode Rollback:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Rollback

      It takes under a minute. It disables the two rules and the redirect and deletes nothing. The alias stays as Apply left it. If the redirect was on before you started, it is now off: switch it back on in Firewall → NAT → Destination NAT.

      To put the whole configuration back as it was before Apply, restore the backup on the router: go to System → Configuration → Backups, choose the file named config-Apply-before-<timestamp>.xml from the router-backups folder, and restore it. Each Apply run saves one such file; the earliest holds the configuration from before your first Apply. That also undoes any other change made on the router since.

      When you have finished with the script, whether you keep the fix or not, remove the key. On the router go to System → Access → Users, click the pencil on the same user, and remove the key in the API keys section (the ApiKeys tab). Then delete the key file from the PC:

      Remove-Item .\apikey.txt

      This deletes the file at once, with no recycle bin. When you no longer need the backups, delete the router-backups folder too: it holds password hashes and private keys.

    Security notes. The script sends the key with every request. It does not print or log the secret, and the test kit checks that in each of its 30 cases. Its certificate check accepts any certificate presented for the router’s address, so a device on the LAN posing as the router would receive the key. I deleted my key on 13 October 2026, two days after the run, and the router’s configuration history records the deletion.

    The backups are the router’s whole configuration: password hashes, and the private keys of its certificates and VPN tunnels. Keep that folder private, and do not attach a backup to a forum post.

    Deep dive: the script’s other checks
    • The backup must look like a backup. After downloading, the script checks the file is at least 50,000 bytes and has <opnsense> in its first three lines.
    • A failed save is caught. A reply carrying validations counts as a failed save, as it does in the router’s own web pages; so does a result of failed. Alias and redirect changes are read back. Rule changes are checked by the rules’ presence and order, and by live connection tests.
    • Rule order. After adding Rules A and B, the script stops if either sorts after “Default allow LAN to any rule”, because a rule below the allow-all rule would never match.
    • The alias must fill. It polls the alias every 5 seconds for up to 90 seconds and stops unless it holds at least 500 addresses.
    • Normal browsing must still work. Before declaring the rules good, it opens a connection to www.google.com:443.
    • A partial result says so. If only the redirect stage fails, the run ends Apply PARTLY finished, says what state it left the redirect in, and exits with code 2.
    Deep dive: accepting a bad certificate only for the router’s address

    The router’s web interface uses a self-signed certificate. PowerShell 7 has -SkipCertificateCheck, which the script uses there. Windows PowerShell 5.1 has no such switch. A common workaround is a callback that accepts every certificate for the whole session. The script’s callback accepts a failed certificate check only when the request’s host is the router’s address:

    public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
        if (e == SslPolicyErrors.None) return true;
        HttpWebRequest r = sender as HttpWebRequest;
        return r != null && r.RequestUri.Host == Host;
    }

    This narrows the exception. It does not pin the certificate: any certificate presented for that address passes. Checking the certificate’s thumbprint would close that gap. The script also sets TLS 1.2 for 5.1.

    Deep dive: a precaution, not a failure: Expect: 100-continue

    Check mode sends only GET requests. Apply sends POSTs. Windows PowerShell 5.1 runs on the .NET Framework, where ServicePointManager.Expect100Continue is true by default and adds an Expect: 100-continue header to POST requests that carry a body (Microsoft’s documentation). Version 2.2 switches the header off before the first request:

    [Net.ServicePointManager]::Expect100Continue = $false

    I did not test whether the router’s web server would have objected to the header.

    Deep dive: the finished run, line by line

    The log of the 15:04 run. The router’s address and the name of one of its interfaces are replaced with placeholders in angle brackets; the local folder and the PowerShell build number are removed, and the digits in the byte counts are grouped in threes. The opening tests show all three ways around the blocklist open; the closing tests show them shut, for the three IPv4 addresses tested.

    15:04:49  Mode: Apply   Router: https://<router-ip-address>   PowerShell 5.1
    15:04:55  Router reports: OPNsense series 26.7, amd64
    15:04:55  Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
    15:04:56  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200
    15:04:56  'Default allow LAN to any rule': sort_order=400000.1000023
    15:04:56  NAT 'Redirect non-local DNS to Local': disabled=1
    15:04:56  Router resolves example.com            : True   (want True)
    15:04:56  Router blocks the ad domain (blocklist) : True   (want True)
    15:04:56  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
    15:04:56  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
    15:04:56  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
    15:04:56  Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
    15:04:58  Alias DoH_IPs holds 1434 addresses.
    15:04:58  Rule 'Reject DoH to known resolvers (A)' enabled.
    15:04:58  Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
    15:04:58  Firewall rules applied. Verifying...
    15:05:08  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.
    15:06:19  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:06:19  Rule A: present, enabled=1, sort_order=400000.0000100
    15:06:19  Rule B: present, enabled=1, sort_order=400000.0000200
    15:06:19  'Default allow LAN to any rule': sort_order=400000.1000023
    15:06:19  NAT 'Redirect non-local DNS to Local': disabled=0
    15:06:23  Router resolves example.com            : True   (want True)
    15:06:23  Router blocks the ad domain (blocklist) : True   (want True)
    15:06:23  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
    15:06:23  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
    15:06:23  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
    15:06:23  Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
    15:06:23  Apply finished. Expected: router tests True, all three bypass tests False.

    The alias held one entry I had not put there on purpose: the network of one of the router’s interfaces, ahead of the URL. The run printed the old contents before replacing them, so they can be restored from the log.

    Deep dive: what the test kit checks, and what it cannot

    The mock answers the script’s API paths, keeps the router’s state in memory, records every call, and can be set to misbehave: a wrong version, a bad API key, a small backup, a backup that fails after changes, an alias of the wrong type, a reply with an empty key, a save the router rejects, an alias that does not fill, rules that sort below the allow-all rule, DoH still reachable, normal HTTPS broken, a missing redirect rule or allow rule, a redirect that does not take effect, and a redirect that was already on. It also plays the states my router went through: the alias with a stray entry, the two rules left disabled by version 2.3, and everything already applied. Its reply with an empty key is written by hand, after the router’s get_item reply, and served on the endpoint the script reads.

    The harness runs the script once per case, as a separate process, and checks the exit code, the log, the backup files, every call the mock received, and the mock router’s state at the end. In every case it checks that neither the secret nor the encoded key appears in the output or the log, that nothing was deleted, and that a stop after the log is opened is written to the log.

    The harness tests a copy of the script, not the script itself. In the copy, the two network tests ask the mock instead of the internet, and every wait is cut to a millisecond; before any case runs, the harness checks that each of those patterns matched the expected number of times. The copy talks to the mock over plain HTTP on the PC; the script accepts plain HTTP only for an address on the PC itself.

    So the kit does not test: the certificate check and TLS; the real network tests; failure 3, because the mock has no state table and the waits are cut; replies from a real router, apart from the one hand-written empty-key reply; the script’s refusal to overwrite a backup; the fallback for the work folder, because every case names one; or an undo step that itself fails.

    The ten deliberate breaks and the cases each one made fail are listed with the kit at the end of the page.

    Deep dive: OPNsense 26.7 API notes
    • The script’s header records that each configuration path was taken from the router’s own web pages on the day: alias/search_item, alias/add_item, alias/set_item, alias/reconfigure, filter/search_rule, filter/add_rule, filter/set_rule, filter/apply, d_nat/search_rule, d_nat/set_rule, d_nat/apply, alias_util/list and core/backup/download/this. It also calls core/firmware/info for the version and core/firmware/status as a reachability check.
    • The search endpoints answer a GET with ?rowCount=-1&current=1 and return every row, with the fields the script needs.
    • alias/get_item returns option lists with empty-named keys, which PowerShell cannot turn into object properties.
    • GET /api/core/backup/download/this returns the full configuration as XML.
    • POST bodies are JSON with Content-Type: application/json. Rule changes take effect after the matching apply; alias changes after reconfigure.
    Glossary
    • Windows PowerShell 5.1: the PowerShell that comes with Windows, built on the .NET Framework. Started as powershell.
    • PowerShell 7: the newer PowerShell, installed separately, built on modern .NET. Started as pwsh.
    • REST API: a set of web addresses a program calls to read or change settings; OPNsense’s replies are JSON.
    • JSON: a text format for structured data.
    • Mock: a stand-in for a real system, used for testing; here, a small web server that answers like the router.
    • Test harness: a script that runs another script in many set situations and checks the results.
    • API key: a key and secret that let a script act as a router user without a password.
    • Alias (URL table): an OPNsense list of addresses that the router downloads from a web address and refreshes.
    • NAT redirect: a rule that changes where matching traffic goes; here it sends stray DNS queries to the router.
    • State table: the firewall’s list of connections it has already seen. Later packets of a known connection follow the decision made for the first.
    • DoH, DoT: DNS over HTTPS (port 443) and DNS over TLS (port 853), two ways for a device to look up names without asking the router.
    • Expect: 100-continue: an HTTP header that asks the server to approve a request before its body is sent.

    Script हर test में पास हुई, ग़लत जगह पर

    10 मिनट में पढ़ें · अंग्रेज़ी मूल से अनूदित। Code, commands और तकनीकी नाम अंग्रेज़ी में रखे गए हैं।

    11 अक्टूबर 2026 की दोपहर मैंने अपने OPNsense router की API पर एक script चलाई, Windows PowerShell 5.1 से, यानी वह PowerShell जो Windows के साथ आता है। Script अपने log की पहली line लिखने से पहले ही रुक गई। Router को script की पहली call उस line के बाद आती है, इसलिए, जहाँ तक मैं बता सकता हूँ, router तक कुछ नहीं पहुँचा।

    वह वर्ज़न 2.0 था। वर्ज़न 2.4 ने काम 15:06 पर पूरा किया, वर्ज़न 2.0 save करने के 37 मिनट बाद। हर वर्ज़न पहले Claude के sandbox में अपने tests पास कर चुका था। वे tests ग़लत जगह पर चले थे: असली router की जगह एक mock router पर, और Windows PowerShell 5.1 की जगह PowerShell 7 पर। Mock ने उन तीनों वर्ज़नों को पास किया जो बाद में router पर fail हुए। PowerShell के फ़र्क़ की failure 1 में कोई भूमिका थी या नहीं, मुझे नहीं पता। Failure 2 में उसकी कोई भूमिका नहीं थी, और बाद में उसकी वजह से मेरा test harness fail हुआ। तीन runs fail हुए, हर एक अलग वजह से। किसी ने भी कोई बदलाव चालू नहीं छोड़ा।

    यह काम मैंने Claude के साथ किया। Script को किन नियमों पर चलना है, यह मैंने तय किया, API key बनाई और बाद में delete की, और हर वर्ज़न अपने PC से अपने router पर चलाया। Script, जिस mock router पर उसे test किया गया, और हर fix, Claude ने लिखे। उसने इन्हें PowerShell 7 पर test किया, जो उसके sandbox में मौजूद अकेला PowerShell था।

    Script, एक mock router और एक test harness इस पेज के आख़िर में हैं, MIT licence के तहत। Script router से उसकी DNS blocklist को bypass करने के तीन आम तरीक़े बंद करवाती है: DNS over HTTPS, DNS over TLS या QUIC, और किसी दूसरे server को भेजा गया सादा DNS। यह पेज runs का record और मैं क्या बदलूँगा, यह बताता है, और आख़िर के पास एक panel आपके अपने router पर script चलाने के चरण समझाता है।

    Command line आपके लिए नई है? Boxes को कैसे पढ़ें

    PS> का मतलब है: इसे Windows में PowerShell में type करें (Start menu → powershell type करें → Enter)। PS> को ख़ुद type न करें।

    जिस भी line की शुरुआत PS> से होती है, वह एक command है। सिर्फ़ उस line को copy करने के लिए उसके PS> पर click करें, उसे paste करें, Enter दबाएँ, और अगली command से पहले उसके पूरा होने का इंतज़ार करें। ऊपर Copy button वाला box एक command (या एक file) रखता है, इसलिए उसे पूरा copy करें। टूटी (dashed) रेखा वाला box दिखाता है कि जवाब में आपको क्या दिखना चाहिए, या पढ़ने के लिए code; उसे आप type नहीं करते।

    Script क्या करती है

    Script एक OPNsense 26.7 router पर DNS का एक fix लगाती है। मेरे router की blocklist सिर्फ़ उन devices को filter करती है जो router से पूछते हैं; फ़ोन, browsers और कुछ devices दूसरे servers से पूछते हैं। इस fix में चार objects हैं:

    • एक alias, DoH_IPs, जो Hagezi project की रखी DNS-over-HTTPS servers के पतों की एक public list download करता है (उस दिन 1,434 पते);
    • Rule A, जो उन पतों पर port 443 की LAN traffic को reject करता है;
    • Rule B, जो किसी भी पते पर port 853 की LAN traffic को reject करता है, जिसे DNS over TLS और DNS over QUIC इस्तेमाल करते हैं;
    • एक NAT redirect, जो router को छोड़कर कहीं और जाने वाली port 53 की हर query को वापस router पर भेजता है।

    मेरे router पर alias और redirect rule पहले से मौजूद थे, और redirect बंद था। Script alias को साफ़ करती है, दोनों rules न हों तो बनाती है, और redirect को चालू करती है। वह redirect rule नहीं बनाती। Rules सिर्फ़ IPv4 और LAN interface को cover करते हैं; सीमाएँ आख़िर के पास step-by-step panel में दी गई हैं।

    ये चार objects मैं click करके भी लगा सकता था। Script इसलिए लिखी क्योंकि मुझे यह बदलाव ऐसे रूप में चाहिए था जिसे मैं कुछ बदले बिना जाँच सकूँ, दोबारा चला सकूँ, और एक command से बंद कर सकूँ।

    किन नियमों पर चलती है

    1. तीन modes। Check पढ़ता है और report देता है। Apply बदलाव करता है। Rollback दोनों rules और redirect को बंद करता है और कुछ delete नहीं करता। -Mode के बिना command Check चलाती है।
    2. वर्ज़न की जाँच। Script पहले router से पूछती है कि उस पर क्या चल रहा है, और जवाब 26.7 series न हो तो रुक जाती है।
    3. उसके बाद backup। कोई भी configuration पढ़ने या बदलने से पहले, हर run router की पूरी configuration एक नई file में download करता है। वह किसी मौजूदा file को overwrite करने से मना करता है।
    4. हर बदलाव का test। पहले alias, फिर दोनों rules, फिर redirect। वर्ज़न 2.3 में एक fail हुआ test उस run के सारे बदलाव undo कर देता था। वर्ज़न 2.4 से, अगर सिर्फ़ redirect fail हो, तो सिर्फ़ redirect बंद होता है, और जो rules पास हुए वे बने रहते हैं।
    5. Script में कोई secret नहीं। API key एक अलग file में रहती है।

    सैंतीस मिनट

    शुरू वर्ज़न Mode क्या हुआ Router पर क्या बचा
    14:29 के बाद 2.0 log नहीं हुआ अपनी पहली log line से पहले रुकी कुछ नहीं
    14:43 2.1 Check सिर्फ़ पढ़ने वाली report, पूरी कुछ नहीं
    14:51 2.2 Apply किसी save से पहले अपनी ही सुरक्षा-जाँच पर रुकी कुछ नहीं
    14:56 2.3 Apply Rules चले; redirect test fail; undo हुआ दो rules, बंद
    15:04 2.4 Apply 15:06 पर पूरी, हर test पास Fix

    वर्ज़न 2.0 ने कोई log नहीं लिखा, इसलिए उसका समय वह मिनट है जब मैंने file save की। बाक़ी समय script के अपने logs से हैं।

    कामों के क्रम ने नुक़सान सीमित रखा। Script वर्ज़न जाँचती है, backup लेती है, और लिखने से पहले पढ़ती है। Failure 1 router को कोई भी call जाने से पहले रुका। Failure 2 किसी भी save से पहले रुका, एक ऐसी जाँच पर जो किसी दूसरी समस्या के लिए लिखी गई थी। Failure 3 बदलाव होने के बाद हुआ, और उस वर्ज़न के undo ने उन्हें बंद कर दिया।

    Failure 1: एक वजह जो मैंने ग़लत समझी

    वर्ज़न 2.0 अपना working folder एक parameter default से लेता था:

    [string]$WorkDir = $PSScriptRoot

    $PSScriptRoot वह folder है जिसमें script रखी है। Script इससे अपने logs folder का path बनाती है, जिसे वह key पढ़ने या router को call करने से पहले बनाती है।

    वर्ज़न 2.1 ने तीन चीज़ें बदलीं। उसने folder script के body में तय किया, वह folder मौजूद न होने पर रुकने लगी, और दो गिनतियों को wrap किया ताकि DNS का ख़ाली जवाब शून्य गिना जाए। इनमें से सिर्फ़ folder वाले बदलाव पहली log line से पहले आते हैं। उस दिन Claude और मैंने यह नतीजा निकाला कि Windows PowerShell 5.1 ने $PSScriptRoot ख़ाली छोड़ दिया था, और इस post के पहले drafts में यही लिखा था।

    इस post के test kit ने इसकी जाँच की, और वह नतीजा ग़लत निकला। मेरे PC पर Windows PowerShell 5.1 ने, -File के साथ शुरू करने पर, जैसे मैं script शुरू करता हूँ, parameter default में $PSScriptRoot में folder डाल दिया। PowerShell 7.4.6 ने भी। मैंने script शुरू करने के हर तरीक़े को test नहीं किया, इसलिए मैं इस संभावना को ख़ारिज नहीं कर सकता कि कुछ तरीक़ों में वह ख़ाली रहता है। उस दोपहर मैंने वर्ज़न 2.0 को कैसे शुरू किया, या उसने कौन-सा error दिखाया, यह मैंने दर्ज नहीं किया, इसलिए मुझे नहीं पता कि उसे किस चीज़ ने रोका। सबूत इससे कम बात का समर्थन करते हैं: वर्ज़न 2.0 अपनी पहली log line से पहले रुका, और इसलिए, जहाँ तक सबूत दिखाते हैं, router को कोई भी call जाने से पहले रुका। प्रकाशित script की एक comment कहती है कि Windows PowerShell 5.1 में folder ख़ाली हो सकता है। वह comment मेरे पहले नतीजे को दोहराती है; मैंने test की हुई file को वैसा ही रहने दिया।

    वर्ज़न 2.1 का बदलाव बना रहता है। इसकी कोई क़ीमत नहीं है और script किसी भी तरह शुरू हो, यह काम करता है:

    if ([string]::IsNullOrWhiteSpace($WorkDir)) {
        if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
        else { $WorkDir = (Get-Location).Path }
    }

    वर्ज़न 2.1 का Check run 14:43 पर पूरा हुआ।

    Failure 2: router की ख़ासियतों के बिना एक mock

    Alias का type जाँचने के लिए वर्ज़न 2.2 ने router का alias/get_item endpoint call किया। 14:51 का run log:

    14:51:46  Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
    14:51:46  Nothing to undo.
    ...
    14:51:47  STOP: Apply did not complete; changes from this run were undone.

    Alias का type ख़ाली नहीं था। Router के जवाब में ऐसी entries हैं जिनका नाम एक ख़ाली string है ("":)। JSON इसकी इजाज़त देता है। PowerShell ख़ाली नाम वाली object property नहीं बना सकता। ConvertFrom-Json के लिए Microsoft के दस्तावेज़ यही कहते हैं (PowerShell 7.4 का reference), और ऐसे जवाबों के लिए -AsHashtable switch देते हैं। Windows PowerShell 5.1 में यह switch नहीं है। Invoke-RestMethod ने कोई error नहीं दिया। उसने जवाब सादे text के रूप में लौटाया, और script को उस text से type ख़ाली मिला।

    यह PowerShell वर्ज़नों का फ़र्क़ नहीं था। Test kit script को ख़ाली key वाला एक जवाब देता है। PowerShell 7.4.6 पर, और मेरे PC पर Windows PowerShell 5.1 में, Invoke-RestMethod ने उसे text के रूप में लौटाया, बिना किसी error के। वर्ज़न 2.2 mock पर इसलिए पास हुआ क्योंकि mock के जवाब में कोई ख़ाली key नहीं थी। Router के जवाब में थीं।

    जिस सुरक्षा-जाँच ने run रोका वह एक दूसरी समस्या के लिए लिखी गई थी: ग़लत type का पहले से मौजूद alias। उसने यह run इसलिए रोका क्योंकि ख़ाली type urltable नहीं है। उसके बिना, run नया URL save कर देता और फिर undo पर alias में एक ख़ाली string लिख देता।

    14:43 के Check run ने यह नहीं पकड़ा था। Check alias को alias/search_item से पढ़ता था। सिर्फ़ Apply ने get_item call किया।

    वर्ज़न 2.3 दो बदलाव करता है। Router के search_item और search_rule endpoints पहले से type और contents लौटाते हैं, और उनके जवाब parse हो गए थे, इसलिए script सिर्फ़ उन्हीं से पढ़ती है। और अब हर API call एक helper से होकर जाती है जो ऐसा जवाब मानने से मना करता है जिसे वह parse न कर सके:

    $r = Invoke-RestMethod @p
    if ($r -is [string]) {
        $t = $r.TrimStart()
        if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
    }

    Failure 3: बहुत जल्दी test किया गया redirect

    वर्ज़न 2.3 आगे पहुँचा। उसने alias साफ़ किया, दोनों rules जोड़े और उन्हें test किया। फिर उसने NAT redirect चालू किया और पाँच सेकंड बाद उसे test किया:

    14:57:16  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    14:57:17  NAT rule enabled and applied. Verifying...
    14:57:22  Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
    14:57:22  Undoing changes made in this run...

    Test 8.8.8.8 को दो queries भेजता है: एक example.com के लिए और एक किसी ad domain के लिए। Firewall के log में दोनों में से एक redirect हुई दिखी। Ad domain असली पतों के साथ लौटा, इसलिए redirect न होने वाली query वही थी। Redirect चालू करने से तेरह सेकंड पहले, script की शुरुआती जाँच ने यही नाम 8.8.8.8 को भेजा था, यह दिखाने के लिए कि bypass खुला है।

    मेरे पास दो व्याख्याएँ हैं, और मैंने किसी को test नहीं किया। Firewall हर उस connection की state entry रखता है जो वह देख चुका है, और redirect सिर्फ़ नए connections पर लागू करता है। अगर ad domain की दूसरी query मेरे PC से उसी source port से निकली जिससे पहली, तो वह पुरानी entry से match हुई और Google तक चली गई। या मेरे PC पर किसी चीज़ ने दोहराए गए सवाल का जवाब याद से दे दिया, और query PC से बाहर निकली ही नहीं।

    इस router के UDP state timeouts, जो Firewall → Diagnostics → Statistics से पढ़े, udp.first और udp.multiple के लिए 60 सेकंड और udp.single के लिए 30 सेकंड हैं। वर्ज़न 2.4 test करने से पहले 70 सेकंड रुकता है, और test पास हुआ:

    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.

    यह इंतज़ार firewall की state entries से लंबा है। क्या यह PC पर याद रखे गए जवाब से भी लंबा है, यह इस पर निर्भर है कि वह जवाब कितनी देर रखा जाता है, जो मैंने नहीं मापा। इसलिए यह नतीजा दोनों व्याख्याओं में फ़र्क़ नहीं करता। पहले न पूछे गए किसी नाम के साथ, firewall की state table खोलकर किया गया test यह फ़र्क़ कर सकेगा।

    वर्ज़न 2.3 के undo ने redirect बंद किया, दोनों नए rules disable किए और alias के contents वापस रखे। उसने rules delete नहीं किए, और alias का refresh interval एक दिन पर छोड़ दिया। Undo के बाद लिया गया backup run से पहले वाले backup से 4,788 bytes बड़ा है। वर्ज़न 2.4 ने शुरुआत में ही उन दोनों rules को ढूँढ लिया:

    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200

    तो “undo हुआ” का मतलब था “कुछ भी चालू नहीं बचा”, न कि “router जैसा था वैसा”। वर्ज़न 2.4 ने नई copies जोड़ने की जगह दोनों मौजूदा rules चालू किए, क्योंकि वह rules बनाने से पहले उन्हें description से ढूँढता है।

    Mock से क्या छूटा, और tests का दूसरा दौर

    मेरे router पर चलाने से पहले Claude हर वर्ज़न अपने mock पर चला चुका था। उस session के record के अनुसार, हर वर्ज़न एक बार सामान्य रूप से चला और एक बार ज़बरदस्ती कराई गई failure के साथ, undo जाँचने के लिए। वर्ज़न 2.0 से 2.3 mock पर पास हुए। Router पर चार में से तीन fail हुए। Mock कभी Windows PowerShell 5.1 पर नहीं चला, और उसके जवाबों में router की ख़ाली keys नहीं थीं।

    इस पेज के आख़िर में दी गई script वर्ज़न 2.5.1 है, 2.4 नहीं। Publish करने से पहले मैंने Claude से script का फिर review कराया, और वर्ज़न 2.5 उस review में मिली चीज़ें ठीक करता है: ऐसे messages जो router की state को ग़लत बता सकते थे, ऐसे stops जो log में नहीं लिखे जाते थे, एक undo जो alias का enabled flag वापस नहीं रखता था, और ऐसे runs जो redirect rule या LAN allow-all rule के बिना वाले router पर शुरू हो सकते थे। यह ऐसे router पते को भी मना करता है जो https:// से शुरू न हो, सिवाय PC पर ही मौजूद पते के, जिसे test kit इस्तेमाल करता है। मेरे router पर वर्ज़न 2.4 चला था। वर्ज़न 2.5.1, जो 2.5 से सिर्फ़ अपनी header comments में अलग है, सिर्फ़ mock पर चला है।

    Tests के दूसरे दौर में एक नया mock इस्तेमाल हुआ, जो उसी तरह गड़बड़ करने के लिए बनाया गया था जैसे कोई router कर सकता है, ख़ाली key वाले जवाब समेत। एक harness ने script की एक copy उस पर 30 cases में से हर एक के लिए एक बार चलाई। PowerShell 7.4.6 पर सभी 30 पास हुए।

    मेरे PC पर Windows PowerShell 5.1 के तहत पहले run में दो cases fail हुए। Script के logs दिखाते थे कि उसने सही काम किया था; harness ने नहीं। जब कोई PowerShell function एक item वाली list लौटाता है, तो call करने वाले को वह item ही मिलता है। PowerShell 7 आपको उस item को list की तरह गिनने और index करने देता है। Windows PowerShell 5.1 इस तरह के object के लिए ऐसा नहीं करता। Harness सिर्फ़ PowerShell 7 पर चला था। यह ठीक करने के बाद, script के publish किए गए वर्ज़न पर Windows PowerShell 5.1 में भी सभी 30 cases पास हुए।

    ख़ुद harness को जाँचने के लिए Claude ने script को दस तरह से तोड़ा, जैसे undo, JSON की जाँच या HTTPS की जाँच हटाकर। हर बिगाड़ से कम से कम एक case fail हुआ। यह जाँच PowerShell 7.4.6 पर, वर्ज़न 2.5 के विरुद्ध, harness के एक पहले वर्ज़न के साथ चली थी।

    अगली script के लिए मैं क्या साथ ले जाऊँगा

    1. उसी PowerShell पर test करें जिस पर script चलेगी, और tests भी वहीं चलाएँ। मेरा harness PowerShell 7 पर पास हुआ और 5.1 पर अपने पहले run में fail हुआ।
    2. Mock के जवाब असली जवाबों से बनाएँ। Router के get_item से save किया गया एक जवाब failure 2 को router तक script पहुँचने से पहले पकड़ लेता।
    3. सिर्फ़ पढ़ने वाला mode वे सारे reads करे जो लिखने वाला mode करेगा। यहाँ Check और Apply alias को अलग-अलग endpoints से पढ़ते थे।
    4. जब आप object की उम्मीद कर रहे हों, तो Invoke-RestMethod से मिली string को failure मानें। वह हमेशा error नहीं देता।
    5. Redirect चालू करने के बाद firewall के state timeout से ज़्यादा इंतज़ार करें, और ऐसे नाम से test करें जो आपने पहले query न किया हो।
    6. अगर undo delete करने की जगह disable करता है, तो अगला run वह ढूँढे जो पिछला छोड़ गया।
    7. Script को जान-बूझकर तोड़ें, यह जाँचने के लिए कि tests fail हो सकते हैं।
    8. API key को script से बाहर रखें और काम पूरा होने पर उसे delete करें। मैंने root user की key इस्तेमाल की। सिर्फ़ उतने privileges वाला user बेहतर होगा जितने script को चाहिए; यह मैंने आज़माया नहीं है।
    अपने router पर चरण-दर-चरण चलाएँ

    शुरू करने से पहले। आपको चाहिए:

    • एक Windows PC, जो router वाले ही network पर हो। आप दो जगह type करेंगे: PC पर PowerShell में, और browser में router के web page पर;
    • OPNsense 26.7। Script किसी दूसरी series पर रुक जाती है, क्योंकि उसके API paths उसी series के अपने pages से पढ़े गए थे;
    • DNS blocklist चालू, Services → Unbound DNS → Blocklist में (OPNsense के दस्तावेज़ उस page का नाम देते हैं), और आपके devices DNS के लिए router से पूछते हों;
    • एक Destination NAT rule जो router को छोड़कर कहीं और जाने वाली DNS queries (port 53) को वापस router पर भेजता है, पहले से बना हुआ, description “Redirect non-local DNS to Local” के साथ। Script उसे चालू करती है। वह उसे बनाती नहीं है। Script यह rule नहीं बनाती, यह panel भी इसे बनाना नहीं बताता, और इसके बिना Apply रुक जाता है। OPNsense forum पर एक community how-to एक तरीक़ा दिखाता है;
    • एक LAN rule जिसका नाम “Default allow LAN to any rule” है, जिसे OPNsense default रूप से बनाता है। Script जाँचती है कि उसके दो नए rules उसके ऊपर बैठते हैं।

    वर्ज़न 2.5.1, यानी इस panel की script, सिर्फ़ test kit के mock router पर चली है। मेरे router पर वर्ज़न 2.4 चला था।

    लगभग 20 मिनट रखें; बदलाव ख़ुद लगभग दो मिनट लेता है। Router में पहला बदलाव step 3 की API key है। Step 5 का Check run उसमें कुछ नहीं बदलता। Step 6 का Apply बदलता है। Step 8 fix को बंद करता है और पूरी configuration restore करना दिखाता है। हर run router की configuration पढ़ने से पहले उसका backup PC पर save करता है।

    पहले सीमाएँ पढ़ें। अगर उनमें से कोई आपके network का वर्णन करती है, तो script आपके लिए ठीक नहीं है, इसलिए आगे न बढ़ें।

    सीमाएँ

    • सिर्फ़ IPv4। Rules A और B IPv4 के लिए बनते हैं, और हर test एक IPv4 पता इस्तेमाल करता है। अगर आपके LAN पर IPv6 है, तो IPv6 पर DoH और DoT न block होते हैं, न test। (Interfaces → LAN में एक IPv6 Configuration Type दिखता है; None का मतलब IPv6 नहीं है।)
    • सिर्फ़ LAN interface। दूसरे interfaces और VLANs cover नहीं होते।
    • LAN का हर host। LAN पर कोई Pi-hole या AdGuard Home जो upstream के लिए DoH या DoT इस्तेमाल करता है, अपना upstream खो देता है। अगर वह किसी public server को सादा DNS भेजता है, तो आपका redirect rule उसे भी पकड़ सकता है, यह इस पर निर्भर है कि rule कैसे बना है।
    • जो devices encrypted DNS पर ही अड़े रहते हैं। जो device सिर्फ़ किसी encrypted DNS provider के लिए set है, जैसे Private DNS में hostname वाला फ़ोन, उसका DNS lookup इस network पर बंद हो सकता है, जब rules उसका रास्ता refuse कर दें। वह setting device पर बदलें।
    • Redirect rule मौजूद होना चाहिए Firewall → NAT → Destination NAT में, description “Redirect non-local DNS to Local” के साथ, या जो भी आप $NatDesc में रखें। वह बनाया नहीं जाता, और यह जाँचा नहीं जाता कि वह कैसे बना है।
    • Alias overwrite होता है Hagezi URL से। पुराने contents log में लिखे जाते हैं।
    • Test domain जो $AdTestDomain में है, आपके router की blocklist से block होना चाहिए, यानी उसका जवाब 0.0.0.0 या बिना किसी पते का हो, वरना redirect test fail होता है।
    • भरोसे का LAN। Script की certificate जाँच router के पते के लिए पेश किया गया कोई भी certificate मान लेती है, इसलिए LAN पर router होने का दिखावा करने वाले device को key मिल जाएगी। इसे सिर्फ़ ऐसे network पर चलाएँ जो आपके नियंत्रण में हो।
    • इंतज़ार जो $NatWaitSeconds में है, आपके router के UDP state timeouts से लंबा होना चाहिए।
    • Rollback दोनों rules और redirect rule को बंद कर देता है, भले ही redirect आपके पहली बार Apply चलाने से पहले चालू रहा हो। वह alias को restore नहीं करता।
    1. PowerShell खोलें और एक folder बनाएँ। Start menu खोलें, powershell type करें और Enter दबाएँ। Windows PowerShell नाम की एक window खुलती है, और उसका prompt PS से शुरू होता है। अगर prompt में PS नहीं है, तो आप Command Prompt में हैं: उसे बंद करें और उसकी जगह PowerShell खोलें, क्योंकि नीचे के commands सिर्फ़ PowerShell में चलते हैं। Window के अंदर click करें। नीचे की दो lines एक-एक करके इस्तेमाल करें: एक line copy करने के लिए PS> पर click करें, उसे paste करें (Ctrl + V, या right-click), और Enter दबाएँ।

      New-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns"
      Set-Location "$env:USERPROFILE\opnsense-dns"

      पहली line आपके user folder के अंदर opnsense-dns नाम का folder बनाती है और एक छोटी listing print करती है; दूसरी PowerShell को उसके अंदर ले जाती है, और तब prompt opnsense-dns> पर ख़त्म होता है। हर एक एक सेकंड से कम लेती है। अगर पहली line कहे कि folder पहले से है, तो आगे बढ़ें। यह window खुली रखें, और folder को OneDrive, Dropbox और shared जगहों से बाहर रखें: यहाँ save होने वाले backups में router की पूरी configuration होती है।

    2. Script save करें। इस page के आख़िर में The script, the mock router and the test harness तक scroll करें, opnsense-dns-bypass.ps1 (version 2.5.1) खोलें, उसे पढ़ें, और Copy पर click करें। वह 491 lines की है। वह आपके router की key इस्तेमाल करेगी, इसलिए चलाने से पहले उसे पढ़ें। Browser से download की गई files पर Windows निशान लगाता है कि वे internet से आई हैं; नीचे के command से लिखी गई file पर ऐसा कोई निशान नहीं होता, इसलिए Unblock-File की ज़रूरत नहीं है। Command इस folder में उसी नाम की file को replace कर देता है। PowerShell की window में:

      Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1

      Get-Clipboard वह पढ़ता है जो आपने copy किया और Set-Content उसे file में लिखता है; script सादी ASCII है, इसलिए वह encoding सुरक्षित है। यह एक सेकंड से कम लेता है और कुछ print नहीं करता। जाँचें कि सब कुछ पहुँच गया:

      (Get-Content .\opnsense-dns-bypass.ps1).Count
      491

      अलग संख्या का मतलब हो सकता है कि copy बीच में कट गई या बदल गई। Page पर वापस जाएँ, दोबारा Copy पर click करें और पहला command दोहराएँ।

    3. Router पर एक API key बनाएँ। Web browser में https:// type करें और वह पता जो आप router के settings page के लिए इस्तेमाल करते हैं (जैसे https://192.168.1.1), और Enter दबाएँ। Browser चेतावनी दे सकता है कि connection private नहीं है, क्योंकि router अपना certificate ख़ुद sign करता है। वह विकल्प चुनें जो उस पते तक जारी रखता है (Chrome में: Advanced, फिर Proceed)। अपने router के login से log in करें। फिर:

      1. बाईं ओर के menu में System पर click करें, फिर Access, फिर Users।
      2. जिस administrator के रूप में आप log in करते हैं, उसकी row के आख़िर में pencil (edit) icon पर click करें।
      3. User की settings में API keys वाला section ढूँढें (OPNsense के दस्तावेज़ उसे ApiKeys tab कहते हैं) और उसके grid में key बनाने वाले button का इस्तेमाल करें।
      4. Browser कुछ सेकंड के भीतर एक छोटी text file download करता है। उसमें एक key= line और एक secret= line होती है। दस्तावेज़ कहते हैं कि secret सिर्फ़ एक बार बनता है; file खो जाए तो नई key बनाएँ।

      Key उसी user की तरह काम करती है जिसकी वह है। मैंने root user की key इस्तेमाल की और बाद में उसे delete कर दिया; root key router का पूरा नियंत्रण देती है। सिर्फ़ firewall, NAT और backup pages तक सीमित user के पास कम अधिकार होगा, पर script router की पूरी configuration download करती है, इसलिए वह user भी उसमें के password hashes और private keys पढ़ सकता है। मैंने सीमित user आज़माया नहीं है। अगर आपका menu अलग दिखता है, तो local users पर OPNsense के दस्तावेज़ यही step बताते हैं। Key file को कहीं paste न करें: उसमें का secret router का नियंत्रण देता है।

    4. Key file को folder में रखें। PowerShell में वापस आकर, अपने Downloads folder की सबसे नई text files की list निकालें:

      Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTime
      Name                  LastWriteTime
      ----                  -------------
      example_apikey.txt    <date and time>

      अगर list ख़ाली है, तो आपके browser ने file कहीं और save की है: browser में Ctrl + J दबाकर देखें कि कहाँ। अब file को उस नाम से folder में ले जाएँ जो script उम्मीद करती है। <file-name> को, angle brackets समेत, list के नाम से बदलें:

      Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txt

      यह एक सेकंड से कम लेता है और कुछ print नहीं करता। यह folder में पहले से मौजूद apikey.txt को overwrite नहीं करेगा; अगर वह इसी कारण मना करे, तो वहाँ पहले की कोई key file है। उस key को router पर हटाएँ (step 8 बताता है कहाँ), Remove-Item .\apikey.txt चलाएँ, और यह step दोहराएँ। अगर वह path के बारे में error बताए, तो हो सकता है path में अब भी <file-name> हो, या नाम list के नाम से अलग हो। अब जाँचें कि key file में उसकी दो lines हैं। यह हर = से पहले का सिर्फ़ शब्द print करता है, मान कभी नहीं:

      Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }
      key
      secret

      अगर आपको दूसरे शब्द दिखें, तो शायद यह key file नहीं है। नई key download करें (step 3)।

    5. Check चलाएँ। यह सिर्फ़ पढ़ता है। पहले PowerShell को अपने router का पता बताएँ। Line copy करने के लिए PS> पर click करें, उसे paste करें, और अभी Enter न दबाएँ। <router-ip-address> को, angle brackets समेत, step 3 के पते की संख्याओं से बदलें (जैसे 192.168.1.1), और https:// को वैसा ही रहने दें। Cursor को arrow keys से हिलाएँ, क्योंकि PowerShell में mouse click से cursor नहीं हिलता; Backspace मिटाता है। फिर Enter दबाएँ। अगर angle brackets अब भी वहाँ हैं तो script रुक जाती है।

      $RouterUrl = 'https://<router-ip-address>'

      यह पता सिर्फ़ इस window के लिए याद रखा जाता है। Window बंद करें तो इसे दोहराएँ।

      अब script चलाएँ। powershell -ExecutionPolicy Bypass -File एक नया Windows PowerShell 5.1 शुरू करता है जो file चलाता है। Command line पर दिया गया -ExecutionPolicy Bypass सिर्फ़ उसी एक run के लिए रहता है, और execution policies पर Microsoft के दस्तावेज़ कहते हैं कि वह store नहीं होता। यह किसी employer की लगाई Group Policy को override नहीं करता। -Mode के बिना script Check चलाती है।

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      यह 10 से 60 सेकंड लेता है और router पर कुछ नहीं बदलता। यह router की configuration का backup router-backups folder में, जो opnsense-dns के अंदर है, एक log logs में save करता है, और पाँच live tests चलाता है। ज़रूरी lines:

      HH:MM:SS  Router reports: OPNsense series 26.7, amd64
      HH:MM:SS  Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes)
      ...
      HH:MM:SS  Router resolves example.com            : True   (want True)
      HH:MM:SS  Router blocks the ad domain (blocklist) : True   (want True)
      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
      HH:MM:SS  Check mode: nothing was changed on the router.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.log

      दोनों “want True” lines True होनी चाहिए। अगर “Router blocks the ad domain” False है, तो आपकी blocklist test domain को block नहीं करती और step 6 का redirect test fail होगा। Script के ऊपरी हिस्से में $AdTestDomain को ऐसे domain पर set करें जिसे आपकी blocklist block करती है, या blocklist चालू करें। अगर कोई पीली line Apply would stop: से शुरू होती है, तो वह किसी ग़ायब rule का नाम बताती है: redirect rule या LAN allow-all rule। Step 6 से पहले उसे router पर ठीक करें।

      अगर कुछ गड़बड़ हुई। Script एक लाल line print करती है (ज़्यादातर में शब्द STOP होता है) और router पर कुछ नहीं बदलती। Line क्या कहती है, और उसका मतलब क्या है:

      • Set -Router to your router’s address: इस step के पते में angle brackets अब भी हैं।
      • Missing an argument for parameter ‘Router’: शायद ऊपर की पते वाली line इस window में चलाई नहीं गई। उसे फिर चलाएँ।
      • -Router must start with https://: पता http:// से शुरू होता है। https:// इस्तेमाल करें।
      • STOP: Key file not found: apikey.txt opnsense-dns folder में नहीं है। Step 4 फिर करें।
      • STOP: Cannot reach the router API with this key: पता ग़लत है, key हटा दी गई थी, या PC router के network पर नहीं है। पते को browser में खोलकर जाँचें।
      • STOP: Script was built for OPNsense 26.7: आपका router दूसरी series पर है, और script के API paths 26.7 से पढ़े गए थे। यहीं रुक जाएँ।
      • PowerShell कहता है कि scripts चलाना बंद है: आपके PC की एक policy scripts को रोकती है, और command-line option उसे override नहीं कर सकता। यहीं रुक जाएँ।
    6. Apply चलाएँ। यह router को बदलता है। यह alias DoH_IPs को Hagezi list के पते से overwrite करता है (पुराने contents log में जाते हैं), दो reject rules जोड़ता है अगर वे न हों, और redirect rule को चालू करता है। आपके network के जो devices किसी DNS-over-HTTPS या DNS-over-TLS server से सीधे बात करते हैं, वे वह रास्ता खो देते हैं; यही मक़सद है। वही command चलाएँ, -Mode Apply जोड़कर:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Apply

      यह लगभग दो मिनट लेता है, और चार तक, अगर alias को पहले अपनी list download करनी पड़े। एक line कहती है Waiting 70 s for older DNS states to expire before testing...; उसका इंतज़ार करें और window बंद न करें। आख़िरी lines ऐसी होनी चाहिए:

      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
      HH:MM:SS  Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes)
      HH:MM:SS  Apply finished. Expected: router tests True, all three bypass tests False.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.log

      अगर कुछ गड़बड़ हुई। Apply did not complete; changes from this run were undone: कोई test fail हुआ, और script ने जो बदला था उसे बंद कर दिया। जो rules उसने जोड़े वे बंद हालत में रहते हैं। उसने नतीजे का backup save किया। कारण के लिए वह line पढ़ें जो Problem: से शुरू होती है। अगर कोई line UNDO STEP FAILED कहे, तो “before” backup को restore करें, जैसा step 8 बताता है। Apply PARTLY finished (पीले में): alias और दोनों rules लग चुके हैं और test हो चुके हैं, और redirect पास नहीं हुआ; line बताती है कि redirect चालू छोड़ा गया या बंद। Fix को बंद करने के लिए step 8 इस्तेमाल करें।

    7. जाँचें कि काम हुआ। Step 5 का Check command फिर चलाएँ:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      अब तीनों Bypass lines False दिखाती हैं और दोनों Router lines True। Router के web page में आप Firewall → Rules भी देख सकते हैं (interface selector में LAN चुनें), जहाँ दोनों rules Reject DoH to known resolvers (A) और Reject DoT/DoQ 853 from LAN (B) अब दिखते हैं, और Firewall → NAT → Destination NAT में, जहाँ Redirect non-local DNS to Local चालू है।

    8. इसे बंद करें, ज़रूरत हो तो restore करें, और key हटाएँ। Fix को बंद करने के लिए command को -Mode Rollback के साथ चलाएँ:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Rollback

      यह एक मिनट से कम लेता है। यह दोनों rules और redirect को disable करता है और कुछ delete नहीं करता। Alias वैसा ही रहता है जैसा Apply ने छोड़ा। अगर redirect आपके शुरू करने से पहले चालू था, तो वह अब बंद है: उसे Firewall → NAT → Destination NAT में फिर चालू करें।

      पूरी configuration को Apply से पहले जैसी थी वैसी वापस लाने के लिए, router पर backup restore करें: System → Configuration → Backups पर जाएँ, config-Apply-before-<timestamp>.xml नाम की file चुनें, जो router-backups folder में है, और उसे restore करें। हर Apply run ऐसी एक file save करता है; सबसे पुरानी में आपके पहले Apply से पहले की configuration है। इससे router पर उसके बाद किया गया कोई भी दूसरा बदलाव भी undo हो जाता है।

      जब script का काम पूरा हो जाए, चाहे fix रखें या नहीं, key हटा दें। Router पर System → Access → Users पर जाएँ, उसी user पर pencil पर click करें, और API keys वाले section में key हटा दें (ApiKeys tab)। फिर key file को PC से delete करें:

      Remove-Item .\apikey.txt

      यह file को तुरंत delete कर देता है, recycle bin के बिना। जब आपको backups की ज़रूरत न रहे, तो router-backups folder भी delete करें: उसमें password hashes और private keys हैं।

    सुरक्षा संबंधी नोट। Script हर request के साथ key भेजती है। वह secret को print या log नहीं करती, और test kit अपने 30 cases में से हर एक में यह जाँचता है। उसकी certificate जाँच router के पते के लिए पेश किया गया कोई भी certificate मान लेती है, इसलिए LAN पर router होने का दिखावा करने वाले device को key मिल जाएगी। मैंने अपनी key 13 अक्टूबर 2026 को delete की, run के दो दिन बाद, और router की configuration का history इस deletion को दर्ज करता है।

    Backups router की पूरी configuration हैं: password hashes, और उसके certificates और VPN tunnels की private keys। उस folder को निजी रखें, और किसी forum post के साथ backup attach न करें।

    विस्तार से: script की दूसरी जाँचें
    • Backup, backup जैसा दिखना चाहिए। Download के बाद script जाँचती है कि file कम से कम 50,000 bytes की है और उसकी पहली तीन lines में <opnsense> है।
    • Fail हुआ save पकड़ा जाता है। validations वाला जवाब fail हुआ save गिना जाता है, जैसा router के अपने web pages में होता है; result का failed होना भी। Alias और redirect के बदलाव वापस पढ़े जाते हैं। Rule के बदलाव rules की मौजूदगी और क्रम से, और live connection tests से जाँचे जाते हैं।
    • Rule का क्रम। Rules A और B जोड़ने के बाद, अगर दोनों में से कोई “Default allow LAN to any rule” के बाद sort होता है तो script रुक जाती है, क्योंकि allow-all rule के नीचे का rule कभी match नहीं होगा।
    • Alias भरना चाहिए। यह alias को हर 5 सेकंड पर, 90 सेकंड तक poll करती है और जब तक उसमें कम से कम 500 पते न हों, रुक जाती है।
    • सामान्य browsing चलती रहनी चाहिए। Rules को ठीक घोषित करने से पहले, यह www.google.com:443 से एक connection खोलती है।
    • अधूरा नतीजा अधूरा ही बताया जाता है। अगर सिर्फ़ redirect वाला चरण fail होता है, तो run Apply PARTLY finished पर ख़त्म होता है, बताता है कि redirect को किस state में छोड़ा, और code 2 के साथ exit करता है।
    विस्तार से: ख़राब certificate सिर्फ़ router के पते के लिए मानना

    Router का web interface एक self-signed certificate इस्तेमाल करता है। PowerShell 7 में -SkipCertificateCheck है, जिसे script वहाँ इस्तेमाल करती है। Windows PowerShell 5.1 में ऐसा कोई switch नहीं है। एक आम workaround एक callback है जो पूरे session के लिए हर certificate मान लेता है। Script का callback fail हुई certificate जाँच को सिर्फ़ तब मानता है जब request का host router का पता हो:

    public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
        if (e == SslPolicyErrors.None) return true;
        HttpWebRequest r = sender as HttpWebRequest;
        return r != null && r.RequestUri.Host == Host;
    }

    यह छूट को सीमित करता है। यह certificate को pin नहीं करता: उस पते के लिए पेश किया गया कोई भी certificate पास हो जाता है। Certificate का thumbprint जाँचने से यह कमी बंद हो जाएगी। Script 5.1 के लिए TLS 1.2 भी set करती है।

    विस्तार से: एक एहतियात, failure नहीं: Expect: 100-continue

    Check mode सिर्फ़ GET requests भेजता है। Apply POSTs भेजता है। Windows PowerShell 5.1 .NET Framework पर चलता है, जहाँ ServicePointManager.Expect100Continue default रूप से true होता है और body वाली POST requests में एक Expect: 100-continue header जोड़ता है (Microsoft के दस्तावेज़)। वर्ज़न 2.2 पहली request से पहले यह header बंद कर देता है:

    [Net.ServicePointManager]::Expect100Continue = $false

    मैंने test नहीं किया कि router का web server इस header पर आपत्ति करता या नहीं।

    विस्तार से: पूरा हुआ run, line दर line

    15:04 वाले run का log। Router का पता और उसके एक interface का नाम angle brackets में placeholders से बदले गए हैं; local folder और PowerShell का build number हटाए गए हैं, और bytes की गिनती के अंक तीन-तीन के समूहों में रखे गए हैं। शुरुआती tests blocklist से बचने के तीनों रास्ते खुले दिखाते हैं; आख़िरी tests उन्हें बंद दिखाते हैं, test किए गए तीन IPv4 पतों के लिए।

    15:04:49  Mode: Apply   Router: https://<router-ip-address>   PowerShell 5.1
    15:04:55  Router reports: OPNsense series 26.7, amd64
    15:04:55  Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
    15:04:56  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200
    15:04:56  'Default allow LAN to any rule': sort_order=400000.1000023
    15:04:56  NAT 'Redirect non-local DNS to Local': disabled=1
    15:04:56  Router resolves example.com            : True   (want True)
    15:04:56  Router blocks the ad domain (blocklist) : True   (want True)
    15:04:56  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
    15:04:56  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
    15:04:56  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
    15:04:56  Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
    15:04:58  Alias DoH_IPs holds 1434 addresses.
    15:04:58  Rule 'Reject DoH to known resolvers (A)' enabled.
    15:04:58  Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
    15:04:58  Firewall rules applied. Verifying...
    15:05:08  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.
    15:06:19  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:06:19  Rule A: present, enabled=1, sort_order=400000.0000100
    15:06:19  Rule B: present, enabled=1, sort_order=400000.0000200
    15:06:19  'Default allow LAN to any rule': sort_order=400000.1000023
    15:06:19  NAT 'Redirect non-local DNS to Local': disabled=0
    15:06:23  Router resolves example.com            : True   (want True)
    15:06:23  Router blocks the ad domain (blocklist) : True   (want True)
    15:06:23  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
    15:06:23  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
    15:06:23  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
    15:06:23  Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
    15:06:23  Apply finished. Expected: router tests True, all three bypass tests False.

    Alias में एक entry थी जो मैंने जान-बूझकर नहीं डाली थी: router के एक interface का network, URL से पहले। Run ने बदलने से पहले पुराने contents print किए, इसलिए उन्हें log से वापस लाया जा सकता है।

    विस्तार से: test kit क्या जाँचता है, और क्या नहीं जाँच सकता

    Mock script के API paths का जवाब देता है, router की state memory में रखता है, हर call दर्ज करता है, और गड़बड़ करने के लिए set किया जा सकता है: ग़लत वर्ज़न, ख़राब API key, छोटा backup, बदलावों के बाद fail होने वाला backup, ग़लत type का alias, ख़ाली key वाला जवाब, ऐसा save जिसे router reject करे, ऐसा alias जो न भरे, allow-all rule के नीचे sort होने वाले rules, DoH का फिर भी पहुँच में होना, सामान्य HTTPS का टूटना, redirect rule या allow rule का न होना, ऐसा redirect जो असर न करे, और ऐसा redirect जो पहले से चालू था। यह उन states को भी दोहराता है जिनसे मेरा router गुज़रा: एक भटकी हुई entry वाला alias, वर्ज़न 2.3 के disable छोड़े गए दो rules, और सब कुछ पहले से लागू (applied)। इसका ख़ाली key वाला जवाब हाथ से लिखा गया है, router के get_item जवाब के आधार पर, और उस endpoint पर दिया जाता है जिसे script पढ़ती है।

    Harness script को हर case के लिए एक बार, अलग process के रूप में चलाता है, और exit code, log, backup files, mock को मिली हर call, और आख़िर में mock router की state जाँचता है। हर case में यह जाँचता है कि न secret और न encoded key output या log में दिखे, कि कुछ भी delete न हुआ हो, और कि log खुलने के बाद का कोई भी stop log में लिखा जाए।

    Harness script की एक copy को test करता है, ख़ुद script को नहीं। Copy में दोनों network tests internet की जगह mock से पूछते हैं, और हर इंतज़ार एक millisecond कर दिया जाता है; कोई भी case चलने से पहले harness जाँचता है कि इनमें से हर pattern उम्मीद जितनी बार match हुआ। Copy PC पर सादे HTTP से mock से बात करती है; script सादा HTTP सिर्फ़ PC पर ही मौजूद पते के लिए मानती है।

    तो kit ये चीज़ें test नहीं करता: certificate जाँच और TLS; असली network tests; failure 3, क्योंकि mock में कोई state table नहीं है और इंतज़ार छोटे कर दिए गए हैं; असली router के जवाब, हाथ से लिखे एक ख़ाली key वाले जवाब के सिवा; script का backup overwrite करने से मना करना; work folder का fallback, क्योंकि हर case एक folder का नाम देता है; या ऐसा undo step जो ख़ुद fail हो जाए।

    script में जान-बूझकर किए गए दस बिगाड़ और हर एक से fail हुए cases, पेज के आख़िर में kit के साथ दिए गए हैं।

    विस्तार से: OPNsense 26.7 API पर टिप्पणियाँ
    • Script का header दर्ज करता है कि हर configuration path उस दिन router के अपने web pages से लिया गया था: alias/search_item, alias/add_item, alias/set_item, alias/reconfigure, filter/search_rule, filter/add_rule, filter/set_rule, filter/apply, d_nat/search_rule, d_nat/set_rule, d_nat/apply, alias_util/list और core/backup/download/this। यह वर्ज़न के लिए core/firmware/info और पहुँच की जाँच के लिए core/firmware/status भी call करती है।
    • Search endpoints ?rowCount=-1&current=1 वाली GET का जवाब देते हैं और हर row लौटाते हैं, उन fields के साथ जो script को चाहिए।
    • alias/get_item ख़ाली नाम वाली keys के साथ option lists लौटाता है, जिन्हें PowerShell object properties में नहीं बदल सकता।
    • GET /api/core/backup/download/this पूरी configuration XML के रूप में लौटाता है।
    • POST bodies Content-Type: application/json के साथ JSON होती हैं। Rule के बदलाव मेल खाते apply के बाद असर करते हैं; alias के बदलाव reconfigure के बाद।
    शब्दावली
    • Windows PowerShell 5.1: वह PowerShell जो Windows के साथ आता है, .NET Framework पर बना। powershell से शुरू होता है।
    • PowerShell 7: नया PowerShell, अलग से install होता है, आधुनिक .NET पर बना। pwsh से शुरू होता है।
    • REST API: web पतों का एक set जिसे कोई program settings पढ़ने या बदलने के लिए call करता है; OPNsense के जवाब JSON में होते हैं।
    • JSON: structured data के लिए एक text format।
    • Mock: किसी असली system की जगह खड़ा किया गया नक़ली system, testing के लिए; यहाँ, एक छोटा web server जो router की तरह जवाब देता है।
    • Test harness: एक script जो किसी दूसरी script को कई तय स्थितियों में चलाती है और नतीजे जाँचती है।
    • API key: एक key और secret जो script को बिना password के router user की तरह काम करने देते हैं।
    • Alias (URL table): पतों की एक OPNsense list जिसे router एक web पते से download करता है और refresh करता है।
    • NAT redirect: एक rule जो match होने वाली traffic की मंज़िल बदलता है; यहाँ यह भटकी DNS queries को router पर भेजता है।
    • State table: firewall की वह list जिसमें उन connections का हिसाब रहता है जिन्हें वह पहले देख चुका है। किसी जाने-पहचाने connection के बाद के packets पहले packet के लिए लिए गए फ़ैसले के हिसाब से चलते हैं।
    • DoH, DoT: DNS over HTTPS (port 443) और DNS over TLS (port 853), किसी device के लिए router से पूछे बिना नामों का पता लगाने (DNS lookup) के दो तरीक़े।
    • Expect: 100-continue: एक HTTP header जो server से कहता है कि request की body भेजे जाने से पहले उसे मंज़ूरी दे।

    ప్రతి టెస్ట్‌లోనూ పాసైంది, తప్పు చోట

    చదవడానికి 10 నిమిషాలు · ఇంగ్లీష్ మూలం నుంచి అనువదించినది. Code, commands, సాంకేతిక పేర్లు ఇంగ్లీష్‌లోనే ఉన్నాయి.

    11 అక్టోబర్ 2026 మధ్యాహ్నం నా OPNsense router API మీద Windows PowerShell 5.1 నుంచి ఒక script నడిపాను. ఇది Windows తో పాటు వచ్చే PowerShell. script తన log లో ఒక్క లైన్ కూడా రాయకముందే ఆగిపోయింది. router కి script చేసే మొదటి call ఆ లైన్ తర్వాత వస్తుంది. కాబట్టి, నాకు తెలిసినంతవరకు, router వరకు ఏదీ చేరలేదు.

    అది వెర్షన్ 2.0. వెర్షన్ 2.4 పనిని 15:06 కి పూర్తి చేసింది, నేను వెర్షన్ 2.0 ని save చేసిన 37 నిమిషాల తర్వాత. ప్రతి వెర్షన్ ముందుగా Claude sandbox లో తన టెస్ట్‌లను పాసైంది. ఆ టెస్ట్‌లు తప్పు చోట నడిచాయి: నిజమైన router కి బదులు ఒక mock router మీద, Windows PowerShell 5.1 కి బదులు PowerShell 7 కింద. తర్వాత router మీద ఫెయిల్ అయిన మూడు వెర్షన్లనూ mock పాస్ చేసింది. వైఫల్యం 1 లో PowerShell తేడా పాత్ర పోషించిందో లేదో నాకు తెలియదు. వైఫల్యం 2 లో అది ఏ పాత్రా పోషించలేదు, తర్వాత నా test harness ని ఫెయిల్ చేసింది. మూడు రన్‌లు ఫెయిల్ అయ్యాయి, ఒక్కొక్కటి వేరే కారణంతో. వాటిలో ఏదీ ఏ మార్పునూ on లో వదిలిపెట్టలేదు.

    ఈ పని Claude తో కలిసి చేశాను. script పాటించాల్సిన rules నేను నిర్ణయించాను, API key సృష్టించాను, తర్వాత దాన్ని delete చేశాను, ప్రతి వెర్షన్‌నీ నా సొంత PC లో, నా సొంత router మీద నడిపాను. script, దాన్ని టెస్ట్ చేసిన mock router, ప్రతి fix Claude రాసింది. వాటిని PowerShell 7 కింద టెస్ట్ చేసింది. దాని sandbox లో ఉన్న PowerShell అదొక్కటే.

    script, ఒక mock router, ఒక test harness ఈ పేజీ చివర MIT licence కింద ఉన్నాయి. router తన DNS blocklist ని తప్పించుకునే మూడు సాధారణ మార్గాలను నిరాకరించేలా script చేస్తుంది: DNS over HTTPS, DNS over TLS లేదా QUIC, వేరే server కి పంపే plain DNS. ఈ పేజీ రన్‌లను, నేను ఏం మారుస్తానో నమోదు చేస్తుంది; చివర దగ్గర ఉన్న ఒక panel మీ సొంత router మీద script ని ఎలా నడపాలో step by step చెబుతుంది.

    command line కి కొత్తవారా? boxes ని ఎలా చదవాలి

    PS> అంటే: దీన్ని Windows లోని PowerShell లో టైప్ చేయండి (Start menu → powershell అని టైప్ చేయండి → Enter). PS> ని మాత్రం టైప్ చేయవద్దు.

    PS> తో మొదలయ్యే ప్రతి లైన్ ఒక command. ఆ PS> మీద click చేస్తే ఆ లైన్ మాత్రమే copy అవుతుంది; దాన్ని paste చేసి, Enter నొక్కి, అది పూర్తయ్యే వరకు ఆగి, ఆ తర్వాతే తర్వాతి దాన్ని చేయండి. పైన Copy button ఉన్న box లో ఒక command (లేదా ఒక file) ఉంటుంది, కాబట్టి దాన్ని పూర్తిగా copy చేయండి. చుక్కల గీతల (dashed) box మీరు తిరిగి చూడాల్సినదాన్ని, లేదా చదవాల్సిన code ని చూపుతుంది; దాన్ని టైప్ చేయరు.

    ఈ script ఏం చేస్తుంది

    ఈ script ఒక OPNsense 26.7 router మీద ఒక DNS fix ని అమలు చేస్తుంది. నా router blocklist, router ని అడిగే devices ని మాత్రమే filter చేస్తుంది; phones, browsers, కొన్ని devices వేరే servers ని అడుగుతాయి. ఈ fix లో నాలుగు objects ఉంటాయి:

    • DoH_IPs అనే alias. ఇది Hagezi project నిర్వహించే DNS-over-HTTPS server అడ్రసుల public జాబితాను download చేస్తుంది (ఆ రోజు అందులో 1,434 అడ్రసులు);
    • Rule A. ఆ అడ్రసులకు port 443 మీద వెళ్లే LAN traffic ని reject చేస్తుంది;
    • Rule B. ఏ అడ్రసుకైనా port 853 మీద వెళ్లే LAN traffic ని reject చేస్తుంది. DNS over TLS, DNS over QUIC ఈ port వాడతాయి;
    • ఒక NAT redirect. router ని దాటి వెళ్లే ఏ port 53 query నైనా తిరిగి router కే పంపుతుంది.

    నా router లో alias, redirect rule ముందే ఉన్నాయి; redirect off లో ఉంది. script alias ని శుభ్రం చేస్తుంది, రెండు rules లేకపోతే సృష్టిస్తుంది, redirect ని on చేస్తుంది. redirect rule ని అది సృష్టించదు. rules IPv4 ని, LAN interface ని మాత్రమే cover చేస్తాయి; పరిమితులు చివర దగ్గర ఉన్న step-by-step panel లో ఉన్నాయి.

    ఈ నాలుగు objects ని click చేసి పెట్టడం నాకు సాధ్యమే. అయినా script రాశాను, ఎందుకంటే ఈ మార్పు ఒక రూపంలో ఉండాలనుకున్నాను: ఏదీ మార్చకుండా చెక్ చేయగలిగేలా, మళ్లీ నడపగలిగేలా, ఒక్క command తో off చేయగలిగేలా.

    అది పాటించే rules

    1. మూడు modes. Check చదివి report ఇస్తుంది. Apply మార్పు చేస్తుంది. Rollback రెండు rules నీ redirect నీ off చేస్తుంది, దేన్నీ delete చేయదు. -Mode లేని command Check నడుపుతుంది.
    2. వెర్షన్ guard. script ముందుగా router ఏం నడుపుతోందో అడుగుతుంది. జవాబు 26.7 series కాకపోతే ఆగిపోతుంది.
    3. వెర్షన్ guard తర్వాత backup. ఏ configuration ని చదవడానికి గానీ మార్చడానికి గానీ ముందే, ప్రతి రన్ router పూర్తి configuration ని ఒక కొత్త file లోకి download చేస్తుంది. ఉన్న file ని overwrite చేయడానికి నిరాకరిస్తుంది.
    4. ప్రతి మార్పునూ టెస్ట్ చేయండి. ముందు alias, తర్వాత రెండు rules, తర్వాత redirect. వెర్షన్ 2.3 లో ఒక టెస్ట్ ఫెయిల్ అయితే ఆ రన్ చేసిన మార్పులన్నీ undo అయ్యేవి. వెర్షన్ 2.4 నుంచి, redirect ఒక్కటే ఫెయిల్ అయితే redirect ఒక్కటే off అవుతుంది; పాసైన rules అలాగే ఉంటాయి.
    5. script లో secret ఉండదు. API key వేరే file లో ఉంటుంది.

    ముప్పై ఏడు నిమిషాలు

    మొదలైన సమయం వెర్షన్ Mode ఏం జరిగింది router మీద మిగిలింది
    14:29 తర్వాత 2.0 log కాలేదు మొదటి log లైన్ కంటే ముందే ఆగింది ఏమీ లేదు
    14:43 2.1 Check read-only report, పూర్తైంది ఏమీ లేదు
    14:51 2.2 Apply ఏ save కంటే ముందే తన సొంత guard వల్ల ఆగింది ఏమీ లేదు
    14:56 2.3 Apply rules పనిచేశాయి; redirect టెస్ట్ ఫెయిల్; undo అయింది రెండు rules, disabled
    15:04 2.4 Apply 15:06 కి పూర్తైంది, ప్రతి టెస్ట్ పాసైంది fix

    వెర్షన్ 2.0 log రాయలేదు, కాబట్టి దాని సమయం నేను file ని save చేసిన నిమిషం. మిగతా సమయాలు script సొంత logs నుంచి.

    పనుల క్రమం నష్టాన్ని పరిమితం చేసింది. script వెర్షన్ చెక్ చేస్తుంది, backup తీసుకుంటుంది, రాసే ముందు చదువుతుంది. వైఫల్యం 1 router కి ఏ call కంటే ముందే ఆగింది. వైఫల్యం 2 ఏ save కంటే ముందే ఆగింది, వేరే సమస్య కోసం రాసిన guard వల్ల. వైఫల్యం 3 మార్పులు జరిగిన తర్వాత వచ్చింది; ఆ వెర్షన్ undo వాటిని off చేసింది.

    వైఫల్యం 1: నేను తప్పుగా గుర్తించిన కారణం

    వెర్షన్ 2.0 తన working folder ని ఒక parameter default నుంచి తీసుకుంది:

    [string]$WorkDir = $PSScriptRoot

    $PSScriptRoot అంటే script ఉన్న folder. script దాన్ని తన logs folder path కట్టడానికి వాడుతుంది. ఆ folder ని key చదవడానికి, router ని call చేయడానికి ముందే సృష్టిస్తుంది.

    వెర్షన్ 2.1 మూడు విషయాలు మార్చింది. folder ని script body లో లెక్కించింది. ఆ folder లేకపోతే ఆగింది. ఖాళీ DNS జవాబు సున్నాగా లెక్కకు వచ్చేలా రెండు counts ని wrap చేసింది. వీటిలో folder మార్పులు మాత్రమే మొదటి log లైన్ కంటే ముందు వస్తాయి. ఆ రోజు Windows PowerShell 5.1 $PSScriptRoot ని ఖాళీగా వదిలిందనే నిర్ధారణకు Claude, నేను వచ్చాం. ఈ post మొదటి drafts కూడా అదే చెప్పాయి.

    ఈ post కోసం తయారు చేసిన test kit దాన్ని చెక్ చేసింది, ఆ నిర్ధారణ తప్పు. నా PC లో, నేను script ని మొదలుపెట్టే విధంగానే -File తో మొదలుపెట్టిన Windows PowerShell 5.1, parameter default లో $PSScriptRoot లోకి folder ని పెట్టింది. PowerShell 7.4.6 కూడా అలాగే చేసింది. script ని మొదలుపెట్టే పద్ధతుల్లో కొన్నింటినే టెస్ట్ చేశాను, కాబట్టి కొన్ని పద్ధతుల్లో అది ఖాళీగా ఉండే అవకాశాన్ని కొట్టిపారేయలేను. ఆ మధ్యాహ్నం వెర్షన్ 2.0 ని ఎలా మొదలుపెట్టానో, అది చూపిన error ఏమిటో నేను record చేయలేదు, కాబట్టి దాన్ని ఏది ఆపిందో నాకు తెలియదు. ఆధారాలు సమర్థించేది ఇంతకంటే పరిమితమైనది: వెర్షన్ 2.0 తన మొదటి log లైన్ కంటే ముందే ఆగింది, కాబట్టి, ఆధారాలు చూపినంతవరకు, router కి ఏ call కంటే ముందే. ప్రచురించిన script లోని ఒక comment, Windows PowerShell 5.1 కింద ఆ folder ఖాళీగా ఉండవచ్చని చెబుతుంది. ఆ comment నా మొదటి నిర్ధారణనే పునరావృతం చేస్తుంది; టెస్ట్ చేసిన file ని నేను అలాగే వదిలేశాను.

    వెర్షన్ 2.1 లోని మార్పు అలాగే ఉంటుంది. దానికి ఖర్చు ఏమీ లేదు. script ని ఏ విధంగా మొదలుపెట్టినా అది పనిచేస్తుంది:

    if ([string]::IsNullOrWhiteSpace($WorkDir)) {
        if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
        else { $WorkDir = (Get-Location).Path }
    }

    వెర్షన్ 2.1 యొక్క Check రన్ 14:43 కి పూర్తైంది.

    వైఫల్యం 2: router విచిత్రాలు లేని mock

    alias type చెక్ చేయడానికి వెర్షన్ 2.2 router alias/get_item endpoint ని call చేసింది. 14:51 నాటి run log:

    14:51:46  Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
    14:51:46  Nothing to undo.
    ...
    14:51:47  STOP: Apply did not complete; changes from this run were undone.

    alias type ఖాళీ కాదు. router జవాబులో పేరు ఖాళీ string గా ఉన్న entries ఉన్నాయి ("":). JSON దీన్ని అనుమతిస్తుంది. ఖాళీ పేరుతో object property ని PowerShell తయారు చేయలేదు. ConvertFrom-Json గురించి Microsoft documentation ఇదే చెబుతుంది (PowerShell 7.4 reference), అలాంటి జవాబుల కోసం -AsHashtable switch ని సూచిస్తుంది. Windows PowerShell 5.1 లో ఆ switch లేదు. Invoke-RestMethod ఏ error నూ ఇవ్వలేదు. జవాబును plain text గా తిరిగి ఇచ్చింది, script ఆ text నుంచి type ని ఏమీ లేనిదిగా చదివింది.

    ఇది PowerShell వెర్షన్ల మధ్య తేడా కాదు. test kit script కి ఖాళీ key ఉన్న జవాబును ఇస్తుంది. PowerShell 7.4.6 కింద, నా PC లో Windows PowerShell 5.1 కింద కూడా, Invoke-RestMethod దాన్ని text గా, error లేకుండా తిరిగి ఇచ్చింది. వెర్షన్ 2.2 mock మీద పాసైంది, ఎందుకంటే mock జవాబులో ఖాళీ keys లేవు. router జవాబులో ఉన్నాయి.

    రన్‌ని ఆపిన guard వేరే సమస్య కోసం రాసినది: తప్పు type తో ముందే ఉన్న alias. ఖాళీ type urltable కాదు కాబట్టి అది ఈ రన్‌ని ఆపింది. అది లేకపోతే రన్ కొత్త URL ని save చేసి ఉండేది, తర్వాత undo లో alias లోకి ఖాళీ string రాసి ఉండేది.

    14:43 Check రన్ దీన్ని పట్టుకోలేదు. Check alias ని alias/search_item ద్వారా చదివింది. Apply మాత్రమే get_item ని call చేసింది.

    వెర్షన్ 2.3 రెండు మార్పులు చేస్తుంది. router search_item, search_rule endpoints ఇప్పటికే type నీ contents నీ ఇస్తాయి, వాటి జవాబులు parse అయ్యాయి. కాబట్టి script వాటి ద్వారా మాత్రమే చదువుతుంది. ఇంకా, ప్రతి API call ఇప్పుడు ఒకే helper ద్వారా వెళ్తుంది. parse చేయలేని జవాబును ఆ helper తిరస్కరిస్తుంది:

    $r = Invoke-RestMethod @p
    if ($r -is [string]) {
        $t = $r.TrimStart()
        if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
    }

    వైఫల్యం 3: మరీ త్వరగా టెస్ట్ చేసిన redirect

    వెర్షన్ 2.3 ఇంకా ముందుకు వెళ్లింది. alias ని శుభ్రం చేసింది, రెండు rules జోడించి టెస్ట్ చేసింది. తర్వాత NAT redirect ని on చేసి, ఐదు సెకన్ల తర్వాత దాన్ని టెస్ట్ చేసింది:

    14:57:16  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    14:57:17  NAT rule enabled and applied. Verifying...
    14:57:22  Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
    14:57:22  Undoing changes made in this run...

    టెస్ట్ 8.8.8.8 కి రెండు queries పంపుతుంది: ఒకటి example.com కోసం, ఒకటి ఒక ad domain కోసం. firewall log లో రెండింటిలో ఒకటి redirect అయినట్లు కనిపించింది. ad domain నిజమైన అడ్రసులతో తిరిగి వచ్చింది, కాబట్టి redirect కానిది అదే. redirect ని on చేయడానికి పదమూడు సెకన్ల ముందు, bypass తెరిచి ఉందని చూపడానికి script ప్రారంభ చెక్ అదే పేరును 8.8.8.8 కి పంపింది.

    నా దగ్గర రెండు వివరణలు ఉన్నాయి, రెండింటినీ నేను టెస్ట్ చేయలేదు. firewall తాను చూసిన ప్రతి connection కీ ఒక state entry ఉంచుకుంటుంది, redirect ని కొత్త connections కి మాత్రమే వర్తింపజేస్తుంది. ad domain కోసం రెండో query మొదటిదాని source port నుంచే నా PC ని వదిలి ఉంటే, అది పాత entry తో match అయి Google కి వెళ్లి ఉంటుంది. లేదా నా PC లో ఏదో ఒకటి మళ్లీ అడిగిన ప్రశ్నకు cache నుంచి జవాబిచ్చి ఉంటుంది; అప్పుడు query PC ని వదిలి వెళ్లనే లేదు.

    ఈ router లోని UDP state timeouts, Firewall → Diagnostics → Statistics నుంచి చదివినవి: udp.first, udp.multiple కి 60 సెకన్లు, udp.single కి 30 సెకన్లు. వెర్షన్ 2.4 టెస్ట్ చేసే ముందు 70 సెకన్లు ఆగుతుంది, టెస్ట్ పాసైంది:

    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.

    ఈ ఆగే సమయం firewall state entries కంటే ఎక్కువ సేపు ఉంటుంది. PC లో గుర్తుంచుకున్న జవాబు కంటే కూడా ఎక్కువ సేపు ఉంటుందా అన్నది ఆ జవాబును ఎంత సేపు ఉంచుకుంటారనే దానిపై ఆధారపడుతుంది; అది నేను కొలవలేదు. కాబట్టి ఈ ఫలితం రెండు వివరణల మధ్య తేడాను చెప్పదు. ఇంతకు ముందు query చేయని పేరుతో, firewall state table తెరిచి పెట్టి చేసే టెస్ట్ తేడాను చెప్పగలదు.

    వెర్షన్ 2.3 లోని undo redirect ని off చేసింది, రెండు కొత్త rules ని disable చేసింది, alias contents ని పునరుద్ధరించింది. rules ని delete చేయలేదు, alias refresh interval ని ఒక రోజుగానే వదిలేసింది. undo తర్వాత తీసిన backup రన్ ముందు తీసినదాని కంటే 4,788 bytes పెద్దది. వెర్షన్ 2.4 మొదట ఆ రెండు rules ని కనుగొంది:

    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200

    కాబట్టి “undone” అంటే “on లో ఏదీ మిగల్లేదు” అని, “router ముందున్నట్లే ఉంది” అని కాదు. వెర్షన్ 2.4 కొత్త copies జోడించకుండా, ఉన్న రెండు rules నే on చేసింది, ఎందుకంటే అది rules ని సృష్టించే ముందు description తో వెతుకుతుంది.

    mock పట్టుకోనివి, రెండో రౌండ్ టెస్ట్‌లు

    నేను router మీద నడపక ముందే Claude ప్రతి వెర్షన్‌నీ తన mock మీద నడిపింది. ఆ session record ప్రకారం, undo ని చెక్ చేయడానికి ప్రతి వెర్షన్ ఒకసారి మామూలుగా, ఒకసారి బలవంతంగా కలిగించిన failure తో నడిచింది. వెర్షన్లు 2.0 నుంచి 2.3 వరకు mock మీద పాసయ్యాయి. router మీద, ఆ నాలుగింటిలో మూడు ఫెయిల్ అయ్యాయి. mock ఎప్పుడూ Windows PowerShell 5.1 కింద నడవలేదు, దాని జవాబుల్లో router జవాబుల్లోని ఖాళీ keys లేవు.

    ఈ పేజీ చివర ఉన్న script వెర్షన్ 2.5.1, 2.4 కాదు. publish చేసే ముందు Claude తో script ని మళ్లీ review చేయించాను. ఆ review కనుగొన్నవాటిని వెర్షన్ 2.5 సరిచేస్తుంది: router స్థితిని తప్పుగా వర్ణించగల messages, log లో రాయని stops, alias enabled flag ని పునరుద్ధరించని undo, redirect rule గానీ LAN allow-all rule గానీ లేని router మీద మొదలవగల runs. https:// తో మొదలుకాని router అడ్రసును కూడా అది తిరస్కరిస్తుంది, PC మీదే ఉన్న అడ్రసు తప్ప; test kit దాన్ని వాడుతుంది. నా router మీద నడిచింది వెర్షన్ 2.4. వెర్షన్ 2.5.1, వెర్షన్ 2.5 కి header comments లో మాత్రమే భిన్నంగా ఉంటుంది; అది mock మీద మాత్రమే నడిచింది.

    రెండో రౌండ్ టెస్ట్‌లు ఒక కొత్త mock ని వాడాయి. router తప్పుగా ప్రవర్తించగల విధంగానే అది తప్పుగా ప్రవర్తించేలా తయారైంది, ఖాళీ key ఉన్న జవాబుతో సహా. ఒక harness 30 cases లో ప్రతిదానికీ ఒకసారి script copy ని దానిపై నడిపింది. PowerShell 7.4.6 కింద 30 అన్నీ పాసయ్యాయి.

    నా PC లో Windows PowerShell 5.1 కింద మొదటి రన్‌లో రెండు cases ఫెయిల్ అయ్యాయి. script logs ప్రకారం script సరైన పనే చేసింది; harness చేయలేదు. ఒక PowerShell function ఒకే item ఉన్న list ని return చేస్తే, caller కి ఆ item నేరుగా వస్తుంది. PowerShell 7 ఆ item ని list లాగే count చేయడానికి, index చేయడానికి అనుమతిస్తుంది. ఈ రకమైన object కి Windows PowerShell 5.1 అనుమతించదు. harness PowerShell 7 కింద మాత్రమే నడిచింది. అది సరిచేశాక, publish చేసిన script వెర్షన్‌పై Windows PowerShell 5.1 కింద కూడా 30 cases అన్నీ పాసయ్యాయి.

    harness నే చెక్ చేయడానికి, Claude script ని పది రకాలుగా పాడుచేసింది, ఉదాహరణకు undo ని, JSON చెక్‌ని లేదా HTTPS చెక్‌ని తీసేయడం. ప్రతి పాడుచేత కనీసం ఒక case ని ఫెయిల్ చేసింది. ఆ చెక్ PowerShell 7.4.6 కింద, వెర్షన్ 2.5 మీద, harness యొక్క ఒక పాత వెర్షన్‌తో నడిచింది.

    తర్వాతి script కి నేను తీసుకెళ్లేవి

    1. script ని నడపబోయే PowerShell మీదే టెస్ట్ చేయండి, టెస్ట్‌లను కూడా అక్కడే నడపండి. నా harness PowerShell 7 కింద పాసైంది, 5.1 కింద మొదటి రన్‌లో ఫెయిల్ అయింది.
    2. mock జవాబులను నిజమైన జవాబుల నుంచి కట్టండి. router get_item నుంచి save చేసిన ఒక జవాబు ఉండి ఉంటే, router script ని చూడక ముందే వైఫల్యం 2 పట్టుబడేది.
    3. write mode చేసే ప్రతి read నీ read-only mode కూడా చేసేలా చూడండి. ఇక్కడ Check, Apply alias ని వేర్వేరు endpoints ద్వారా చదివాయి.
    4. object ఆశించినప్పుడు Invoke-RestMethod నుంచి string వస్తే దాన్ని failure గా చూడండి. అది ప్రతిసారీ error ఇవ్వదు.
    5. redirect ని on చేశాక, firewall state timeout కంటే ఎక్కువ సేపు ఆగండి. ఇంతకు ముందు query చేయని పేరుతో టెస్ట్ చేయండి.
    6. undo delete చేయకుండా disable చేస్తే, గత రన్ వదిలినవాటి కోసం తర్వాతి రన్ వెతికేలా చేయండి.
    7. టెస్ట్‌లు ఫెయిల్ కాగలవని చెక్ చేయడానికి script ని కావాలని పాడుచేయండి.
    8. API key ని script బయట ఉంచండి, పని అయ్యాక దాన్ని delete చేయండి. నేను root user key వాడాను. script కి కావాల్సిన privileges మాత్రమే ఉన్న user మంచిది; అది నేను ప్రయత్నించలేదు.
    మీ router మీద దశల వారీగా నడపండి

    మొదలుపెట్టే ముందు. మీకు ఇవి కావాలి:

    • router ఉన్న network లోనే ఉన్న ఒక Windows PC. మీరు రెండు చోట్ల type చేస్తారు: PC లో PowerShell, browser లో router web page;
    • OPNsense 26.7. ఇతర series లో script ఆగిపోతుంది, ఎందుకంటే దాని API paths ఆ series సొంత pages నుంచి తీసుకున్నవి;
    • DNS blocklist on లో, Services → Unbound DNS → Blocklist కింద (OPNsense documentation ఆ page పేరు చెబుతుంది), మీ devices DNS కోసం router నే అడుగుతూ ఉండాలి;
    • port 53 మీద router కాకుండా ఇంకెక్కడికైనా వెళ్లే DNS queries ని తిరిగి router కే పంపే Destination NAT rule, ముందే సృష్టించినది, “Redirect non-local DNS to Local” అనే description తో. script దాన్ని on చేస్తుంది. సృష్టించదు. ఈ rule ని script సృష్టించదు, ఒకటి సృష్టించడం ఈ panel లో లేదు, అది లేకపోతే Apply ఆగిపోతుంది. OPNsense forum లోని ఒక community how-to ఒక పద్ధతి చూపిస్తుంది;
    • “Default allow LAN to any rule” అనే LAN rule, OPNsense దాన్ని default గా సృష్టిస్తుంది. దాని పైన తన రెండు కొత్త rules ఉన్నాయో లేదో script చెక్ చేస్తుంది.

    వెర్షన్ 2.5.1, ఈ panel లోని script, test kit లోని mock router మీద మాత్రమే నడిచింది. నా router మీద నడిచింది వెర్షన్ 2.4.

    సుమారు 20 నిమిషాలు కేటాయించండి; మార్పుకే సుమారు రెండు నిమిషాలు పడుతుంది. router కి చేసే మొదటి మార్పు 3వ దశలోని API key. 5వ దశలోని Check రన్ దానిపై ఏదీ మార్చదు. 6వ దశలోని Apply మారుస్తుంది. 8వ దశ fix ని off చేయడాన్ని, మొత్తం configuration ను ఎలా restore చేయాలో చూపిస్తుంది. ప్రతి రన్, configuration ను చదివే ముందు router configuration backup ను PC లో save చేస్తుంది.

    ఇప్పుడు పరిమితులు చదవండి. వాటిలో ఒకటి మీ network ని వర్ణిస్తే, script మీకు సరిపోదు, కాబట్టి ముందుకు వెళ్లకండి.

    పరిమితులు

    • IPv4 మాత్రమే. Rules A, B ను script IPv4 కోసమే సృష్టిస్తుంది, ప్రతి టెస్ట్ IPv4 అడ్రసు వాడుతుంది. మీ LAN లో IPv6 ఉంటే, IPv6 మీద DoH, DoT block కావు, టెస్ట్ కూడా కావు. (Interfaces → LAN లో IPv6 Configuration Type కనిపిస్తుంది; None అంటే IPv6 లేదు.)
    • LAN interface మాత్రమే. ఇతర interfaces, VLANs cover కావు.
    • LAN లో ప్రతి host. upstream కోసం DoH లేదా DoT వాడే LAN లోని Pi-hole లేదా AdGuard Home తన upstream ని కోల్పోతుంది. అది plain DNS ని ఒక public server కి పంపితే, మీ redirect rule ఎలా కట్టబడిందో దాన్ని బట్టి, ఆ rule దాన్ని కూడా పట్టుకోవచ్చు.
    • encrypted DNS నే కోరే devices. encrypted DNS provider ని మాత్రమే వాడేలా set చేసిన device, ఉదాహరణకు Private DNS ని ఒక hostname కి set చేసిన phone, rules దాని దారిని తిరస్కరించాక ఈ network లో పేర్లను వెతకలేకపోవచ్చు. ఆ setting ని device మీద మార్చండి.
    • redirect rule ముందే ఉండాలి Firewall → NAT → Destination NAT లో, “Redirect non-local DNS to Local” description తో, లేదా మీరు $NatDesc లో పెట్టిన దానితో. script దాన్ని సృష్టించదు, అది ఎలా కట్టబడిందో చెక్ చేయదు.
    • alias overwrite అవుతుంది Hagezi URL తో. పాత contents ను script log లో రాస్తుంది.
    • టెస్ట్ domain $AdTestDomain లోది. మీ router blocklist దాన్ని block చేసి, 0.0.0.0 గా లేదా అడ్రసు లేకుండా జవాబివ్వాలి; లేకపోతే redirect టెస్ట్ ఫెయిల్ అవుతుంది.
    • మీరు నమ్మే LAN. script certificate చెక్ router అడ్రసు కోసం చూపిన ఏ certificate నైనా అంగీకరిస్తుంది, కాబట్టి LAN లో router లా నటించే device కి key అందుతుంది. మీరు నియంత్రించే network లోనే నడపండి.
    • ఆగే సమయం $NatWaitSeconds లోది. ఇది మీ router UDP state timeouts కంటే ఎక్కువ ఉండాలి.
    • Rollback రెండు rules నీ redirect rule నీ off చేస్తుంది, మీరు మొదటిసారి Apply నడపక ముందే redirect on లో ఉన్నా. alias ని పునరుద్ధరించదు.
    1. PowerShell తెరిచి ఒక folder సృష్టించండి. Start menu తెరిచి, powershell అని type చేసి Enter నొక్కండి. Windows PowerShell అనే title తో ఒక window తెరుచుకుంటుంది, దాని prompt PS తో మొదలవుతుంది. prompt లో PS లేకపోతే మీరు Command Prompt లో ఉన్నారు: దాన్ని మూసి బదులుగా PowerShell తెరవండి, ఎందుకంటే కింది commands PowerShell లో మాత్రమే పనిచేస్తాయి. window లోపల click చేయండి. కింది రెండు లైన్లను ఒక్కొక్కటిగా వాడండి: లైన్‌ను copy చేయడానికి PS> మీద click చేయండి, paste చేయండి (Ctrl + V, లేదా right-click), Enter నొక్కండి.

      New-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns"
      Set-Location "$env:USERPROFILE\opnsense-dns"

      మొదటి లైన్ మీ user folder లోపల opnsense-dns అనే folder ను సృష్టించి, చిన్న listing ను print చేస్తుంది; రెండోది PowerShell ని అందులోకి తీసుకెళ్తుంది, తర్వాత prompt opnsense-dns> తో ముగుస్తుంది. ఒక్కొక్కటి ఒక సెకను కంటే తక్కువ పడుతుంది. మొదటి లైన్ folder ఉందని చెబితే, ముందుకు వెళ్లండి. ఈ window ని తెరిచి ఉంచండి, ఈ folder ని OneDrive, Dropbox, shared locations బయట ఉంచండి: ఇక్కడ save అయ్యే backups లో router మొత్తం configuration ఉంటుంది.

    2. script ని save చేయండి. ఈ page చివర ఉన్న The script, the mock router and the test harness దగ్గరికి scroll చేసి, opnsense-dns-bypass.ps1 (version 2.5.1) ను తెరిచి, చదివి, Copy మీద click చేయండి. అది 491 లైన్లు. ఇది మీ router key ని వాడుతుంది, కాబట్టి నడపక ముందు చదవండి. browser download చేసిన files ని Windows internet నుంచి వచ్చినవిగా గుర్తు పెడుతుంది; కింది command రాసిన file కి ఆ గుర్తు ఉండదు, కాబట్టి Unblock-File అవసరం లేదు. ఈ command ఈ folder లో అదే పేరున్న file ను భర్తీ చేస్తుంది. PowerShell window లో:

      Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1

      Get-Clipboard మీరు copy చేసినదాన్ని చదువుతుంది, Set-Content దాన్ని ఒక file లో రాస్తుంది; script plain ASCII, కాబట్టి ఆ encoding సురక్షితం. ఇది ఒక సెకను కంటే తక్కువ పడుతుంది, ఏదీ print చేయదు. అంతా వచ్చిందో చెక్ చేయండి:

      (Get-Content .\opnsense-dns-bypass.ps1).Count
      491

      వేరే సంఖ్య వస్తే, copy మధ్యలోనే ఆగిపోయిందని లేదా మారిందని అనిపిస్తుంది. page కి తిరిగి వెళ్లి, Copy మీద మళ్లీ click చేసి, మొదటి command ను మళ్లీ నడపండి.

    3. router మీద API key సృష్టించండి. web browser లో https:// అని, మీరు router settings page కోసం వాడే అడ్రసును (ఉదాహరణకు https://192.168.1.1) type చేసి Enter నొక్కండి. router తన certificate ని తానే sign చేస్తుంది కాబట్టి, connection private కాదని browser హెచ్చరించవచ్చు. ఆ అడ్రసుకు కొనసాగించే ఎంపికను ఎంచుకోండి (Chrome లో: Advanced, తర్వాత Proceed). మీ సొంత router login తో log in అవండి. తర్వాత:

      1. ఎడమవైపు menu లో System మీద, తర్వాత Access మీద, తర్వాత Users మీద click చేయండి.
      2. మీరు log in అయ్యే administrator వరుస చివర ఉన్న పెన్సిల్ (edit) icon మీద click చేయండి.
      3. user settings లో API keys section ను కనుక్కోండి (OPNsense documentation దాన్ని ApiKeys tab అంటుంది), దాని grid లో key ను సృష్టించే button ను వాడండి.
      4. కొన్ని సెకన్లలో browser ఒక చిన్న text file ను download చేస్తుంది. అందులో key= లైన్, secret= లైన్ ఉంటాయి. secret ఒక్కసారి మాత్రమే generate అవుతుందని documentation చెబుతుంది; file పోతే కొత్త key సృష్టించండి.

      key తన user లాగే పనిచేస్తుంది. నేను root user key వాడి, తర్వాత దాన్ని delete చేశాను; root key router మీద పూర్తి నియంత్రణ ఇస్తుంది. firewall, NAT, backup pages కి మాత్రమే పరిమితమైన user కి తక్కువ అధికారం ఉంటుంది, కానీ script router మొత్తం configuration ను download చేస్తుంది, కాబట్టి ఆ user కూడా అందులోని password hashes, private keys ను చదవగలడు. పరిమిత user ను నేను ప్రయత్నించలేదు. మీ menu వేరేగా కనిపిస్తే, local users మీద OPNsense documentation అదే దశను వివరిస్తుంది. key file ను ఎక్కడా paste చేయకండి: అందులోని secret router మీద నియంత్రణ ఇస్తుంది.

    4. key file ను folder లో పెట్టండి. PowerShell కి తిరిగి వచ్చి, మీ Downloads folder లోని కొత్త text files జాబితా చూడండి:

      Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTime
      Name                  LastWriteTime
      ----                  -------------
      example_apikey.txt    <date and time>

      జాబితా ఖాళీగా ఉంటే, browser ఆ file ను వేరే చోట save చేసింది: ఎక్కడ save అయిందో చూడటానికి browser లో Ctrl + J నొక్కండి. ఇప్పుడు ఆ file ను script ఆశించే పేరుతో folder లోకి తరలించండి. <file-name> ను, angle brackets తో సహా, జాబితాలోని పేరుతో మార్చండి:

      Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txt

      ఇది ఒక సెకను కంటే తక్కువ పడుతుంది, ఏదీ print చేయదు. folder లో ముందే ఉన్న apikey.txt ను ఇది overwrite చేయదు; ఆ కారణంతో నిరాకరిస్తే, ఇంతకు ముందటి key file అక్కడ ఉంది. ఆ key ను router మీద తీసేసి (ఆ key ఎక్కడ ఉందో 8వ దశ చూపిస్తుంది), Remove-Item .\apikey.txt నడిపి, ఈ దశను మళ్లీ చేయండి. path గురించి error వస్తే, path లో ఇంకా <file-name> ఉండి ఉండవచ్చు, లేదా పేరు జాబితాలోని పేరుతో సరిపోకపోవచ్చు. ఇప్పుడు key file లో రెండు లైన్లు ఉన్నాయో చెక్ చేయండి. ఇది ప్రతి = కి ముందున్న పదాన్ని మాత్రమే print చేస్తుంది, విలువలను ఎప్పుడూ కాదు:

      Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }
      key
      secret

      వేరే పదాలు కనిపిస్తే, ఇది బహుశా key file కాదు. కొత్త key ను download చేయండి (3వ దశ).

    5. Check నడపండి. ఇది చదువుతుంది మాత్రమే. ముందు PowerShell కి మీ router అడ్రసు చెప్పండి. లైన్‌ను copy చేయడానికి PS> మీద click చేసి, paste చేయండి, ఇంకా Enter నొక్కకండి. <router-ip-address> ను, angle brackets తో సహా, 3వ దశలోని అడ్రసు సంఖ్యలతో మార్చండి (ఉదాహరణకు 192.168.1.1), https:// ను అలాగే ఉంచండి. cursor ను arrow keys తో కదిలించండి, ఎందుకంటే PowerShell లో mouse click cursor ను కదిలించదు; Backspace తీసేస్తుంది. తర్వాత Enter నొక్కండి. angle brackets ఇంకా ఉంటే script ఆగిపోతుంది.

      $RouterUrl = 'https://<router-ip-address>'

      ఇది అడ్రసును ఈ window కి మాత్రమే గుర్తుంచుకుంటుంది. window ను మూసేస్తే, దీన్ని మళ్లీ చేయండి.

      ఇప్పుడు script ను నడపండి. powershell -ExecutionPolicy Bypass -File ఆ file ను నడిపే కొత్త Windows PowerShell 5.1 ను మొదలుపెడుతుంది. command line మీది -ExecutionPolicy Bypass ఆ ఒక్క రన్ కి మాత్రమే ఉంటుంది, execution policies మీద Microsoft documentation అది store కాదని చెబుతుంది. మీ సంస్థ set చేసిన Group Policy ని అది override చేయదు. -Mode లేకుండా script Check నడుపుతుంది.

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      ఇది 10 నుంచి 60 సెకన్లు పడుతుంది, router మీద ఏదీ మార్చదు. router configuration backup ను router-backups folder లో (అది opnsense-dns లోపల ఉంటుంది), log ను logs లో save చేసి, ఐదు live టెస్ట్‌లు నడుపుతుంది. ముఖ్యమైన లైన్లు:

      HH:MM:SS  Router reports: OPNsense series 26.7, amd64
      HH:MM:SS  Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes)
      ...
      HH:MM:SS  Router resolves example.com            : True   (want True)
      HH:MM:SS  Router blocks the ad domain (blocklist) : True   (want True)
      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
      HH:MM:SS  Check mode: nothing was changed on the router.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.log

      రెండు “want True” లైన్లూ True అయి ఉండాలి. “Router blocks the ad domain” False అయితే, మీ blocklist టెస్ట్ domain ను block చేయడం లేదు, 6వ దశలోని redirect టెస్ట్ ఫెయిల్ అవుతుంది. script పైభాగంలోని $AdTestDomain ను మీ blocklist block చేసే domain కి set చేయండి, లేదా blocklist ను on చేయండి. పసుపు లైన్ Apply would stop: తో మొదలైతే, అది లేని rule ను చెబుతుంది: redirect rule లేదా LAN allow-all rule. 6వ దశకు ముందు router మీద దాన్ని సరిచేయండి.

      ఏదైనా తప్పు జరిగితే. script ఎరుపు లైన్ print చేస్తుంది (చాలావాటిలో STOP అనే పదం ఉంటుంది), router మీద ఏదీ మార్చదు. లైన్ ఏం చెబుతుంది, దాని అర్థం ఏమిటి:

      • Set -Router to your router’s address: ఈ దశలోని అడ్రసులో angle brackets ఇంకా ఉన్నాయి.
      • Missing an argument for parameter ‘Router’: బహుశా పై అడ్రసు లైన్‌ను ఈ window లో నడపలేదు. దాన్ని మళ్లీ నడపండి.
      • -Router must start with https://: అడ్రసు http:// తో మొదలవుతోంది. https:// వాడండి.
      • STOP: Key file not found: apikey.txt opnsense-dns folder లో లేదు. 4వ దశను మళ్లీ చేయండి.
      • STOP: Cannot reach the router API with this key: అడ్రసు తప్పు, key ను తీసేశారు, లేదా PC router network లో లేదు. చెక్ చేయడానికి browser లో అడ్రసును తెరవండి.
      • STOP: Script was built for OPNsense 26.7: మీ router వేరే series నడుపుతోంది, script API paths 26.7 నుంచి తీసుకున్నవి. ఇక్కడే ఆగండి.
      • scripts నడపడం disabled అని PowerShell చెబుతుంది: మీ PC లోని policy scripts ను block చేస్తోంది, command-line option దాన్ని override చేయలేదు. ఇక్కడే ఆగండి.
    6. Apply నడపండి. ఇది router ను మారుస్తుంది. ఇది DoH_IPs alias ను Hagezi list అడ్రసుతో overwrite చేస్తుంది (పాత contents log కి వెళ్తాయి), రెండు reject rules లేకపోతే జోడిస్తుంది, redirect rule ను on చేస్తుంది. DNS-over-HTTPS లేదా DNS-over-TLS server తో నేరుగా మాట్లాడే మీ network లోని devices ఆ దారిని కోల్పోతాయి; అదే ఉద్దేశం. అదే command ను -Mode Apply జోడించి నడపండి:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Apply

      ఇది సుమారు రెండు నిమిషాలు పడుతుంది, alias ముందుగా తన list ను download చేయాల్సి వస్తే నాలుగు నిమిషాల వరకు. ఒక లైన్ Waiting 70 s for older DNS states to expire before testing... అని ఉంటుంది; దాని కోసం ఆగండి, window ను మూసేయకండి. చివరి లైన్లు ఇలా ఉండాలి:

      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
      HH:MM:SS  Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes)
      HH:MM:SS  Apply finished. Expected: router tests True, all three bypass tests False.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.log

      ఏదైనా తప్పు జరిగితే. Apply did not complete; changes from this run were undone: ఒక టెస్ట్ ఫెయిల్ అయింది, script తాను మార్చినదాన్ని off చేసింది. అది జోడించిన rules off స్థితిలో అలాగే ఉంటాయి. ఫలితం యొక్క backup ను save చేసింది. కారణం కోసం Problem: తో మొదలయ్యే లైన్ చదవండి. ఏ లైన్ అయినా UNDO STEP FAILED అంటే, 8వ దశ వివరించినట్లు “before” backup ను restore చేయండి. Apply PARTLY finished (పసుపు రంగులో): alias, రెండు rules అమల్లో ఉన్నాయి, టెస్ట్ అయ్యాయి, redirect పాసవ్వలేదు; redirect ను on లో వదిలిందో off లో వదిలిందో లైన్ చెబుతుంది. fix ను off చేయడానికి 8వ దశ వాడండి.

    7. అది పనిచేసిందో చెక్ చేయండి. 5వ దశలోని Check command ను మళ్లీ నడపండి:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      ఇప్పుడు మూడు Bypass లైన్లు False, రెండు Router లైన్లు True అని చూపిస్తాయి. router web page లో Firewall → Rules (interface selector లో LAN ఎంచుకోండి) చూడవచ్చు; అక్కడ Reject DoH to known resolvers (A), Reject DoT/DoQ 853 from LAN (B) అనే రెండు rules ఇప్పుడు కనిపిస్తాయి. Firewall → NAT → Destination NAT లో Redirect non-local DNS to Local enabled గా ఉంటుంది.

    8. దాన్ని off చేయండి, అవసరమైతే restore చేయండి, key ను తీసేయండి. fix ను off చేయడానికి command ను -Mode Rollback తో నడపండి:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Rollback

      ఇది ఒక నిమిషం కంటే తక్కువ పడుతుంది. రెండు rules నీ redirect నీ disable చేస్తుంది, దేన్నీ delete చేయదు. alias Apply వదిలినట్లే ఉంటుంది. మీరు మొదలుపెట్టే ముందే redirect on లో ఉంటే, ఇప్పుడు అది off: Firewall → NAT → Destination NAT లో దాన్ని మళ్లీ on చేయండి.

      మొత్తం configuration ను Apply కి ముందున్నట్లు తిరిగి పెట్టడానికి, router మీద backup ను restore చేయండి: System → Configuration → Backups కి వెళ్లి, config-Apply-before-<timestamp>.xml అనే file ను router-backups folder నుంచి ఎంచుకుని restore చేయండి. ప్రతి Apply రన్ ఇలాంటి ఒక file ను save చేస్తుంది; అన్నిటికంటే పాతది మీ మొదటి Apply కి ముందున్న configuration ను కలిగి ఉంటుంది. అది అప్పటి నుంచి router మీద చేసిన ఇతర మార్పులనూ undo చేస్తుంది.

      script తో పని అయ్యాక, fix ను ఉంచుకున్నా లేకపోయినా, key ను తీసేయండి. router మీద System → Access → Users కి వెళ్లి, అదే user మీద పెన్సిల్ click చేసి, API keys section లో key ను తీసేయండి (ApiKeys tab). తర్వాత key file ను PC నుంచి delete చేయండి:

      Remove-Item .\apikey.txt

      ఇది file ను వెంటనే delete చేస్తుంది, recycle bin ఉండదు. backups అవసరం లేనప్పుడు router-backups folder ను కూడా delete చేయండి: అందులో password hashes, private keys ఉన్నాయి.

    భద్రతా గమనికలు. script ప్రతి request తో key ను పంపుతుంది. secret ను print చేయదు, log చేయదు, test kit తన 30 cases లో ప్రతిదానిలో అది చెక్ చేస్తుంది. దాని certificate చెక్ router అడ్రసు కోసం చూపిన ఏ certificate నైనా అంగీకరిస్తుంది, కాబట్టి LAN లో router లా నటించే device కి key అందుతుంది. నా key ను 13 అక్టోబర్ 2026 న, రన్ తర్వాత రెండు రోజులకు delete చేశాను, router configuration history ఆ deletion ను record చేస్తుంది.

    backups అంటే router మొత్తం configuration: password hashes, దాని certificates, VPN tunnels private keys. ఆ folder ను private గా ఉంచండి, forum post కి backup ను attach చేయకండి.

    లోతుగా: script చేసే ఇతర చెక్‌లు
    • backup, backup లాగే కనిపించాలి. download చేశాక, file కనీసం 50,000 bytes ఉందో, మొదటి మూడు లైన్లలో <opnsense> ఉందో script చెక్ చేస్తుంది.
    • ఫెయిల్ అయిన save పట్టుబడుతుంది. validations ఉన్న జవాబు ఫెయిల్ అయిన save గా లెక్క, router సొంత web pages లో లాగే; result విలువ failed అయినా అంతే. alias, redirect మార్పులను తిరిగి చదువుతుంది. rule మార్పులను rules ఉనికి, క్రమం ద్వారా, live connection టెస్ట్‌ల ద్వారా చెక్ చేస్తుంది.
    • Rule క్రమం. Rules A, B జోడించాక, వాటిలో ఏదైనా “Default allow LAN to any rule” తర్వాత sort అయితే script ఆగుతుంది. ఎందుకంటే allow-all rule కింద ఉన్న rule ఎప్పుడూ match కాదు.
    • alias నిండాలి. ప్రతి 5 సెకన్లకు, 90 సెకన్ల వరకు alias ని poll చేస్తుంది. కనీసం 500 అడ్రసులు లేకపోతే ఆగుతుంది.
    • మామూలు browsing పనిచేస్తూనే ఉండాలి. rules బాగున్నాయని ప్రకటించే ముందు, www.google.com:443 కి ఒక connection తెరుస్తుంది.
    • పాక్షిక ఫలితం ఆ మాటే చెబుతుంది. redirect దశ ఒక్కటే ఫెయిల్ అయితే, రన్ Apply PARTLY finished తో ముగుస్తుంది, redirect ని ఏ స్థితిలో వదిలిందో చెబుతుంది, code 2 తో exit అవుతుంది.
    లోతుగా: router అడ్రసుకు మాత్రమే చెడ్డ certificate ని అంగీకరించడం

    router web interface ఒక self-signed certificate వాడుతుంది. PowerShell 7 లో -SkipCertificateCheck ఉంది; అక్కడ script దాన్ని వాడుతుంది. Windows PowerShell 5.1 లో అలాంటి switch లేదు. సాధారణంగా వాడే workaround, మొత్తం session కి ప్రతి certificate నీ అంగీకరించే callback. script callback, request host router అడ్రసు అయినప్పుడు మాత్రమే ఫెయిల్ అయిన certificate చెక్‌ని అంగీకరిస్తుంది:

    public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
        if (e == SslPolicyErrors.None) return true;
        HttpWebRequest r = sender as HttpWebRequest;
        return r != null && r.RequestUri.Host == Host;
    }

    ఇది మినహాయింపును పరిమితం చేస్తుంది. certificate ని pin చేయదు: ఆ అడ్రసు కోసం చూపిన ఏ certificate అయినా పాసవుతుంది. certificate thumbprint ని చెక్ చేస్తే ఆ లోపం మూసుకుంటుంది. 5.1 కోసం script TLS 1.2 ని కూడా set చేస్తుంది.

    లోతుగా: వైఫల్యం కాదు, ముందు జాగ్రత్త: Expect: 100-continue

    Check mode GET requests మాత్రమే పంపుతుంది. Apply POSTs పంపుతుంది. Windows PowerShell 5.1 .NET Framework మీద నడుస్తుంది. అక్కడ ServicePointManager.Expect100Continue default గా true. body ఉన్న POST requests కి అది Expect: 100-continue header జోడిస్తుంది (Microsoft documentation). వెర్షన్ 2.2 మొదటి request కంటే ముందే ఆ header ని off చేస్తుంది:

    [Net.ServicePointManager]::Expect100Continue = $false

    router web server ఆ header కి అభ్యంతరం చెప్పి ఉండేదా అని నేను టెస్ట్ చేయలేదు.

    లోతుగా: పూర్తైన రన్, లైన్ వారీగా

    15:04 రన్ log. router అడ్రసు, దాని interfaces లో ఒకదాని పేరు స్థానంలో angle brackets లో placeholders పెట్టాను; local folder, PowerShell build number తీసేశాను, byte counts లోని అంకెలను మూడేసి చొప్పున group చేశాను. ప్రారంభ టెస్ట్‌లు blocklist ని దాటే మూడు దారులూ తెరిచి ఉన్నాయని చూపుతాయి. ముగింపు టెస్ట్‌లు, టెస్ట్ చేసిన మూడు IPv4 అడ్రసుల వరకు, అవి మూసుకున్నాయని చూపుతాయి.

    15:04:49  Mode: Apply   Router: https://<router-ip-address>   PowerShell 5.1
    15:04:55  Router reports: OPNsense series 26.7, amd64
    15:04:55  Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
    15:04:56  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200
    15:04:56  'Default allow LAN to any rule': sort_order=400000.1000023
    15:04:56  NAT 'Redirect non-local DNS to Local': disabled=1
    15:04:56  Router resolves example.com            : True   (want True)
    15:04:56  Router blocks the ad domain (blocklist) : True   (want True)
    15:04:56  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
    15:04:56  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
    15:04:56  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
    15:04:56  Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
    15:04:58  Alias DoH_IPs holds 1434 addresses.
    15:04:58  Rule 'Reject DoH to known resolvers (A)' enabled.
    15:04:58  Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
    15:04:58  Firewall rules applied. Verifying...
    15:05:08  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.
    15:06:19  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:06:19  Rule A: present, enabled=1, sort_order=400000.0000100
    15:06:19  Rule B: present, enabled=1, sort_order=400000.0000200
    15:06:19  'Default allow LAN to any rule': sort_order=400000.1000023
    15:06:19  NAT 'Redirect non-local DNS to Local': disabled=0
    15:06:23  Router resolves example.com            : True   (want True)
    15:06:23  Router blocks the ad domain (blocklist) : True   (want True)
    15:06:23  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
    15:06:23  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
    15:06:23  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
    15:06:23  Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
    15:06:23  Apply finished. Expected: router tests True, all three bypass tests False.

    alias లో నేను కావాలని పెట్టని ఒక entry ఉంది: URL కంటే ముందు, router interfaces లో ఒకదాని network. రన్ పాత contents ని మార్చే ముందు print చేసింది, కాబట్టి వాటిని log నుంచి పునరుద్ధరించవచ్చు.

    లోతుగా: test kit ఏం చెక్ చేస్తుంది, ఏం చెక్ చేయలేదు

    mock script API paths కి జవాబిస్తుంది, router స్థితిని memory లో ఉంచుకుంటుంది, తనకు వచ్చిన ప్రతి call నీ record చేస్తుంది. దాన్ని తప్పుగా ప్రవర్తించేలా set చేయవచ్చు: తప్పు వెర్షన్, చెడ్డ API key, చిన్న backup, మార్పుల తర్వాత ఫెయిల్ అయ్యే backup, తప్పు type ఉన్న alias, ఖాళీ key ఉన్న జవాబు, router తిరస్కరించే save, నిండని alias, allow-all rule కింద sort అయ్యే rules, ఇంకా చేరగలిగే DoH, పాడైన మామూలు HTTPS, లేని redirect rule లేదా allow rule, ప్రభావం చూపని redirect, ముందే on లో ఉన్న redirect. నా router గడిచిన స్థితులను కూడా ఇది అనుకరిస్తుంది: అదనపు entry ఉన్న alias, వెర్షన్ 2.3 disable చేసి వదిలిన రెండు rules, అన్నీ ముందే apply అయిన స్థితి. ఖాళీ key ఉన్న దాని జవాబు router get_item జవాబు ఆధారంగా చేతితో రాసినది. script చదివే endpoint మీదే అది serve అవుతుంది.

    harness ప్రతి case కీ script ని ఒకసారి, వేరే process గా నడుపుతుంది. exit code, log, backup files, mock కి వచ్చిన ప్రతి call, చివర్లో mock router స్థితి చెక్ చేస్తుంది. ప్రతి case లో ఇవి చెక్ చేస్తుంది: secret గానీ encoded key గానీ output లో, log లో కనిపించలేదని; ఏదీ delete కాలేదని; log తెరిచిన తర్వాత జరిగే stop log లో రాయబడిందని.

    harness script నే కాదు, దాని copy ని టెస్ట్ చేస్తుంది. copy లో, రెండు network టెస్ట్‌లు internet ని కాకుండా mock ని అడుగుతాయి. ప్రతి ఆగే సమయాన్ని ఒక millisecond కి తగ్గిస్తారు. ఏ case నడవక ముందే, ఆ patterns లో ప్రతిదీ ఆశించిన సంఖ్యలో match అయిందని harness చెక్ చేస్తుంది. copy PC మీద plain HTTP ద్వారా mock తో మాట్లాడుతుంది; script plain HTTP ని PC మీదే ఉన్న అడ్రసుకు మాత్రమే అంగీకరిస్తుంది.

    కాబట్టి kit టెస్ట్ చేయనివి: certificate చెక్, TLS; నిజమైన network టెస్ట్‌లు; వైఫల్యం 3, ఎందుకంటే mock కి state table లేదు, ఆగే సమయాలు తగ్గించబడ్డాయి; నిజమైన router నుంచి జవాబులు, చేతితో రాసిన ఒక ఖాళీ-key జవాబు తప్ప; backup ని overwrite చేయడానికి script నిరాకరించడం; work folder fallback, ఎందుకంటే ప్రతి case ఒక folder పేరు ఇస్తుంది; లేదా తానే ఫెయిల్ అయ్యే undo దశ.

    కావాలని చేసిన పది పాడుచేతలు, ఒక్కొక్కటి ఫెయిల్ చేసిన cases, పేజీ చివర kit తో పాటు జాబితాగా ఉన్నాయి.

    లోతుగా: OPNsense 26.7 API గమనికలు
    • script header ప్రకారం, ప్రతి configuration path ఆ రోజు router సొంత web pages నుంచి తీసుకున్నది: alias/search_item, alias/add_item, alias/set_item, alias/reconfigure, filter/search_rule, filter/add_rule, filter/set_rule, filter/apply, d_nat/search_rule, d_nat/set_rule, d_nat/apply, alias_util/list, core/backup/download/this. వెర్షన్ కోసం core/firmware/info ని, reachability చెక్ గా core/firmware/status ని కూడా call చేస్తుంది.
    • search endpoints ?rowCount=-1&current=1 తో GET కి జవాబిస్తాయి. ప్రతి row నీ, script కి కావాల్సిన fields తో తిరిగి ఇస్తాయి.
    • alias/get_item ఖాళీ పేరున్న keys తో option lists ఇస్తుంది. వాటిని PowerShell object properties గా మార్చలేదు.
    • GET /api/core/backup/download/this పూర్తి configuration ని XML గా ఇస్తుంది.
    • POST bodies Content-Type: application/json తో JSON. Rule మార్పులు సరిపోయే apply తర్వాత అమల్లోకి వస్తాయి; alias మార్పులు reconfigure తర్వాత.
    పదకోశం
    • Windows PowerShell 5.1: Windows తో పాటు వచ్చే PowerShell, .NET Framework మీద కట్టినది. powershell గా మొదలవుతుంది.
    • PowerShell 7: కొత్త PowerShell, విడిగా install చేసేది, modern .NET మీద కట్టినది. pwsh గా మొదలవుతుంది.
    • REST API: settings చదవడానికి లేదా మార్చడానికి ఒక program call చేసే web అడ్రసుల సమితి; OPNsense జవాబులు JSON.
    • JSON: structured data కోసం ఒక text format.
    • Mock: టెస్టింగ్ కోసం నిజమైన system స్థానంలో వాడేది; ఇక్కడ, router లా జవాబిచ్చే ఒక చిన్న web server.
    • Test harness: మరొక script ని నిర్ణయించిన అనేక పరిస్థితుల్లో నడిపి ఫలితాలు చెక్ చేసే script.
    • API key: password లేకుండా ఒక script router user లా పనిచేయడానికి అనుమతించే key, secret.
    • Alias (URL table): router ఒక web అడ్రసు నుంచి download చేసి refresh చేసే అడ్రసుల OPNsense జాబితా.
    • NAT redirect: match అయిన traffic ఎక్కడికి వెళ్లాలో మార్చే rule; ఇక్కడ దారి తప్పిన DNS queries ని router కి పంపుతుంది.
    • State table: firewall ఇప్పటికే చూసిన connections జాబితా. తెలిసిన connection తర్వాతి packets మొదటిదానికి తీసుకున్న నిర్ణయాన్నే పాటిస్తాయి.
    • DoH, DoT: DNS over HTTPS (port 443), DNS over TLS (port 853). router ని అడగకుండా ఒక device పేర్లను వెతకడానికి రెండు దారులు.
    • Expect: 100-continue: request body పంపే ముందు దాన్ని ఆమోదించమని server ని అడిగే HTTP header.

    ผ่านทุกการทดสอบ ในที่ที่ผิด

    อ่าน 10 นาที · แปลจากต้นฉบับภาษาอังกฤษ; โค้ด คำสั่ง และชื่อทางเทคนิคคงไว้เป็นภาษาอังกฤษ

    บ่ายวันที่ 11 ตุลาคม 2026 ผมรัน script ตัวหนึ่งกับ API ของ router OPNsense ของผม จาก Windows PowerShell 5.1 ซึ่งเป็น PowerShell ที่มากับ Windows มันหยุดก่อนจะเขียน log ของตัวเองได้แม้แต่บรรทัดเดียว การเรียก router ครั้งแรกของ script อยู่หลังบรรทัดนั้น จึงเท่าที่ผมดูออก ไม่มีอะไรไปถึง router

    นั่นคือเวอร์ชัน 2.0 เวอร์ชัน 2.4 ทำงานเสร็จเมื่อ 15:06 คือ 37 นาทีหลังจากผมบันทึกเวอร์ชัน 2.0 ทุกเวอร์ชันผ่านการทดสอบใน sandbox ของ Claude ก่อน แต่การทดสอบเหล่านั้นทำในที่ที่ผิด คือรันกับ mock router แทน router ตัวจริง และรันบน PowerShell 7 แทน Windows PowerShell 5.1 เวอร์ชันทั้งสามที่ต่อมาล้มเหลวบน router ผ่านการทดสอบกับ mock ความต่างของ PowerShell มีส่วนในความล้มเหลวครั้งที่ 1 หรือไม่ ผมไม่รู้ ในครั้งที่ 2 ไม่มีส่วน และภายหลังมันทำให้ test harness ของผมพัง มีสามครั้งที่รันแล้วล้มเหลว แต่ละครั้งด้วยสาเหตุต่างกัน ไม่มีครั้งไหนทิ้งการเปลี่ยนแปลงที่เปิดใช้งานค้างไว้

    ผมทำงานนี้ร่วมกับ Claude ผมเป็นคนกำหนดกฎที่ script ต้องทำตาม สร้าง API key และลบมันทิ้งหลังเสร็จงาน และรันทุกเวอร์ชันบน PC ของผมเองกับ router ของผมเอง Claude เขียน script, mock router ที่ใช้ทดสอบ และการแก้ไขแต่ละครั้ง Claude ทดสอบทั้งหมดบน PowerShell 7 ซึ่งเป็น PowerShell ตัวเดียวที่ sandbox ของมันมี

    script, mock router และ test harness อยู่ท้ายหน้านี้ ภายใต้สัญญาอนุญาต MIT script นี้ทำให้ router ปฏิเสธสามวิธีทั่วไปที่ใช้เลี่ยง blocklist ของ DNS คือ DNS over HTTPS, DNS over TLS หรือ QUIC และ DNS ธรรมดาที่ส่งไปยัง server อื่น หน้านี้บันทึกการรันและสิ่งที่ผมจะเปลี่ยน และแผงใกล้ท้ายหน้าแสดงขั้นตอนการรัน script บน router ของคุณเอง ทีละขั้น

    ไม่คุ้นกับ command line? วิธีอ่านกล่องคำสั่ง

    PS> หมายถึง: พิมพ์คำสั่งนี้ใน PowerShell บน Windows (เมนู Start → พิมพ์ powershell → Enter) อย่าพิมพ์ PS> เอง

    แต่ละบรรทัดที่ขึ้นต้นด้วย PS> คือหนึ่งคำสั่ง คลิกที่ PS> เพื่อคัดลอกเฉพาะบรรทัดนั้น วางลงไป กด Enter และรอให้ทำงานเสร็จก่อนจะไปคำสั่งถัดไป กล่องที่มีปุ่ม Copy อยู่ด้านบนใส่หนึ่งคำสั่ง (หรือหนึ่งไฟล์) จึงให้คัดลอกทั้งกล่อง กล่องเส้นประแสดงสิ่งที่คุณควรเห็นตอบกลับมา หรือโค้ดไว้อ่าน คุณไม่ต้องพิมพ์

    สิ่งที่ script ทำ

    script นี้ใช้แก้ปัญหา DNS บน router OPNsense 26.7 blocklist ของ router ผมกรองได้เฉพาะอุปกรณ์ที่ถาม router ส่วนโทรศัพท์ เบราว์เซอร์ และอุปกรณ์บางตัวไปถาม server อื่น การแก้นี้เกี่ยวกับ object สี่ตัว:

    • alias ชื่อ DoH_IPs ที่ดาวน์โหลดรายการสาธารณะของ address ของ server DNS-over-HTTPS ซึ่งโปรเจกต์ Hagezi ดูแลไว้ (วันนั้นมี 1,434 รายการ);
    • Rule A ซึ่ง reject ทราฟฟิกจาก LAN ที่ไปยัง address เหล่านั้นบน port 443;
    • Rule B ซึ่ง reject ทราฟฟิกจาก LAN ที่ไปยัง address ใดก็ได้บน port 853 ซึ่ง DNS over TLS และ DNS over QUIC ใช้;
    • NAT redirect ที่ส่ง query ทุกตัวบน port 53 ที่ส่งไปยัง server อื่นโดยไม่ผ่าน router กลับมาที่ router

    บน router ของผม alias และ rule redirect มีอยู่แล้ว และ redirect ถูกปิดไว้ script จะทำความสะอาด alias สร้าง rule สองตัวถ้ายังไม่มี และเปิด redirect มันไม่สร้าง rule redirect rule เหล่านี้ครอบคลุมเฉพาะ IPv4 และ interface LAN ข้อจำกัดต่าง ๆ อยู่ในแผงขั้นตอนใกล้ท้ายหน้า

    ผมคลิกสร้าง object ทั้งสี่นี้เองก็ได้ แต่ผมเขียน script เพราะอยากได้การเปลี่ยนแปลงในรูปที่ตรวจสอบได้โดยไม่เปลี่ยนอะไร รันซ้ำได้ และปิดได้ด้วยคำสั่งเดียว

    กฎที่ script ต้องทำตาม

    1. สามโหมด Check อ่านและรายงาน Apply ทำการเปลี่ยนแปลง Rollback ปิด rule สองตัวและ redirect โดยไม่ลบอะไร คำสั่งที่ไม่ระบุ -Mode จะรัน Check
    2. ตรวจเวอร์ชัน script ถาม router ก่อนว่ารันอะไรอยู่ และหยุดถ้าคำตอบไม่ใช่ซีรีส์ 26.7
    3. backup เป็นลำดับถัดไป ก่อนจะอ่านหรือเปลี่ยน configuration ใด ๆ ทุกการรันจะดาวน์โหลด configuration ทั้งหมดของ router ลงไฟล์ใหม่ และไม่ยอมเขียนทับไฟล์ที่มีอยู่แล้ว
    4. ทดสอบทุกการเปลี่ยนแปลง alias ก่อน แล้วตามด้วย rule ทั้งสอง แล้วจึง redirect ในเวอร์ชัน 2.3 ถ้าการทดสอบล้มเหลว จะ undo ทุกอย่างที่การรันนั้นเปลี่ยนไป ตั้งแต่เวอร์ชัน 2.4 ถ้าล้มเหลวเฉพาะ redirect ก็จะปิดเฉพาะ redirect ส่วน rule ที่ผ่านแล้วยังอยู่
    5. ไม่มีความลับใน script API key เก็บอยู่ในไฟล์แยก

    สามสิบเจ็ดนาที

    เริ่ม เวอร์ชัน โหมด เกิดอะไรขึ้น สิ่งที่เหลืออยู่บน router
    หลัง 14:29 2.0 ไม่ได้บันทึกใน log หยุดก่อน log บรรทัดแรก ไม่มี
    14:43 2.1 Check รายงานแบบอ่านอย่างเดียว ครบถ้วน ไม่มี
    14:51 2.2 Apply หยุดเพราะ guard ของตัวเองก่อนการ save ใด ๆ ไม่มี
    14:56 2.3 Apply rule ใช้ได้; การทดสอบ redirect ล้มเหลว; undo แล้ว rule สองตัว ถูกปิดไว้
    15:04 2.4 Apply เสร็จเมื่อ 15:06 ผ่านทุกการทดสอบ การแก้ไขนี้

    เวอร์ชัน 2.0 ไม่ได้เขียน log เวลาของมันจึงเป็นนาทีที่ผมบันทึกไฟล์ เวลาอื่น ๆ มาจาก log ของ script เอง

    ลำดับการทำงานช่วยจำกัดความเสียหาย script ตรวจเวอร์ชัน ทำ backup และอ่านก่อนเขียน ความล้มเหลวครั้งที่ 1 หยุดก่อนเรียก router ใด ๆ ความล้มเหลวครั้งที่ 2 หยุดก่อนการ save ใด ๆ ด้วย guard ที่เขียนไว้สำหรับปัญหาอื่น ความล้มเหลวครั้งที่ 3 เกิดหลังจากมีการเปลี่ยนแปลงแล้ว และ undo ของเวอร์ชันนั้นปิดการเปลี่ยนแปลงเหล่านั้น

    ความล้มเหลวครั้งที่ 1: สาเหตุที่ผมเข้าใจผิด

    เวอร์ชัน 2.0 เอาโฟลเดอร์ทำงานมาจากค่า default ของ parameter:

    [string]$WorkDir = $PSScriptRoot

    $PSScriptRoot คือโฟลเดอร์ที่ script อยู่ script ใช้มันสร้าง path ของโฟลเดอร์ logs ซึ่ง script สร้างขึ้นก่อนจะอ่าน key หรือเรียก router

    เวอร์ชัน 2.1 เปลี่ยนสามอย่าง มันหาโฟลเดอร์ในตัว script เอง หยุดถ้าโฟลเดอร์นั้นไม่มีอยู่ และครอบการนับสองจุดไว้เพื่อให้คำตอบ DNS ที่ว่างเปล่านับเป็นศูนย์ มีเพียงการเปลี่ยนเรื่องโฟลเดอร์ที่อยู่ก่อน log บรรทัดแรก ในวันนั้น Claude กับผมสรุปว่า Windows PowerShell 5.1 ปล่อยให้ $PSScriptRoot ว่าง และร่างแรก ๆ ของโพสต์นี้ก็เขียนไว้อย่างนั้น

    ชุดทดสอบของโพสต์นี้ตรวจเรื่องนั้น และข้อสรุปนั้นผิด บน PC ของผม Windows PowerShell 5.1 ที่เริ่มด้วย -File แบบที่ผมเริ่ม script ใส่โฟลเดอร์ลงใน $PSScriptRoot ในค่า default ของ parameter เช่นเดียวกับ PowerShell 7.4.6 ผมไม่ได้ทดสอบทุกวิธีที่ใช้เริ่ม script จึงตัดความเป็นไปได้ไม่ได้ว่าบางวิธีทำให้มันว่าง ผมไม่ได้บันทึกว่าบ่ายวันนั้นผมเริ่มเวอร์ชัน 2.0 อย่างไร หรือ error ที่มันแสดง ผมจึงไม่รู้ว่าอะไรทำให้มันหยุด สิ่งที่หลักฐานรองรับแคบกว่านั้น: เวอร์ชัน 2.0 หยุดก่อน log บรรทัดแรก ดังนั้น เท่าที่หลักฐานแสดง จึงหยุดก่อนการเรียก router ใด ๆ คอมเมนต์ใน script ที่เผยแพร่บอกว่าโฟลเดอร์นี้อาจว่างบน Windows PowerShell 5.1 คอมเมนต์นั้นตรงกับข้อสรุปแรกของผม ผมปล่อยไฟล์ที่ผ่านการทดสอบแล้วไว้ตามเดิม

    การเปลี่ยนในเวอร์ชัน 2.1 ยังคงไว้ มันไม่มีต้นทุนอะไร และใช้ได้ไม่ว่าจะเริ่ม script ด้วยวิธีไหน:

    if ([string]::IsNullOrWhiteSpace($WorkDir)) {
        if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
        else { $WorkDir = (Get-Location).Path }
    }

    การรัน Check ของเวอร์ชัน 2.1 เมื่อ 14:43 ทำงานจนจบ

    ความล้มเหลวครั้งที่ 2: mock ที่ไม่มีพฤติกรรมเฉพาะตัวของ router

    เพื่อตรวจชนิดของ alias เวอร์ชัน 2.2 เรียก endpoint alias/get_item ของ router log ของการรันเมื่อ 14:51:

    14:51:46  Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
    14:51:46  Nothing to undo.
    ...
    14:51:47  STOP: Apply did not complete; changes from this run were undone.

    ชนิดของ alias ไม่ได้ว่าง คำตอบของ router มีรายการที่ชื่อเป็นสตริงว่าง ("":) JSON อนุญาตให้ทำเช่นนั้นได้ แต่ PowerShell สร้าง property ของ object ที่มีชื่อว่างไม่ได้ เอกสารของ Microsoft สำหรับ ConvertFrom-Json บอกไว้อย่างนั้น (เอกสารอ้างอิง PowerShell 7.4) และเสนอ switch -AsHashtable สำหรับคำตอบแบบนี้ Windows PowerShell 5.1 ไม่มี switch นั้น Invoke-RestMethod ไม่แจ้ง error ใด ๆ มันคืนคำตอบมาเป็นข้อความธรรมดา และ script อ่านชนิดจากข้อความนั้นออกมาเป็นค่าว่าง

    นี่ไม่ใช่ความต่างระหว่างเวอร์ชันของ PowerShell ชุดทดสอบป้อนคำตอบที่มี key ว่างให้ script บน PowerShell 7.4.6 และบน PC ของผมบน Windows PowerShell 5.1 Invoke-RestMethod คืนค่าเป็นข้อความโดยไม่มี error เวอร์ชัน 2.2 ผ่านการทดสอบกับ mock เพราะคำตอบของ mock ไม่มี key ว่าง แต่คำตอบของ router มี

    guard ที่หยุดการรันนี้เขียนไว้สำหรับปัญหาอื่น คือ alias ที่มีอยู่แล้วแต่เป็นชนิดผิด มันหยุดการรันนี้เพราะชนิดที่ว่างไม่ใช่ urltable ถ้าไม่มี guard นี้ การรันจะ save URL ใหม่ แล้วตอน undo ก็จะเขียนสตริงว่างลงใน alias

    การรัน Check เมื่อ 14:43 ไม่ได้จับปัญหานี้ Check อ่าน alias ผ่าน alias/search_item มีแค่ Apply ที่เรียก get_item

    เวอร์ชัน 2.3 เปลี่ยนสองอย่าง endpoint search_item และ search_rule ของ router คืนชนิดและเนื้อหาอยู่แล้ว และคำตอบของมัน parse ได้ script จึงอ่านผ่าน endpoint เหล่านี้เท่านั้น และทุกการเรียก API ตอนนี้ผ่าน helper ตัวเดียวที่ปฏิเสธคำตอบที่มัน parse ไม่ได้:

    $r = Invoke-RestMethod @p
    if ($r -is [string]) {
        $t = $r.TrimStart()
        if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
    }

    ความล้มเหลวครั้งที่ 3: redirect ที่ทดสอบเร็วเกินไป

    เวอร์ชัน 2.3 ไปได้ไกลกว่า มันทำความสะอาด alias เพิ่ม rule ทั้งสองและทดสอบ จากนั้นเปิด NAT redirect และทดสอบห้าวินาทีต่อมา:

    14:57:16  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    14:57:17  NAT rule enabled and applied. Verifying...
    14:57:22  Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
    14:57:22  Undoing changes made in this run...

    การทดสอบส่ง query สองตัวไปที่ 8.8.8.8: ตัวหนึ่งสำหรับ example.com และอีกตัวสำหรับโดเมนโฆษณา log ของ firewall แสดงว่ามีหนึ่งในสองตัวถูก redirect โดเมนโฆษณาได้ address จริงกลับมา ตัวที่ไม่ถูก redirect จึงเป็นตัวนั้น สิบสามวินาทีก่อนเปิด redirect การตรวจตอนเริ่มของ script ได้ส่งชื่อเดียวกันนั้นไปที่ 8.8.8.8 เพื่อแสดงว่าทางเลี่ยงยังเปิดอยู่

    ผมมีคำอธิบายสองแบบ และไม่ได้ทดสอบเลยสักแบบ firewall เก็บ state entry ไว้สำหรับแต่ละ connection ที่มันเคยเห็น และใช้ redirect กับ connection ใหม่เท่านั้น ถ้า query ครั้งที่สองของโดเมนโฆษณาออกจาก PC ของผมจาก source port เดียวกับครั้งแรก มันจะตรงกับ entry เดิมและออกไปถึง Google หรือมีบางอย่างบน PC ของผมตอบคำถามซ้ำนั้นจากแคช และ query ไม่เคยออกจาก PC เลย

    timeout ของ UDP state บน router นี้ ซึ่งอ่านจาก Firewall → Diagnostics → Statistics คือ 60 วินาทีสำหรับ udp.first และ udp.multiple และ 30 วินาทีสำหรับ udp.single เวอร์ชัน 2.4 รอ 70 วินาทีก่อนทดสอบ และการทดสอบผ่าน:

    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.

    การรอนี้นานกว่า state entry ของ firewall แต่จะนานกว่าคำตอบที่ PC จำไว้หรือไม่ ขึ้นกับว่าคำตอบนั้นถูกเก็บไว้นานแค่ไหน ซึ่งผมไม่ได้วัด ผลลัพธ์นี้จึงแยกคำอธิบายทั้งสองแบบออกจากกันไม่ได้ การทดสอบด้วยชื่อที่ไม่เคย query มาก่อน โดยเปิด state table ของ firewall ดูไปด้วย จะแยกได้

    undo ในเวอร์ชัน 2.3 ปิด redirect ปิด rule ใหม่ทั้งสองตัว และคืนเนื้อหาของ alias มันไม่ได้ลบ rule และปล่อยให้ช่วงเวลา refresh ของ alias เป็นหนึ่งวัน backup ที่ทำหลัง undo ใหญ่กว่า backup ก่อนการรัน 4,788 ไบต์ เวอร์ชัน 2.4 เริ่มต้นด้วยการพบ rule ทั้งสองตัว:

    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200

    ดังนั้น “undo แล้ว” หมายถึง “ไม่มีอะไรเหลือที่เปิดใช้งานอยู่” ไม่ใช่ “router กลับเป็นเหมือนเดิม” เวอร์ชัน 2.4 เปิด rule สองตัวที่มีอยู่แล้วแทนที่จะเพิ่มสำเนาใหม่ เพราะมันค้นหา rule จากคำอธิบายก่อนจะสร้าง

    สิ่งที่ mock พลาด และการทดสอบรอบที่สอง

    Claude รันแต่ละเวอร์ชันกับ mock ก่อนที่ผมจะรันกับ router ตามบันทึกของ session นั้น แต่ละเวอร์ชันรันครั้งหนึ่งแบบปกติ และอีกครั้งแบบบังคับให้ล้มเหลว เพื่อตรวจ undo เวอร์ชัน 2.0 ถึง 2.3 ผ่านการทดสอบกับ mock แต่เมื่อรันกับ router สามในสี่เวอร์ชันล้มเหลว mock ไม่เคยรันบน Windows PowerShell 5.1 และคำตอบของมันไม่มี key ว่างแบบที่ router มี

    script ท้ายหน้านี้คือเวอร์ชัน 2.5.1 ไม่ใช่ 2.4 ก่อนเผยแพร่ ผมให้ Claude รีวิว script อีกครั้ง และเวอร์ชัน 2.5 แก้สิ่งที่รีวิวนั้นพบ: ข้อความที่อาจบรรยายสถานะของ router ผิด, การหยุดที่ไม่ได้เขียนลง log, undo ที่ไม่ได้คืนค่า enabled ของ alias และการรันที่อาจเริ่มได้บน router ที่ไม่มี rule redirect หรือ rule allow-all ของ LAN มันยังปฏิเสธ address ของ router ที่ไม่ได้ขึ้นต้นด้วย https:// ยกเว้น address บน PC เครื่องที่รัน script เอง ซึ่งชุดทดสอบใช้ เวอร์ชัน 2.4 คือตัวที่รันบน router ของผม เวอร์ชัน 2.5.1 ซึ่งต่างจาก 2.5 เฉพาะคอมเมนต์ส่วนหัว รันกับ mock เท่านั้น

    การทดสอบรอบที่สองใช้ mock ตัวใหม่ ที่สร้างให้ทำตัวผิดปกติแบบที่ router อาจทำได้ รวมถึงคำตอบที่มี key ว่าง harness รันสำเนาของ script กับ mock นี้ครั้งละหนึ่งกรณี รวม 30 กรณี บน PowerShell 7.4.6 ผ่านทั้ง 30 กรณี

    การรันครั้งแรกบน Windows PowerShell 5.1 บน PC ของผมล้มเหลวสองกรณี log ของ script แสดงว่า script ทำถูกแล้ว แต่ harness ทำไม่ถูก เมื่อ function ของ PowerShell คืน list ที่มีสมาชิกตัวเดียว ผู้เรียกจะได้ตัวสมาชิกนั้นเอง PowerShell 7 ให้นับและ index สมาชิกนั้นได้เหมือนเป็น list แต่ Windows PowerShell 5.1 ไม่ให้ สำหรับ object ชนิดนี้ harness เคยรันบน PowerShell 7 เท่านั้น เมื่อแก้ตรงนั้นแล้ว ทั้ง 30 กรณีผ่านบน Windows PowerShell 5.1 ด้วย กับ script เวอร์ชันที่เผยแพร่

    เพื่อตรวจ harness เอง Claude ทำให้ script พังสิบแบบ เช่น เอา undo, การตรวจ JSON หรือการตรวจ HTTPS ออก การทำพังแต่ละแบบทำให้อย่างน้อยหนึ่งกรณีล้มเหลว การตรวจนั้นรันบน PowerShell 7.4.6 กับเวอร์ชัน 2.5 โดยใช้ harness รุ่นก่อนหน้า

    สิ่งที่ผมจะนำไปใช้กับ script ตัวต่อไป

    1. ทดสอบบน PowerShell ที่จะใช้รัน script และรันการทดสอบบนตัวนั้นด้วย (harness ผ่านบน PowerShell 7 และล้มเหลวในการรันครั้งแรกบน 5.1)
    2. สร้างคำตอบของ mock จากคำตอบจริง คำตอบที่ save มาจาก get_item ของ router จะจับความล้มเหลวครั้งที่ 2 ได้ก่อนที่ router จะเห็น script
    3. ทำให้โหมดอ่านอย่างเดียวอ่านทุกอย่างที่โหมดเขียนจะอ่าน ในกรณีนี้ Check และ Apply อ่าน alias ผ่าน endpoint ต่างกัน
    4. ถือว่าสตริงจาก Invoke-RestMethod คือความล้มเหลว เมื่อคุณคาดว่าจะได้ object มันไม่ได้แจ้ง error เสมอไป
    5. หลังเปิด redirect ให้รอนานกว่า state timeout ของ firewall และทดสอบด้วยชื่อที่ยังไม่เคย query มาก่อน
    6. ถ้า undo ใช้วิธีปิดแทนการลบ ให้การรันครั้งถัดไปมองหาสิ่งที่ครั้งก่อนทิ้งไว้
    7. ทำให้ script พังโดยตั้งใจ เพื่อตรวจว่าการทดสอบล้มเหลวได้
    8. เก็บ API key ไว้นอก script และลบมันเมื่องานเสร็จ ผมใช้ key ของ user root การใช้ user ที่มีเฉพาะสิทธิ์ที่ script ต้องใช้จะดีกว่า ผมไม่ได้ลอง
    วิธีรันกับ router ของคุณเอง ทีละขั้น

    ก่อนเริ่ม คุณต้องมี:

    • PC Windows ที่อยู่ในเครือข่ายเดียวกับ router คุณพิมพ์ในสองที่ คือ PowerShell บน PC และหน้าเว็บของ router ในเบราว์เซอร์;
    • OPNsense 26.7 script จะหยุดถ้าเป็นซีรีส์อื่น เพราะ path ของ API อ่านมาจากหน้าเว็บของซีรีส์นั้นเอง;
    • DNS blocklist ที่เปิดอยู่ ใน Services → Unbound DNS → Blocklist (เอกสารของ OPNsense ระบุหน้านั้น) และอุปกรณ์ของคุณถาม router เรื่อง DNS;
    • rule Destination NAT ที่ส่ง query DNS (port 53) ซึ่งเล็งไปที่ใดก็ได้ที่ไม่ใช่ router กลับมาที่ router สร้างไว้แล้ว โดยมีคำอธิบาย “Redirect non-local DNS to Local” script เปิดมัน แต่ไม่ได้สร้าง script ไม่สร้าง rule นี้ แผงนี้ไม่ครอบคลุมการสร้าง rule นี้ และถ้าไม่มี Apply จะหยุด วิธีทำจากชุมชนในฟอรัม OPNsense แสดงวิธีหนึ่ง;
    • rule LAN ชื่อ “Default allow LAN to any rule” ซึ่ง OPNsense สร้างให้โดย default script ตรวจว่า rule ใหม่สองตัวของมันอยู่เหนือ rule นี้

    เวอร์ชัน 2.5.1 ซึ่งเป็น script ในแผงนี้ รันกับ mock router ในชุดทดสอบเท่านั้น เวอร์ชัน 2.4 คือตัวที่รันบน router ของผม

    ใช้เวลาราว 20 นาที ตัวการเปลี่ยนเองใช้ราวสองนาที การเปลี่ยนแปลงแรกบน router คือ API key ในขั้น 3 การรัน Check ในขั้น 5 ไม่เปลี่ยนอะไรบน router Apply ในขั้น 6 เปลี่ยนค่าบน router ขั้น 8 ปิดการแก้ไขและแสดงวิธีกู้คืน configuration ทั้งหมด ทุกการรันจะบันทึก backup ของ configuration ของ router ลงบน PC ก่อนอ่าน configuration

    อ่านข้อจำกัดต่อไป ถ้าข้อใดตรงกับเครือข่ายของคุณ script ไม่เหมาะกับเครือข่ายนั้น อย่าทำต่อ

    ข้อจำกัด

    • IPv4 เท่านั้น Rule A และ B สร้างสำหรับ IPv4 และทุกการทดสอบใช้ address IPv4 ถ้า LAN ของคุณมี IPv6 DoH และ DoT ผ่าน IPv6 จะไม่ถูกบล็อกและไม่ถูกทดสอบ (Interfaces → LAN แสดง IPv6 Configuration Type; None หมายถึงไม่มี IPv6)
    • interface LAN เท่านั้น interface อื่นและ VLAN ไม่ครอบคลุม
    • ทุก host ใน LAN Pi-hole หรือ AdGuard Home ใน LAN ที่ใช้ DoH หรือ DoT เป็น upstream จะเสีย upstream ไป ถ้ามันส่ง DNS ธรรมดาไปที่ server สาธารณะ rule redirect ของคุณอาจจับสิ่งนั้นด้วย ขึ้นกับว่า rule สร้างไว้อย่างไร
    • อุปกรณ์ที่บังคับใช้ DNS แบบเข้ารหัสเท่านั้น อุปกรณ์ที่ตั้งให้ใช้เฉพาะผู้ให้บริการ DNS แบบเข้ารหัส เช่น โทรศัพท์ที่ตั้ง Private DNS เป็น hostname อาจค้นหาชื่อบนเครือข่ายนี้ไม่ได้ เมื่อ rule ปฏิเสธเส้นทางของมัน ให้เปลี่ยนค่านั้นบนอุปกรณ์
    • rule redirect ต้องมีอยู่แล้ว ใน Firewall → NAT → Destination NAT โดยมีคำอธิบาย “Redirect non-local DNS to Local” หรือค่าที่คุณตั้งใน $NatDesc script ไม่ได้สร้างมัน และไม่ได้ตรวจว่ามันสร้างไว้อย่างไร
    • alias จะถูกเขียนทับ ด้วย URL ของ Hagezi เนื้อหาเดิมจะถูกเขียนลง log
    • โดเมนทดสอบ ใน $AdTestDomain ต้องถูก blocklist ของ router บล็อก โดยตอบเป็น 0.0.0.0 หรือไม่มี address ไม่เช่นนั้นการทดสอบ redirect จะล้มเหลว
    • LAN ที่คุณเชื่อถือ การตรวจ certificate ของ script ยอมรับ certificate ใดก็ได้ที่แสดงสำหรับ address ของ router ดังนั้นอุปกรณ์ใน LAN ที่ปลอมตัวเป็น router จะได้ key ไป รันเฉพาะบนเครือข่ายที่คุณควบคุม
    • เวลารอ ใน $NatWaitSeconds ควรนานกว่า UDP state timeout ของ router คุณ
    • Rollback ปิด rule สองตัวและ rule redirect แม้ว่า redirect จะเปิดอยู่ก่อนที่คุณจะรัน Apply ครั้งแรก มันไม่คืนค่า alias
    1. เปิด PowerShell และสร้างโฟลเดอร์ เปิดเมนู Start พิมพ์ powershell แล้วกด Enter หน้าต่างชื่อ Windows PowerShell จะเปิดขึ้น และ prompt ของมันขึ้นต้นด้วย PS ถ้า prompt ไม่มี PS แสดงว่าคุณอยู่ใน Command Prompt ให้ปิดแล้วเปิด PowerShell แทน เพราะคำสั่งด้านล่างใช้ได้เฉพาะใน PowerShell คลิกในหน้าต่าง ใช้สองบรรทัดด้านล่างทีละบรรทัด: คลิก PS> เพื่อคัดลอกบรรทัดนั้น วางมัน (Ctrl + V หรือคลิกขวา) แล้วกด Enter

      New-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns"
      Set-Location "$env:USERPROFILE\opnsense-dns"

      บรรทัดแรกสร้างโฟลเดอร์ชื่อ opnsense-dns ในโฟลเดอร์ผู้ใช้ของคุณและแสดงรายการสั้น ๆ; บรรทัดที่สองย้าย PowerShell เข้าไปในโฟลเดอร์นั้น และ prompt จะลงท้ายด้วย opnsense-dns> แต่ละบรรทัดใช้เวลาไม่ถึงหนึ่งวินาที ถ้าบรรทัดแรกบอกว่ามีโฟลเดอร์อยู่แล้ว ให้ทำต่อ เปิดหน้าต่างนี้ไว้ และเก็บโฟลเดอร์ให้อยู่นอก OneDrive, Dropbox และที่เก็บที่แชร์ร่วม: backup ที่บันทึกที่นี่มี configuration ทั้งหมดของ router

    2. บันทึก script เลื่อนไปที่ The script, the mock router and the test harness ท้ายหน้านี้ เปิด opnsense-dns-bypass.ps1 (version 2.5.1) อ่านมัน แล้วคลิก Copy มันยาว 491 บรรทัด มันจะใช้ key ของ router คุณ จึงอ่านก่อนรัน Windows ทำเครื่องหมายไฟล์ที่เบราว์เซอร์ดาวน์โหลดว่ามาจากอินเทอร์เน็ต ไฟล์ที่เขียนด้วยคำสั่งด้านล่างไม่มีเครื่องหมายนั้น จึงไม่ต้องใช้ Unblock-File คำสั่งนี้เขียนทับไฟล์ชื่อเดียวกันในโฟลเดอร์นี้ ในหน้าต่าง PowerShell:

      Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1

      Get-Clipboard อ่านสิ่งที่คุณคัดลอก และ Set-Content เขียนลงไฟล์ ตัว script เป็น ASCII ล้วน encoding นี้จึงปลอดภัย ใช้เวลาไม่ถึงหนึ่งวินาทีและไม่พิมพ์อะไร ตรวจว่าทั้งหมดมาครบ:

      (Get-Content .\opnsense-dns-bypass.ps1).Count
      491

      ตัวเลขที่ต่างออกไปบ่งว่าการคัดลอกถูกตัดหรือถูกเปลี่ยน กลับไปที่หน้านั้น คลิก Copy อีกครั้ง แล้วทำคำสั่งแรกซ้ำ

    3. สร้าง API key บน router ในเว็บเบราว์เซอร์ พิมพ์ https:// ตามด้วย address ที่คุณใช้เปิดหน้า settings ของ router (เช่น https://192.168.1.1) แล้วกด Enter เบราว์เซอร์อาจเตือนว่าการเชื่อมต่อไม่เป็นส่วนตัว เพราะ router เซ็น certificate เอง เลือกตัวเลือกที่ไปต่อยัง address นั้น (ใน Chrome: Advanced แล้ว Proceed) ล็อกอินด้วย login ของคุณเองบน router จากนั้น:

      1. ในเมนูทางซ้าย คลิก System แล้ว Access แล้ว Users
      2. คลิกไอคอนดินสอ (edit) ที่ท้ายแถวของผู้ดูแลที่คุณล็อกอินเป็น
      3. หาส่วน API keys ในการตั้งค่าของ user (เอกสารของ OPNsense เรียกว่าแท็บ ApiKeys) และใช้ปุ่มในตารางของมันที่สร้าง key
      4. เบราว์เซอร์จะดาวน์โหลดไฟล์ข้อความขนาดเล็กภายในไม่กี่วินาที ไฟล์มีบรรทัด key= และบรรทัด secret= เอกสารบอกว่า secret ถูกสร้างเพียงครั้งเดียว ถ้าไฟล์หาย ให้สร้าง key ใหม่

      key ทำงานในฐานะ user ที่เป็นเจ้าของมัน ผมใช้ key ของ user root และลบทิ้งหลังจากนั้น key ของ root ให้สิทธิ์ควบคุม router เต็มที่ user ที่จำกัดเฉพาะหน้า firewall, NAT และ backup จะมีสิทธิ์น้อยกว่า แต่ script ดาวน์โหลด configuration ทั้งหมดของ router user นั้นจึงยังอ่าน hash ของรหัสผ่านและ private key ใน configuration ได้ ผมไม่ได้ลอง user ที่จำกัดสิทธิ์ ถ้าเมนูของคุณหน้าตาต่างออกไป เอกสารของ OPNsense เรื่อง local user อธิบายขั้นเดียวกัน อย่านำเนื้อหาในไฟล์ key ไปวางที่ใด: secret ในไฟล์ให้สิทธิ์ควบคุม router

    4. ใส่ไฟล์ key ในโฟลเดอร์ กลับมาที่ PowerShell แสดงรายการไฟล์ข้อความใหม่ล่าสุดในโฟลเดอร์ Downloads ของคุณ:

      Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTime
      Name                  LastWriteTime
      ----                  -------------
      example_apikey.txt    <date and time>

      ถ้ารายการว่าง เบราว์เซอร์บันทึกไฟล์ไว้ที่อื่น: กด Ctrl + J ในเบราว์เซอร์เพื่อดูว่าอยู่ที่ไหน ตอนนี้ย้ายไฟล์เข้าโฟลเดอร์ภายใต้ชื่อที่ script คาดไว้ แทน <file-name> รวมวงเล็บมุม ด้วยชื่อจากรายการ:

      Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txt

      ใช้เวลาไม่ถึงหนึ่งวินาทีและไม่พิมพ์อะไร มันจะไม่เขียนทับ apikey.txt ที่มีอยู่แล้วในโฟลเดอร์ ถ้ามันปฏิเสธด้วยเหตุนั้น แสดงว่ามีไฟล์ key เก่าอยู่ที่นั่น ลบ key นั้นบน router (ขั้น 8 บอกว่าอยู่ที่ไหน) รัน Remove-Item .\apikey.txt และทำขั้นนี้ซ้ำ ถ้ามันรายงาน error เรื่อง path แสดงว่า path อาจยังมี <file-name> อยู่ หรือชื่ออาจไม่ตรงกับชื่อในรายการ ตอนนี้ตรวจว่าไฟล์ key มีสองบรรทัด คำสั่งนี้พิมพ์เฉพาะคำก่อนเครื่องหมาย = แต่ละตัว ไม่พิมพ์ค่า:

      Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }
      key
      secret

      ถ้าคุณเห็นคำอื่น ไฟล์นี้น่าจะไม่ใช่ไฟล์ key ดาวน์โหลด key ใหม่ (ขั้น 3)

    5. รัน Check — คำสั่งนี้อ่านอย่างเดียว ก่อนอื่นบอก PowerShell ว่า address ของ router คืออะไร คลิก PS> เพื่อคัดลอกบรรทัด วางมัน และอย่าเพิ่งกด Enter แทน <router-ip-address> รวมวงเล็บมุม ด้วยตัวเลขของ address จากขั้น 3 (เช่น 192.168.1.1) และปล่อย https:// ไว้ตามเดิม ขยับ cursor ด้วยปุ่มลูกศร เพราะการคลิกเมาส์ไม่ย้าย cursor ใน PowerShell; Backspace ลบตัวอักษร จากนั้นกด Enter ถ้ายังมีวงเล็บมุมอยู่ script จะหยุด

      $RouterUrl = 'https://<router-ip-address>'

      ค่านี้จำ address ไว้เฉพาะหน้าต่างนี้ ถ้าปิดหน้าต่าง ให้ทำซ้ำ

      ตอนนี้รัน script powershell -ExecutionPolicy Bypass -File เริ่ม Windows PowerShell 5.1 ตัวใหม่ที่รันไฟล์นั้น -ExecutionPolicy Bypass บน command line มีผลเฉพาะการรันครั้งนั้น และ เอกสารของ Microsoft เรื่อง execution policy บอกว่าค่านี้ไม่ถูกเก็บไว้ มันไม่ override Group Policy ที่นายจ้างตั้งไว้ ถ้าไม่มี -Mode script จะรัน Check

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      ใช้เวลา 10 ถึง 60 วินาทีและไม่เปลี่ยนอะไรบน router มันบันทึก backup ของ configuration ของ router ไว้ในโฟลเดอร์ router-backups ภายใน opnsense-dns บันทึก log ใน logs และรันการทดสอบจริงห้าตัว บรรทัดที่สำคัญ:

      HH:MM:SS  Router reports: OPNsense series 26.7, amd64
      HH:MM:SS  Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes)
      ...
      HH:MM:SS  Router resolves example.com            : True   (want True)
      HH:MM:SS  Router blocks the ad domain (blocklist) : True   (want True)
      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
      HH:MM:SS  Check mode: nothing was changed on the router.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.log

      บรรทัด “want True” ทั้งสองต้องเป็น True ถ้า “Router blocks the ad domain” เป็น False แสดงว่า blocklist ของคุณไม่บล็อกโดเมนทดสอบ และการทดสอบ redirect ในขั้น 6 จะล้มเหลว ตั้ง $AdTestDomain ใกล้ต้น script เป็นโดเมนที่ blocklist ของคุณบล็อก หรือเปิด blocklist ถ้าบรรทัดสีเหลืองขึ้นต้นด้วย Apply would stop: มันระบุ rule ที่ขาด: rule redirect หรือ rule allow-all ของ LAN แก้บน router ก่อนขั้น 6

      ถ้าเกิดปัญหา script พิมพ์บรรทัดสีแดง (ส่วนใหญ่มีคำว่า STOP) และไม่เปลี่ยนอะไรบน router บรรทัดนั้นบอกอะไร และหมายความว่าอย่างไร:

      • Set -Router to your router’s address: วงเล็บมุมยังอยู่ใน address จากขั้นนี้
      • Missing an argument for parameter ‘Router’: น่าจะไม่ได้รันบรรทัด address ข้างบนในหน้าต่างนี้ รันอีกครั้ง
      • -Router must start with https://: address ขึ้นต้นด้วย http:// ใช้ https://
      • STOP: Key file not found: apikey.txt ไม่อยู่ในโฟลเดอร์ opnsense-dns ทำขั้น 4 ใหม่
      • STOP: Cannot reach the router API with this key: address ผิด key ถูกลบแล้ว หรือ PC ไม่ได้อยู่ในเครือข่ายของ router เปิด address ในเบราว์เซอร์เพื่อทดสอบ
      • STOP: Script was built for OPNsense 26.7: router ของคุณรันซีรีส์อื่น และ path API ของ script อ่านมาจาก 26.7 หยุดที่นี่
      • PowerShell บอกว่าการรัน script ถูกปิด: นโยบายบน PC ของคุณบล็อก script และตัวเลือกบน command line override ไม่ได้ หยุดที่นี่
    6. รัน Apply — คำสั่งนี้เปลี่ยนค่าบน router มันเขียนทับ alias DoH_IPs ด้วย address ของรายการ Hagezi (เนื้อหาเดิมไปอยู่ใน log) เพิ่ม rule reject สองตัวถ้ายังไม่มี และเปิด rule redirect อุปกรณ์ในเครือข่ายของคุณที่คุยกับ server DNS-over-HTTPS หรือ DNS-over-TLS โดยตรงจะเสียเส้นทางนั้น นั่นคือจุดประสงค์ รันคำสั่งเดิมโดยเพิ่ม -Mode Apply:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Apply

      ใช้เวลาราวสองนาที และนานสุดสี่นาทีถ้า alias ต้องดาวน์โหลดรายการก่อน มีหนึ่งบรรทัดที่เขียนว่า Waiting 70 s for older DNS states to expire before testing...; รอมันและอย่าปิดหน้าต่าง บรรทัดสุดท้ายควรเป็น:

      HH:MM:SS  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
      HH:MM:SS  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
      HH:MM:SS  Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes)
      HH:MM:SS  Apply finished. Expected: router tests True, all three bypass tests False.
      HH:MM:SS  Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.log

      ถ้าเกิดปัญหา Apply did not complete; changes from this run were undone: การทดสอบล้มเหลว และ script ปิดสิ่งที่มันเปลี่ยน rule ที่มันเพิ่มยังอยู่ แต่ถูกปิดไว้ มันบันทึก backup ของผลลัพธ์ อ่านบรรทัดที่ขึ้นต้นด้วย Problem: เพื่อดูเหตุผล ถ้าบรรทัดใดมี UNDO STEP FAILED ให้กู้คืน backup “before” ตามที่ขั้น 8 อธิบาย Apply PARTLY finished (สีเหลือง): alias และ rule สองตัวอยู่ครบและผ่านการทดสอบ และ redirect ไม่ผ่าน บรรทัดนั้นบอกว่า redirect ถูกทิ้งไว้เปิดหรือปิด ถ้าต้องการปิดการแก้ไข ใช้ขั้น 8

    7. ตรวจว่าได้ผล รันคำสั่ง Check จากขั้น 5 อีกครั้ง:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      ตอนนี้สามบรรทัด Bypass เป็น False และสองบรรทัด Router เป็น True ในหน้าเว็บของ router คุณยังดู Firewall → Rules ได้ (เลือก LAN ในตัวเลือก interface) ซึ่ง rule สองตัว Reject DoH to known resolvers (A) และ Reject DoT/DoQ 853 from LAN (B) ปรากฏอยู่ และดู Firewall → NAT → Destination NAT ซึ่ง Redirect non-local DNS to Local เปิดใช้งานอยู่

    8. ปิดการแก้ไข กู้คืนถ้าจำเป็น และลบ key ถ้าต้องการปิดการแก้ไข รันคำสั่งโดยใช้ -Mode Rollback:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Rollback

      ใช้เวลาไม่ถึงหนึ่งนาที มันปิด rule สองตัวและ redirect และไม่ลบอะไร alias ยังอยู่ตามที่ Apply ทิ้งไว้ ถ้า redirect เปิดอยู่ก่อนที่คุณเริ่ม ตอนนี้มันปิดอยู่: เปิดกลับใน Firewall → NAT → Destination NAT

      ถ้าต้องการคืน configuration ทั้งหมดให้เป็นเหมือนก่อน Apply ให้กู้คืน backup บน router: ไปที่ System → Configuration → Backups เลือกไฟล์ชื่อ config-Apply-before-<timestamp>.xml จากโฟลเดอร์ router-backups แล้วกู้คืน การรัน Apply แต่ละครั้งบันทึกไฟล์แบบนี้หนึ่งไฟล์ ไฟล์แรกสุดเก็บ configuration จากก่อน Apply ครั้งแรกของคุณ การกู้คืนนี้จะย้อนการเปลี่ยนแปลงอื่นทุกอย่างที่ทำบน router หลังจากนั้นด้วย

      เมื่อใช้ script เสร็จ ไม่ว่าจะเก็บการแก้ไขไว้หรือไม่ ให้ลบ key บน router ไปที่ System → Access → Users คลิกดินสอที่ user เดิม และลบ key ในส่วน API keys (แท็บ ApiKeys) จากนั้นลบไฟล์ key จาก PC:

      Remove-Item .\apikey.txt

      คำสั่งนี้ลบไฟล์ทันที ไม่ผ่านถังรีไซเคิล เมื่อไม่ต้องใช้ backup อีกแล้ว ให้ลบโฟลเดอร์ router-backups ด้วย: มี hash ของรหัสผ่านและ private key อยู่

    หมายเหตุด้านความปลอดภัย script ส่ง key ไปกับทุก request มันไม่พิมพ์หรือเขียน secret ลง log และชุดทดสอบตรวจเรื่องนั้นในทั้ง 30 กรณี การตรวจ certificate ของมันยอมรับ certificate ใดก็ได้ที่แสดงสำหรับ address ของ router ดังนั้นอุปกรณ์ใน LAN ที่ปลอมตัวเป็น router จะได้ key ไป ผมลบ key ของผมเมื่อ 13 ตุลาคม 2026 สองวันหลังการรัน และประวัติ configuration ของ router บันทึกการลบนั้นไว้

    backup คือ configuration ทั้งหมดของ router: hash ของรหัสผ่าน และ private key ของ certificate และ VPN tunnel ต่าง ๆ เก็บโฟลเดอร์นั้นไว้เป็นส่วนตัว และอย่าแนบ backup ไปกับโพสต์ในฟอรัม

    เจาะลึก: การตรวจอื่น ๆ ของ script
    • backup ต้องดูเหมือน backup หลังดาวน์โหลด script ตรวจว่าไฟล์มีขนาดอย่างน้อย 50,000 ไบต์ และมี <opnsense> ในสามบรรทัดแรก
    • การ save ที่ล้มเหลวจะถูกจับได้ คำตอบที่มี validations นับเป็นการ save ที่ล้มเหลว เหมือนที่หน้าเว็บของ router เองทำ result ที่เป็น failed ก็เช่นกัน การเปลี่ยน alias และ redirect จะถูกอ่านกลับมาตรวจ การเปลี่ยน rule ตรวจจากการมีอยู่และลำดับของ rule และจากการทดสอบ connection จริง
    • ลำดับ rule หลังเพิ่ม Rule A และ B script จะหยุดถ้า rule ตัวใดเรียงอยู่หลัง “Default allow LAN to any rule” เพราะ rule ที่อยู่ใต้ rule allow-all จะไม่มีวัน match
    • alias ต้องมีข้อมูลเข้ามา script ตรวจ alias ทุก 5 วินาที นานสูงสุด 90 วินาที และหยุดถ้า alias มี address ไม่ถึง 500 รายการ
    • การท่องเว็บปกติต้องยังใช้ได้ ก่อนจะสรุปว่า rule ใช้ได้ script เปิด connection ไปที่ www.google.com:443
    • ผลที่สำเร็จบางส่วนจะบอกว่าเป็นเช่นนั้น ถ้าล้มเหลวเฉพาะขั้น redirect การรันจะจบด้วย Apply PARTLY finished บอกว่าทิ้ง redirect ไว้ในสถานะใด และออกด้วย exit code 2
    เจาะลึก: ยอมรับ certificate ที่ไม่ผ่านการตรวจ เฉพาะ address ของ router

    หน้าเว็บของ router ใช้ certificate แบบ self-signed PowerShell 7 มี -SkipCertificateCheck ซึ่ง script ใช้ในกรณีนั้น Windows PowerShell 5.1 ไม่มี switch นี้ วิธีแก้ที่ใช้กันทั่วไปคือ callback ที่ยอมรับทุก certificate ตลอดทั้ง session callback ของ script ยอมรับการตรวจ certificate ที่ล้มเหลวเฉพาะเมื่อ host ของ request เป็น address ของ router:

    public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
        if (e == SslPolicyErrors.None) return true;
        HttpWebRequest r = sender as HttpWebRequest;
        return r != null && r.RequestUri.Host == Host;
    }

    วิธีนี้ทำให้ข้อยกเว้นแคบลง แต่ไม่ได้ pin certificate: certificate ใดก็ตามที่แสดงสำหรับ address นั้นจะผ่าน การตรวจ thumbprint ของ certificate จะปิดช่องว่างนั้นได้ script ยังตั้ง TLS 1.2 สำหรับ 5.1 ด้วย

    เจาะลึก: มาตรการป้องกันไว้ก่อน ไม่ใช่ความล้มเหลว: Expect: 100-continue

    โหมด Check ส่งเฉพาะ request แบบ GET ส่วน Apply ส่ง POST Windows PowerShell 5.1 รันบน .NET Framework ซึ่ง ServicePointManager.Expect100Continue เป็น true โดย default และเพิ่ม header Expect: 100-continue ให้ request แบบ POST ที่มี body (เอกสารของ Microsoft) เวอร์ชัน 2.2 ปิด header นี้ก่อน request แรก:

    [Net.ServicePointManager]::Expect100Continue = $false

    ผมไม่ได้ทดสอบว่า web server ของ router จะมีปัญหากับ header นี้หรือไม่

    เจาะลึก: การรันที่สำเร็จ ทีละบรรทัด

    log ของการรันเมื่อ 15:04 address ของ router และชื่อของ interface หนึ่งของมันถูกแทนด้วย placeholder ในวงเล็บมุม โฟลเดอร์ในเครื่องและหมายเลข build ของ PowerShell ถูกตัดออก และตัวเลขในจำนวนไบต์ถูกจัดกลุ่มทีละสามหลัก การทดสอบตอนเริ่มแสดงว่าทางเลี่ยง blocklist ทั้งสามทางเปิดอยู่ การทดสอบตอนจบแสดงว่าทั้งสามทางปิดแล้ว สำหรับ address IPv4 สามตัวที่ทดสอบ

    15:04:49  Mode: Apply   Router: https://<router-ip-address>   PowerShell 5.1
    15:04:55  Router reports: OPNsense series 26.7, amd64
    15:04:55  Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
    15:04:56  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:04:56  Rule A: present, enabled=0, sort_order=400000.0000100
    15:04:56  Rule B: present, enabled=0, sort_order=400000.0000200
    15:04:56  'Default allow LAN to any rule': sort_order=400000.1000023
    15:04:56  NAT 'Redirect non-local DNS to Local': disabled=1
    15:04:56  Router resolves example.com            : True   (want True)
    15:04:56  Router blocks the ad domain (blocklist) : True   (want True)
    15:04:56  Bypass DoH  1.1.1.1:443 reachable       : True   (want False after Apply)
    15:04:56  Bypass DoT  9.9.9.9:853 reachable       : True   (want False after Apply)
    15:04:56  Bypass 8.8.8.8 gives real ad IPs        : True   (want False after Apply)
    15:04:56  Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
    15:04:58  Alias DoH_IPs holds 1434 addresses.
    15:04:58  Rule 'Reject DoH to known resolvers (A)' enabled.
    15:04:58  Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
    15:04:58  Firewall rules applied. Verifying...
    15:05:08  Rules A and B verified: DoH and DoT refused, normal HTTPS works.
    15:05:08  NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
    15:06:18  NAT redirect verified: queries to 8.8.8.8 are answered by your router.
    15:06:19  Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
    15:06:19  Rule A: present, enabled=1, sort_order=400000.0000100
    15:06:19  Rule B: present, enabled=1, sort_order=400000.0000200
    15:06:19  'Default allow LAN to any rule': sort_order=400000.1000023
    15:06:19  NAT 'Redirect non-local DNS to Local': disabled=0
    15:06:23  Router resolves example.com            : True   (want True)
    15:06:23  Router blocks the ad domain (blocklist) : True   (want True)
    15:06:23  Bypass DoH  1.1.1.1:443 reachable       : False   (want False after Apply)
    15:06:23  Bypass DoT  9.9.9.9:853 reachable       : False   (want False after Apply)
    15:06:23  Bypass 8.8.8.8 gives real ad IPs        : False   (want False after Apply)
    15:06:23  Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
    15:06:23  Apply finished. Expected: router tests True, all three bypass tests False.

    alias มีรายการหนึ่งที่ผมไม่ได้ตั้งใจใส่ไว้: network ของ interface หนึ่งของ router อยู่ก่อน URL การรันพิมพ์เนื้อหาเดิมออกมาก่อนแทนที่ จึงคืนค่าได้จาก log

    เจาะลึก: ชุดทดสอบตรวจอะไร และตรวจอะไรไม่ได้

    mock ตอบ path API ที่ script ใช้ เก็บสถานะของ router ไว้ในหน่วยความจำ บันทึกทุกการเรียก และตั้งให้ทำตัวผิดปกติได้: เวอร์ชันผิด, API key ไม่ถูกต้อง, backup ขนาดเล็ก, backup ที่ล้มเหลวหลังมีการเปลี่ยนแปลง, alias ชนิดผิด, คำตอบที่มี key ว่าง, การ save ที่ router ปฏิเสธ, alias ที่ไม่มีข้อมูลเข้ามา, rule ที่เรียงอยู่ใต้ rule allow-all, DoH ที่ยังเข้าถึงได้, HTTPS ปกติใช้ไม่ได้, rule redirect หรือ rule allow-all ที่ไม่มีอยู่, redirect ที่ไม่มีผล และ redirect ที่เปิดอยู่แล้ว มันยังจำลองสถานะที่ router ของผมผ่านมา: alias ที่มีรายการแปลกปลอม, rule สองตัวที่เวอร์ชัน 2.3 ปิดทิ้งไว้ และสถานะที่ apply ทุกอย่างแล้ว คำตอบที่มี key ว่างของมันเขียนด้วยมือ ตามแบบคำตอบ get_item ของ router และตอบบน endpoint ที่ script อ่าน

    harness รัน script ครั้งละหนึ่งกรณี เป็น process แยก และตรวจ exit code, log, ไฟล์ backup, ทุกการเรียกที่ mock ได้รับ และสถานะของ mock router ตอนจบ ในทุกกรณี มันตรวจว่าทั้ง secret และ key ที่ encode แล้วไม่ปรากฏใน output หรือ log ว่าไม่มีอะไรถูกลบ และว่าการหยุดหลังเปิด log แล้วถูกเขียนลง log

    harness ทดสอบสำเนาของ script ไม่ใช่ตัว script เอง ในสำเนานั้น การทดสอบเครือข่ายสองตัวจะถาม mock แทนอินเทอร์เน็ต และทุกการรอถูกตัดเหลือหนึ่งมิลลิวินาที ก่อนรันกรณีใด ๆ harness ตรวจว่าแต่ละ pattern เหล่านั้น match ตามจำนวนครั้งที่คาดไว้ สำเนานั้นคุยกับ mock ผ่าน HTTP ธรรมดาบน PC ส่วน script ยอมรับ HTTP ธรรมดาเฉพาะ address บน PC เครื่องนั้นเองเท่านั้น

    ดังนั้นชุดทดสอบไม่ได้ทดสอบ: การตรวจ certificate และ TLS; การทดสอบเครือข่ายจริง; ความล้มเหลวครั้งที่ 3 เพราะ mock ไม่มี state table และการรอถูกตัดสั้น; คำตอบจาก router จริง ยกเว้นคำตอบ key ว่างที่เขียนด้วยมือหนึ่งตัว; การที่ script ไม่ยอมเขียนทับ backup; ทางสำรองสำหรับโฟลเดอร์ทำงาน เพราะทุกกรณีระบุโฟลเดอร์ไว้; หรือขั้น undo ที่ตัวมันเองล้มเหลว

    การทำพังโดยตั้งใจสิบแบบ และกรณีที่แต่ละแบบทำให้ล้มเหลว อยู่ในรายการพร้อมชุดทดสอบท้ายหน้า

    เจาะลึก: บันทึกเกี่ยวกับ API ของ OPNsense 26.7
    • header ของ script บันทึกว่า path ของ configuration แต่ละตัวนำมาจากหน้าเว็บของ router เองในวันนั้น: alias/search_item, alias/add_item, alias/set_item, alias/reconfigure, filter/search_rule, filter/add_rule, filter/set_rule, filter/apply, d_nat/search_rule, d_nat/set_rule, d_nat/apply, alias_util/list และ core/backup/download/this มันยังเรียก core/firmware/info เพื่อดูเวอร์ชัน และ core/firmware/status เพื่อตรวจว่าเข้าถึง router ได้
    • endpoint สำหรับค้นหาตอบ GET ที่มี ?rowCount=-1&current=1 และคืนทุกแถว พร้อม field ที่ script ต้องใช้
    • alias/get_item คืนรายการตัวเลือกที่มี key ชื่อว่าง ซึ่ง PowerShell แปลงเป็น property ของ object ไม่ได้
    • GET /api/core/backup/download/this คืน configuration ทั้งหมดเป็น XML
    • body ของ POST เป็น JSON พร้อม Content-Type: application/json การเปลี่ยน rule มีผลหลัง apply ที่คู่กัน การเปลี่ยน alias มีผลหลัง reconfigure
    อภิธานศัพท์
    • Windows PowerShell 5.1: PowerShell ที่มากับ Windows สร้างบน .NET Framework เรียกใช้ด้วย powershell
    • PowerShell 7: PowerShell รุ่นใหม่ ติดตั้งแยก สร้างบน .NET รุ่นใหม่ เรียกใช้ด้วย pwsh
    • REST API: ชุดของ web address ที่โปรแกรมเรียกเพื่ออ่านหรือเปลี่ยนค่าตั้ง คำตอบของ OPNsense เป็น JSON
    • JSON: รูปแบบข้อความสำหรับข้อมูลที่มีโครงสร้าง
    • Mock: ตัวแทนของระบบจริงที่ใช้ทดสอบ ในที่นี้คือ web server ขนาดเล็กที่ตอบเหมือน router
    • Test harness: script ที่รัน script อีกตัวในสถานการณ์ที่กำหนดไว้หลายแบบ และตรวจผลลัพธ์
    • API key: key และ secret ที่ให้ script ทำงานในฐานะ user ของ router โดยไม่ต้องใช้รหัสผ่าน
    • Alias (URL table): รายการ address ของ OPNsense ที่ router ดาวน์โหลดจาก web address และ refresh
    • NAT redirect: rule ที่เปลี่ยนปลายทางของทราฟฟิกที่ match ในที่นี้ใช้ส่ง query DNS ที่ส่งไปยัง server อื่นกลับมาที่ router
    • State table: รายการ connection ที่ firewall เคยเห็นแล้ว packet ถัดไปของ connection ที่รู้จักจะทำตามการตัดสินใจที่ทำไว้กับ packet แรก
    • DoH, DoT: DNS over HTTPS (port 443) และ DNS over TLS (port 853) สองวิธีที่อุปกรณ์ใช้ค้นหาชื่อโดยไม่ต้องถาม router
    • Expect: 100-continue: header ของ HTTP ที่ขอให้ server อนุมัติ request ก่อนส่ง body

    The script, the mock router and the test harness

    Code is the same in every language. MIT licence. कोड हर भाषा में एक ही है। కోడ్ అన్ని భాషలలో ఒకేలా ఉంటుంది. โค้ดเหมือนกันทุกภาษา

    opnsense-dns-bypass.ps1 (version 2.5.1)
    <#
      opnsense-dns-bypass.ps1   (version 2.5.1, 28/10/2026)
      Prepared by Vivek Sanghi with Claude (Anthropic).
      Copyright (c) 2026 Vivek Sanghi. MIT licence: see the end of this header.
      Built for: OPNsense 26.7 series (amd64). Version 2.4 of this script ran against the author's router
      on 11/10/2026. Version 2.5.1 has been tested only against the mock router published with it.
      Changes from 2.4:
        - the router address is a placeholder you must replace; https is required (plain http is
          accepted only for an address on this PC, as the test kit uses)
        - Apply stops before changing anything if the NAT rule or the LAN allow rule is not found
        - an undo of the alias restores its enabled flag as well as its contents
        - messages corrected: the NAT stage says what state it left the redirect in, a failed backup
          says whether changes had been made, and every stop after the log file is opened is
          written to the log (the checks on -Router and the work folder stop earlier, on screen only)
        - the test domain and the NAT wait are settings near the top
        - this header: usage, scope and limits, firmware paths, licence
      Every API path used here was taken from the router's own web pages on that date:
        Aliases page       : alias/search_item, alias/add_item, alias/set_item, alias/reconfigure
        Rules page         : filter/search_rule, filter/add_rule, filter/set_rule, filter/apply
      get_item/get_rule are NOT used: their replies contain empty JSON keys ("":), which PowerShell
      cannot turn into object properties, so Invoke-RestMethod returns raw text. Checked 11/10/2026.
        Destination NAT    : d_nat/search_rule, d_nat/set_rule, d_nat/apply
        Diagnostics        : alias_util/list ; Backups: core/backup/download/this
      Also used, not listed in 2.4's header: core/firmware/info (version check), core/firmware/status (reachability).
      The script stops before changing anything if the router reports a different OPNsense series.
    
      What it does (Apply):
        1. Alias  DoH_IPs : URL table, Hagezi DoH IP list, refresh daily (created, or cleaned to the URL only)
        2. Rule A : LAN in, reject TCP/UDP to DoH_IPs port 443
        3. Rule B : LAN in, reject TCP/UDP to any port 853
        4. NAT    : "Redirect non-local DNS to Local" (port 53) switched ON (the rule must already exist)
    
      Scope and limits (read before running):
        - IPv4 only. Rules A and B are created for IPv4 (ipprotocol inet) and every test uses an IPv4
          address. If your LAN has IPv6, DoH and DoT over IPv6 are neither blocked nor tested.
        - LAN interface only (interface 'lan'). Other interfaces and VLANs are not covered.
        - Rules A and B apply to every host on the LAN. A Pi-hole or AdGuard Home on the LAN that uses
          DoH or DoT upstream loses its upstream.
        - The NAT rule must already exist (Firewall > NAT > Destination NAT) with the description in
          $NatDesc. The script only switches it on or off; it does not create it or check how it is built.
        - The alias named in $AliasName is overwritten with the Hagezi URL; its old contents are logged.
        - $AdTestDomain must be blocked by your router's DNS blocklist and answered as 0.0.0.0.
        - Rollback switches the NAT rule off even if it was on before you first ran Apply.
        - The API key acts as an OPNsense user. A root user's key gives full control of the router, to
          the script and to anyone who obtains the key. The certificate check accepts any certificate
          presented for the router's address, so a LAN device posing as the router would receive the key.
    
      Modes:
        -Mode Check     (default) Backup, then READ-ONLY report and live tests.
        -Mode Apply     Backup, check that the NAT rule and the LAN allow rule exist, make the changes and
                        verify them; on a failure it undoes what this run changed. If only the NAT stage
                        fails, only the NAT change is undone and it exits with code 2.
        -Mode Rollback  Backup, then DISABLE rules A and B and the NAT rule. Nothing is deleted.
    
      Files written on this PC (never overwritten):
        <WorkDir>\router-backups\config-<mode>-<before|after>-<timestamp>.xml
        <WorkDir>\logs\run-<mode>-<timestamp>.log
      The API secret is read from -KeyFile and is never printed or logged.
    
      Usage (Windows PowerShell 5.1):
        powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router https://<router-ip-address>
        Add -Mode Apply or -Mode Rollback to change the router; without -Mode it only checks.
    
      MIT licence
      Permission is hereby granted, free of charge, to any person obtaining a copy of this software
      and associated documentation files (the "Software"), to deal in the Software without restriction,
      including without limitation the rights to use, copy, modify, merge, publish, distribute,
      sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
      furnished to do so, subject to the following conditions:
      The above copyright notice and this permission notice shall be included in all copies or
      substantial portions of the Software.
      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
      NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
      NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
      OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
      CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    #>
    [CmdletBinding()]
    param(
        [ValidateSet('Check','Apply','Rollback')]
        [string]$Mode = 'Check',
        [Parameter(Mandatory = $true)]
        [string]$KeyFile,
        [string]$Router = 'https://<router-ip-address>',
        [string]$WorkDir = $PSScriptRoot
    )
    
    $ErrorActionPreference = 'Stop'
    Set-StrictMode -Version 1
    $LogFile = $null
    
    # $PSScriptRoot in a param() default can be empty under Windows PowerShell 5.1, so resolve the folder here.
    if ([string]::IsNullOrWhiteSpace($WorkDir)) {
        if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
        else { $WorkDir = (Get-Location).Path }
    }
    if (-not (Test-Path -LiteralPath $WorkDir -PathType Container)) { Write-Host "Work folder not found: $WorkDir" -ForegroundColor Red; exit 1 }
    if ($Router -match '[<>]') { Write-Host "Set -Router to your router's address, for example -Router https://192.168.1.1 . Nothing was done." -ForegroundColor Red; exit 1 }
    try { $RouterUri = [Uri]$Router } catch { Write-Host "-Router is not a valid address: $Router . Nothing was done." -ForegroundColor Red; exit 1 }
    if ($RouterUri.Scheme -ne 'https' -and -not $RouterUri.IsLoopback) { Write-Host "-Router must start with https:// because the API key goes with every request. Nothing was done." -ForegroundColor Red; exit 1 }
    
    # ---------- fixed settings ----------
    $ExpectedSeries = '26.7'
    $AliasName   = 'DoH_IPs'
    $AliasUrl    = 'https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt'
    $AliasDesc   = 'Hagezi DoH resolver IPs'
    $DescA       = 'Reject DoH to known resolvers (A)'
    $DescB       = 'Reject DoT/DoQ 853 from LAN (B)'
    $NatDesc     = 'Redirect non-local DNS to Local'
    $AllowLan    = 'Default allow LAN to any rule'
    $AdTestDomain   = 'googleads.g.doubleclick.net'   # must be blocked by your router's blocklist (answered as 0.0.0.0)
    $NatWaitSeconds = 70   # longer than the router's udp.first / udp.multiple timeouts (Firewall > Diagnostics > Statistics)
    $MinAliasIPs = 500
    $RuleDefs = @(
        @{ description = $DescA; destination_net = $AliasName; destination_port = '443' },
        @{ description = $DescB; destination_net = 'any';      destination_port = '853' }
    )
    
    # ---------- logging ----------
    $stamp  = Get-Date -Format 'yyyyMMdd-HHmmss'
    $logDir = Join-Path $WorkDir 'logs'
    New-Item -ItemType Directory -Force -Path $logDir | Out-Null
    $LogFile = Join-Path $logDir ("run-{0}-{1}.log" -f $Mode, $stamp)
    function Log([string]$msg, [string]$color = 'Gray') {
        $line = '{0}  {1}' -f (Get-Date -Format 'HH:mm:ss'), $msg
        Write-Host $line -ForegroundColor $color
        if ($LogFile) { Add-Content -Path $LogFile -Value $line }
    }
    function Fail([string]$msg) { Log "STOP: $msg" 'Red'; Log "Log file: $LogFile" 'Red'; exit 1 }
    # Any error that no try/catch below handles is written to the log before the script stops.
    trap { Log "STOP: $($_.Exception.Message)" 'Red'; Log "Log file: $LogFile" 'Red'; exit 1 }
    
    # ---------- API key ----------
    if (-not (Test-Path -LiteralPath $KeyFile)) { Fail "Key file not found: $KeyFile" }
    $kv = @{}
    foreach ($l in Get-Content -LiteralPath $KeyFile) {
        if ($l -match '^\s*(key|secret)\s*=\s*(\S+)\s*$') { $kv[$Matches[1]] = $Matches[2] }
    }
    if (-not $kv.ContainsKey('key') -or -not $kv.ContainsKey('secret')) { Fail "Key file must contain lines key=... and secret=..." }
    $Auth = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($kv['key'] + ':' + $kv['secret']))
    $kv = $null
    
    # ---------- TLS: accept the router's self-signed certificate, for the router's address only ----------
    $IsPS7 = $PSVersionTable.PSVersion.Major -ge 6
    if (-not $IsPS7) {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        # Windows PowerShell 5.1 adds 'Expect: 100-continue' to POSTs; switch it off so the router's web server gets a plain request.
        [Net.ServicePointManager]::Expect100Continue = $false
        if (-not ('RouterCertTrust' -as [type])) {
            Add-Type -TypeDefinition @"
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public static class RouterCertTrust {
        public static string Host;
        public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
            if (e == SslPolicyErrors.None) return true;
            HttpWebRequest r = sender as HttpWebRequest;
            return r != null && r.RequestUri.Host == Host;
        }
        public static void Enable(string host) {
            Host = host;
            ServicePointManager.ServerCertificateValidationCallback = Check;
        }
    }
    "@
        }
        [RouterCertTrust]::Enable(([Uri]$Router).Host)
    }
    
    # ---------- API helper ----------
    function Api([string]$Method, [string]$Path, $Body = $null) {
        $p = @{ Uri = $Router + $Path; Method = $Method; Headers = @{ Authorization = $Auth }; TimeoutSec = 60 }
        if ($Method -eq 'POST') {
            if ($null -eq $Body) { $p.Body = '{}' } else { $p.Body = ($Body | ConvertTo-Json -Depth 10 -Compress) }
            $p.ContentType = 'application/json'
        }
        if ($IsPS7) { $p.SkipCertificateCheck = $true }
        $r = Invoke-RestMethod @p
        if ($r -is [string]) {
            $t = $r.TrimStart()
            if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
        }
        return $r
    }
    function Assert-Saved($resp, [string]$what) {
        # The router's own GUI (opnsense_ui.js) treats a reply carrying 'validations' as a failure.
        # A reply with result 'failed' is also a failure. Every save is additionally verified by reading state back.
        $names = @()
        if ($resp) { $names = @($resp.PSObject.Properties.Name) }
        $bad = (-not $resp) -or ($names -contains 'validations') -or (($names -contains 'result') -and "$($resp.result)" -eq 'failed')
        if ($bad) { throw "$what was not saved. Router replied: $($resp | ConvertTo-Json -Compress -Depth 6)" }
    }
    
    # ---------- live tests from this PC ----------
    function Test-Tcp([string]$TargetHost, [int]$Port, [int]$Ms = 4000) {
        $c = New-Object Net.Sockets.TcpClient
        try {
            $t = $c.ConnectAsync($TargetHost, $Port)
            if ($t.Wait($Ms)) { return $c.Connected } else { return $false }
        } catch { return $false } finally { $c.Dispose() }
    }
    function Get-ARecords([string]$Name, [string]$Server) {
        try {
            $a = Resolve-DnsName -Name $Name -Server $Server -Type A -DnsOnly -QuickTimeout -ErrorAction Stop
            return @($a | Where-Object { $_.Type -eq 'A' } | ForEach-Object { $_.IPAddress })
        } catch { return @() }
    }
    function Test-Leaks([string]$Server) {
        # $true if $Server hands out a real address for $AdTestDomain, which your blocklist blocks
        $ips = Get-ARecords $AdTestDomain $Server
        return (@($ips | Where-Object { $_ -ne '0.0.0.0' }).Count -gt 0)
    }
    function Show-Tests {
        $routerHost = ([Uri]$Router).Host
        $r = [ordered]@{
            RouterResolves = (@(Get-ARecords 'example.com' $routerHost).Count -gt 0)
            RouterBlocks   = (-not (Test-Leaks $routerHost))
            DoH443Open     = (Test-Tcp '1.1.1.1' 443)
            DoT853Open     = (Test-Tcp '9.9.9.9' 853)
            Google53Leaks  = (Test-Leaks '8.8.8.8')
        }
        Log ("Router resolves example.com            : {0}   (want True)" -f $r.RouterResolves)
        Log ("Router blocks the ad domain (blocklist) : {0}   (want True)" -f $r.RouterBlocks)
        Log ("Bypass DoH  1.1.1.1:443 reachable       : {0}   (want False after Apply)" -f $r.DoH443Open)
        Log ("Bypass DoT  9.9.9.9:853 reachable       : {0}   (want False after Apply)" -f $r.DoT853Open)
        Log ("Bypass 8.8.8.8 gives real ad IPs        : {0}   (want False after Apply)" -f $r.Google53Leaks)
        return $r
    }
    
    # ---------- router state ----------
    function Get-State {
        $aliases = Api GET '/api/firewall/alias/search_item?rowCount=-1&current=1'
        $alias   = @($aliases.rows | Where-Object { $_.name -eq $AliasName }) | Select-Object -First 1
        $rules   = Api GET '/api/firewall/filter/search_rule?rowCount=-1&current=1'
        $mvc     = @($rules.rows | Where-Object { -not (($_.PSObject.Properties.Name -contains 'legacy') -and $_.legacy) })
        $ruleA   = @($mvc | Where-Object { $_.description -eq $DescA }) | Select-Object -First 1
        $ruleB   = @($mvc | Where-Object { $_.description -eq $DescB }) | Select-Object -First 1
        $allow   = @($rules.rows | Where-Object { $_.description -eq $AllowLan }) | Select-Object -First 1
        $nats    = Api GET '/api/firewall/d_nat/search_rule?rowCount=-1&current=1'
        $nat     = @($nats.rows | Where-Object { $_.descr -eq $NatDesc }) | Select-Object -First 1
        $count   = 0
        if ($alias) { try { $count = [int](Api GET "/api/firewall/alias_util/list/$AliasName").total } catch { $count = 0 } }
        return [pscustomobject]@{ Alias = $alias; AliasCount = $count; RuleA = $ruleA; RuleB = $ruleB; Allow = $allow; Nat = $nat }
    }
    function Show-State($s) {
        if ($s.Alias) {
            $c = ("$($s.Alias.content)" -replace "`r?`n", ' | ')
            Log ("Alias {0}: present, enabled={1}, entries loaded={2}, content=[{3}]" -f $AliasName, $s.Alias.enabled, $s.AliasCount, $c)
        } else { Log ("Alias {0}: not present" -f $AliasName) }
        foreach ($pair in @(@('Rule A', $s.RuleA), @('Rule B', $s.RuleB))) {
            $r = $pair[1]
            if ($r) { Log ("{0}: present, enabled={1}, sort_order={2}" -f $pair[0], $r.enabled, $r.sort_order) }
            else    { Log ("{0}: not present" -f $pair[0]) }
        }
        if ($s.Allow) { Log ("'{0}': sort_order={1}" -f $AllowLan, $s.Allow.sort_order) }
        if ($s.Nat)   { Log ("NAT '{0}': disabled={1}" -f $NatDesc, $s.Nat.disabled) }
        else          { Log ("NAT '{0}': NOT FOUND" -f $NatDesc) 'Yellow' }
    }
    
    # ---------- backup ----------
    function Save-Backup([string]$when) {
        $dir = Join-Path $WorkDir 'router-backups'
        New-Item -ItemType Directory -Force -Path $dir | Out-Null
        $file = Join-Path $dir ("config-{0}-{1}-{2}.xml" -f $Mode, $when, $stamp)
        if (Test-Path -LiteralPath $file) { Fail "Backup file already exists, refusing to overwrite: $file" }
        $p = @{ Uri = "$Router/api/core/backup/download/this"; Method = 'GET'; Headers = @{ Authorization = $Auth }; OutFile = $file; UseBasicParsing = $true; TimeoutSec = 60 }
        if ($IsPS7) { $p.SkipCertificateCheck = $true }
        Invoke-WebRequest @p | Out-Null
        $size = (Get-Item -LiteralPath $file).Length
        $head = (Get-Content -LiteralPath $file -TotalCount 3) -join ' '
        if ($size -lt 50000 -or $head -notmatch '<opnsense>') {
            if ($when -eq 'before') { Fail "Backup looks wrong ($size bytes): $file. Nothing changed on the router." }
            Fail "Backup ($when) looks wrong ($size bytes): $file. The changes logged above were made; check the router."
        }
        Log ("Backup ({0}) saved: {1} ({2:N0} bytes)" -f $when, $file, $size) 'Green'
    }
    
    # ================= START =================
    Log "Mode: $Mode   Router: $Router   PowerShell $($PSVersionTable.PSVersion)"
    try { $info = Api GET '/api/core/firmware/info' } catch { Fail "Cannot reach the router API with this key: $($_.Exception.Message)" }
    $series = "$($info.product.product_series)"
    Log ("Router reports: {0} series {1}, {2}" -f $info.product.product_name, $series, $info.product.product_arch)
    if ($series -ne $ExpectedSeries) { Fail "Script was built for OPNsense $ExpectedSeries; router reports $series. Nothing changed. Check the API paths against your router's own web pages before changing ExpectedSeries." }
    
    # Backup next (after the version check), in every mode, before any configuration is read or changed.
    Save-Backup 'before'
    
    $state = Get-State
    Show-State $state
    $tests = Show-Tests
    
    # Apply needs both of these before it changes anything; Check reports them.
    $problems = @()
    if (-not $state.Nat)   { $problems += "NAT rule '$NatDesc' not found. Create it in Firewall > NAT > Destination NAT, or set `$NatDesc to its description." }
    if (-not $state.Allow) { $problems += "Rule '$AllowLan' not found, so rule order cannot be checked. Set `$AllowLan to the description of your LAN allow-all rule." }
    if ($Mode -eq 'Check') {
        foreach ($p in $problems) { Log "Apply would stop: $p" 'Yellow' }
        Log 'Check mode: nothing was changed on the router.' 'Green'; Log "Log file: $LogFile"; exit 0
    }
    if ($Mode -eq 'Apply' -and $problems.Count -gt 0) { Fail (($problems -join ' ') + ' Nothing changed.') }
    
    # ---------- undo bookkeeping ----------
    $Undo = New-Object System.Collections.ArrayList
    function Invoke-Undo {
        if ($Undo.Count -eq 0) { Log 'Nothing to undo.'; return }
        Log 'Undoing changes made in this run...' 'Yellow'
        for ($i = $Undo.Count - 1; $i -ge 0; $i--) {
            $u = $Undo[$i]
            try {
                switch ($u.kind) {
                    'rule'         { $null = Api POST "/api/firewall/filter/set_rule/$($u.uuid)" @{ rule = @{ enabled = '0' } }; $null = Api POST '/api/firewall/filter/apply'; Log "  rule $($u.uuid) disabled" 'Yellow' }
                    'nat'          { $null = Api POST "/api/firewall/d_nat/set_rule/$($u.uuid)" @{ rule = @{ disabled = '1' } }; $null = Api POST '/api/firewall/d_nat/apply'; Log '  NAT rule switched back off' 'Yellow' }
                    'aliascontent' { $null = Api POST "/api/firewall/alias/set_item/$($u.uuid)" @{ alias = @{ content = $u.old; enabled = $u.oldEnabled } }; $null = Api POST '/api/firewall/alias/reconfigure'; Log '  alias content and enabled flag restored (refresh interval left at 1 day)' 'Yellow' }
                    'aliasnew'     { $null = Api POST "/api/firewall/alias/set_item/$($u.uuid)" @{ alias = @{ enabled = '0' } }; $null = Api POST '/api/firewall/alias/reconfigure'; Log '  new alias disabled' 'Yellow' }
                }
            } catch { Log "  UNDO STEP FAILED ($($u.kind)): $($_.Exception.Message). Restore the 'before' backup from System > Configuration > Backups." 'Red' }
        }
    }
    
    # ================= ROLLBACK =================
    if ($Mode -eq 'Rollback') {
        try {
            $changed = $false
            foreach ($r in @($state.RuleA, $state.RuleB)) {
                if ($r -and "$($r.enabled)" -eq '1') {
                    Assert-Saved (Api POST "/api/firewall/filter/set_rule/$($r.uuid)" @{ rule = @{ enabled = '0' } }) "Disable rule '$($r.description)'"
                    Log "Disabled rule '$($r.description)'" 'Yellow'; $changed = $true
                }
            }
            if ($changed) { $null = Api POST '/api/firewall/filter/apply'; Log 'Firewall rules applied.' }
            if ($state.Nat -and "$($state.Nat.disabled)" -ne '1') {
                Assert-Saved (Api POST "/api/firewall/d_nat/set_rule/$($state.Nat.uuid)" @{ rule = @{ disabled = '1' } }) 'Disable NAT rule'
                $null = Api POST '/api/firewall/d_nat/apply'
                Log "Disabled NAT rule '$NatDesc' and applied." 'Yellow'
            }
        } catch { Fail "Rollback error: $($_.Exception.Message)" }
        Start-Sleep -Seconds 3
        Show-State (Get-State); $null = Show-Tests
        Save-Backup 'after'
        Log 'Rollback finished.' 'Green'; Log "Log file: $LogFile"; exit 0
    }
    
    # ================= APPLY =================
    if (-not $tests.RouterResolves) { Fail 'The router itself is not resolving example.com. Fix that first; nothing changed.' }
    
    try {
        # ---- 1. Alias ----
        if (-not $state.Alias) {
            $body = @{ alias = @{ enabled = '1'; name = $AliasName; type = 'urltable'; updatefreq = '1'; content = $AliasUrl; description = $AliasDesc } }
            $r = Api POST '/api/firewall/alias/add_item' $body
            Assert-Saved $r "Alias $AliasName"
            $newId = "$($r.uuid)"
            if (-not $newId) { $newId = "$((@((Api GET '/api/firewall/alias/search_item?rowCount=-1&current=1').rows | Where-Object { $_.name -eq $AliasName }) | Select-Object -First 1).uuid)" }
            [void]$Undo.Add(@{ kind = 'aliasnew'; uuid = $newId })
            Log "Alias $AliasName created." 'Green'
        } else {
            $uuid = "$($state.Alias.uuid)"
            $oldContent = ("$($state.Alias.content)" -replace "`r`n", "`n").Trim()
            if ("$($state.Alias.type)" -ne 'urltable') { throw "Existing alias $AliasName is type '$($state.Alias.type)', not urltable. Fix or delete it in the GUI, then rerun." }
            if ($oldContent -ne $AliasUrl -or "$($state.Alias.enabled)" -ne '1') {
                Assert-Saved (Api POST "/api/firewall/alias/set_item/$uuid" @{ alias = @{ enabled = '1'; content = $AliasUrl; updatefreq = '1' } }) "Clean alias $AliasName"
                [void]$Undo.Add(@{ kind = 'aliascontent'; uuid = $uuid; old = $oldContent; oldEnabled = "$($state.Alias.enabled)" })
                Log ("Alias {0} set to the URL only (was: {1})." -f $AliasName, ($oldContent -replace "`r?`n", ' | ')) 'Green'
            } else { Log "Alias $AliasName already correct." }
        }
        $null = Api POST '/api/firewall/alias/reconfigure'
        $nowRow = @((Api GET '/api/firewall/alias/search_item?rowCount=-1&current=1').rows | Where-Object { $_.name -eq $AliasName }) | Select-Object -First 1
        if (-not $nowRow) { throw "Alias $AliasName not found after saving." }
        $nowContent = ("$($nowRow.content)" -replace "`r`n", "`n").Trim()
        if ($nowContent -ne $AliasUrl) { throw "Alias $AliasName content reads back as [$($nowContent -replace "`r?`n", ' | ')], not the URL alone." }
        $count = 0
        for ($i = 0; $i -lt 18; $i++) {
            try { $count = [int](Api GET "/api/firewall/alias_util/list/$AliasName").total } catch { $count = 0 }
            if ($count -ge $MinAliasIPs) { break }
            Start-Sleep -Seconds 5
        }
        if ($count -lt $MinAliasIPs) { throw "Alias $AliasName loaded only $count entries after 90 s." }
        Log "Alias $AliasName holds $count addresses." 'Green'
    
        # ---- 2. Rules A and B ----
        $current = @{ $DescA = $state.RuleA; $DescB = $state.RuleB }
        foreach ($d in $RuleDefs) {
            $existing = $current[$d.description]
            if (-not $existing) {
                $body = @{ rule = @{
                    enabled = '1'; action = 'reject'; quick = '1'; interface = 'lan'; direction = 'in'
                    ipprotocol = 'inet'; protocol = 'TCP/UDP'; source_net = 'any'
                    destination_net = $d.destination_net; destination_port = $d.destination_port
                    log = '1'; description = $d.description } }
                $r = Api POST '/api/firewall/filter/add_rule' $body
                Assert-Saved $r "Rule '$($d.description)'"
                $newId = "$($r.uuid)"
                if (-not $newId) { $newId = "$((@((Api GET '/api/firewall/filter/search_rule?rowCount=-1&current=1').rows | Where-Object { $_.description -eq $d.description }) | Select-Object -First 1).uuid)" }
                if (-not $newId) { throw "Rule '$($d.description)' saved but its id could not be found; stopping before apply." }
                [void]$Undo.Add(@{ kind = 'rule'; uuid = $newId })
                Log "Rule '$($d.description)' added." 'Green'
            } elseif ("$($existing.enabled)" -ne '1') {
                Assert-Saved (Api POST "/api/firewall/filter/set_rule/$($existing.uuid)" @{ rule = @{ enabled = '1' } }) "Enable rule '$($d.description)'"
                [void]$Undo.Add(@{ kind = 'rule'; uuid = $existing.uuid })
                Log "Rule '$($d.description)' enabled." 'Green'
            } else { Log "Rule '$($d.description)' already present and enabled." }
        }
        $null = Api POST '/api/firewall/filter/apply'
        Log 'Firewall rules applied. Verifying...' 'Cyan'
        Start-Sleep -Seconds 5
    
        $after = Get-State
        foreach ($r in @($after.RuleA, $after.RuleB)) {
            if (-not $r) { throw 'A rule is missing after apply.' }
            if (-not $after.Allow) { throw "Rule '$AllowLan' not found after apply." }
            if ([double]"$($r.sort_order)" -ge [double]"$($after.Allow.sort_order)") {
                throw ("'{0}' sorts after '{1}' ({2} vs {3}) and would never match." -f $r.description, $AllowLan, $r.sort_order, $after.Allow.sort_order)
            }
        }
        try { $null = Api GET '/api/core/firmware/status' } catch { throw 'Router API not reachable after apply.' }
        if (-not (Test-Tcp 'www.google.com' 443)) { throw 'Ordinary HTTPS to www.google.com failed after apply.' }
        if (Test-Tcp '1.1.1.1' 443) { throw 'DoH to 1.1.1.1:443 is still reachable.' }
        if (Test-Tcp '9.9.9.9' 853) { throw 'DoT to 9.9.9.9:853 is still reachable.' }
        Log 'Rules A and B verified: DoH and DoT refused, normal HTTPS works.' 'Green'
    
    }
    catch {
        Log "Problem: $($_.Exception.Message)" 'Red'
        Invoke-Undo
        Show-State (Get-State)
        Save-Backup 'after-undo'
        Fail 'Apply did not complete; changes from this run were undone.'
    }
    
    # ---- 3. NAT rule (separate stage: if it fails, only the NAT change is undone; alias and rules A/B stay) ----
    $natUndoFrom = $Undo.Count
    $natOk = $true
    $nat = $null
    $natWaited = $false
    $natEnd = ''
    try {
        $nat = (Get-State).Nat
        if (-not $nat) { throw "NAT rule '$NatDesc' not found." }
        if ("$($nat.disabled)" -eq '1') {
            Assert-Saved (Api POST "/api/firewall/d_nat/set_rule/$($nat.uuid)" @{ rule = @{ disabled = '0' } }) 'Enable NAT rule'
            [void]$Undo.Add(@{ kind = 'nat'; uuid = $nat.uuid })
            $null = Api POST '/api/firewall/d_nat/apply'
            $chk = @($((Api GET '/api/firewall/d_nat/search_rule?rowCount=-1&current=1').rows) | Where-Object { $_.uuid -eq $nat.uuid }) | Select-Object -First 1
            if ("$($chk.disabled)" -ne '0') { throw "Router still shows the NAT rule disabled (disabled=$($chk.disabled))." }
            # A redirect applies only to NEW connections. A DNS query that matches a state opened before the
            # redirect (this script's own test query, or a device that keeps reusing one source port) still goes
            # to 8.8.8.8 until that state expires. The author's router reported udp.first/udp.multiple = 60s, udp.single = 30s
            # (Firewall > Diagnostics > Statistics, read 11/10/2026). Wait them out with no queries to 8.8.8.8.
            Log ("NAT rule enabled and applied. Waiting {0} s for older DNS states to expire before testing..." -f $NatWaitSeconds) 'Cyan'
            Start-Sleep -Seconds $NatWaitSeconds
            $natWaited = $true
        } else { Log 'NAT rule already enabled. Testing it...' }
        if (@(Get-ARecords 'example.com' '8.8.8.8').Count -eq 0) { throw 'example.com no longer resolves through 8.8.8.8 after the redirect.' }
        $waitNote = ''
        if ($natWaited) { $waitNote = " after $NatWaitSeconds s" }
        if (Test-Leaks '8.8.8.8') { throw "8.8.8.8 still returns real ad addresses$waitNote; the redirect is not taking effect." }
        Log 'NAT redirect verified: queries to 8.8.8.8 are answered by your router.' 'Green'
    }
    catch {
        $natOk = $false
        Log "Problem (NAT stage): $($_.Exception.Message)" 'Red'
        if ($Undo.Count -gt $natUndoFrom) {
            $u = $Undo[$Undo.Count - 1]
            try {
                $null = Api POST "/api/firewall/d_nat/set_rule/$($u.uuid)" @{ rule = @{ disabled = '1' } }
                $null = Api POST '/api/firewall/d_nat/apply'
                Log '  NAT rule switched back off. Alias and rules A/B are kept: they passed their checks.' 'Yellow'
                $natEnd = 'This run switched it on and has switched it off again.'
            } catch {
                Log "  UNDO OF NAT FAILED: $($_.Exception.Message). Switch it off in Firewall > NAT > Destination NAT." 'Red'
                $natEnd = 'This run switched it on and could not switch it off again: switch it off in Firewall > NAT > Destination NAT.'
            }
        } elseif ($nat -and "$($nat.disabled)" -ne '1') {
            $natEnd = 'It was already on before this run and is left on: check it in Firewall > NAT > Destination NAT.'
        } else {
            $natEnd = 'It is still off.'
        }
    }
    
    Show-State (Get-State)
    $null = Show-Tests
    Save-Backup 'after'
    if ($natOk) {
        Log 'Apply finished. Expected: router tests True, all three bypass tests False.' 'Green'
        Log "Log file: $LogFile"
    } else {
        Log ('Apply PARTLY finished: alias and rules A/B are in place and verified; the NAT redirect did not pass. ' + $natEnd) 'Yellow'
        Log "Log file: $LogFile"
        exit 2
    }
    
    mock-opnsense.ps1
    <#
      mock-opnsense.ps1 (v2)  -  a stand-in for the OPNsense 26.7 API, for testing opnsense-dns-bypass.ps1
      Prepared by Vivek Sanghi with Claude (Anthropic). Copyright (c) 2026 Vivek Sanghi. MIT licence (see opnsense-dns-bypass.ps1).
      Runs on Windows PowerShell 5.1 and PowerShell 7. Listens on 127.0.0.1 only. Writes no files.
    
      It answers the API paths the script uses, keeps the router's state in memory, and records every call.
      Test-only paths (not part of OPNsense):
        POST /__test/reset   {"scenario":"name"}  start a scenario with fresh state
        GET  /__test/state                         the current state
        GET  /__test/calls                         every call received since the last reset
        GET  /__test/tcp?h=host&p=port             mocked "can this PC reach host:port?"
        GET  /__test/dns?n=name&s=server           mocked DNS answer from that server
        GET  /__test/ping                          liveness
        POST /__test/stop                          stop the mock
    #>
    param([int]$Port = 18443)
    
    $ErrorActionPreference = 'Stop'
    $Url        = 'https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt'
    $DescA      = 'Reject DoH to known resolvers (A)'
    $DescB      = 'Reject DoT/DoQ 853 from LAN (B)'
    $GoodAuth   = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('testkey:testsecret'))
    $AdReal     = '142.250.183.2'
    $ExampleIp  = '93.184.215.14'
    
    function New-State([string]$scenario) {
        $s = @{
            scenario = $scenario; series = '26.7'; nextId = 1
            alias = @{ uuid = 'alias-1'; name = 'DoH_IPs'; type = 'urltable'; content = "__lan_network`n$Url"; enabled = '1'; loaded = 1434 }
            rules = New-Object System.Collections.ArrayList
            allow = @{ uuid = 'allow-1'; description = 'Default allow LAN to any rule'; sort_order = '400000.1000023'; enabled = '1' }
            nat = @{ uuid = 'nat-1'; descr = 'Redirect non-local DNS to Local'; disabled = '1' }
            natLive = $false
            backups = 0
            calls = New-Object System.Collections.ArrayList
        }
        switch ($scenario) {
            'version-mismatch' { $s.series = '26.1' }
            'alias-wrong-type' { $s.alias.type = 'host' }
            'fresh-alias'      { $s.alias = $null }
            'fresh-alias-doh-open' { $s.alias = $null }
            'nat-missing'      { $s.nat = $null }
            'allow-missing'    { $s.allow = $null }
            'nat-already-on-ineffective' { $s.nat.disabled = '0'; $s.natLive = $true }
            'alias-disabled-doh-open' { $s.alias.enabled = '0' }
            'already-applied'  {
                $s.alias.content = $Url
                [void]$s.rules.Add(@{ uuid = 'rule-a'; description = $DescA; enabled = '1'; live = '1'; sort_order = '400000.0000100' })
                [void]$s.rules.Add(@{ uuid = 'rule-b'; description = $DescB; enabled = '1'; live = '1'; sort_order = '400000.0000200' })
                $s.nat.disabled = '0'; $s.natLive = $true
            }
            'left-disabled' {
                # what version 2.3's undo left on the real router: both rules present, disabled
                [void]$s.rules.Add(@{ uuid = 'rule-a'; description = $DescA; enabled = '0'; live = '0'; sort_order = '400000.0000100' })
                [void]$s.rules.Add(@{ uuid = 'rule-b'; description = $DescB; enabled = '0'; live = '0'; sort_order = '400000.0000200' })
            }
        }
        return $s
    }
    $S = New-State 'default'
    
    function Find-Rule([string]$desc) { foreach ($r in $S.rules) { if ($r.description -eq $desc) { return $r } }; return $null }
    function Find-RuleById([string]$id) { foreach ($r in $S.rules) { if ($r.uuid -eq $id) { return $r } }; return $null }
    function Json($o) { return (ConvertTo-Json -InputObject $o -Depth 10 -Compress) }
    function Saved($extra) { $o = @{ result = 'saved' }; if ($extra) { foreach ($k in $extra.Keys) { $o[$k] = $extra[$k] } }; return (Json $o) }
    function Invalid([string]$field) { return (Json @{ result = 'failed'; validations = @{ $field = 'Mock validation error.' } }) }
    
    function Get-Query([string]$q) {
        $h = @{}
        foreach ($pair in ($q -split '&')) {
            if ($pair -match '^([^=]+)=(.*)$') { $h[$Matches[1]] = [Uri]::UnescapeDataString($Matches[2]) }
        }
        return $h
    }
    
    function Alias-Row {
        $a = $S.alias
        return @{ uuid = $a.uuid; name = $a.name; type = $a.type; content = $a.content; enabled = $a.enabled; description = 'mock' }
    }
    
    function Handle([string]$method, [string]$path, [string]$query, [string]$body, [string]$auth) {
        # returns @(status, contentType, body)
        if ($path -like '/__test/*') {
            switch ("$method $path") {
                'GET /__test/ping'  { return @(200, 'application/json', '{"ok":true}') }
                'POST /__test/reset' {
                    $sc = 'default'
                    if ($body) { $j = ConvertFrom-Json $body; if ($j.scenario) { $sc = "$($j.scenario)" } }
                    $script:S = New-State $sc
                    return @(200, 'application/json', (Json @{ ok = $true; scenario = $sc }))
                }
                'GET /__test/state' {
                    $o = @{ scenario = $S.scenario; alias = $S.alias; rules = @($S.rules); nat = $S.nat; natLive = $S.natLive }
                    return @(200, 'application/json', (Json $o))
                }
                'GET /__test/calls' { return @(200, 'application/json', (Json @{ calls = @($S.calls) })) }
                'GET /__test/tcp' {
                    $q = Get-Query $query; $hostPort = "$($q.h):$($q.p)"
                    $ruleA = Find-Rule $DescA; $ruleB = Find-Rule $DescB
                    $aliasOk = ($S.alias -ne $null) -and ($S.alias.loaded -ge 500) -and ($S.alias.enabled -eq '1')
                    $open = $true
                    switch ($hostPort) {
                        '1.1.1.1:443' { if ($ruleA -and $ruleA.live -eq '1' -and $aliasOk -and $S.scenario -notlike '*doh-open*') { $open = $false } }
                        '9.9.9.9:853' { if ($ruleB -and $ruleB.live -eq '1') { $open = $false } }
                        'www.google.com:443' { if ($S.scenario -eq 'https-broken' -and $ruleA -and $ruleA.live -eq '1') { $open = $false } }
                    }
                    return @(200, 'application/json', (Json @{ open = $open }))
                }
                'GET /__test/dns' {
                    $q = Get-Query $query; $ips = @()
                    $isAd = ($q.n -eq 'googleads.g.doubleclick.net')
                    if ($q.s -eq '8.8.8.8') {
                        $redirected = $S.natLive -and ($S.scenario -notlike '*ineffective*')
                        if ($isAd) { if ($redirected) { $ips = @('0.0.0.0') } else { $ips = @($AdReal) } }
                        elseif ($q.n -eq 'example.com') { $ips = @($ExampleIp) }
                    } else {
                        # the router itself
                        if ($isAd) { $ips = @('0.0.0.0') } elseif ($q.n -eq 'example.com') { $ips = @($ExampleIp) }
                    }
                    return @(200, 'application/json', (Json @{ ips = $ips }))
                }
                'POST /__test/stop' { $script:Running = $false; return @(200, 'application/json', '{"ok":true}') }
            }
            return @(404, 'application/json', '{"error":"unknown test path"}')
        }
    
        [void]$S.calls.Add(@{ method = $method; path = $path; body = $body })
        if ($auth -ne $GoodAuth) { return @(401, 'application/json', '{"status":401,"message":"Authentication Failed"}') }
    
        switch -Regex ("$method $path") {
            '^GET /api/core/firmware/info$' {
                return @(200, 'application/json', (Json @{ product = @{ product_name = 'OPNsense'; product_series = $S.series; product_arch = 'amd64' } }))
            }
            '^GET /api/core/firmware/status$' { return @(200, 'application/json', '{"status":"ok"}') }
            '^GET /api/core/backup/download/this$' {
                $S.backups++
                if ($S.scenario -eq 'small-backup' -or ($S.scenario -eq 'small-backup-after' -and $S.backups -gt 1)) { return @(200, 'application/xml', '<?xml version="1.0"?><error/>') }
                $pad = 'x' * 60000
                return @(200, 'application/xml', "<?xml version=`"1.0`"?>`n<opnsense>`n<!-- mock $pad -->`n</opnsense>`n")
            }
            '^GET /api/firewall/alias/search_item$' {
                if ($S.scenario -eq 'empty-key-reply') {
                    # a reply carrying an empty JSON key, as alias/get_item does on a real router
                    return @(200, 'application/json', '{"rows":[{"uuid":"alias-1","name":"DoH_IPs","type":{"":{"value":"","selected":0},"urltable":{"value":"URL Table","selected":1}},"content":"x","enabled":"1"}],"total":1}')
                }
                $rows = @(); if ($S.alias) { $rows = @(Alias-Row) }
                return @(200, 'application/json', (Json @{ rows = $rows; total = $rows.Count }))
            }
            '^GET /api/firewall/alias_util/list/DoH_IPs$' {
                $n = 0; if ($S.alias) { $n = $S.alias.loaded }
                return @(200, 'application/json', (Json @{ total = $n; rows = @() }))
            }
            '^POST /api/firewall/alias/add_item$' {
                if ($S.scenario -eq 'alias-validation') { return @(200, 'application/json', (Invalid 'alias.name')) }
                $j = (ConvertFrom-Json $body).alias
                $S.alias = @{ uuid = 'alias-new'; name = "$($j.name)"; type = "$($j.type)"; content = "$($j.content)"; enabled = "$($j.enabled)"; loaded = 0 }
                return @(200, 'application/json', (Saved @{ uuid = 'alias-new' }))
            }
            '^POST /api/firewall/alias/set_item/(.+)$' {
                if ($S.scenario -eq 'alias-validation') { return @(200, 'application/json', (Invalid 'alias.content')) }
                $j = (ConvertFrom-Json $body).alias
                foreach ($p in $j.PSObject.Properties) { if ($p.Name -ne 'updatefreq') { $S.alias[$p.Name] = "$($p.Value)" } }
                return @(200, 'application/json', (Saved $null))
            }
            '^POST /api/firewall/alias/reconfigure$' {
                if ($S.alias) {
                    $ok = ($S.alias.enabled -eq '1') -and (("$($S.alias.content)" -replace "`r", '').Trim() -eq $Url)
                    if ($ok) { if ($S.scenario -eq 'alias-not-filling') { $S.alias.loaded = 12 } else { $S.alias.loaded = 1434 } }
                }
                return @(200, 'application/json', '{"status":"ok"}')
            }
            '^GET /api/firewall/filter/search_rule$' {
                $rows = @()
                foreach ($r in $S.rules) { $rows += @{ uuid = $r.uuid; description = $r.description; enabled = $r.enabled; sort_order = $r.sort_order } }
                if ($S.allow) { $rows += @{ uuid = $S.allow.uuid; description = $S.allow.description; enabled = '1'; sort_order = $S.allow.sort_order } }
                return @(200, 'application/json', (Json @{ rows = $rows; total = $rows.Count }))
            }
            '^POST /api/firewall/filter/add_rule$' {
                $j = (ConvertFrom-Json $body).rule
                if ($S.scenario -eq 'rule-validation' -and "$($j.description)" -eq $DescB) { return @(200, 'application/json', (Invalid 'rule.destination_port')) }
                $S.nextId++
                $id = "rule-new-$($S.nextId)"
                $base = '400000.00001'; if ($S.scenario -eq 'rule-order') { $base = '500000.00001' }
                [void]$S.rules.Add(@{ uuid = $id; description = "$($j.description)"; enabled = "$($j.enabled)"; live = '0'; sort_order = ('{0}{1:00}' -f $base, $S.rules.Count) })
                return @(200, 'application/json', (Saved @{ uuid = $id }))
            }
            '^POST /api/firewall/filter/set_rule/(.+)$' {
                $r = Find-RuleById $Matches[1]
                if (-not $r) { return @(200, 'application/json', (Invalid 'rule.uuid')) }
                $j = (ConvertFrom-Json $body).rule
                if ($j.PSObject.Properties.Name -contains 'enabled') { $r.enabled = "$($j.enabled)" }
                return @(200, 'application/json', (Saved $null))
            }
            '^POST /api/firewall/filter/apply$' {
                foreach ($r in $S.rules) { $r.live = $r.enabled }
                return @(200, 'application/json', '{"status":"OK"}')
            }
            '^GET /api/firewall/d_nat/search_rule$' {
                $rows = @(); if ($S.nat) { $rows = @(@{ uuid = $S.nat.uuid; descr = $S.nat.descr; disabled = $S.nat.disabled }) }
                return @(200, 'application/json', (Json @{ rows = $rows; total = $rows.Count }))
            }
            '^POST /api/firewall/d_nat/set_rule/(.+)$' {
                if (-not $S.nat -or $Matches[1] -ne $S.nat.uuid) { return @(200, 'application/json', (Invalid 'rule.uuid')) }
                $j = (ConvertFrom-Json $body).rule
                if ($S.scenario -eq 'nat-validation' -and "$($j.disabled)" -eq '0') { return @(200, 'application/json', (Invalid 'rule.target')) }
                if ($j.PSObject.Properties.Name -contains 'disabled') { $S.nat.disabled = "$($j.disabled)" }
                return @(200, 'application/json', (Saved $null))
            }
            '^POST /api/firewall/d_nat/apply$' {
                $S.natLive = ($S.nat -ne $null) -and ($S.nat.disabled -eq '0')
                return @(200, 'application/json', '{"status":"OK"}')
            }
        }
        return @(404, 'application/json', '{"errorMessage":"Endpoint not found"}')
    }
    
    # ---------- minimal HTTP/1.1 server on 127.0.0.1 ----------
    $listener = New-Object System.Net.Sockets.TcpListener([Net.IPAddress]::Loopback, $Port)
    $listener.Start()
    Write-Host "mock-opnsense listening on http://127.0.0.1:$Port"
    $script:Running = $true
    $enc = New-Object System.Text.UTF8Encoding($false)
    while ($script:Running) {
        $client = $listener.AcceptTcpClient()
        try {
            $stream = $client.GetStream()
            $reader = New-Object System.IO.StreamReader($stream, $enc, $false, 65536, $true)
            $first = $reader.ReadLine()
            if (-not $first) { continue }
            $parts = $first -split ' '
            $method = $parts[0]; $target = $parts[1]
            $headers = @{}
            while ($true) {
                $line = $reader.ReadLine()
                if ([string]::IsNullOrEmpty($line)) { break }
                $i = $line.IndexOf(':')
                if ($i -gt 0) { $headers[$line.Substring(0, $i).Trim().ToLowerInvariant()] = $line.Substring($i + 1).Trim() }
            }
            if ($headers.ContainsKey('expect') -and $headers['expect'] -match '100-continue') {
                $c = $enc.GetBytes("HTTP/1.1 100 Continue`r`n`r`n"); $stream.Write($c, 0, $c.Length); $stream.Flush()
            }
            $body = ''
            if ($headers.ContainsKey('content-length')) {
                $len = [int]$headers['content-length']
                if ($len -gt 0) { $buf = New-Object char[] $len; $got = 0; while ($got -lt $len) { $n = $reader.Read($buf, $got, $len - $got); if ($n -le 0) { break }; $got += $n }; $body = New-Object System.String -ArgumentList $buf, 0, $got }
            }
            $path = $target; $query = ''
            $q = $target.IndexOf('?'); if ($q -ge 0) { $path = $target.Substring(0, $q); $query = $target.Substring($q + 1) }
            $auth = ''; if ($headers.ContainsKey('authorization')) { $auth = $headers['authorization'] }
            try { $res = Handle $method $path $query $body $auth }
            catch { $res = @(500, 'application/json', (ConvertTo-Json -InputObject @{ mockError = "$($_.Exception.Message)" } -Compress)) }
            $status = $res[0]
            $reason = @{ 200 = 'OK'; 401 = 'Unauthorized'; 404 = 'Not Found'; 500 = 'Internal Server Error' }[$status]
            $bytes = $enc.GetBytes([string]$res[2])
            $head = "HTTP/1.1 $status $reason`r`nContent-Type: $($res[1]); charset=utf-8`r`nContent-Length: $($bytes.Length)`r`nConnection: close`r`n`r`n"
            $hb = $enc.GetBytes($head)
            $stream.Write($hb, 0, $hb.Length); $stream.Write($bytes, 0, $bytes.Length); $stream.Flush()
        } catch {
            Write-Host "mock: request failed: $($_.Exception.Message)"
        } finally {
            $client.Close()
        }
    }
    $listener.Stop()
    Write-Host 'mock-opnsense stopped'
    
    Test-OpnsenseScript.ps1
    <#
      Test-OpnsenseScript.ps1 (v4)  -  runs opnsense-dns-bypass.ps1 against mock-opnsense.ps1, one case per failure path
      Prepared by Vivek Sanghi with Claude (Anthropic). Copyright (c) 2026 Vivek Sanghi. MIT licence (see opnsense-dns-bypass.ps1).
      Runs on Windows PowerShell 5.1 and PowerShell 7.
    
      What it touches:
        - reads the script under test; never changes it
        - writes a test copy and one folder per case under .\test-run-<timestamp>\ (next to this file)
        - starts mock-opnsense.ps1 on 127.0.0.1:<Port> and stops it at the end
        - contacts nothing else: the test copy's two network-test functions ask the mock instead of the internet,
          and every run points -Router at the mock. No real router, no real API key.
      The test copy differs from the script in exactly three ways, each checked before any case runs:
        Test-Tcp and Get-ARecords ask the mock; every Start-Sleep is cut to 1 ms.
    #>
    param(
        [string]$ScriptPath = '',
        [string]$MockPath = '',
        [int]$Port = 18443
    )
    $ErrorActionPreference = 'Stop'
    Set-StrictMode -Version 1
    # Work out this file's folder in the body, not in param(): the article's failure 1.
    $Here = ''
    if ($MyInvocation.MyCommand.Path) { $Here = Split-Path -Parent $MyInvocation.MyCommand.Path }
    if (-not $Here) { $Here = (Get-Location).Path }
    if (-not $ScriptPath) { $ScriptPath = Join-Path $Here 'opnsense-dns-bypass.ps1' }
    if (-not $MockPath) { $MockPath = Join-Path $Here 'mock-opnsense.ps1' }
    if (-not (Test-Path -LiteralPath $MockPath)) { Write-Host "Mock not found: $MockPath" -ForegroundColor Red; exit 1 }
    $Exe   = (Get-Process -Id $PID).Path
    $Base  = "http://127.0.0.1:$Port"
    $Url   = 'https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt'
    $DescA = 'Reject DoH to known resolvers (A)'
    $DescB = 'Reject DoT/DoQ 853 from LAN (B)'
    foreach ($n in 'NO_PROXY', 'no_proxy') { [Environment]::SetEnvironmentVariable($n, '127.0.0.1,localhost') }
    if ($PSVersionTable.PSVersion.Major -lt 6) { [Net.ServicePointManager]::Expect100Continue = $false }
    
    if (-not (Test-Path -LiteralPath $ScriptPath)) { Write-Host "Script not found: $ScriptPath" -ForegroundColor Red; exit 1 }
    $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $ScriptPath).Hash.ToLowerInvariant()
    Write-Host "PowerShell $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition))"
    Write-Host "Script under test: $ScriptPath"
    Write-Host "SHA-256: $hash"
    
    # ---------- test copy ----------
    $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
    $Run   = Join-Path $Here "test-run-$stamp"
    New-Item -ItemType Directory -Path $Run | Out-Null
    $text = [IO.File]::ReadAllText($ScriptPath)
    function Swap([string]$t, [string]$pattern, [string]$new, [int]$want, [string]$what) {
        $m = [regex]::Matches($t, $pattern)
        if ($m.Count -ne $want) { throw "Test copy: expected $want match(es) for $what, found $($m.Count). Has the script changed?" }
        foreach ($x in @($m | Sort-Object Index -Descending)) { $t = $t.Remove($x.Index, $x.Length).Insert($x.Index, $new) }
        return $t
    }
    $tcp = @'
    function Test-Tcp([string]$TargetHost, [int]$Port, [int]$Ms = 4000) {
        return [bool](Invoke-RestMethod -Uri ("$Router/__test/tcp?h={0}&p={1}" -f [Uri]::EscapeDataString($TargetHost), $Port) -TimeoutSec 10).open
    }
    
    '@
    $dns = @'
    function Get-ARecords([string]$Name, [string]$Server) {
        return @((Invoke-RestMethod -Uri ("$Router/__test/dns?n={0}&s={1}" -f [Uri]::EscapeDataString($Name), [Uri]::EscapeDataString($Server)) -TimeoutSec 10).ips)
    }
    
    '@
    $text = Swap $text '(?s)function Test-Tcp\(.*?\r?\n\}\r?\n' $tcp 1 'function Test-Tcp'
    $text = Swap $text '(?s)function Get-ARecords\(.*?\r?\n\}\r?\n' $dns 1 'function Get-ARecords'
    $text = Swap $text 'Start-Sleep -Seconds (\d+|\$\w+)' 'Start-Sleep -Milliseconds 1' 4 'Start-Sleep'
    $Copy = Join-Path $Run 'script-under-test.ps1'
    [IO.File]::WriteAllText($Copy, $text, (New-Object Text.UTF8Encoding($false)))
    
    # Evidence, not a pass/fail case: what this PowerShell puts in $PSScriptRoot when it is a parameter default.
    $probe = Join-Path $Run 'probe-psscriptroot.ps1'
    [IO.File]::WriteAllText($probe, 'param([string]$WorkDir = $PSScriptRoot)' + "`n" + '"[" + $WorkDir + "]"' + "`n")
    $probeOut = "$(& $Exe -NoProfile -ExecutionPolicy Bypass -File $probe)"
    $Evidence = "Evidence: `$PSScriptRoot as a parameter default, run with -File, gave $probeOut (empty brackets = empty)"
    Write-Host $Evidence
    
    $GoodKey = Join-Path $Run 'key-good.txt'; [IO.File]::WriteAllText($GoodKey, "key=testkey`nsecret=testsecret`n")
    $BadKey  = Join-Path $Run 'key-bad.txt';  [IO.File]::WriteAllText($BadKey,  "key=testkey`nsecret=wrongsecret`n")
    
    # ---------- mock ----------
    function Q([string]$a) { return '"' + $a + '"' }
    $mockOut = Join-Path $Run 'mock-output.txt'
    $mockArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Q $MockPath), '-Port', $Port)
    $mock = Start-Process -FilePath $Exe -ArgumentList $mockArgs -PassThru -NoNewWindow -RedirectStandardOutput $mockOut -RedirectStandardError (Join-Path $Run 'mock-errors.txt')
    $up = $false
    for ($i = 0; $i -lt 60; $i++) { try { $null = Invoke-RestMethod "$Base/__test/ping" -TimeoutSec 2; $up = $true; break } catch { Start-Sleep -Milliseconds 500 } }
    if (-not $up) { Write-Host "The mock did not start. See $mockOut" -ForegroundColor Red; if (-not $mock.HasExited) { Stop-Process -Id $mock.Id -Force }; exit 1 }
    Write-Host "Mock: $MockPath (SHA-256 $((Get-FileHash -Algorithm SHA256 -LiteralPath $MockPath).Hash.ToLowerInvariant()))"
    $Secret64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('testkey:testsecret'))
    
    function Reset([string]$scenario) { $null = Invoke-RestMethod -Method POST -Uri "$Base/__test/reset" -Body (ConvertTo-Json @{ scenario = $scenario }) -ContentType 'application/json' }
    function State { return Invoke-RestMethod "$Base/__test/state" }
    function Calls { return @((Invoke-RestMethod "$Base/__test/calls").calls) }
    function Rule($st, [string]$desc) { return @(@($st.rules) | Where-Object { $_.description -eq $desc }) }
    
    # ---------- cases ----------
    $Results = New-Object System.Collections.ArrayList
    function Run-Case {
        param([string]$Name, [string]$Scenario, [string]$Mode = 'Apply', [int[]]$Exit, [scriptblock]$Check, [switch]$NoRouter, [string]$Key = $GoodKey, [string]$ModeRaw = '', [string]$RouterArg = '')
        Reset $Scenario
        $dir = Join-Path $Run $Name; New-Item -ItemType Directory -Path $dir | Out-Null
        $a = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Q $Copy), '-KeyFile', (Q $Key), '-WorkDir', (Q $dir))
        if ($RouterArg) { $a += @('-Router', $RouterArg) } elseif (-not $NoRouter) { $a += @('-Router', $Base) }
        if ($ModeRaw) { $a += @('-Mode', $ModeRaw) } else { $a += @('-Mode', $Mode) }
        $out = Join-Path $dir 'console.txt'; $err = Join-Path $dir 'console-errors.txt'
        $p = Start-Process -FilePath $Exe -ArgumentList $a -PassThru -Wait -NoNewWindow -RedirectStandardOutput $out -RedirectStandardError $err
        $code = $p.ExitCode
        $console = ((Get-Content -LiteralPath $out -Raw -ErrorAction SilentlyContinue) + (Get-Content -LiteralPath $err -Raw -ErrorAction SilentlyContinue))
        $logs = @(Get-ChildItem -LiteralPath (Join-Path $dir 'logs') -Filter '*.log' -ErrorAction SilentlyContinue)
        $log = ''; if ($logs.Count -gt 0) { $log = Get-Content -LiteralPath $logs[0].FullName -Raw }
        $backups = @(Get-ChildItem -LiteralPath (Join-Path $dir 'router-backups') -Filter '*.xml' -ErrorAction SilentlyContinue | ForEach-Object { $_.Name })
        $calls = Calls; $posts = @($calls | Where-Object { $_.method -eq 'POST' })
        $st = State
        $script:fails = New-Object System.Collections.ArrayList
        function Want([bool]$ok, [string]$msg) { if (-not $ok) { [void]$script:fails.Add($msg) } }
        Want ($Exit -contains $code) "exit code $code, wanted $($Exit -join ' or ')"
        Want (-not (($console + $log) -match 'testsecret|wrongsecret')) 'the API secret appeared in the output or log'
        Want (-not (($console + $log).Contains($Secret64))) 'the encoded API key appeared in the output or log'
        if ($code -ne 0 -and $log) { Want ($log -match 'STOP: |PARTLY finished') 'the run stopped without saying so in the log' }
        Want (@($posts | Where-Object { $_.path -match 'del' }).Count -eq 0) 'a delete call was made'
        $ctx = @{ code = $code; console = $console; log = $log; all = ($console + "`n" + $log); backups = $backups; calls = $calls; posts = $posts; state = $st; dir = $dir }
        & $Check $ctx
        $status = 'PASS'; if ($script:fails.Count -gt 0) { $status = 'FAIL' }
        [void]$Results.Add([pscustomobject]@{ Case = $Name; Result = $status; Exit = $code; Posts = $posts.Count; Notes = ($script:fails -join '; ') })
        $colour = 'Green'; if ($status -eq 'FAIL') { $colour = 'Red' }
        Write-Host ("{0,-24} {1}  exit={2}  POSTs={3}  {4}" -f $Name, $status, $code, $posts.Count, ($script:fails -join '; ')) -ForegroundColor $colour
    }
    
    try {
    Write-Host ''
    Run-Case 'placeholder-router' 'default' -Mode Check -NoRouter -Exit 1 -Check { param($c)
        Want ($c.calls.Count -eq 0) 'the mock received calls'
        Want (-not (Test-Path -LiteralPath (Join-Path $c.dir 'logs'))) 'a logs folder was created'
        Want ($c.console -match 'Set -Router') 'no "Set -Router" message' }
    Run-Case 'bad-mode' 'default' -ModeRaw 'Aply' -Exit 1 -Check { param($c)
        Want ($c.calls.Count -eq 0) 'the mock received calls' }
    Run-Case 'bad-key' 'default' -Mode Check -Key $BadKey -Exit 1 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'POSTs were sent'
        Want ($c.backups.Count -eq 0) 'a backup was written'
        Want ($c.log -match 'Cannot reach the router API') 'no "Cannot reach the router API" message' }
    Run-Case 'version-mismatch' 'version-mismatch' -Exit 1 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'POSTs were sent'
        Want ($c.backups.Count -eq 0) 'a backup was written'
        Want ($c.log -match 'built for OPNsense 26\.7; router reports 26\.1') 'no version message' }
    Run-Case 'small-backup' 'small-backup' -Exit 1 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'POSTs were sent'
        Want ($c.log -match 'Backup looks wrong') 'no "Backup looks wrong" message' }
    Run-Case 'check' 'default' -Mode Check -Exit 0 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'Check sent POSTs'
        Want (@($c.backups | Where-Object { $_ -like 'config-Check-before-*.xml' }).Count -eq 1) 'no Check backup'
        Want ($c.log -match 'Check mode: nothing was changed') 'no Check message'
        Want (@([regex]::Matches($c.log, 'want False after Apply\)')).Count -eq 3) 'not three bypass tests' }
    Run-Case 'empty-key-reply' 'empty-key-reply' -Exit 1 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'POSTs were sent'
        Want ($c.log -match 'STOP: .*could not be read as JSON') 'the JSON guard stop is not in the log' }
    Run-Case 'http-router' 'default' -Mode Check -RouterArg 'http://192.0.2.1' -Exit 1 -Check { param($c)
        Want ($c.calls.Count -eq 0) 'the mock received calls'
        Want ($c.console -match 'must start with https://') 'no https message' }
    Run-Case 'check-nat-missing' 'nat-missing' -Mode Check -Exit 0 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'Check sent POSTs'
        Want ($c.log -match "Apply would stop: NAT rule 'Redirect non-local DNS to Local' not found") 'no "Apply would stop" warning' }
    Run-Case 'allow-missing' 'allow-missing' -Exit 1 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'POSTs were sent'
        Want ($c.log -match "Rule 'Default allow LAN to any rule' not found, so rule order cannot be checked") 'no allow-rule message'
        Want ($c.log -match 'Nothing changed\.') 'no "Nothing changed"' }
    Run-Case 'small-backup-after' 'small-backup-after' -Exit 1 -Check { param($c)
        Want ($c.log -match 'The changes logged above were made') 'no "changes were made" message'
        Want (-not ($c.log -match 'Nothing changed on the router')) 'claims nothing changed after changes' }
    Run-Case 'alias-undo-enabled' 'alias-disabled-doh-open' -Exit 1 -Check { param($c)
        Want ("$($c.state.alias.enabled)" -eq '0') 'alias enabled flag not restored'
        Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias content not restored'
        Want ($c.log -match 'alias content and enabled flag restored') 'no restore message' }
    Run-Case 'alias-wrong-type' 'alias-wrong-type' -Exit 1 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'POSTs were sent'
        Want ($c.log -match "is type 'host', not urltable") 'no type message'
        Want ($c.log -match 'Nothing to undo') 'no "Nothing to undo"'
        Want (@($c.backups | Where-Object { $_ -like '*after-undo*' }).Count -eq 1) 'no after-undo backup' }
    Run-Case 'alias-validation' 'alias-validation' -Exit 1 -Check { param($c)
        Want ($c.log -match 'was not saved') 'no "was not saved" message'
        Want ($c.log -match 'Nothing to undo') 'no "Nothing to undo"'
        Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias content changed' }
    Run-Case 'alias-not-filling' 'alias-not-filling' -Exit 1 -Check { param($c)
        Want ($c.log -match 'loaded only 12 entries') 'no "loaded only" message'
        Want ($c.log -match 'alias content and enabled flag restored') 'alias not restored'
        Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias content not back to the original' }
    Run-Case 'rule-validation' 'rule-validation' -Exit 1 -Check { param($c)
        Want ($c.log -match "Rule 'Reject DoT/DoQ 853 from LAN \(B\)' was not saved") 'no rule B message'
        $ra = @(Rule $c.state $DescA)
        Want ($ra.Count -eq 1 -and "$($ra[0].enabled)" -eq '0') 'rule A not disabled by the undo'
        Want (@(Rule $c.state $DescB).Count -eq 0) 'rule B exists'
        Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias not restored'
        Want ("$($c.state.nat.disabled)" -eq '1') 'NAT touched' }
    Run-Case 'rule-order' 'rule-order' -Exit 1 -Check { param($c)
        Want ($c.log -match 'would never match') 'no rule-order message'
        Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled'
        Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias not restored' }
    Run-Case 'doh-still-open' 'doh-open' -Exit 1 -Check { param($c)
        Want ($c.log -match 'DoH to 1\.1\.1\.1:443 is still reachable') 'no DoH message'
        Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled'
        Want ("$($c.state.nat.disabled)" -eq '1') 'NAT touched' }
    Run-Case 'https-broken' 'https-broken' -Exit 1 -Check { param($c)
        Want ($c.log -match 'Ordinary HTTPS to www\.google\.com failed') 'no HTTPS message'
        Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled' }
    Run-Case 'fresh-alias' 'fresh-alias' -Exit 0 -Check { param($c)
        Want (@($c.posts | Where-Object { $_.path -eq '/api/firewall/alias/add_item' }).Count -eq 1) 'alias not created once'
        Want ("$($c.state.alias.content)" -eq $Url) 'alias content wrong'
        Want ($c.log -match 'Apply finished') 'no "Apply finished"' }
    Run-Case 'fresh-alias-fails' 'fresh-alias-doh-open' -Exit 1 -Check { param($c)
        Want ($c.log -match 'new alias disabled') 'new alias not disabled'
        Want ("$($c.state.alias.enabled)" -eq '0') 'alias still enabled' }
    Run-Case 'apply' 'default' -Exit 0 -Check { param($c)
        Want ("$($c.state.alias.content)" -eq $Url) 'alias content not cleaned'
        Want ($c.log -match 'Alias DoH_IPs set to the URL only \(was: __lan_network \|') 'old alias content not logged'
        $ra = @(Rule $c.state $DescA); $rb = @(Rule $c.state $DescB)
        Want ($ra.Count -eq 1 -and "$($ra[0].enabled)" -eq '1') 'rule A not enabled'
        Want ($rb.Count -eq 1 -and "$($rb[0].enabled)" -eq '1') 'rule B not enabled'
        Want ("$($c.state.nat.disabled)" -eq '0') 'NAT not enabled'
        Want ($c.log -match 'Waiting 70 s') 'no 70 s wait message'
        Want ($c.log -match 'Apply finished') 'no "Apply finished"'
        Want (@($c.backups | Where-Object { $_ -like 'config-Apply-before-*' }).Count -eq 1 -and @($c.backups | Where-Object { $_ -like 'config-Apply-after-*' }).Count -eq 1) 'backups not before + after' }
    Run-Case 'leftover-rules' 'left-disabled' -Exit 0 -Check { param($c)
        Want (@($c.posts | Where-Object { $_.path -eq '/api/firewall/filter/add_rule' }).Count -eq 0) 'rules added again'
        Want (@($c.state.rules).Count -eq 2) 'duplicate rules'
        Want ($c.log -match "Rule 'Reject DoH to known resolvers \(A\)' enabled\.") 'rule A not re-enabled' }
    Run-Case 'already-applied' 'already-applied' -Exit 0 -Check { param($c)
        Want (@($c.posts | Where-Object { $_.path -like '/api/firewall/filter/add_rule' -or $_.path -like '/api/firewall/filter/set_rule/*' -or $_.path -like '/api/firewall/d_nat/set_rule/*' -or $_.path -like '/api/firewall/alias/set_item/*' }).Count -eq 0) 'something was re-saved'
        Want ($c.log -match 'already present and enabled') 'no "already present" message'
        Want ($c.log -match 'NAT rule already enabled') 'no "NAT already enabled" message' }
    Run-Case 'nat-missing' 'nat-missing' -Exit 1 -Check { param($c)
        Want ($c.posts.Count -eq 0) 'POSTs were sent before the missing NAT rule was reported'
        Want ($c.log -match "NAT rule 'Redirect non-local DNS to Local' not found\. Create it in Firewall > NAT > Destination NAT") 'no NAT-missing message' }
    Run-Case 'nat-ineffective' 'nat-ineffective' -Exit 2 -Check { param($c)
        Want ($c.log -match 'still returns real ad addresses after 70 s') 'no redirect message'
        Want ("$($c.state.nat.disabled)" -eq '1') 'NAT left on'
        Want ($c.log -match 'NAT rule switched back off') 'no switch-off message'
        Want ($c.log -match 'This run switched it on and has switched it off again') 'PARTLY message does not say what happened to NAT'
        Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -eq '1' }).Count -eq 2) 'rules not kept' }
    Run-Case 'nat-validation' 'nat-validation' -Exit 2 -Check { param($c)
        Want ($c.log -match 'Enable NAT rule was not saved') 'no NAT save message'
        Want ("$($c.state.nat.disabled)" -eq '1') 'NAT changed'
        Want ($c.log -match 'did not pass\. It is still off\.') 'PARTLY message wrong for a NAT rule that never switched on'
        Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -eq '1' }).Count -eq 2) 'rules not kept' }
    Run-Case 'nat-already-on' 'nat-already-on-ineffective' -Exit 2 -Check { param($c)
        Want ("$($c.state.nat.disabled)" -eq '0') 'NAT rule that was on before was switched off'
        Want (-not ($c.log -match 'after 70 s')) 'claims a 70 s wait that did not happen'
        Want ($c.log -match 'It was already on before this run and is left on') 'PARTLY message does not say NAT was left on' }
    Run-Case 'rollback' 'already-applied' -Mode Rollback -Exit 0 -Check { param($c)
        Want (@($c.state.rules).Count -eq 2) 'rules deleted'
        Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled'
        Want ("$($c.state.nat.disabled)" -eq '1') 'NAT left on'
        Want ($c.log -match 'Rollback finished') 'no "Rollback finished"'
        Want (@($c.backups | Where-Object { $_ -like 'config-Rollback-after-*' }).Count -eq 1) 'no after backup' }
    Run-Case 'rollback-nothing-to-do' 'default' -Mode Rollback -Exit 0 -Check { param($c)
        Want (@($c.posts | Where-Object { $_.path -like '*set_rule*' }).Count -eq 0) 'something was changed'
        Want ($c.log -match 'Rollback finished') 'no "Rollback finished"' }
    
    } finally {
        # ---------- always stop the mock ----------
        try { $null = Invoke-RestMethod -Method POST -Uri "$Base/__test/stop" -TimeoutSec 5 } catch { }
        Start-Sleep -Milliseconds 500
        if (-not $mock.HasExited) { Stop-Process -Id $mock.Id -Force -ErrorAction SilentlyContinue }
    }
    
    $failed = @($Results | Where-Object { $_.Result -eq 'FAIL' }).Count
    $summary = "{0} cases, {1} passed, {2} failed. PowerShell {3}. Script SHA-256 {4}" -f $Results.Count, ($Results.Count - $failed), $failed, $PSVersionTable.PSVersion, $hash
    $Results | Format-Table -AutoSize | Out-String -Width 200 | Set-Content -LiteralPath (Join-Path $Run 'results.txt')
    Add-Content -LiteralPath (Join-Path $Run 'results.txt') -Value $summary
    Add-Content -LiteralPath (Join-Path $Run 'results.txt') -Value $Evidence
    Write-Host ''
    if ($failed -eq 0) { Write-Host $summary -ForegroundColor Green } else { Write-Host $summary -ForegroundColor Red }
    Write-Host "Details: $Run"
    if ($failed -gt 0) { exit 1 } else { exit 0 }
    
    Mutation check results
    Mutation check of opnsense-dns-bypass.v2.5.ps1 (SHA-256 df017f33269979e9...; 2.5.1 differs only in header comments) with Test-OpnsenseScript.v3.ps1 and mock-opnsense.v2.ps1
    PowerShell 7.4.6, 28/10/2026. Each line: a deliberately broken copy of the script, and the cases that then failed.
    no-undo                9 failed: alias-undo-enabled alias-wrong-type alias-validation alias-not-filling rule-validation rule-order doh-still-open https-broken fresh-alias-fails
    no-exit2               3 failed: nat-ineffective nat-validation nat-already-on
    no-json-guard          1 failed: empty-key-reply
    no-router-guard        1 failed: placeholder-router
    no-order-check         1 failed: rule-order
    no-https-guard         1 failed: http-router
    no-preflight           2 failed: allow-missing nat-missing
    no-trap                1 failed: empty-key-reply
    old-undo-content-only  1 failed: alias-undo-enabled
    old-backup-message     1 failed: small-backup-after
    Unbroken script: 30 cases, 30 passed.
    
  • The law I cannot read · กฎหมายที่ผมอ่านไม่ออก

    The law I cannot read · กฎหมายที่ผมอ่านไม่ออก

    The law I cannot read

    I am studying Thai law, and I cannot read Thai.

    That is an awkward position for a lawyer. Thailand’s statutes are published in Thai, and the Thai text is the law. Anything in English is somebody’s reading of it. For the Codes that govern property, family and succession, the Thai government’s own legal drafting office holds no English text at all. I checked, and how I checked is part of this post.

    So I built a second law library on my own computer. The first one, of Indian statutes and judgments, is a separate project. This one holds Thai law in Thai, with every line of English labelled by how far it can be trusted, and it answers a search in a fraction of a second.

    I built it with Claude, Anthropic’s AI model, working as an agent: it could run programs on my computer and use my Chrome browser, under rules I set. I made the decisions. The scripts and most of the investigation came from the model, and so did a good number of the mistakes. The work started on 4 September 2026; most of it ran in the last week of September.

    One thing to say before anything else: I am an Indian advocate, not a Thai lawyer. This is a post about building a research tool, not advice on Thai law. There is a fuller note at the end.

    Every English word gets a label

    The first decision was a rule about English.

    Thailand is a civil law country. Thai courts are not formally bound by earlier decisions, the Supreme Court’s included, though those decisions carry weight. The statute book matters more than case law, and the statute book is Thai. If I am going to rely on any of this, every English sentence has to say where it came from.

    So there are four tiers:

    T1  Thai official text, or English the agency published as part of the instrument
    T2  English published by a Thai agency, marked unofficial
    T3  third-party English: commercial translations, law firm sites
    T4  machine output, ours: for finding and reading only, never quoted, never cited

    Every text file carries a tier: line in its header, and the search tool prints the tier beside every result. Machine English comes out as T4 machine translation - NEVER quote or cite, in capitals, every time. That label is what stops a fluent sentence from turning into a citation.

    Finding the statute book

    The Office of the Council of State publishes the official consolidated text of Thai laws. Its old address, krisdika.go.th, no longer served it; the office had moved to ocs.go.th.

    The new site’s search page is backed by a form-encoded endpoint, POST /searchlaw/indexs/list_table_search. Two things stood between it and a clean list.

    The first was TLS. The server does not send its intermediate certificate. A browser fetches the missing certificate itself; Python’s requests does not, and fails. Setting verify=False would have silenced the error by switching the check off. The fix used instead was truststore, which hands verification to Windows’ own certificate chain building, and Windows can find the missing intermediate. The check still happens.

    The second was a filter. The site’s own search page sends the parameter query[lawCategoryName] with the value 1B,1C. Sent that way, the index hid 7 of 147 records. Sent empty, all 147 came back. I would not have known without counting both ways.

    That gave titles and PDFs, not text. The text sits behind a viewer, an Angular single-page app, and five guessed endpoints returned 404. What worked was opening the viewer in a browser and reading how the page itself asks the server for a law, from its network traffic and its JavaScript bundle. The viewer uses a public JSON endpoint:

    POST https://searchlaw.ocs.go.th/ocs-api/public/doc/getLawDoc
    Content-Type: application/json
    
    { "reqHeader": { ...request id, channel, timestamp, service name... },
      "reqBody":   { "timelineId": "<id from the index>", "isTransEng": false,
                     "sectionIds": [], "sectionAndExplains": [] } }

    What comes back is structured: each section with its number, label and HTML content, plus every version of that law. For the Civil and Commercial Code that was 2,254 entries and 605,706 characters, in force from 25 March 2025. File downloads on the same site go through a route that needs a token the viewer holds. The token was never read or reused: the English PDFs mentioned below were saved through the viewer’s own download button, as any reader would save them.

    The English that was not there

    The same request has a flag, isTransEng. Set to true, it asks for English.

    For all eight Thai Codes, the answer was SUCCESS with zero sections. The system knows the English names of the Codes. It holds none of their English text.

    There was one exception. The Civil and Commercial Code’s timeline has 73 versions, and one of them, the original 1925 text, is marked as having a translation: a 242 KB file. For a week the working assumption was that this was an English translation of the 1925 Code. When the file came down and was read, its title page said otherwise. It is the Act Amending the Civil and Commercial Code (No. 20), B.E. 2557 (2014): one amending Act, filed against the original version.

    The note was corrected with the date of the correction, and the earlier reading left on record. A timeline entry tells you a file exists. Only the file tells you what it is.

    The Council of State does hold English for other laws, and 70 such PDFs, covering 57 laws, are now in the library. They are T2, and they say on their face that the Thai is the sole authority. Many turned out to be amending Acts rather than the main Act, which is one more reason the library reads the Thai consolidation first.

    A section 2 that appeared 36 times

    With the endpoint working, the eight Codes came down as structured text: 5,526 entries, of which 4,453 are numbered provisions. Then the counting started, and the counting is where the bugs were.

    Section 2 appeared 36 times in the Civil and Commercial Code file. Each Code’s file carries the Acts that amended it, appended at the end, and each of those Acts numbers its own sections from 1. Left as it was, a search for section 2 would find 36 candidates and one of them would be right. Every entry now carries a flag saying whether it belongs to the Code itself. That is how the 2,254 entries in the Civil and Commercial Code file come down to its 1,850 provisions; the rest are headings and the appended Acts.

    Some of the others:

    • The Land Code has eight entries in a row all labelled section 105. They are 105, 105 bis, ter and on to octies. The label field cuts the number short, so the real reference is parsed from the text.
    • The same ordinal is spelled two ways: อัฎฐ with ฎ in the Civil Procedure Code, อัฏฐ with ฏ in the Land Code.
    • The site served escaped HTML comments, &lt;!--[endif]--&gt;, which only became comments after unescaping, so the comment-stripper never saw them. The selftest had passed because its fixture used a real comment: it was written from the fix, not from the data.

    Once all of these were fixed, no reference in any of the eight Codes appeared twice.

    When a repealed law is still current

    Each version in a law’s timeline carries a stateId. 01 looked like “in force” and 00 like “superseded”.

    Of the 652 index rows whose titles carry the repeal marker (ยกเลิก), 638 sit at 01. The last version of a repealed law is still that law’s current version. So repeal is read from the title marker, never from the state.

    A probe on 24 September found a third state, 02: published but not yet in force, with a fifth version type, a future consolidation showing the law as it will read once a pending amendment starts. On 30 September that turned up a trap. A value-added tax decree showed a future consolidation in force from 1 October 2026, and it left out a separate amending decree of the same date that keeps the reduced rate for another year. Read alone, the future text would have given the wrong rate. The library now holds the amending decree separately and flags any future version that matches the current one.

    That same day the whole library was checked against the Council of State: 837 timeline entries under the parent laws held, and all 773 laws unchanged since they were fetched. The consolidations themselves can trail behind amendments. The Revenue Code’s latest consolidation on the site is dated 9 November 2021. The site cannot show an amendment it has not yet worked in, so the issuing department is the cross-check.

    Working with an agent that can be wrong

    An agent that can run programs on my computer and drive my browser can do a great deal in an afternoon. It can also be wrong about a file it has not looked at, and it writes fluent explanations of things that did not happen. The rules I work under came out of incidents.

    The separation rule came first. The Thai library sits beside the Indian one on the same disk, and early on a Thai backup was written into the Indian backup folder. Nothing was lost, but since then a guard refuses any path under the Indian backups, and a checker audits every script for where it can reach. Building that checker produced two of the stranger moments of the month:

    • io.open(path, "w", newline=...) empties the file before it raises on a bad newline argument. The checker truncated itself to zero bytes that way. Everything now writes to a temporary file and os.replaces it.
    • A Windows path such as D:\...\Thai_Backup is, to a Linux program, an ordinary file name. Run from the agent’s side, a backup created a folder whose name was the whole Windows path, inside the library. It looked like a successful backup.

    The second rule is that every claim has to be shown. If the agent says a backup exists, it shows the listing. If it asks me to run a file, it first opens that file and quotes the line that does the work. That rule came after a session with five errors of this kind, one of which was a recommendation to run a batch file that would have thrown away three days of work.

    The third is a backup before anything that rewrites a file. Once, a batch file suggested in passing rewrote a file another script had written its OCR results into, and hours of machine time went with it. Now a copy comes first, and both checksums are shown. On 1 October that rule ran on something small: one translation cache file carried 1,443 NUL bytes left over from an interrupted run on 29 September. Nothing was lost, since the work had been redone, but the copy was taken, the bad line removed and all 776 cache files scanned before the index was rebuilt.

    The agent works within limits I set. It uses the sites’ public pages and endpoints only, respects robots.txt, does not solve CAPTCHAs, enter passwords or handle login tokens, and anything I have to do myself comes as numbered steps from the first click. When it saves a file from a page, the page builds the file and a click on a link saves it to my Downloads folder.

    PDFs that show one thing and say another

    Not everything comes through the endpoint. Ministerial regulations, schedules and forms come as PDFs, and a PDF can look perfect on screen while its text layer says something else. The page is drawn from the glyph outlines in the embedded font; text extraction goes through a separate mapping from character codes to Unicode (the ToUnicode map, or the font’s encoding and glyph names when there is no map). If that mapping is wrong, the screen is right and the text is junk.

    Three faults turned up.

    Broken glyph maps. The outlines were intact; only the map was broken. So every glyph outline was hashed, hash-to-character was learned from pages whose maps are sound, and the junk glyphs were looked up by shape. On the first 29 junk pages that gave 27,277 glyphs and 88 distinct shapes, all decoded. One bug worth remembering: the font cache was keyed by PDF object id, and object ids repeat across files.

    Mac Thai. Seven files decoded at 0% through the glyph table. All used one font pair, and the glyph names inside were Mac Roman names standing at the positions of Apple’s old Mac OS Thai encoding. The text was Thai written in Mac Thai and read back as Mac Roman. The repair is a table:

    # simplified; Python has no mac_thai codec
    MAC_EXTRA = {0x83: "\u0E48", 0x88: "\u0E48", 0x89: "\u0E49", 0x8C: "\u0E4C",
                 0x92: "\u0E31", 0x93: "\u0E47", 0x94: "\u0E34", 0x95: "\u0E35",
                 0x97: "\u0E37", 0x8D: "\u201C", 0x8E: "\u201D"}
    
    def macthai_decode(s):
        out = []
        for ch in s:
            try:
                b = ch.encode("mac_roman")[0]
            except UnicodeEncodeError:
                out.append("\uFFFD"); continue
            if b < 0x80:
                out.append(ch)
            elif 0xA1 <= b <= 0xFB:            # Thai letters as in TIS-620; Apple's dashes and
                                               # symbols in this range differ and come out unknown
                out.append(bytes([b]).decode("cp874", errors="replace"))
            elif b in MAC_EXTRA:               # Apple's extra bytes, read from the pages
                out.append(MAC_EXTRA[b])
            else:
                out.append("\uFFFD")           # counted as unknown, never guessed
        return "".join(out)

    The first trial dropped every ส. Mac Roman 0xCA is a no-break space; in Mac Thai, 0xCA is ส, and the first trial read it as a space. A wrong decode can also come out looking like Thai, so a decoded page is accepted only if Thai spelling holds: a vowel or tone mark must follow a consonant, the leading vowels must precede one, and the violation rate must be under 1%.

    Sara aa written as sara am. Ten PDFs, 30 pages, wrote every า as ำ, and every real ำ with a space in front of it: กำร for การ, ก ำหนด for กำหนด. The page test called them Thai, because they are Thai letters. The repair is exact:

    # simplified
    import re
    MARK = "\uE000"
    def fix_sara_aa(t):
        t = re.sub(r" ([\u0E48-\u0E4B]?)\u0E33", lambda m: m.group(1) + MARK, t)  # " ำ" is the real ำ
        return t.replace("\u0E33", "\u0E32").replace(MARK, "\u0E33")             # every other ำ is า

    Detection is by impossible spellings, กำร, ตำม, จำก and a few more, appearing at least twice with none of the correct forms on the page. On the PDF folder it selected exactly those 30 pages. One of the ten files was the Land Code regulation on registration fees for transfers and mortgages.

    Then a check against the official source became possible. Seventy-three regulations under the main Acts came back as official text through the endpoint, with the same identifiers as PDFs already read. The measure is the share of each PDF page’s Thai letters found, in order, in the official text:

    method     pages   median
    macthai      24    0.984
    glyph        31    0.978
    pua          38    0.978
    layer       108    0.942
    ocr         160    0.717

    layer is a text layer taken as it is, pua a layer using the Unicode private-use area. Every page below 0.8 that was not one of the sara aa pages was a form or an annex: the official text holds the operative regulation only, and the PDF is the only source for forms and schedules. The 0.717 median for Tesseract on scanned Thai is why OCR text sits at T4. Thai numerals are the worst of it.

    Machine English I will not quote

    Accurate Thai I cannot read is of limited use to me. So every section has a machine English rendering, made locally by Google’s open Gemma model (gemma3:27b) through Ollama on a desktop graphics card. The 26,978 sections were split into 27,198 pieces for translation, and the run log records about 36 hours of model time between the evening of 28 September and the afternoon of 30 September.

    All of it is T4. The checks were there to make it good enough to search with and to read beside the Thai.

    1. Refusal at translation time: an answer is refused if it is empty, mostly Thai, far too short or far too long for the Thai it came from.
    2. Mechanical checks on every piece after every run: numbers in the Thai missing from the English; a section number that differs; a suffix section (มาตรา ๓ ตรี) not rendered as “3 ter”; fewer numbered items than the Thai; runaway repetition; chatter such as “Here is the translation”. A failure goes back with the reason written into the retry prompt, at most twice; after that it is listed for reading.
    3. A sample sheet of 30 random pieces, Thai beside English, at the end of every report.
    4. A termbase adherence table: for each fixed legal term, how often the English used the agreed rendering, and the Thai contexts the term turned up in.

    The fourth caught the best mistake of the month. The termbase said อาศัย means “habitation”, as in a right of habitation. Only 24% of pieces followed it, and the commonest context was อาศัยอำนาจ, “by virtue of the power”. The word inside other words was being translated as habitation. Land Code section 96 bis came out as aliens obtaining land “through habitation based on a treaty”; the Thai says by virtue of a treaty. The entry was narrowed to สิทธิอาศัย, right of habitation, and the bad renderings fell from 202 to 6, each of the 6 a proper use.

    Flagged pieces fell from 83 on the first pass to 7 on the last. Claude read those 7 against the Thai: six are real omissions of a number or a cross-reference and are listed as known defects, and one is a typo in the source. That is a machine checking a machine, which is the reason none of it is ever quoted.

    One file, a fifth of a second

    The Indian library runs on parquet files and DuckDB, because a million judgments need it. This one is a single SQLite file with two FTS5 indexes.

    • Thai uses the trigram tokenizer (SQLite 3.34 or later). Thai is written without spaces between words, and trigram matching needs no word-splitting. A query term shorter than three code points cannot use the trigram index, so it falls back to LIKE. Thai vowels and tone marks are separate code points, so ที่ is three of them.
    • English uses Porter stemming with prefix matching, a small synonym list (sale/sell, land/immovable, wife/spouse, foreigner/alien), and the termbase: an English phrase that matches a termbase rendering also searches the Thai term, at half weight.

    SQLite could not write its database file on the folder as the agent’s environment mounts it; the first attempt failed with disk I/O error. So the index is built in memory and written out in one go:

    # simplified; serialize() needs Python 3.11+
    import os, sqlite3
    mem = sqlite3.connect(":memory:")
    mem.execute("CREATE VIRTUAL TABLE fts_th USING fts5(text_th, tokenize='trigram')")
    # ... load sections, agency texts, notes ...
    with open(tmp_path, "wb") as f:
        f.write(mem.serialize())
    os.replace(tmp_path, index_path)   # the old index survives until the new one is complete

    A search looks like this. The square brackets mark the words that matched:

    python3 th_ask.py "matrimonial property"
    
    Civil and Commercial Code, section 1474
      TH  [T1 Thai, Council of State consolidation, in force from 2025-03-25]
          มาตรา ๑๔๗๔ สินสมรสได้แก่ทรัพย์สิน (๑) ที่คู่สมรสได้มาระหว่างสมรส ...
      EN  [T4 machine translation - NEVER quote or cite]
          Section 1474 [Matrimonial] [property] consists of [property] (1) which
          the spouses obtained during marriage. ...

    As of 1 October 2026: 26,978 sections, all with machine English; 1,218 third-party English pages; about 8,400 chunks of agency, tax, OCR, treaty and note text. The index is 146 MB, a full rebuild takes about 11 seconds, and a search returns in 0.1 to 0.2 seconds. I looked at moving it to the parquet-and-DuckDB layout of the Indian library and left it as it is. That layout exists for a 5.8 GB judgment index; an 11-second rebuild gains nothing from it.

    Case law, later

    Thai Supreme Court decisions are not in the library yet. That is a choice of order. In a civil law system a Supreme Court decision is not a precedent that binds; it carries persuasive weight and helps in reading the Code. The statute book had to come first. Case law is on the list for later, as a targeted set of decisions on property, family and succession rather than a bulk download.

    What I check before relying on it

    • The machine English. It is for finding and reading. Anything to be acted on needs an official English text where one exists, or a reading of the Thai by someone who reads it.
    • The consolidations. They trail behind amendments; the issuing department is the cross-check.
    • OCR text. It finds the page; then the page is read.
    • Forms and schedules. They exist only in the PDFs, and some of those PDFs are still unread.
    • The Bank of Thailand’s PDFs. 1,821 pages with junk text layers are measured and not solved. An improved glyph method can hash 98% of their glyphs, but more than half of those glyphs never appear on a clean page to learn from.

    What this is for

    I wanted to start any question of Thai law I study from the Thai text, with an honest label on every English word I lean on. The library does that now. A search gives me a Thai section, a T4 rendering to tell me what it says, and an official source to confirm it in.

    A note on what this is not

    I am an advocate enrolled in India. I am not a Thai lawyer, I do not practise Thai law, and as a foreign national I could not. Thai law allows only Thai nationals to register as lawyers (Lawyers Act B.E. 2528, section 35), and legal and litigation services are among the work Thai law reserves to Thai nationals, with narrow exceptions for arbitration. This library is a personal research tool for my own study. Nothing in this post is advice on Thai law. For any Thai-law matter, consult a lawyer licensed in Thailand.

    The texts in the library are public: Thai legislation, regulations, official notices and judgments, and translations of them made by Thai state agencies, are outside copyright under the Thai Copyright Act (section 7). Third-party English is held for private research only and is not reproduced here.

    Glossary

    B.E.: Buddhist Era. Thai dates count from it; B.E. = C.E. + 543, so B.E. 2569 is 2026.

    Council of State (ocs.go.th): the Thai government’s legal drafting office, which publishes consolidated texts of Thai laws.

    Consolidation: the text of a law with its amendments worked in. A convenience; the law itself is what was published in the Royal Gazette.

    Royal Gazette: the official gazette in which Thai laws are published and from which they take effect.

    มาตรา: section. bis, ter, quater: inserted sections numbered after an existing one.

    Termbase: a fixed list of Thai legal terms and their agreed English renderings, used to keep the machine translation consistent.

    FTS5: SQLite’s full-text search extension. Trigram tokenizer: indexes every run of three characters, so text without word boundaries can be searched without splitting it into words.

    ToUnicode map: the table inside a PDF that tells software which Unicode character each character code stands for. When it is wrong, a page looks right and extracts as nonsense.

    Mac Thai: Apple’s old 8-bit encoding for Thai, close to TIS-620 for the letters, with extra bytes for tone marks and vowels.

    OCR: optical character recognition. Tesseract is the open-source OCR engine used here.

    กฎหมายที่ผมอ่านไม่ออก

    ผมกำลังศึกษากฎหมายไทย แต่ผมอ่านภาษาไทยไม่ออก

    สำหรับคนเป็นนักกฎหมาย นี่เป็นสถานการณ์ที่ลำบากใจ กฎหมายไทยประกาศใช้เป็นภาษาไทย และตัวบทภาษาไทยคือตัวกฎหมาย ฉบับภาษาอังกฤษใด ๆ เป็นเพียงการอ่านของใครคนหนึ่ง สำหรับประมวลกฎหมายที่ว่าด้วยทรัพย์สิน ครอบครัว และมรดก หน่วยงานยกร่างกฎหมายของรัฐบาลไทยเองไม่มีตัวบทภาษาอังกฤษเลย ผมตรวจสอบแล้ว และวิธีที่ผมตรวจสอบก็เป็นส่วนหนึ่งของบทความนี้

    ผมจึงสร้างห้องสมุดกฎหมายแห่งที่สองขึ้นในคอมพิวเตอร์ของตัวเอง แห่งแรกเป็นตัวบทและคำพิพากษาของอินเดีย ซึ่งเป็นอีกโครงการหนึ่ง แห่งนี้เก็บกฎหมายไทยเป็นภาษาไทย ภาษาอังกฤษทุกบรรทัดมีป้ายบอกว่าเชื่อถือได้แค่ไหน และค้นหาได้ในเสี้ยววินาที

    ผมสร้างมันร่วมกับ Claude โมเดล AI ของ Anthropic ซึ่งทำงานในฐานะเอเจนต์ คือสั่งรันโปรแกรมบนคอมพิวเตอร์ของผมและใช้เบราว์เซอร์ Chrome ของผมได้ ภายใต้กฎที่ผมกำหนด การตัดสินใจเป็นของผม สคริปต์และการสืบค้นส่วนใหญ่มาจากโมเดล และความผิดพลาดจำนวนไม่น้อยก็เช่นกัน งานเริ่มเมื่อวันที่ 4 กันยายน 2026 และส่วนใหญ่ทำในสัปดาห์สุดท้ายของเดือนกันยายน

    ขอกล่าวไว้ก่อนเรื่องอื่น ผมเป็นทนายความอินเดีย ไม่ใช่ทนายความไทย บทความนี้เล่าเรื่องการสร้างเครื่องมือค้นคว้า ไม่ใช่คำแนะนำเกี่ยวกับกฎหมายไทย รายละเอียดอยู่ในหมายเหตุท้ายบทความ

    ภาษาอังกฤษทุกคำต้องมีป้าย

    การตัดสินใจแรกคือกฎว่าด้วยภาษาอังกฤษ

    ประเทศไทยใช้ระบบซีวิลลอว์ ศาลไทยไม่ผูกพันตามคำพิพากษาก่อนหน้าอย่างเป็นทางการ รวมถึงคำพิพากษาศาลฎีกา แม้คำพิพากษาเหล่านั้นจะมีน้ำหนักก็ตาม ตัวบทกฎหมายจึงสำคัญกว่าคำพิพากษา และตัวบทเป็นภาษาไทย ถ้าผมจะพึ่งพาสิ่งเหล่านี้ ประโยคภาษาอังกฤษทุกประโยคต้องบอกได้ว่ามาจากไหน

    จึงแบ่งเป็นสี่ระดับ:

    T1  ตัวบทภาษาไทยที่เป็นทางการ หรือภาษาอังกฤษที่หน่วยงานเผยแพร่เป็นส่วนหนึ่งของตัวกฎหมาย
    T2  ภาษาอังกฤษที่หน่วยงานรัฐของไทยเผยแพร่ โดยระบุว่าไม่เป็นทางการ
    T3  ภาษาอังกฤษจากบุคคลภายนอก เช่น คำแปลเชิงพาณิชย์ เว็บไซต์สำนักงานกฎหมาย
    T4  ผลงานแปลด้วยเครื่องของเราเอง ใช้เพื่อค้นหาและอ่านเท่านั้น ห้ามยกอ้าง ห้ามอ้างอิง

    ไฟล์ข้อความทุกไฟล์มีบรรทัด tier: ในส่วนหัว และเครื่องมือค้นหาพิมพ์ระดับไว้ข้างผลลัพธ์ทุกรายการ ภาษาอังกฤษที่แปลด้วยเครื่องจะขึ้นป้าย T4 machine translation - NEVER quote or cite เป็นตัวพิมพ์ใหญ่ทุกครั้ง ป้ายนี้คือสิ่งที่กันไม่ให้ประโยคที่อ่านลื่นไหลกลายเป็นข้อความที่ถูกนำไปอ้างอิง

    ตามหาตัวบท

    สำนักงานคณะกรรมการกฤษฎีกาเผยแพร่ตัวบทกฎหมายไทยฉบับปรับปรุงอย่างเป็นทางการ ที่อยู่เดิม krisdika.go.th ไม่ได้ให้บริการแล้ว หน่วยงานย้ายไปที่ ocs.go.th

    หน้าค้นหาของเว็บไซต์ใหม่ทำงานบน endpoint แบบ form-encoded คือ POST /searchlaw/indexs/list_table_search มีสองเรื่องที่ขวางอยู่ก่อนจะได้รายการที่ครบถ้วน

    เรื่องแรกคือ TLS เซิร์ฟเวอร์ไม่ส่งใบรับรองระดับกลาง (intermediate certificate) มาด้วย เบราว์เซอร์ไปดึงใบรับรองที่ขาดมาเองได้ แต่ไลบรารี requests ของ Python ทำไม่ได้และล้มเหลว การตั้ง verify=False จะทำให้ข้อผิดพลาดหายไปด้วยการปิดการตรวจสอบ วิธีที่ใช้แทนคือ truststore ซึ่งส่งงานตรวจสอบไปให้ระบบสร้างสายการรับรองของ Windows เอง และ Windows หาใบรับรองระดับกลางที่ขาดได้ การตรวจสอบจึงยังคงเกิดขึ้น

    เรื่องที่สองคือตัวกรอง หน้าค้นหาของเว็บไซต์ส่งพารามิเตอร์ query[lawCategoryName] ด้วยค่า 1B,1C เมื่อส่งแบบนั้น ดัชนีซ่อนไป 7 รายการจาก 147 รายการ เมื่อส่งเป็นค่าว่าง ได้ครบทั้ง 147 รายการ ถ้าไม่นับทั้งสองแบบ ผมคงไม่รู้

    ผลที่ได้คือชื่อกฎหมายและไฟล์ PDF แต่ยังไม่ใช่ตัวบท ตัวบทอยู่หลังหน้าแสดงผลซึ่งเป็นแอป Angular แบบหน้าเดียว และ endpoint ห้าแห่งที่ลองเดาได้ผล 404 ทั้งหมด สิ่งที่ได้ผลคือเปิดหน้าแสดงผลในเบราว์เซอร์ แล้วอ่านดูว่าหน้าเว็บขอตัวบทจากเซิร์ฟเวอร์อย่างไร จากการรับส่งข้อมูลบนเครือข่ายและจาก JavaScript bundle ของมัน หน้าแสดงผลใช้ endpoint JSON สาธารณะ:

    POST https://searchlaw.ocs.go.th/ocs-api/public/doc/getLawDoc
    Content-Type: application/json
    
    { "reqHeader": { ...request id, channel, timestamp, service name... },
      "reqBody":   { "timelineId": "<id from the index>", "isTransEng": false,
                     "sectionIds": [], "sectionAndExplains": [] } }

    คำตอบที่ได้เป็นข้อมูลมีโครงสร้าง แต่ละมาตรามีเลขมาตรา ป้าย และเนื้อหา HTML พร้อมทุกฉบับของกฎหมายนั้น สำหรับประมวลกฎหมายแพ่งและพาณิชย์ ได้ 2,254 รายการ 605,706 ตัวอักษร ใช้บังคับตั้งแต่วันที่ 25 มีนาคม 2025 การดาวน์โหลดไฟล์บนเว็บไซต์เดียวกันใช้อีกเส้นทางหนึ่งที่ต้องมีโทเคนซึ่งหน้าแสดงผลถืออยู่ โทเคนนั้นไม่เคยถูกอ่านหรือนำไปใช้ซ้ำ ไฟล์ PDF ภาษาอังกฤษที่กล่าวถึงด้านล่างบันทึกผ่านปุ่มดาวน์โหลดของหน้าแสดงผลเอง เหมือนผู้อ่านทั่วไปบันทึกไฟล์

    ภาษาอังกฤษที่ไม่มีอยู่จริง

    คำขอเดียวกันนี้มีแฟล็ก isTransEng เมื่อตั้งเป็น true จะเป็นการขอภาษาอังกฤษ

    สำหรับประมวลกฎหมายไทยทั้งแปดฉบับ คำตอบคือ SUCCESS แต่มีศูนย์มาตรา ระบบรู้จักชื่อภาษาอังกฤษของประมวลกฎหมายเหล่านี้ แต่ไม่มีตัวบทภาษาอังกฤษเลย

    มีข้อยกเว้นอยู่หนึ่งกรณี ไทม์ไลน์ของประมวลกฎหมายแพ่งและพาณิชย์มี 73 ฉบับ และหนึ่งในนั้น คือตัวบทดั้งเดิมปี 1925 มีเครื่องหมายว่ามีคำแปล เป็นไฟล์ขนาด 242 KB ตลอดหนึ่งสัปดาห์ สมมติฐานในการทำงานคือไฟล์นี้เป็นคำแปลภาษาอังกฤษของประมวลฯ ฉบับปี 1925 เมื่อดาวน์โหลดไฟล์มาอ่าน หน้าปกบอกไว้อีกอย่าง มันคือพระราชบัญญัติแก้ไขเพิ่มเติมประมวลกฎหมายแพ่งและพาณิชย์ (ฉบับที่ 20) พ.ศ. 2557 เป็นพระราชบัญญัติแก้ไขเพิ่มเติมเพียงฉบับเดียว ที่ถูกจัดเก็บไว้กับฉบับดั้งเดิม

    บันทึกจึงได้รับการแก้ไข พร้อมวันที่แก้ และการอ่านเดิมยังคงถูกเก็บไว้ รายการในไทม์ไลน์บอกได้เพียงว่ามีไฟล์อยู่ ตัวไฟล์เองเท่านั้นที่บอกว่ามันคืออะไร

    สำนักงานคณะกรรมการกฤษฎีกามีภาษาอังกฤษสำหรับกฎหมายฉบับอื่น และตอนนี้ PDF เหล่านั้น 70 ไฟล์ ครอบคลุมกฎหมาย 57 ฉบับ อยู่ในห้องสมุดแล้ว จัดอยู่ในระดับ T2 และระบุไว้ในตัวเองว่าภาษาไทยเป็นฉบับที่มีผลบังคับแต่ผู้เดียว หลายไฟล์กลายเป็นพระราชบัญญัติแก้ไขเพิ่มเติม ไม่ใช่ตัวพระราชบัญญัติหลัก ซึ่งเป็นอีกเหตุผลหนึ่งที่ห้องสมุดนี้อ่านตัวบทฉบับปรับปรุงภาษาไทยก่อนเสมอ

    มาตรา 2 ที่ปรากฏ 36 ครั้ง

    เมื่อ endpoint ใช้งานได้ ประมวลกฎหมายทั้งแปดฉบับก็ถูกดึงลงมาเป็นข้อความมีโครงสร้าง ได้ 5,526 รายการ ในจำนวนนี้เป็นบทบัญญัติที่มีเลขกำกับ 4,453 รายการ จากนั้นการนับก็เริ่มขึ้น และบั๊กอยู่ในการนับนั่นเอง

    มาตรา 2 ปรากฏ 36 ครั้งในไฟล์ประมวลกฎหมายแพ่งและพาณิชย์ ไฟล์ของประมวลกฎหมายแต่ละฉบับมีพระราชบัญญัติที่แก้ไขประมวลฯ นั้นต่อท้ายไว้ และพระราชบัญญัติแต่ละฉบับก็นับมาตราของตัวเองเริ่มจาก 1 ถ้าปล่อยไว้อย่างนั้น การค้นหามาตรา 2 จะพบ 36 รายการ และมีเพียงรายการเดียวที่ถูก ตอนนี้ทุกรายการมีแฟล็กระบุว่าเป็นของตัวประมวลฯ เองหรือไม่ นี่คือเหตุที่ 2,254 รายการในไฟล์ประมวลกฎหมายแพ่งและพาณิชย์ เหลือเป็นบทบัญญัติของประมวลฯ 1,850 มาตรา ส่วนที่เหลือคือหัวข้อและพระราชบัญญัติที่ต่อท้าย

    ตัวอย่างอื่น ๆ:

    • ประมวลกฎหมายที่ดินมีแปดรายการติดกันที่ป้ายเขียนว่ามาตรา 105 ทั้งหมด ความจริงคือมาตรา 105, 105 ทวิ, ตรี ไปจนถึงอัฏฐ ฟิลด์ป้ายตัดเลขมาตราให้สั้นลง จึงต้องแยกเลขมาตราจริงจากตัวข้อความ
    • เลขลำดับคำเดียวกันสะกดได้สองแบบ คือ อัฎฐ ใช้ ฎ ในประมวลกฎหมายวิธีพิจารณาความแพ่ง และ อัฏฐ ใช้ ฏ ในประมวลกฎหมายที่ดิน
    • เว็บไซต์ส่งคอมเมนต์ HTML ที่ถูก escape มา คือ &lt;!--[endif]--&gt; ซึ่งจะกลายเป็นคอมเมนต์ก็ต่อเมื่อ unescape แล้ว ตัวลบคอมเมนต์จึงมองไม่เห็น selftest ผ่านเพราะ fixture ใช้คอมเมนต์จริง มันถูกเขียนจากวิธีแก้ ไม่ใช่จากข้อมูล

    เมื่อแก้ทั้งหมดนี้แล้ว ไม่มีเลขมาตราใดในประมวลกฎหมายทั้งแปดฉบับที่ซ้ำกันอีก

    เมื่อกฎหมายที่ถูกยกเลิกแล้วยังเป็น “ฉบับปัจจุบัน”

    แต่ละฉบับในไทม์ไลน์ของกฎหมายมี stateId กำกับ 01 ดูเหมือนแปลว่า “มีผลใช้บังคับ” และ 00 ดูเหมือนแปลว่า “ถูกแทนที่แล้ว”

    ในแถวดัชนี 652 แถวที่ชื่อมีคำว่า (ยกเลิก) มีถึง 638 แถวที่อยู่ในสถานะ 01 ฉบับสุดท้ายของกฎหมายที่ถูกยกเลิกแล้ว ยังคงเป็นฉบับปัจจุบันของกฎหมายนั้น การยกเลิกจึงอ่านจากเครื่องหมายในชื่อ ไม่ใช่จากสถานะ

    การทดสอบเมื่อวันที่ 24 กันยายน พบสถานะที่สาม คือ 02 ประกาศแล้วแต่ยังไม่มีผลใช้บังคับ พร้อมประเภทฉบับที่ห้า คือฉบับปรับปรุงล่วงหน้าที่แสดงว่ากฎหมายจะเป็นอย่างไรเมื่อการแก้ไขที่รออยู่มีผล วันที่ 30 กันยายน เรื่องนี้ทำให้เจอกับดัก พระราชกฤษฎีกาว่าด้วยภาษีมูลค่าเพิ่มฉบับหนึ่งแสดงฉบับปรับปรุงล่วงหน้าที่มีผลตั้งแต่วันที่ 1 ตุลาคม 2026 และไม่ได้รวมพระราชกฤษฎีกาแก้ไขอีกฉบับที่ลงวันที่เดียวกัน ซึ่งคงอัตราที่ลดลงไว้อีกหนึ่งปี ถ้าอ่านฉบับล่วงหน้านั้นเพียงลำพัง จะได้อัตราที่ผิด ตอนนี้ห้องสมุดเก็บพระราชกฤษฎีกาแก้ไขฉบับนั้นแยกไว้ และติดธงเตือนฉบับล่วงหน้าใดก็ตามที่เหมือนฉบับปัจจุบัน

    ในวันเดียวกัน ห้องสมุดทั้งหมดได้รับการตรวจเทียบกับสำนักงานคณะกรรมการกฤษฎีกา 837 รายการในไทม์ไลน์ของกฎหมายแม่บทที่เก็บไว้ และกฎหมาย 773 ฉบับไม่มีฉบับใดเปลี่ยนแปลงนับจากวันที่ดึงมา แต่ตัวบทฉบับปรับปรุงเองอาจตามหลังการแก้ไขกฎหมาย ฉบับปรับปรุงล่าสุดของประมวลรัษฎากรบนเว็บไซต์ลงวันที่ 9 พฤศจิกายน 2021 เว็บไซต์ไม่สามารถแสดงการแก้ไขที่ยังไม่ได้นำมารวม หน่วยงานที่ออกกฎหมายจึงเป็นแหล่งตรวจสอบซ้ำ

    ทำงานกับเอเจนต์ที่ผิดพลาดได้

    เอเจนต์ที่รันโปรแกรมบนคอมพิวเตอร์ของผมและควบคุมเบราว์เซอร์ของผมได้ ทำงานได้มากในบ่ายวันเดียว แต่มันก็ผิดได้เกี่ยวกับไฟล์ที่มันไม่ได้เปิดดู และมันเขียนคำอธิบายที่อ่านลื่นไหลถึงสิ่งที่ไม่ได้เกิดขึ้นจริง กฎที่ผมใช้ทำงานล้วนเกิดจากเหตุการณ์จริง

    กฎเรื่องการแยกส่วนมาก่อน ห้องสมุดไทยอยู่ข้างห้องสมุดอินเดียบนดิสก์เดียวกัน และในช่วงแรก ข้อมูลสำรองของฝั่งไทยถูกเขียนลงในโฟลเดอร์สำรองของฝั่งอินเดีย ไม่มีอะไรสูญหาย แต่นับจากนั้น มีตัวป้องกันที่ปฏิเสธทุกเส้นทางที่อยู่ใต้โฟลเดอร์สำรองของอินเดีย และมีตัวตรวจที่ตรวจทุกสคริปต์ว่าเข้าถึงที่ใดได้บ้าง การสร้างตัวตรวจนี้ทำให้เกิดเหตุการณ์แปลก ๆ สองครั้งในเดือนนั้น:

    • io.open(path, "w", newline=...) ล้างไฟล์ก่อนที่จะแจ้งข้อผิดพลาดเมื่ออาร์กิวเมนต์ newline ไม่ถูกต้อง ตัวตรวจลบเนื้อหาตัวเองจนเหลือศูนย์ไบต์ด้วยวิธีนี้ ตอนนี้ทุกอย่างเขียนลงไฟล์ชั่วคราวก่อน แล้วจึงใช้ os.replace สลับเข้าที่
    • เส้นทางแบบ Windows อย่าง D:\...\Thai_Backup สำหรับโปรแกรมบน Linux เป็นเพียงชื่อไฟล์ธรรมดา เมื่อสั่งจากฝั่งเอเจนต์ การสำรองข้อมูลจึงสร้างโฟลเดอร์ที่ชื่อเป็นเส้นทาง Windows ทั้งเส้นขึ้นมาในห้องสมุด ดูเผิน ๆ เหมือนการสำรองข้อมูลสำเร็จ

    กฎข้อที่สองคือทุกคำกล่าวอ้างต้องแสดงหลักฐาน ถ้าเอเจนต์บอกว่ามีไฟล์สำรองอยู่ มันต้องแสดงรายการไฟล์ ถ้ามันขอให้ผมรันไฟล์ใด มันต้องเปิดไฟล์นั้นก่อนและยกบรรทัดที่ทำงานจริงมาให้ดู กฎนี้เกิดหลังเซสชันหนึ่งที่มีข้อผิดพลาดแบบนี้ห้าครั้ง หนึ่งในนั้นคือคำแนะนำให้รันไฟล์ batch ที่จะทิ้งงานสามวันไป

    กฎข้อที่สามคือต้องสำรองข้อมูลก่อนทำอะไรก็ตามที่เขียนทับไฟล์ ครั้งหนึ่ง ไฟล์ batch ที่ถูกแนะนำมาแบบผ่าน ๆ ได้เขียนทับไฟล์ที่อีกสคริปต์หนึ่งบันทึกผล OCR ไว้ และเวลาประมวลผลของเครื่องหลายชั่วโมงก็หายไปด้วย ตอนนี้ต้องทำสำเนาก่อนเสมอ และต้องแสดงค่า checksum ทั้งสองค่า เมื่อวันที่ 1 ตุลาคม กฎนี้ถูกใช้กับเรื่องเล็ก ๆ ไฟล์แคชคำแปลไฟล์หนึ่งมีไบต์ NUL 1,443 ไบต์ที่หลงเหลือจากการทำงานที่หยุดกลางคันเมื่อวันที่ 29 กันยายน ไม่มีอะไรสูญหาย เพราะงานส่วนนั้นถูกทำใหม่แล้ว แต่ก็ทำสำเนาก่อน ลบบรรทัดที่เสีย และสแกนไฟล์แคชทั้ง 776 ไฟล์ก่อนสร้างดัชนีใหม่

    เอเจนต์ทำงานภายในขอบเขตที่ผมกำหนด มันใช้เฉพาะหน้าเว็บและ endpoint สาธารณะของเว็บไซต์ เคารพ robots.txt ไม่แก้ CAPTCHA ไม่กรอกรหัสผ่าน ไม่จัดการโทเคนสำหรับล็อกอิน และงานใดที่ผมต้องทำเอง จะมาเป็นขั้นตอนมีเลขกำกับตั้งแต่การคลิกครั้งแรก เมื่อมันบันทึกไฟล์จากหน้าเว็บ หน้าเว็บจะสร้างไฟล์ขึ้น แล้วการคลิกลิงก์จะบันทึกไฟล์ลงในโฟลเดอร์ Downloads ของผม

    PDF ที่แสดงอย่างหนึ่งแต่บอกอีกอย่างหนึ่ง

    ไม่ใช่ทุกอย่างที่มาทาง endpoint กฎกระทรวง บัญชีท้าย และแบบฟอร์ม มาในรูป PDF และ PDF อาจดูสมบูรณ์บนหน้าจอ ขณะที่ชั้นข้อความของมันบอกอีกอย่างหนึ่ง หน้ากระดาษวาดจากโครงร่าง glyph ในฟอนต์ที่ฝังไว้ ส่วนการดึงข้อความผ่านการจับคู่อีกชุดหนึ่งจากรหัสอักขระไปเป็น Unicode (ตาราง ToUnicode หรือ encoding และชื่อ glyph ของฟอนต์เมื่อไม่มีตาราง) ถ้าการจับคู่นั้นผิด หน้าจอจะถูก แต่ข้อความจะเป็นขยะ

    พบข้อผิดพลาดสามแบบ

    ตาราง glyph เสีย โครงร่างยังสมบูรณ์ มีแต่ตารางที่เสีย จึงแฮชโครงร่างของทุก glyph เรียนรู้การจับคู่แฮชกับตัวอักษรจากหน้าที่ตารางถูกต้อง แล้วค้นหา glyph ที่เสียด้วยรูปร่าง ใน 29 หน้าแรกที่เสีย ได้ 27,277 glyph จากรูปร่างที่ไม่ซ้ำกัน 88 รูป ถอดได้ทั้งหมด บั๊กหนึ่งที่ควรจำไว้ แคชฟอนต์ใช้ object id ของ PDF เป็นคีย์ และ object id ซ้ำกันข้ามไฟล์ได้

    Mac Thai เจ็ดไฟล์ถอดได้ 0% ผ่านตาราง glyph ทุกไฟล์ใช้ฟอนต์คู่เดียวกัน และชื่อ glyph ข้างในเป็นชื่อแบบ Mac Roman ที่วางอยู่ตามตำแหน่งของรหัส Mac OS Thai เก่าของ Apple ข้อความเป็นภาษาไทยที่เขียนด้วย Mac Thai แต่ถูกอ่านกลับเป็น Mac Roman วิธีซ่อมคือตาราง:

    # simplified; Python has no mac_thai codec
    MAC_EXTRA = {0x83: "\u0E48", 0x88: "\u0E48", 0x89: "\u0E49", 0x8C: "\u0E4C",
                 0x92: "\u0E31", 0x93: "\u0E47", 0x94: "\u0E34", 0x95: "\u0E35",
                 0x97: "\u0E37", 0x8D: "\u201C", 0x8E: "\u201D"}
    
    def macthai_decode(s):
        out = []
        for ch in s:
            try:
                b = ch.encode("mac_roman")[0]
            except UnicodeEncodeError:
                out.append("\uFFFD"); continue
            if b < 0x80:
                out.append(ch)
            elif 0xA1 <= b <= 0xFB:            # Thai letters as in TIS-620; Apple's dashes and
                                               # symbols in this range differ and come out unknown
                out.append(bytes([b]).decode("cp874", errors="replace"))
            elif b in MAC_EXTRA:               # Apple's extra bytes, read from the pages
                out.append(MAC_EXTRA[b])
            else:
                out.append("\uFFFD")           # counted as unknown, never guessed
        return "".join(out)

    ความพยายามครั้งแรกทำ ส หายไปทุกตัว ไบต์ 0xCA ใน Mac Roman คือช่องว่างไม่ตัดบรรทัด แต่ใน Mac Thai 0xCA คือ ส และครั้งแรกอ่านมันเป็นช่องว่าง การถอดรหัสที่ผิดก็อาจออกมาดูเหมือนภาษาไทยได้ หน้าที่ถอดแล้วจึงยอมรับเฉพาะเมื่อการสะกดแบบไทยถูกต้อง คือสระหรือวรรณยุกต์ต้องตามหลังพยัญชนะ สระหน้าต้องนำหน้าพยัญชนะ และอัตราการผิดต้องต่ำกว่า 1%

    สระอา ที่เขียนเป็นสระอำ PDF สิบไฟล์ 30 หน้า เขียน า ทุกตัวเป็น ำ และ ำ ตัวจริงทุกตัวมีช่องว่างนำหน้า เช่น กำร แทน การ และ ก ำหนด แทน กำหนด การตรวจหน้ากระดาษบอกว่าเป็นภาษาไทย เพราะเป็นตัวอักษรไทยจริง วิธีซ่อมแม่นยำ:

    # simplified
    import re
    MARK = "\uE000"
    def fix_sara_aa(t):
        t = re.sub(r" ([\u0E48-\u0E4B]?)\u0E33", lambda m: m.group(1) + MARK, t)  # " ำ" is the real ำ
        return t.replace("\u0E33", "\u0E32").replace(MARK, "\u0E33")             # every other ำ is า

    การตรวจจับใช้การสะกดที่ภาษาไทยไม่มี เช่น กำร ตำม จำก และอีกเล็กน้อย ที่ปรากฏอย่างน้อยสองครั้ง โดยไม่มีรูปที่ถูกต้องเลยในหน้านั้น ในโฟลเดอร์ PDF วิธีนี้เลือกได้ตรง 30 หน้านั้นพอดี หนึ่งในสิบไฟล์คือกฎกระทรวงตามประมวลกฎหมายที่ดินว่าด้วยค่าธรรมเนียมจดทะเบียนการโอนและการจำนอง

    จากนั้นก็สามารถตรวจเทียบกับแหล่งทางการได้ กฎกระทรวงและพระราชกฤษฎีกา 73 ฉบับภายใต้พระราชบัญญัติหลักได้ตัวบททางการกลับมาผ่าน endpoint โดยมีรหัสเดียวกับ PDF ที่อ่านไปแล้ว ตัววัดคือสัดส่วนของตัวอักษรไทยในแต่ละหน้า PDF ที่พบเรียงตามลำดับในตัวบททางการ:

    method     pages   median
    macthai      24    0.984
    glyph        31    0.978
    pua          38    0.978
    layer       108    0.942
    ocr         160    0.717

    layer คือชั้นข้อความที่ใช้ตามที่เป็น pua คือชั้นข้อความที่ใช้พื้นที่ private-use ของ Unicode ทุกหน้าที่ได้ต่ำกว่า 0.8 ซึ่งไม่ใช่หน้าที่มีปัญหาสระอา เป็นแบบฟอร์มหรือภาคผนวก ตัวบททางการมีเฉพาะบทบัญญัติที่ใช้บังคับ และ PDF เป็นแหล่งเดียวของแบบฟอร์มและบัญชีท้าย ค่ามัธยฐาน 0.717 ของ Tesseract กับภาษาไทยที่สแกนมา คือเหตุผลที่ข้อความจาก OCR อยู่ในระดับ T4 ตัวเลขไทยแย่ที่สุด

    ภาษาอังกฤษจากเครื่องที่ผมจะไม่ยกอ้าง

    ตัวบทไทยที่ถูกต้องแต่ผมอ่านไม่ออกมีประโยชน์กับผมไม่มากนัก ทุกมาตราจึงมีคำแปลภาษาอังกฤษด้วยเครื่อง ทำบนเครื่องของผมเองด้วยโมเดลเปิด Gemma ของ Google (gemma3:27b) ผ่าน Ollama บนการ์ดจอของเครื่องเดสก์ท็อป มาตรา 26,978 มาตราถูกแบ่งเป็น 27,198 ชิ้นเพื่อแปล และบันทึกการทำงานแสดงเวลาประมวลผลของโมเดลราว 36 ชั่วโมง ระหว่างค่ำวันที่ 28 กันยายน ถึงบ่ายวันที่ 30 กันยายน

    ทั้งหมดอยู่ในระดับ T4 การตรวจสอบมีไว้ให้มันดีพอสำหรับใช้ค้นหาและอ่านเคียงข้างภาษาไทย

    1. ปฏิเสธตั้งแต่ตอนแปล: คำตอบจะถูกปฏิเสธถ้าว่างเปล่า เป็นภาษาไทยเสียส่วนใหญ่ หรือสั้นหรือยาวเกินไปมากเมื่อเทียบกับภาษาไทยต้นทาง
    2. การตรวจด้วยโปรแกรมกับทุกชิ้นหลังการแปลทุกรอบ: ตัวเลขในภาษาไทยที่หายไปจากภาษาอังกฤษ เลขมาตราที่ไม่ตรงกัน มาตราที่มีคำต่อท้าย (มาตรา ๓ ตรี) ที่ไม่ได้แปลเป็น “3 ter” จำนวนรายการที่น้อยกว่าภาษาไทย ข้อความวนซ้ำ และคำพูดเกินเลยอย่าง “Here is the translation” ชิ้นที่ไม่ผ่านถูกส่งกลับไปพร้อมเหตุผลที่เขียนไว้ในคำสั่งแปลใหม่ ไม่เกินสองครั้ง หลังจากนั้นจะถูกจดไว้ให้อ่านตรวจ
    3. แผ่นตัวอย่าง 30 ชิ้นสุ่ม ภาษาไทยเคียงภาษาอังกฤษ ท้ายรายงานทุกฉบับ
    4. ตารางการใช้ศัพท์: สำหรับศัพท์กฎหมายแต่ละคำที่กำหนดไว้ ภาษาอังกฤษใช้คำแปลที่ตกลงไว้บ่อยแค่ไหน และศัพท์นั้นปรากฏในบริบทภาษาไทยแบบใด

    ข้อที่สี่จับความผิดพลาดที่ดีที่สุดของเดือนได้ รายการศัพท์กำหนดว่า อาศัย แปลว่า “habitation” อย่างในคำว่าสิทธิอาศัย แต่มีเพียง 24% ของชิ้นงานที่ทำตาม และบริบทที่พบบ่อยที่สุดคือ อาศัยอำนาจ ซึ่งแปลว่า “by virtue of the power” คำนี้เมื่ออยู่ในคำอื่นถูกแปลเป็น habitation มาตรา 96 ทวิ แห่งประมวลกฎหมายที่ดินออกมาเป็นคนต่างด้าวได้ที่ดิน “through habitation based on a treaty” ขณะที่ภาษาไทยหมายถึงโดยอาศัยบทสนธิสัญญา ศัพท์จึงถูกจำกัดให้แคบลงเป็น สิทธิอาศัย = right of habitation และคำแปลที่ผิดลดลงจาก 202 เหลือ 6 ซึ่งทั้ง 6 เป็นการใช้ที่ถูกต้อง

    ชิ้นที่ถูกติดธงลดลงจาก 83 ในรอบแรก เหลือ 7 ในรอบสุดท้าย Claude อ่านทั้ง 7 ชิ้นเทียบกับภาษาไทย หกชิ้นเป็นการตกหล่นของตัวเลขหรือการอ้างอิงมาตราจริง และถูกบันทึกไว้เป็นข้อบกพร่องที่ทราบแล้ว อีกหนึ่งชิ้นเป็นการพิมพ์ผิดในต้นฉบับ นี่คือเครื่องตรวจเครื่อง ซึ่งเป็นเหตุผลที่ไม่มีส่วนใดของมันถูกยกอ้างเลย

    ไฟล์เดียว เสี้ยววินาที

    ห้องสมุดฝั่งอินเดียใช้ไฟล์ parquet กับ DuckDB เพราะคำพิพากษาหนึ่งล้านฉบับต้องการเช่นนั้น แห่งนี้เป็นไฟล์ SQLite ไฟล์เดียวที่มีดัชนี FTS5 สองชุด

    • ภาษาไทยใช้ tokenizer แบบ trigram (SQLite 3.34 ขึ้นไป) ภาษาไทยเขียนโดยไม่เว้นวรรคระหว่างคำ และการจับคู่แบบ trigram ไม่ต้องตัดคำ คำค้นที่สั้นกว่าสาม code point ใช้ดัชนี trigram ไม่ได้ จึงถอยไปใช้ LIKE สระและวรรณยุกต์ไทยเป็น code point แยกกัน ดังนั้น ที่ จึงมีสาม code point
    • ภาษาอังกฤษใช้ Porter stemming กับการจับคู่คำนำหน้า รายการคำพ้องสั้น ๆ (sale/sell, land/immovable, wife/spouse, foreigner/alien) และรายการศัพท์ วลีภาษาอังกฤษที่ตรงกับคำแปลในรายการศัพท์จะค้นหาศัพท์ภาษาไทยด้วย โดยให้น้ำหนักครึ่งหนึ่ง

    SQLite เขียนไฟล์ฐานข้อมูลลงในโฟลเดอร์ตามที่สภาพแวดล้อมของเอเจนต์ mount ไว้ไม่ได้ ความพยายามครั้งแรกล้มเหลวด้วย disk I/O error ดัชนีจึงถูกสร้างในหน่วยความจำ แล้วเขียนออกมาครั้งเดียว:

    # simplified; serialize() needs Python 3.11+
    import os, sqlite3
    mem = sqlite3.connect(":memory:")
    mem.execute("CREATE VIRTUAL TABLE fts_th USING fts5(text_th, tokenize='trigram')")
    # ... load sections, agency texts, notes ...
    with open(tmp_path, "wb") as f:
        f.write(mem.serialize())
    os.replace(tmp_path, index_path)   # the old index survives until the new one is complete

    การค้นหาหน้าตาเป็นแบบนี้ วงเล็บเหลี่ยมคือคำที่ค้นเจอ:

    python3 th_ask.py "matrimonial property"
    
    Civil and Commercial Code, section 1474
      TH  [T1 Thai, Council of State consolidation, in force from 2025-03-25]
          มาตรา ๑๔๗๔ สินสมรสได้แก่ทรัพย์สิน (๑) ที่คู่สมรสได้มาระหว่างสมรส ...
      EN  [T4 machine translation - NEVER quote or cite]
          Section 1474 [Matrimonial] [property] consists of [property] (1) which
          the spouses obtained during marriage. ...

    ณ วันที่ 1 ตุลาคม 2026: 26,978 มาตรา ทุกมาตรามีคำแปลภาษาอังกฤษด้วยเครื่อง หน้าภาษาอังกฤษจากบุคคลภายนอก 1,218 หน้า และข้อความจากหน่วยงาน ภาษี OCR สนธิสัญญา และบันทึก ราว 8,400 ส่วน ดัชนีมีขนาด 146 MB สร้างใหม่ทั้งหมดในราว 11 วินาที และการค้นหาใช้เวลา 0.1 ถึง 0.2 วินาที ผมพิจารณาจะย้ายไปใช้โครงสร้าง parquet และ DuckDB แบบห้องสมุดอินเดีย แล้วก็คงไว้อย่างเดิม โครงสร้างนั้นมีไว้สำหรับดัชนีคำพิพากษาขนาด 5.8 GB การสร้างใหม่ที่ใช้เวลา 11 วินาทีไม่ได้ประโยชน์อะไรจากมัน

    คำพิพากษา ไว้ทีหลัง

    คำพิพากษาศาลฎีกาของไทยยังไม่อยู่ในห้องสมุดนี้ นี่เป็นการเลือกลำดับงาน ในระบบซีวิลลอว์ คำพิพากษาศาลฎีกาไม่ใช่บรรทัดฐานที่มีผลผูกพัน แต่มีน้ำหนักในการโน้มน้าวและช่วยในการตีความประมวลกฎหมาย ตัวบทกฎหมายจึงต้องมาก่อน คำพิพากษาอยู่ในรายการงานภายหลัง โดยจะเลือกเฉพาะคำพิพากษาเรื่องทรัพย์สิน ครอบครัว และมรดก ไม่ใช่ดาวน์โหลดทั้งหมด

    สิ่งที่ผมตรวจสอบก่อนจะพึ่งพา

    • ภาษาอังกฤษจากเครื่อง ใช้เพื่อค้นหาและอ่าน สิ่งใดที่จะนำไปใช้ดำเนินการ ต้องมีตัวบทภาษาอังกฤษที่เป็นทางการถ้ามี หรือต้องมีผู้ที่อ่านภาษาไทยได้อ่านตัวบทภาษาไทย
    • ตัวบทฉบับปรับปรุง อาจตามหลังการแก้ไขกฎหมาย หน่วยงานที่ออกกฎหมายคือแหล่งตรวจสอบซ้ำ
    • ข้อความจาก OCR ใช้หาหน้าที่ต้องการ แล้วจึงอ่านหน้านั้น
    • แบบฟอร์มและบัญชีท้าย มีอยู่ใน PDF เท่านั้น และ PDF บางไฟล์ยังไม่ได้อ่าน
    • PDF ของธนาคารแห่งประเทศไทย มี 1,821 หน้าที่ชั้นข้อความเสีย วัดแล้วแต่ยังแก้ไม่ได้ วิธี glyph ที่ปรับปรุงแล้วแฮช glyph ได้ 98% แต่มากกว่าครึ่งของ glyph เหล่านั้นไม่เคยปรากฏในหน้าที่สมบูรณ์ให้เรียนรู้

    ทำไปเพื่ออะไร

    ผมต้องการเริ่มต้นคำถามทางกฎหมายไทยใดก็ตามที่ผมศึกษาจากตัวบทภาษาไทย โดยภาษาอังกฤษทุกคำที่ผมพึ่งพามีป้ายบอกที่มาอย่างตรงไปตรงมา ตอนนี้ห้องสมุดทำได้แล้ว การค้นหาให้มาตราภาษาไทย คำแปลระดับ T4 ที่บอกว่ามาตรานั้นว่าอย่างไร และแหล่งทางการให้ไปตรวจยืนยัน

    หมายเหตุ: สิ่งที่บทความนี้ไม่ใช่

    ผมเป็นทนายความที่จดทะเบียนในอินเดีย ผมไม่ใช่ทนายความไทย ผมไม่ได้ประกอบวิชาชีพกฎหมายไทย และในฐานะคนต่างชาติ ผมก็ทำไม่ได้ กฎหมายไทยให้เฉพาะผู้มีสัญชาติไทยจดทะเบียนเป็นทนายความได้ (พระราชบัญญัติทนายความ พ.ศ. 2528 มาตรา 35) และงานให้บริการทางกฎหมายหรืออรรถคดีเป็นงานที่กฎหมายไทยสงวนไว้สำหรับคนไทย โดยมีข้อยกเว้นแคบ ๆ สำหรับงานอนุญาโตตุลาการ ห้องสมุดนี้เป็นเครื่องมือค้นคว้าส่วนตัวสำหรับการศึกษาของผมเอง ไม่มีส่วนใดในบทความนี้เป็นคำแนะนำเกี่ยวกับกฎหมายไทย สำหรับเรื่องกฎหมายไทยใด ๆ โปรดปรึกษาทนายความที่ได้รับใบอนุญาตในประเทศไทย

    ตัวบทในห้องสมุดเป็นเอกสารสาธารณะ กฎหมาย ระเบียบ ประกาศ คำสั่ง และคำพิพากษาของไทย รวมทั้งคำแปลที่หน่วยงานรัฐของไทยจัดทำ ไม่ถือเป็นงานอันมีลิขสิทธิ์ตามพระราชบัญญัติลิขสิทธิ์ (มาตรา 7) ภาษาอังกฤษจากบุคคลภายนอกเก็บไว้เพื่อการค้นคว้าส่วนตัวเท่านั้น และไม่ได้นำมาเผยแพร่ในที่นี้

    อภิธานศัพท์

    พ.ศ.: พุทธศักราช ไทยนับปีตามนี้ พ.ศ. = ค.ศ. + 543 ดังนั้น พ.ศ. 2569 คือ ค.ศ. 2026

    สำนักงานคณะกรรมการกฤษฎีกา (ocs.go.th): หน่วยงานยกร่างกฎหมายของรัฐบาลไทย ผู้เผยแพร่ตัวบทกฎหมายไทยฉบับปรับปรุง

    ฉบับปรับปรุง (consolidation): ตัวบทกฎหมายที่รวมการแก้ไขเพิ่มเติมไว้แล้ว ใช้เพื่อความสะดวก ตัวกฎหมายจริงคือสิ่งที่ประกาศในราชกิจจานุเบกษา

    ราชกิจจานุเบกษา: หนังสือราชการที่ใช้ประกาศกฎหมายไทย กฎหมายเริ่มมีผลนับจากการประกาศนี้

    ทวิ ตรี จัตวา: มาตราที่แทรกเพิ่มต่อจากมาตราเดิม เทียบได้กับ bis, ter, quater

    รายการศัพท์ (termbase): รายการศัพท์กฎหมายไทยพร้อมคำแปลภาษาอังกฤษที่ตกลงกันไว้ ใช้ให้คำแปลด้วยเครื่องสม่ำเสมอ

    FTS5: ส่วนขยายการค้นหาข้อความเต็มของ SQLite Trigram tokenizer: สร้างดัชนีจากทุกช่วงสามตัวอักษร ทำให้ค้นหาข้อความที่ไม่มีการแบ่งคำได้โดยไม่ต้องตัดคำ

    ตาราง ToUnicode: ตารางใน PDF ที่บอกซอฟต์แวร์ว่ารหัสอักขระแต่ละตัวคือตัวอักษร Unicode ใด ถ้าตารางผิด หน้าจะดูถูกต้องแต่ดึงข้อความออกมาเป็นขยะ

    Mac Thai: รหัสอักขระภาษาไทยแบบ 8 บิตรุ่นเก่าของ Apple ตัวอักษรใกล้เคียง TIS-620 โดยมีไบต์เพิ่มสำหรับวรรณยุกต์และสระ

    OCR: ซอฟต์แวร์รู้จำตัวอักษร Tesseract คือเครื่องมือ OCR แบบโอเพนซอร์สที่ใช้ในงานนี้

  • The section that wasn’t there

    The section that wasn’t there

    I asked my own law database for section 5 of the Hyderabad Metropolitan Development Authority Act, 2008. It told me there was no such section.

    There is. It is on the printed page in front of me. The database had the text, all of it, and could not find it, because the text was filed under a different number.

    This is a post about building a searchable corpus of Indian statutes and case law on my own machine, and about the fact that the dangerous failure is never the database that says nothing. It is the one that answers with confidence and is wrong.

    I built it over several weeks with Claude. I made the decisions, ran everything on my own hardware, and checked the law myself; the scripts and most of the analysis came from the model. The mistakes are in here as well, because on a project of this shape the mistakes are the content. Nearly every genuine improvement came from something being printed to screen that looked wrong.

    Why hold law locally at all

    I am an advocate. My practice is property, title due diligence, drafting. The work needs the text of statutes, rules, government orders and judgments, constantly, and mostly for a narrow set of jurisdictions: Central Acts, Telangana, and the Andhra Pradesh that Telangana inherited.

    The obvious answer is a subscription database. They work. But two things pushed me the other way.

    The first is cost and dependence. The second matters more: I cannot audit what I cannot see inside. When a subscription database returns nothing for a section, I have no way of knowing whether the section does not exist, or whether their ingestion mangled it the way mine mangled HMDA section 5. When my own corpus does that, I can go and look.

    There is also a speed argument that turns out to be real. Searching a million judgments on my own machine takes about a second.

    What the corpus is made of

    The whole thing lives on a Windows desktop workstation. The pipeline is deliberately dull: scrape original sources, convert to markdown, write parquet, query with DuckDB. No database server, no index server, nothing to keep running. Files on a disk.

    An early decision shaped everything after it. There is a bulk dataset of Indian legislation on Hugging Face, and I downloaded it. Then I decided not to use it for statutes, and to scrape India Code and the Telangana Law Department fresh instead. Not because the dataset is bad, but because I wanted to know the provenance of every section I might cite, and to be able to go back to the page it came from. I kept the dataset to cross-check against, once.

    What the Act surface holds today, counted this morning:

    58,381 rows across eight parquet files
    
      India Code       828 Central Acts     35,390 sections
                       112 Telangana Acts    1,542 sections
      Telangana Law Dept   184 Acts
      Schedules            380 Acts          1,484 schedule rows
      Act-level PDFs       452 Acts
          196  Andhra Pradesh, pre-2014, applies in Telangana
          179  Telangana
           56  Andhra Pradesh, post-2014, residuary AP only
           18  Central
      Harvested G.O.s, circulars, orders   757 rows

    Separately there is a read-only index of my own prior work, so a search can turn up a deed I drafted alongside the section it relied on.

    That AP split is not decorative. Andhra Pradesh was bifurcated on 2 June 2014, and an AP Act from before that date still applies in Telangana while one from after it does not. Every result line says which, because an Act that does not apply is still an Act, and the distinction has to survive into whatever is filed.

    Counting is not checking

    Here is the mistake that reshaped how I check this corpus.

    The corpus held the HMDA Act with 58 sections, numbered up to 58. That looks complete. It is not. Sections 5, 6 and 8 were absent, and their text was inside the row filed as section 9, a row that opens with the repeal of a 1988 water-rates ordinance and runs to 10,362 characters, having swallowed several sections that come before it.

    The cause is visible on the printed page. HMDA prints its section headings as marginal notes, in a column beside the body text. Extract a text layer from that PDF and the headings interleave with the sentences, so 5. never begins a line, and a splitter looking for a number at the start of a line never sees one.

    So I stopped trusting counts and audited numbering continuity instead: for every Act holding eight or more numbered sections, is the run of numbers unbroken?

    When that ran, on 27 August 2026, it found 1,151 Acts with eight or more sections and 99 with a gap. Most gaps are honest: sections repealed, or omitted from the source. But in 38 of them the missing section’s heading was present inside another row. The text was in the corpus, filed under the wrong number.

    Re-running the same audit today gives 1,158 Acts and 86 gaps. The difference is the repair described below.

    The consequence is worth stating plainly. Full-text search reaches misfiled text without difficulty. It is a lookup by section number that fails, and it fails by reporting that a section does not exist when it does. That is the wrong direction to fail in.

    repair.py, and five ways it nearly filed the wrong text

    Recovering misfiled sections sounds simple: find the missing number used as a heading inside another row, cut from there to the next heading, file it under its own number.

    It is not simple, and the first version was wrong in five separate ways. All five were found by running it in a sandbox and reading the output before it touched anything.

    It missed the section it was written for. The heading pattern required text to continue on the same line. India Code prints 5. alone, with (1) There shall be... on the line below. HMDA section 5, the whole reason the script existed, did not match.

    Cuts ran to the end of the host row. A recovered section 8 swallowed section 9 and everything after it. Cuts now end at the next heading of any number.

    Footnotes were recovered as sections. 54. Section 43 substituted by Act No.11 of 1969 is a footnote. It looks exactly like a section heading.

    Page-group rows were used as hosts. Where an Act could not be split reliably it is stored as page groups, which contain the entire text, so every number appears in them. Recovering from those produces nonsense.

    The same number was recovered from six different rows of the Wealth-tax Act.

    The gate that did most of the work is a structural one: a row can only have swallowed sections that precede it. So a recovered number must be lower than its host’s number and within 40 of it. Without that gate, the Greater Hyderabad Municipal Corporation Act “recovered” section 19 out of a row filed as section 687, which is a schedule of cycle-rickshaw fees.

    Ungated, the pass proposed 34 Acts and 133 sections. Gated, it proposed 23 Acts and 49 sections, and the 23 rejected candidates each carry a stated reason.

    Today repairs_acts.parquet holds 49 recovered sections across 23 Acts, each labelled with the row it was cut from and marked medium confidence. It never edits another script’s file. The recovered rows join the same glob the reader already reads.

    A correction

    An earlier note of mine recorded that the GHMC Act had “37 of 53 gaps recoverable”. That was wrong, and it came from a crude heading search with none of the gates above.

    A properly gated pass recovers nothing from GHMC. Its numbering gaps are footnote markers and schedule item numbers, not missing sections. Today the audit still shows GHMC with 635 sections present and 52 numbers missing, and that is the correct answer: they were never sections.

    I am recording the wrong figure as well as the right one because a corpus you cannot correct in public is a corpus nobody should trust, including you.

    Heuristics that fail interestingly

    Three gates keep schedules and tables out of the recovery pass, and each was calibrated against real documents.

    Digit density. Statutory prose runs 3 to 4 per cent digits. Schedules run 24 per cent and up. The threshold sits at 18. This caught a recovered “section” of 247,454 characters that was the Telangana Panchayat Raj Act’s schedule of village names.

    Line length. Text laid out as a table puts each field on its own line. Village schedules average 9 characters per line; statutory prose averages 75.

    That second gate was first set at 28 characters, and it rejected HMDA sections 5 and 8. India Code wraps its prose at about 27, and a section that is a list of committee members has short lines. A threshold tuned on the wrong sample rejected precisely the sections the whole exercise existed to recover. Moved to 15, the pass went from 44 sections to 49, the five additions being HMDA sections 5 and 8, Telangana Municipalities section 32, and two sections of the Telangana State Private Universities Act.

    Capture ratio. Any split that captures under 92 per cent of a document’s text is rejected in favour of page chunks. This exists because of a specific failure: an Act splitter applied to a Government Order treats the numbered list of earlier G.O.s it cites as the sections. G.O.Ms.No.59 came out as a single “section 4” holding 47 per cent of the document, with the abstract and the operative order silently gone. Instruments that are not Acts, Rules or Regulations are no longer split at all.

    Fifty gigabytes of judgments, and what they do not carry

    Judgments come from the open-india-law dataset: 63 parquet files, 53.7 GB. I hold all of them.

    The indexed corpus covers the courts that matter to my practice:

      telangana        1,005,147 judgments
      andhra-pradesh     261,778
      supreme-court       37,014

    Now the part that decides how you use this data. Metadata completeness, measured this morning:

      court            judgments    no citation   no judges
      telangana        1,005,147        100.0%       81.9%
      andhra-pradesh     261,778        100.0%       88.3%
      supreme-court       37,014          0.0%        0.0%

    Every Supreme Court judgment carries a citation and a bench. Not one High Court judgment in over 1.26 million carries a citation. You get the text and the case number and nothing you can put in a plaint.

    That is not a defect in the dataset so much as a fact about what is freely available, and it changes the workflow rather than ending it. The corpus is where I find the case and read the reasoning. The citation comes from elsewhere, and it comes before anything is filed.

    The dates need care too. Telangana decision dates in this data run from 23 October 1952 to 27 December 2079. Twelve judgments are dated in the future. The year column in the Andhra Pradesh file tracks ingestion rather than decision and cannot be used for anything.

    Which court binds

    For a matter in Telangana, a Supreme Court judgment binds, the Telangana High Court binds, and the Andhra Pradesh High Court binds only for the period before bifurcation. Bombay and Madras are persuasive, and worth reading, and they are not the same thing. The distinction has to survive into the document.

    The dataset splits along that line almost exactly, which was a pleasant surprise:

      telangana, decided before 01.01.2019          707,308
      andhra-pradesh, decided before 01.01.2019       1,011
      andhra-pradesh, decided 01.01.2019 onwards    259,200

    The in_telangana file is the predecessor court’s whole corpus going back to 1952. The in_andhra-pradesh file is overwhelmingly the reconstituted court at Amaravati. So the default tier applies a date predicate to the AP file alone, and the binding tier comes to 1,043,172 judgments. Every result line is labelled BINDING or persuasive, and a binding search says on its face that the other High Courts were not searched.

    This nearly went wrong in a way worth describing, because it is the most dangerous class of bug in the whole project.

    DuckDB’s regexp_extract(string, pattern) returns the whole match, not the capture group. The build stored in_telangana_judgments where it meant telangana. Every comparison against a bare court name then failed silently. The effect was that 260,766 post-2019 Amaravati judgments sat in the binding tier, labelled BINDING, and the authority ranking collapsed to plain date order.

    Nothing errored. Nothing looked broken. A one-argument mistake quietly relabelled persuasive authority as binding, which in a document going to court is exactly the sort of error you do not get to explain away. The build now passes the group index, and the reader normalises whatever form it finds, so a stale index cannot mislabel authority even if it is rebuilt wrongly.

    Search without a search engine

    The obvious way to search a million judgments is a full-text index. I could not use one, for a reason that is specific and worth explaining, because it shaped the design.

    The environment Claude reaches my machine through is a small sandbox: 2 CPUs, 3 GB of RAM. My workstation reports 32 CPUs. A full scan of the 9.1 GB binding tier takes seconds on the workstation and over three minutes in the sandbox, which is past the timeout on a single call. DuckDB’s full-text extension cannot be installed in that sandbox at all: the extension installer has no network route it can use there.

    So an index that needed the extension would have been unreadable by the one reader that most needed it. The answer was plain sorted parquet, built natively on the fast machine, read cheaply by anything.

    Four files:

      cases.parquet      one row per judgment            0.05 GB
      text.parquet       chunks, sorted by case          4.24 GB
      vocab.parquet      words and their ids             0.10 GB
      postings.parquet   (token, case, chunk)            0.91 GB
                                                total    5.31 GB

    Over 1,303,939 judgments, 15,057,895 distinct indexed words, and 397,445,969 postings.

    Two calibration decisions matter more than the structure.

    Minimum word length is 4, not 5. Sale, deed, gift, rent and lien all carry legal phrases. Three-letter words are lost, so lis pendens is found on pendens alone, which is fine because the rarer half of a phrase does the work.

    The commonness cut is 10 per cent, not 1. Words appearing in more than that share of cases are not indexed, because indexing them costs enormously and narrows nothing. The first threshold chosen was 1 per cent. Measured against 17,684 Supreme Court cases:

      possession      5.3%
      registration    1.9%
      performance     1.8%
      adverse         1.6%
      injunction      1.1%
      mortgage        1.0%

    A 1 per cent cut would have excluded every one of them. It would have produced a technically excellent index, of a corpus of property judgments, that could not search for possession, registration, performance, adverse or mortgage. Only 375 words are common enough to exclude at 10 per cent, and when a search hits one it is reported by name, so a search for “part performance” says it searched on performance alone.

    Matching is by proximity, not merely co-occurrence. Postings carry the chunk as well as the case, so intersecting on chunk requires the words to fall within the same passage of roughly 2,000 characters. It does not prove the phrase appears in that order. It is much better than “both words are somewhere in this judgment”, and the phrase still has to be confirmed by reading.

    Three performance facts

    Row group size is the difference between a skip and a scan. At 50,000 rows per group, each group in text.parquet held about 80 MB of text, so fetching 200 scattered cases decompressed most of the file and took 29 seconds. At 1,000 rows a group is under a megabyte and the reader skips almost everything.

    An IN-list of literals is pushed down; a JOIN is not. The same 200 lookups written as a join against a temporary table read the entire file: 0.1 seconds became over 40.

    A warm cache lied to me twice. Verifying a phrase by reading the text costs about 20 seconds cold, however few cases it asks for, because a 4 GB store cannot stay resident in 3 GB of RAM. Two earlier measurements of 2.5 seconds were a warm cache, and they misled the design twice before the proximity approach removed the need to read text at query time at all.

    Where it landed, on 2 threads:

      specific performance   1.02s   8,466 cases
      adverse possession     0.91s
      lis pendens            0.85s
      pattadar pass book     0.92s

    Against over three minutes before any of this.

    One further thing had to be designed rather than discovered. Ordering strictly by authority, a window on “specific performance” returned 400 Supreme Court cases and nothing at all from 11,429 Telangana candidates. Telangana is the court I appear before. Display slots are now shared between courts, allocated smallest tier first so slack flows onward.

    What I still do not trust

    A corpus is only as useful as its own account of where it is weak.

    Two Central Acts cannot be completed from India Code. The Income-tax Act 1961 and the EPF Act 1952. India Code holds no Act-level PDF for them and only a fraction of the sections. Both are fetched separately.

    The Hindu Succession (Andhra Pradesh Amendment) Act 1986 matters for coparcenary devolution before 9 September 2005, and the only copy I have is from PRS Legislative Research, which prints its own disclaimer that the text is unverified. It is deliberately kept off the Act surface and findable only in my own-work index. The real text has to come from the Law Department before it is cited.

    Every HMDA document arrived over an unvalidated TLS connection. All 75 are stamped tls=unverified, because hmda.gov.in’s certificate chain does not validate. They are usable and they are flagged, and any one of them is checked against the browser copy before it is cited.

    OCR misreads digits. 522 scanned PDFs, 6,738 pages, English and Telugu, banded 222 high confidence, 193 medium, 107 low. A document number came back as NO,P 2418/2013-14. Any survey number, extent or consideration taken from OCR text is checked against the original PDF. Results drawn from OCR print a warning saying so. And the opening pages of a registered deed are the stamp paper, which OCRs as ornament noise, so an OCR’d deed is judged by its body and not its first lines.

    Some sources cannot be harvested at all. The CCLA site renders a page header and stops: viewActs.do, viewGO.do and viewCirculars.do each return two links and no table. That is not a selector problem, the pages are empty. And goir.telangana.gov.in is an ASP.NET WebForms application with view-state and cascading postbacks, where a result set only exists after a POST carrying the view-state the server has just issued. A listing-page harvester cannot touch it.

    A naming rule learned the hard way. A document’s title becomes its act name, and lookups match that name loosely. A document titled “Registration Rules, Telangana — rules under the Registration Act, 1908” shadowed the Registration Act itself, so asking for section 49 of the Registration Act returned rule 49 instead of section 49, which is the provision on the effect of non-registration. A title must never contain another instrument’s name.

    And one Act answers twice, by design. HMDA section 5 exists in the corpus in two forms: the Act as originally enacted, naming APIIC, APHB and APSRTC, hand-read by me from printed pages; and the India Code text as adapted for Telangana by G.O.Ms.No.45, Law (F) Department, dated 1 June 2016, naming TSIIC, the Telangana Housing Board and TSTRANSCO. Both are correct. For the composition of the Executive Committee as it stands today, the adapted text governs.

    What this is actually for

    It is not a product and I am not proposing that anyone else run one. It is a tool with a known shape, whose weaknesses are written down where I can see them, which answers in about a second, and which does not stop working if a subscription lapses or a website is redesigned.

    The thing I did not expect was how much of the work would be auditing rather than building. The scraping was a weekend. The gates, the calibration, the gap analysis, the five defects in the recovery pass and the one-argument bug that mislabelled a quarter of a million judgments as binding — that was the actual project.

    Which brings it back to HMDA section 5. It was in the corpus the whole time. The lesson is not that the pipeline was bad. It is that a lookup which answers “no such section” and a lookup which answers “here is section 5” can both be produced by a database that holds the same bytes, and the only thing standing between them is whether anyone checked.


    Glossary

    This post has two audiences, and each will find half of it obvious. The terms below are defined in the order they appear, on the assumption that no reader knows both halves.

    Act surface — my term for the set of files a section lookup searches, as distinct from the full-text library. A document promoted to the Act surface can be asked for by section number. One left in the library can only be found by searching its words.

    Parquet — a file format for storing tables in columns rather than rows, compressed, with statistics recorded for blocks of rows. A reader can consult those statistics and skip blocks that cannot contain what it wants, without decompressing them.

    Row group — a block of rows inside a parquet file, and the unit that a reader skips or reads. Their size is a design decision, discussed above.

    DuckDB — a database engine that runs inside your program rather than as a server, and reads parquet files directly from disk. No installation to maintain, no daemon running.

    Predicate pushdown — the behaviour that makes the above work: the filter is handed down to the file reader so it can skip data, instead of the reader returning everything and the filter discarding most of it afterwards. An IN-list of literal values is pushed down. A join against another table generally is not.

    Full-text index / FTS — the conventional machinery for searching text at speed, usually a database extension. Not used here, for the sandbox reasons set out above.

    Vocabulary and postings — the two halves of any word index. The vocabulary maps each word to a number. The postings list records, for each word number, where it occurs. Searching is intersecting postings lists.

    Posting — one entry in that list. Here each posting is a triple of word, case and chunk, which is what makes proximity matching possible.

    Chunk — a passage of a judgment, roughly 2,000 characters. Judgments are stored in chunks so that “these two words appear in the same chunk” can stand in for “these two words appear near each other”.

    Proximity matching — requiring search terms to fall within the same chunk, rather than merely somewhere in the same document. It does not prove the words appear as a phrase in that order.

    MINLEN — the shortest word the index will store. Set to 4 here.

    Commonness cut — the share of documents above which a word is too common to be worth indexing. Set to 10 per cent here, for the reasons measured above.

    OCR — optical character recognition, deriving text from a scanned image. Reliable for prose, unreliable for digits, which is why numbers taken from OCR are checked against the original.

    Text layer — the machine-readable text embedded in a PDF. A PDF produced from a word processor has a good one. A PDF that is a photograph of a page has none, and needs OCR.

    Marginal note — a section heading printed in the margin beside the body text rather than above it. The cause of the HMDA failure: in the text layer the marginal notes interleave with the sentences.

    Splitter — the code that divides a statute into its sections. Most of the failures described here are splitter failures.

    Page group — the fallback when a document cannot be split reliably: it is stored as groups of pages, flagged as unsplit, rather than given section numbers that might be wrong.

    Capture ratio — the proportion of a document’s text that a split accounts for. Below 92 per cent the split is rejected, so no document can silently lose text.

    Digit density — the proportion of characters in a block that are digits. Prose runs 3 to 4 per cent, schedules 24 per cent and up.

    Harvester — the script that fetches documents from government websites, driven by a manifest describing each source, rather than a separate scraper per site.

    Manifest — the configuration file listing each source, its pages, and how to treat what it returns.

    G.O. — Government Order. A departmental instrument. G.O.Ms. is an Ordinary Order; the number and date identify it.

    India Code — the Government of India’s official repository of Central and State legislation.

    Bifurcation — the division of Andhra Pradesh on 2 June 2014, creating Telangana. An Andhra Pradesh Act from before that date continues to apply in Telangana; one from after it does not.

    Binding and persuasive — a judgment of a court above you in your own hierarchy binds. A judgment of a court of equal standing elsewhere is persuasive: worth reading, worth citing, but it does not compel a result.

    Pattadar pass book — the Telangana land record document evidencing a cultivator’s rights. Used above as a search example because it is a phrase of exactly the shape this index handles well.

    Coparcenary — in Hindu law, the body of family members who take an interest in ancestral property by birth. Relevant here because devolution before 9 September 2005 turns on statutory amendments that must be sourced accurately.

    Sandbox — the constrained environment the AI assistant reaches my machine through: 2 CPUs, 3 GB of RAM, restricted network. Several design decisions exist only because of it.

    TLS validation — the check that a website’s certificate chains to a trusted authority. tls=unverified on a stored document means the download was made without that check succeeding, and the document should be confirmed against the browser copy before it is relied upon.

  • A parse error, a stalled upgrade, and fifteen years of silence

    A parse error, a stalled upgrade, and fifteen years of silence

    I knew this site was broken. I did not know for how long, or why, and for years I did not look. It sat at techblog.viveksanghi.com returning nothing, and every year that passed made it a slightly larger thing to open.

    When I finally opened it, the server turned out to have been keeping a precise record of what happened.

    I did the work over one evening with Claude, which matters to how this reads. I made the decisions and ran every command on my own server; the diagnosis, the scripts and several confident wrong turns came from the model. The wrong turns are in here too, because they were the useful part. Tech is a hobby for me. Law is what earns my living, and a fifteen-year-old broken WordPress had long since stopped being a thing I could justify an evening on. Having something that would grind through log files and SQL dumps without getting bored changed that arithmetic.

    What the server was saying

    The first question was whether anything was alive at all. The domain resolved to my host’s IP, same as my other sites, so DNS was fine. HTTPS failed on a certificate error. Over plain HTTP I got a 301 to the www hostname, then a 500 Internal Server Error with an empty response body.

    An empty 500 is a particular kind of unhelpful. No error on the page, no stack trace, nothing to search for. It means PHP died before producing output, with display_errors off, which on a production host it should be.

    The useful clue came from the access log rather than the error log:

    2026-09-02 21:24:28   200   /favicon.ico

    A 200. Static files were being served. That one line rules out most of what an empty 500 can mean. Apache was healthy, the virtual host was configured, the document root pointed at the right folder. Only PHP was dying.

    Which meant anything on the site that was not PHP could still be read. So we asked for the file every WordPress install ships and nobody ever deletes:

    curl http://techblog.viveksanghi.com/readme.html
    Version 3.1.2
    Semantic Personal Publishing Platform

    WordPress 3.1.2, released April 2011.

    The one-line cause

    The error log had been recording the same entry for years:

    [techblog.viveksanghi.com] [warn] mod_fcgid: stderr: PHP Parse error:
    syntax error, unexpected token "new" in
    /home/<user>/techblog.viveksanghi.com/wp-settings.php on line 219

    Line 219 of WordPress 3.1.2 reads:

    $wp_the_query =& new WP_Query();

    That =& is assignment by reference to a newly created object. It was correct in PHP 4, where objects were copied on assignment and the reference avoided the copy. PHP 5 made objects handle-based and the construction became pointless. It was deprecated in PHP 5.3 and removed in PHP 7.0.

    Removed, not deprecated. In PHP 7 and later this is not a warning or a runtime error. It is a parse error. PHP refuses to compile the file, so nothing in it executes, no error handler runs, no output is produced, and Apache has nothing to return but a bare 500.

    The site did not break from anything I did. It broke when my host moved past PHP 5, and it has been serving 500s to search engines and bots ever since.

    Could it be patched? The construction appears 252 times across WordPress core. PHP stops at the first one, but fixing that line only exposes the next. This is not a bug you repair. It is a language incompatibility, and the only answer is a newer WordPress.

    The timestamp in the root directory

    Sitting in the web root was a file called .maintenance, containing one line:

    <?php $upgrading = 1309848013; ?>

    WordPress writes that file when it begins a core update and deletes it when the update finishes. This one was never deleted.

    That Unix timestamp is 05/07/2011, 06:40 UTC.

    WordPress 3.2 was released on 04/07/2011. Alongside .maintenance were two directories in wp-content called wordpress-3.tmp and wordpress-31.tmp, the staging folders the updater uses while unpacking.

    So: the day after 3.2 came out, I clicked update. It stalled. It left the lock file, the temp directories, and a site still running 3.1.2.

    The lock file did no harm. WordPress ignores a .maintenance older than ten minutes, a sensible piece of defensive design and the reason the site kept serving afterwards. But it dates the incident to the minute.

    What the logs cannot tell you is what the site looked like when it stopped.

    It was running Grid Focus, a theme I had modified by hand over several years until not much of the original remained, with a stack of plugins I had chosen one at a time. The update took it down. I troubleshot for a while. Then life happened, and I lost interest the way you do when a thing stops being fun and starts being a chore.

    So I let it sit. Somewhere between 2020 and 2022 I paid a freelancer on Fiverr to bring it back, and for a while it worked. That did not last either.

    Both theme folders were still on the server when I finally went looking. grid_focus_public and gridfocus-v1.5.1b, sitting among fifty other themes I had collected and forgotten, exactly where I left them in 2011.

    Five years of nobody noticing

    The site did not go down in 2011. It went stale in 2011 and died some years later when PHP moved on. The first half is provable.

    An old wp-dbmanager install had been taking weekly database backups and leaving them in wp-content. There were 134 of them, 2.7 GB in total, running from 29/05/2011 to 31/07/2016.

    Comparing the oldest against the newest, by table:

    techblog_..._20110612.sql   posts: 274,916 bytes   comments: 370,174 bytes
    techblog_..._20160731.sql   posts: 274,916 bytes   comments: 370,174 bytes

    Byte for byte identical. Not a single post or comment changed between June 2011 and July 2016. The blog stopped in 2011 and the backups kept copying the same corpse every Sunday until they stopped too.

    But the dumps grew from 1.4 MB to 37 MB over those years. Something was expanding. Breaking the 2016 file down by table:

    12,549,505  wp_usermeta
       370,174  wp_comments
       342,650  wp_options
       274,916  wp_posts
        79,785  wp_postmeta

    Twelve and a half megabytes of user metadata against 275 KB of actual writing, reaching about 35 MB by the final backups. Open registration on an unpatched WordPress 3.1.2, and five years of bots signing up. The comments stayed clean, which I put down to Akismet and the captcha plugin, though I cannot prove that from the data. Nothing at all was guarding the registration form.

    Ninety per cent of my database was junk accounts.

    Deciding not to repair

    Reviving the 3.1.2 install was never really available. There is no supported upgrade path across fifteen years, and the parse error fires before WordPress prints a byte, so I could not reach an admin screen to start one.

    Rebuilding felt right for a less technical reason. The install carried 44 plugins and 51 themes. Among the plugins were disable-wordpress-core-update and disable-wordpress-plugin-updates, which explains a good deal about why it was still on 3.1.2. Copies of wordpress-28.zip through wordpress-284.zip sat in wp-content, publicly readable. There was a forum directory, empty, and two bbPress integration plugins pointing at it.

    A WordPress 3.1.2 install had been exposed to the open internet for roughly eight years before PHP killed it, and that version has a long published list of vulnerabilities. There is an irony worth sitting with: the parse error that took the site down has probably been protecting it since about 2019.

    So: current WordPress, content carried across, nothing else.

    Getting the content out

    The live database was reachable but not trustworthy, and I had 134 dumps provably unchanged since 2011. We took the last one and parsed it directly rather than restoring it anywhere.

    Two things came out of that which looking at the site would never have shown.

    The comments were duplicated. The table held 840. After normalising whitespace and stripping tags, only 606 were distinct. 234 were exact duplicates of another comment on the same post by the same author, each pair differing only in whether the
    tags had survived:

    id=7    2006-09-06 16:54   'Thanks for viewing my Blog. Well... I must say...'
    id=505  2006-09-06 11:24   'Thanks for viewing my Blog. Well... I must say...'

    The second copies sit in a contiguous block of IDs above 500. The database name pointed to Blogger, and the install had a blogger-blogspot-redirect plugin. A Blogger import run twice in 2006, once preserving HTML and once stripping it. Twenty years, and I never noticed, because on the page a duplicate comment just looks like somebody posting twice.

    The spam was not where anyone expected. Given the state of the usermeta table, the assumption was that comments would be full of pharma and casino links. A pattern search for the usual vocabulary returned zero matches. The volume by year decays the way real traffic does, 571 in 2006, 208 in 2007, then single and double digits as the blog went quiet, rather than flooding the way a farmed table does.

    The first attempt to find spam scored comments by link density. On a blog about Blogger and WordPress hacks that is a terrible signal, and it flagged 43 comments, most of them my own replies containing four or five links to code examples. Claude had produced that heuristic, run it, looked at the output and thrown it away unprompted, which was the right call and not one I would have caught if it had not shown me the list.

    The second pass went by author name and destination domain and found the real thing: thirteen keyword-anchor link drops, the kind where the author name is the product. “Mens Suit” linking to a suit retailer. “Website Design Atlanta”, three times. “beats for sale”. “laptop battery”. Short, on-topic enough, easy to approve by accident in 2010.

    That left 593 comments, all genuine, threading intact.

    There was also a post dated 26/12/2020 in a database dumped in 2016. A draft whose post_date carried a mistyped year, its post_modified correctly reading 27/12/2010. It had been sitting ten years in the future for a decade.

    What the rehearsal caught

    Rather than trust the import, we rehearsed it: MariaDB and WP-CLI in a throwaway container, the same WordPress version, a replica of the uploads folder, the real import file.

    Every expected number came back right except one. Attachments came out as zero instead of eighteen.

    The WordPress importer does not simply create attachment records. For each attachment it downloads the file from the URL in wp:attachment_url. In the container that URL was unreachable, so every attachment failed silently.

    On a real server it is worse than a clean failure. The URL points at the site being restored, over HTTPS, at a moment when the certificate has not been issued. And if the download does succeed, it writes a second copy of every file beside the ones already sitting in wp-content/uploads.

    The fix is to tell it not to:

    wp import export.xml --authors=create --skip=attachment

    and then register the files already on disk, in place:

    find wp-content/uploads -type f \( -iname '*.jpg' -o -iname '*.gif' \) \
      | grep -vE -- '-[0-9]+x[0-9]+\.[A-Za-z]+$' \
      | while read -r f; do wp media import "$f" --skip-copy; done

    The grep -v matters. Of 56 files in the uploads folder, 36 were WordPress’s own generated thumbnails. Without that filter every -150x150 crop becomes its own media library entry.

    Nobody would have found this by reading the script. It appeared only by running the whole thing end to end against a real database.

    Four ways the deploy script was wrong

    This is the part I would not have predicted before the evening started. The script that rebuilt the site was written for me to paste into an SSH session, and it had to be fixed four times before it ran clean. Every failure was caught by the script’s own preflight, before anything on my server was touched.

    getent does not exist on my host’s shell. The DNS check used it. The script would have aborted in preflight with a confusing error. Replaced with a PHP lookup, since PHP is guaranteed present there.

    pipefail and head do not mix. The script ran wp --info | head -3. head closes the pipe after three lines, wp gets SIGPIPE and exits 141, and set -o pipefail with set -e turns that into a silent abort. The three lines of output on my screen were the last thing the script printed before killing itself, and the failure looked like nothing at all.

    A $ in a password. My admin password was randomly generated and contained a dollar sign. Inside double quotes bash reads a $ followed by a digit or a name as a parameter; this one did not exist, and set -u correctly aborted. The config block now uses single quotes.

    --raw wrote an undefined constant. This one actually reached my server. The script ran wp config set WP_AUTO_UPDATE_CORE minor --raw, which writes define('WP_AUTO_UPDATE_CORE', minor); without quotes. In PHP 8 an undefined constant is a fatal error, so WordPress could not load at all, and the script reported it as “cannot reach the database” — which was wrong and sent me looking in the wrong place.

    There was a fifth, structural, caught before I ran anything: the original script tested the database connection after renaming my site directory. If the database had been unreachable, it would have moved my entire site aside and then died. That ordering was reversed so every destructive step sits behind a check that has already passed.

    I record these because the honest version of “an AI helped me fix my site” includes the four times it handed me something broken. What made it work was not that the output was right first time. It was that each failure was cheap, legible, and caught before it cost anything.

    The redirect loop I caused myself

    With WordPress installed and content imported, the site returned a redirect loop. techblog.viveksanghi.com redirected to www.techblog.viveksanghi.com, which redirected straight back, forever.

    We assumed the host was misconfigured. I opened a support ticket saying so. One command showed we were half wrong:

    curl -sI http://techblog.viveksanghi.com/readme.html      → 301
    curl -sI http://www.techblog.viveksanghi.com/readme.html  → 200 OK

    A static file that exists on disk gets redirected at the bare hostname and served at www. That first redirect happens above .htaccess, in the host’s virtual host configuration, and nothing on my side could override it. That half was the host’s, and they removed it inside a couple of hours when asked properly.

    The second redirect was mine. Static files at www served fine and only WordPress-handled paths bounced. That is redirect_canonical doing its job, because siteurl and home were set to the bare hostname while the server was serving www. Each half behaved correctly. Together they were an infinite loop.

    Testing a static file rather than the homepage is what separated them. On the homepage both redirects are in play and the trace tells you nothing about which layer owns which. I cancelled the first ticket and filed a more accurate one.

    What I would tell someone with a site in this state

    Test a static file first. Whether readme.html serves tells you in one request whether the web server is broken or only PHP is. Almost everything that followed came out of that one 200.

    The error log is the whole answer, and it is not in the panel. The hosting control panel showed access logs and traffic graphs for days. The actual parse error, repeating identically for years, was in a file on disk.

    Check whether your content changed before you value your backups. 134 weekly backups sound like excellent hygiene. Comparing the first against the last showed 134 copies of the same 2011 content, with only the spam growing. Backup count measures nothing.

    Rehearse the restore. A throwaway database and a full dry run took under an hour and caught a defect that would have cost the entire media library, silently, with a success message.

    Suspect your own configuration before your host’s. I was three quarters of the way to blaming my host for a redirect loop I had created myself.

    If you are working with a model, make it show you its output, not just its conclusions. Every one of the four script defects and the bad spam heuristic surfaced because something got printed and looked wrong. None of them surfaced from reading the code.

    The site is back. Seventy-five posts, 17/04/2006 to 25/05/2011, and 593 comments, on WordPress 7.1 with a clean database and no plugins carried across.

    Sixty-eight images in the older posts still point at photos1.blogger.com and the bp1 to bp3 hosts, which Google retired years ago. Those have been broken far longer than the site was, and there is nothing left to restore them from. I am inclined to leave them, with a note. A blog that ran from 2006 should be allowed to show its age somewhere.

  • Disqus Comment System for WordPress

    This blog is now using an interesting new comment system called DISQUS. I like Disqus for the following reasons:

    1. It allows users to log in via multiple sites such as Twitter, Facebook, Open Id, Yahoo and Disqus itself

    2. It allows users to track all their comments made across multiple sites, at a single place

    3. When users manage their comments through Disqus and / or log into Disqus via one of their social networking accounts, the comment they make also gets published in their social networking feed resulting in greater propagation of the source post where the comment was made

    4. Incredibly easy and smooth integration with wordpress

  • bbPress: Installation and Deep Integration with WordPress

    Hello friends. It’s been a long time since I have posted any new articles here. This is because I have been keeping very busy with my work life and find no time to research and explore blogger/wordpress code.

    Recently I learnt about a forum software by name bbpress which can integrate well with wordpress blogs. I decided to squeeze time out of my schedule to try this software and write about it.

    bbPress is a very easy to use forum or bulletin board software from the creators of wordpress. To quote their website:

    “bbPress is focused on web standards, ease of use, ease of integration, and speed. We’re keeping things as small and light as possible while still allowing for great add-on features through our extensive plugin system.”

    This article will cover installation of bbpress for a wordpress blog and its deep integration with wordpress blog such that the blog and the forum share common logins, cookies and user databases. Make a note of the versions used before you proceed to read the installation/integration tutorial:

    bbPress version: 1.0.2
    Wordpress version: 2.8.9

    bbPress download and server setup

    – As a first step you need to download bbpress from here. Unzip and rename the folder to what ever you like. Whatever name you choose will also become a part of your forum URL in the following format:

    <wordpress blog URL>/<bbPress folder name>

    – Now upload this folder under you main wordpress directory on the server where you are hosting your blog. For example, I had renamed my bbPress directory to “forum” and uploaded it under the folder techblog.viveksanghi.com on the webserver such that my forum url become:

    https://techblog.viveksanghi.com/forum

    WordPress Setup

    bbPress Integration Plugin

    – Now login into you wordpress admin panel, install the plugin bbpress integration into wordpress and activate the plugin. On the plugin’s configuration page enter the URL of your bbpress forum which will be in the following format as already explained earlier:

    <yourblog URL>/<bbpress folder name>.

    Do not change anything else and hit the save button. Scroll down on the same page and you will be shown some code that you need to enter into your wordpress config file. Make a note of this code as we will require it in the next step.

    WordPress Config

    – Apart from the above-mentioned piece of code from the previous step, there are some additional changes that you need to make to your wordpress config file. Let’s looks are what additions are to be made to the wordpress configuration file. Download and edit your wordpress config file. This will be located under your main wordpress folder by the name wp-config.php

    You have to enter the following values in the wp-config.php file:

    AUTH_KEY
    SECURE_AUTH_KEY
    LOGGED_IN_KEY

    Go here to generate complex keys for the above mentioned items. Then paste these keys in the wp-config.php file as shown below:

    Also paste the code we generated earlier from the bbpress integration plugin of wordpress as shown in the image above.

    Now its time to start your bbPress installation. However make sure to have the following details about your wordpress database handy as we will use the same database for wordpress and bbpress.

    – WordPress database name
    – WordPress database hostname (Note that it will not be “localhost” if you are hosting on dreamhost or other such hosting site)
    – WordPress database username
    – WordPress database password
    – WordPress table prefix

    In case you are new to using databases and/or are not sure where to find the above mentioned details, then you might want to install the WP-DBManager plugin in wordpress and should be able to view all these above details from within wordpress.

    Once these details are ready, you may start the installation by proceeding to the following link:

    [your bbPress forum URL]/bb-admin/options-wordpress.php

    Step 1 – Database configuration

    First you will be presented with the following screen:

    Now enter the database details you collated earlier, as shown in the image below. You may also use the question mark symbols to learn more about each of these fields.

    And then proceed to step 2.

    Step 2 – WordPress Integration Settings

    To fill in the details required for step 2, load the options screen of your wordpress blog using the following link:

    [wordpress link]/wp-admin/options.php

    On the bbpress installation page check integration and cookie integration settings as shown in the image. Now add the auth cookie, secure auth cookie and logged in key values (we created these values earlier before starting installation of bbpress) from the wp-config.php file. The salt values will be available from the wordpress options screen we loaded a while ago.

    If you do not find the secure auth cookie salt value, you may leave it blank and it should not be a problem. Then scroll down and also check user database integration settings. Fill in the values from the database values that you noted earlier. Most of you will only require the wordpress database table prefix. Now save the integration settings and you will be prompted to proceed to step three.

    Step 3 – Site settings

    Fill in a name for your forum and the site URL as shown below. Site URL will depend on the folder name you gave to the bbpress folder before uploading it under wordpress folder.

    Select the wordpress admin name from the drop down as the bbpress keymaster unless you wish to alot this supreme role to anyone else. Give a name for your first forum, then hit the save site settings button and you should be ready to proceed to your forum page.

    Now go to the admin panel of your forum and select wordpress integration under the settings tab as shown in the image below.  Here you have to map user roles between wordpress and bbPress users as the user list is now synchronized and/or common between the two.

    Once you save these settings, your wordpress and bbPress will be integrated and you are ready to go.

    I am also planning to research into a system/plugin such that the wordpress posts become topics and the comments on each wordpress post become forum posts under these topics. If I find out some thing on these lines, I will definitely update this post or create a second post on this topic.

    References: I researched the bbPress forums extensively and did a lot of hands on tinkering to learn how to install bbPress and integrate it with wordpress. This link was particularly helpful in my learning process.

  • Contest Suggestion: 31 Days of the Dragon

    ‘lo. After a long time I am posting some thing here for you guys. I hope until now you have enjoyed the existing set of Blogger mods that I had published. While this is not related to blogger mods, I am sure those of you who were unaware, will definitely love it. The other day I came across a big contest while browsing some of sites I read regularly, and simply could not resist sharing it with you.

    HP (in association with Buzz Corps)is promoting its latest 20.1″ notebook i.e. The HP HDX Entertainment Notebook using a contest called “The 31 Days of Dragon”. Before I proceed further note that this contest is open to everyone from any part of the world.

    Contest Info: There are 31 participating web sites, with the sponsorship of HP where HP is working with them to offer 31 prize packages – one a day for 31 days during a period from 09 May through 08 June 2008. Here are the details of the price package (which btw is worth well over USD 5000 in retail value):

    • Display: 20.1″ diagonal WUXGA High-Definition HP Ultra Brightview Widescreen (1920×1200)
    • Operating system: Windows Vista Ultimate (64-bit)
    • Processor: Intel Core2 Extreme Processor X9000 (2.80GHz, 6MB L2 Cache, 800MHz FSB)
    • Memory: 4GB DDR2 System Memory (2 Dimm)
    • Graphics Card: 512MB NVIDIA GeForce 8800M GTS
    • Personalization: HP Imprint Finish (Dragon) + Fingerprint Reader + Webcam + Microphone
    • Networking: Intel(R) PRO/Wireless 4965AGN Network Connection and Bluetooth(TM)
    • Hard Drive: 500GB 5400RPM SATA Dual Hard Drive (250GB x 2)
    • Optical: Blu-Ray ROM with SuperMulti DVD+/-R/RW Double Layer
    • TV & Entertainment Experience: Integrated HP HDTV Hybrid TV Tuner and 4 Altec Lansing speakers + the HP Triple Bass Reflex subwoofer
    • Primary Battery: 9 Cell Lithium Ion Battery
    • Productivity Applications: Microsoft Office 2007, Corel PaintShop Pro Photo X2, Corel Painter 4, Ulead VideoStudio 11.5 Plus
    • Games: Viva Pinata, Microsoft Flight Simulator X, Microsoft Flight Simulator X Acceleration Expansion Pack, Gear of War
    • Blu-Ray movies: The Pirates of the Caribbean Trilogy – The Curse of the Black Pearl, Dead Man’s Chest, At World’s End.

    And here is a list of websites that are running/will run a seven day contest between the following dates (begin – end):

    13 May – 20 May www.geekstogo.com
    14 May – 21 May bink.nu

    15 May – 22 May www.mediablab.com
    16 May – 23 May www.last100.com

    17 May – 24 May www.labnol.org
    18 May – 25 May www.notebooks.com
    19 May – 26 May www.slashdotreview.com
    20 May – 27 May www.neowin.net
    21 May – 28 May www.geek.com
    22 May – 29 Mau www.lockergnome.com

    23 May – 30 May www.planetx64.com
    24 May – 31 May www.thegreenbutton.com
    25 May – 01 Jun www.istartedsomething.com
    26 May – 02 Jun www.bleepingcomputer.com
    27 May – 03 Jun www.hardwaregeeks.com
    28 May – 04 Jun www.geeknewscentral.com

    29 May – 05 Jun www.geekzone.co.nz
    30 May – 06 Jun www.thetabletpc.net
    31 May – 07 Jun www.gearlive.com
    01 Jun – 08 Jun www.gottabemobile.com

    Some of the website site where the winners have already been declared are:

    02 May – 09 May www.absolutevista.com
    03 May – 10 May www.arstechnica.com
    04 May – 11 May www.osnn.net
    05 May – 12 May www.jkontherun.com
    06 May – 13 May digitalmediaphile.wordpress.com

    07 May – 14 May www.bostonpocketpc.com
    08 May – 15 May www.the-gadgeteer.com
    09 May – 16 May www.thedigitallifestyle.com

    10 May – 17 May www.digitalhomethoughts.com
    11 May – 18 May www.windows-now.com
    12 May – 19 May www.windowsconnected.com


    So I suggest you to head over to these website and track them to win the super prize package. For details about the contest please visit here
    . There is an RSS link and an OPML available so that you can track these sites conveniently.

    In addition, most of these site have very good articles which techies and computer enthusiasts will definitely like. So go now and start participating, I am also competing 🙂

  • Google page creator: headache

    Google’s Page Creator software is seriously pissing me off:

    I hope I don’t end up breaking my monitor, keyboard or mouse the next time I see this:

    BTW Google should hire someone who has written error messages for Microsoft :)) Coz: “oops! I don’t like your error messages”. Better still don’t give me the donuts, just get the page working. Just a thought (pun intended)

    Update: Page creator behaves much better after I turned off the experimental features.

  • A Firefox extension and PurpleMoggy’s hacks

    Hello readers,

    I have been using a Firefox extension by name fasterfox. If slow browsing speed has been a problem for you, I recommend that you give it a shot.

    Coming to beta hack, this blog now uses two hacks which I picked up from PurpleMoggy’s blog. It appears that a tutorial has been put up for the search box. Please find the tutorial on implementing a 4-in-1 search box (like I have) here.

    The second hack I found in PurpleMoggy is a javascript based peek-a-boo system for linklists in sidebar. This is almost same as Blogger University’s expand-collapse menu. Just that the hack I am using was picked-up by PurpleMoggy from here and modified using CSS such that it blended very well with my template as well.

  • Google Docs & Spreadsheets (updated)

    You might have come to know by now that Google has released a service called Google Docs & Spreadsheets . In this service, one can use an online text editor (similar to Microsoft Word and others) to create posts and publish it to their blog.

    With this service, you can:

    – Have your documents published online (as a webpage) to share it with others (dedicated URL to each document, as in Google pages)

    – Export your online documents in word, openoffice, HTML and PDF file formats to store it on your hard drive.

    – Import various document (.htm, .doc, .txt, .rtf, .odt, .sxw) and spreadsheet (.csv, .xls, .ods) file formats into this service and publish them online instantly or save it to your hard drive in a different format. So if you want to convert a Microsoft Word file into Adobe PDF format, you can do it easily using this service.

    – Collaborate and work with others on projects and set access permissions to files.

    – Post to other blogging tools (other than Blogger) like wordpress, LiveJournal etc and also use with custom hosted sites.


    To learn more about this service, you may visit this page.

    Problems

    1. Unable to Login to Blogger


    While editing my posts yesterday, I noticed that Blogger had even added a small side-box on the edit post pages to inform users of this service. That’s how I came to know about this service. However, when I used this service, it could not authenticate my blogger beta account (even after my providing the correct login credentials). I knew this was a bug and it was confirmed when in the evening, I noticed that the side-box no longer appeared on the edit post pages.


    Once this service is ready for blogger beta, I need to check how this thing works with the tables. If you are used to copy-pasting text from Microsoft Word you might remember that tables cannot be pasted into the post editor in blogger.

    2. Formating issues with spreadsheets [Updated (14th Oct, 12:36)]


    There are formatting issues with imported Excel files (as seen in the images above).

    3. Issues with Spellcheck

    I noticed that the spell check is not up to the mark:

    Google needs to fix this problem at the earliest, because if any bloggers were to use this service, the bare-minimum they will look for is proper functioning of basic features like spell-check.

    Support

    Other than the usual support by Google, there is a Google help group for Google Docs & Spreadsheets, where you can post you questions, concerns and suggestions regarding this service and share your experiences with other users.

    Conclusion

    Google Docs & Spreadsheets is a powerful software/service but lots of errors and problems need to be ironed out before its ready for use (thats why its in beta stage). In a recent news article, I had read that Google’s CEO Eric Schmidt wants his developers to focus on improving current software/services. I couldn’t agree with him more. In the recent years, Google has brought out a range of powerful softwares and services from its labs but its the continuing improvement, feature additions and support for these services that will win the day for it.

    Update (Nov 12, 2006 IST): It appears that the connectivity problems between Google Docs & Spreadsheets and Blogger Beta is now fixed. So go ahead try using this service now.