fix wixur.ir domain and subdomains ssl's.
This commit is contained in:
BIN
frontend/public/sql-wasm-browser.wasm
Executable file
BIN
frontend/public/sql-wasm-browser.wasm
Executable file
Binary file not shown.
@@ -267,6 +267,21 @@ curl http://wixur.ir/health
|
|||||||
|
|
||||||
**Mobinnet:** public **80** is the modem. Use **443** instead: router forward **TCP 443 → 192.168.1.100**, then `https://wixur.ir`. Let's Encrypt after mobile-data `/health` works (self-signed is enough for that test).
|
**Mobinnet:** public **80** is the modem. Use **443** instead: router forward **TCP 443 → 192.168.1.100**, then `https://wixur.ir`. Let's Encrypt after mobile-data `/health` works (self-signed is enough for that test).
|
||||||
|
|
||||||
|
### HTTPS certificates
|
||||||
|
|
||||||
|
Public port 80 is the modem, so Let's Encrypt cannot renew `wixur.ir` over HTTP. Renewal writes a TXT record in the Arvan zone `wixur.ir` and never uses port 80. That is the same check production uses for `nudentic.ir`. Do not run `install-arvan-renew.sh` on this PC. That script is only for the Linux certbot container.
|
||||||
|
|
||||||
|
One certificate covers `wixur.ir`, `www.wixur.ir`, `gitea.wixur.ir`, and `errors.wixur.ir`. Windows nginx keeps the PEM filenames already in `C:\tools\nginx-1.29.5\conf\nginx.conf`. [`scripts/renew-wixur-cert.ps1`](scripts/renew-wixur-cert.ps1) copies the new chain and key onto each of those paths and reloads nginx.
|
||||||
|
|
||||||
|
Put the Arvan API key on one line in `C:\dyolink\secrets\arvan-api-key`. Do not commit it. Docker Desktop must be running. On this PC:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd C:\path\to\dyolink\infrastructure\scripts
|
||||||
|
.\renew-wixur-cert.ps1 -Register
|
||||||
|
```
|
||||||
|
|
||||||
|
`-Register` schedules that script daily at 03:15 under the signed-in account, then issues or renews immediately. A later run with no switch only renews and reloads.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Test the pipeline
|
## Test the pipeline
|
||||||
@@ -375,6 +390,7 @@ On the Windows host, from repo `infrastructure/`:
|
|||||||
| Git clone fails in workflow | Set `CLONE_HOST=127.0.0.1:3000` |
|
| Git clone fails in workflow | Set `CLONE_HOST=127.0.0.1:3000` |
|
||||||
| Port 80 bind forbidden / access permissions | Portproxy already owns 80. Bind Docker to `18088` and point portproxy **80 → 127.0.0.1:18088**. Free IIS if it holds 80. |
|
| Port 80 bind forbidden / access permissions | Portproxy already owns 80. Bind Docker to `18088` and point portproxy **80 → 127.0.0.1:18088**. Free IIS if it holds 80. |
|
||||||
| `http://wixur.ir` unreachable / empty reply | Docker Desktop: run **portproxy** (§7). `127.0.0.1:18088/health` must work on Windows first. Router must forward **80**. |
|
| `http://wixur.ir` unreachable / empty reply | Docker Desktop: run **portproxy** (§7). `127.0.0.1:18088/health` must work on Windows first. Router must forward **80**. |
|
||||||
|
| Browser says the certificate date is invalid for `wixur.ir`, `gitea.wixur.ir`, or `errors.wixur.ir` | The Let's Encrypt files on the Windows nginx expired. HTTP renewal cannot succeed while public port 80 is the modem. On the PC run `infrastructure\scripts\renew-wixur-cert.ps1`. |
|
||||||
| Port 8088 bind forbidden / access permissions | Portproxy already owns 8088. Bind Docker to `18088` and point portproxy **8088 → 127.0.0.1:18088**. |
|
| Port 8088 bind forbidden / access permissions | Portproxy already owns 8088. Bind Docker to `18088` and point portproxy **8088 → 127.0.0.1:18088**. |
|
||||||
| Port 8088 unreachable from Mac / empty reply | Legacy URL. Prefer `http://wixur.ir`. Same 18088 backend; add portproxy 8088 only as fallback. |
|
| Port 8088 unreachable from Mac / empty reply | Legacy URL. Prefer `http://wixur.ir`. Same 18088 backend; add portproxy 8088 only as fallback. |
|
||||||
| Backend restart loop | JWT secrets still placeholder; fix `backend.staging.env` |
|
| Backend restart loop | JWT secrets still placeholder; fix `backend.staging.env` |
|
||||||
@@ -410,6 +426,8 @@ docker logs dyolink_frontend_staging --tail 50
|
|||||||
| `infrastructure/nginx/http-only.conf` | HTTP reverse proxy **inside Docker** staging |
|
| `infrastructure/nginx/http-only.conf` | HTTP reverse proxy **inside Docker** staging |
|
||||||
| `infrastructure/nginx/windows-edge-http.conf` | Windows **host** nginx on port 80/443 → 18088 |
|
| `infrastructure/nginx/windows-edge-http.conf` | Windows **host** nginx on port 80/443 → 18088 |
|
||||||
| `infrastructure/nginx/windows-gitea.wixur.snippet.conf` | Windows nginx vhost for `https://gitea.wixur.ir` (unlimited body — Docker push) |
|
| `infrastructure/nginx/windows-gitea.wixur.snippet.conf` | Windows nginx vhost for `https://gitea.wixur.ir` (unlimited body — Docker push) |
|
||||||
|
| `infrastructure/scripts/renew-wixur-cert.ps1` | Renew `wixur.ir` / `gitea` / `errors` by Arvan DNS and reload Windows nginx |
|
||||||
|
| `infrastructure/scripts/arvan-dns-auth.py` | Certbot hook: create the Arvan TXT record (`arvan_dns.py`, cleanup hook beside it) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,72 +1,20 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Create the _acme-challenge TXT record for a Certbot DNS-01 renewal.
|
"""Create the _acme-challenge TXT record for a Certbot DNS-01 renewal."""
|
||||||
|
|
||||||
Certbot sets CERTBOT_DOMAIN and CERTBOT_VALIDATION. The Arvan key is one line
|
|
||||||
in /etc/letsencrypt/arvan-api-key (never printed).
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
import time
|
import time
|
||||||
import urllib.error
|
from pathlib import Path
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
|
||||||
|
|
||||||
|
from arvan_dns import txt_visible, upsert_txt, zone_and_record
|
||||||
def auth_header():
|
|
||||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
|
||||||
if raw.lower().startswith("apikey "):
|
|
||||||
return "Apikey " + raw.split(None, 1)[1]
|
|
||||||
return "Apikey " + raw
|
|
||||||
|
|
||||||
|
|
||||||
def request(method, url, body=None):
|
|
||||||
data = None if body is None else json.dumps(body).encode()
|
|
||||||
req = urllib.request.Request(
|
|
||||||
url,
|
|
||||||
data=data,
|
|
||||||
method=method,
|
|
||||||
headers={
|
|
||||||
"Authorization": auth_header(),
|
|
||||||
"Accept": "application/json",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
||||||
return resp.status, resp.read().decode()
|
|
||||||
except urllib.error.HTTPError as err:
|
|
||||||
return err.code, err.read().decode()
|
|
||||||
|
|
||||||
|
|
||||||
def txt_visible(name, value):
|
|
||||||
url = "https://dns.google/resolve?name={}&type=TXT".format(name)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(url, timeout=15) as resp:
|
|
||||||
payload = json.loads(resp.read().decode())
|
|
||||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
|
||||||
return False
|
|
||||||
for answer in payload.get("Answer") or []:
|
|
||||||
data = answer.get("data", "").strip('"')
|
|
||||||
if value in data:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
domain = os.environ["CERTBOT_DOMAIN"]
|
domain = os.environ["CERTBOT_DOMAIN"]
|
||||||
value = os.environ["CERTBOT_VALIDATION"]
|
value = os.environ["CERTBOT_VALIDATION"]
|
||||||
status, body = request(
|
zone, name, fqdn = zone_and_record(domain)
|
||||||
"POST",
|
upsert_txt(zone, name, value)
|
||||||
"{}/{}/dns-records".format(API, domain),
|
|
||||||
{"type": "txt", "name": "_acme-challenge", "value": {"text": value}, "ttl": 120},
|
|
||||||
)
|
|
||||||
if status == 422 and "duplicate" in body.lower():
|
|
||||||
status = 200
|
|
||||||
if status < 200 or status >= 300:
|
|
||||||
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
|
||||||
fqdn = "_acme-challenge.{}".format(domain)
|
|
||||||
for _ in range(18):
|
for _ in range(18):
|
||||||
if txt_visible(fqdn, value):
|
if txt_visible(fqdn, value):
|
||||||
print("TXT record is visible")
|
print("TXT record is visible")
|
||||||
|
|||||||
@@ -1,69 +1,26 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Remove the _acme-challenge TXT record created for one Certbot attempt."""
|
"""Remove the _acme-challenge TXT record created for one Certbot attempt."""
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import urllib.error
|
import sys
|
||||||
import urllib.request
|
from pathlib import Path
|
||||||
|
|
||||||
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
|
||||||
|
|
||||||
|
from arvan_dns import delete_record, list_txt, record_names_match, txt_text, zone_and_record
|
||||||
def auth_header():
|
|
||||||
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
|
||||||
if raw.lower().startswith("apikey "):
|
|
||||||
return "Apikey " + raw.split(None, 1)[1]
|
|
||||||
return "Apikey " + raw
|
|
||||||
|
|
||||||
|
|
||||||
def request(method, url):
|
|
||||||
req = urllib.request.Request(
|
|
||||||
url,
|
|
||||||
method=method,
|
|
||||||
headers={"Authorization": auth_header(), "Accept": "application/json"},
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
||||||
return resp.status, resp.read().decode()
|
|
||||||
except urllib.error.HTTPError as err:
|
|
||||||
return err.code, err.read().decode()
|
|
||||||
|
|
||||||
|
|
||||||
def walk(node):
|
|
||||||
if isinstance(node, list):
|
|
||||||
for item in node:
|
|
||||||
yield from walk(item)
|
|
||||||
elif isinstance(node, dict):
|
|
||||||
if "id" in node and "type" in node:
|
|
||||||
yield node
|
|
||||||
for value in node.values():
|
|
||||||
yield from walk(value)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
domain = os.environ["CERTBOT_DOMAIN"]
|
domain = os.environ["CERTBOT_DOMAIN"]
|
||||||
value = os.environ.get("CERTBOT_VALIDATION", "")
|
value = os.environ.get("CERTBOT_VALIDATION", "")
|
||||||
status, body = request("GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, domain))
|
zone, name, fqdn = zone_and_record(domain)
|
||||||
if status < 200 or status >= 300:
|
for record in list_txt(zone):
|
||||||
raise SystemExit("Arvan DNS list failed: HTTP {}".format(status))
|
|
||||||
payload = json.loads(body)
|
|
||||||
for record in walk(payload):
|
|
||||||
if str(record.get("type", "")).lower() != "txt":
|
if str(record.get("type", "")).lower() != "txt":
|
||||||
continue
|
continue
|
||||||
if record.get("name") not in ("_acme-challenge", "_acme-challenge." + domain):
|
if not record_names_match(record.get("name"), name, fqdn):
|
||||||
continue
|
continue
|
||||||
text = ""
|
if value and value not in txt_text(record):
|
||||||
raw_value = record.get("value")
|
|
||||||
if isinstance(raw_value, dict):
|
|
||||||
text = str(raw_value.get("text", ""))
|
|
||||||
if value and value not in text:
|
|
||||||
continue
|
continue
|
||||||
del_status, _ = request(
|
delete_record(zone, record["id"])
|
||||||
"DELETE",
|
|
||||||
"{}/{}/dns-records/{}".format(API, domain, record["id"]),
|
|
||||||
)
|
|
||||||
if del_status not in (200, 204, 404):
|
|
||||||
raise SystemExit("Arvan DNS delete failed: HTTP {}".format(del_status))
|
|
||||||
print("TXT record removed")
|
print("TXT record removed")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
148
infrastructure/scripts/arvan_dns.py
Normal file
148
infrastructure/scripts/arvan_dns.py
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
"""Arvan DNS helpers for a Certbot DNS-01 check.
|
||||||
|
|
||||||
|
Certbot sets CERTBOT_DOMAIN and CERTBOT_VALIDATION. The API key is one line
|
||||||
|
in /etc/letsencrypt/arvan-api-key and is never printed.
|
||||||
|
|
||||||
|
nudentic.ir is its own zone, so the TXT name is _acme-challenge.
|
||||||
|
A name under wixur.ir uses that zone: gitea.wixur.ir becomes
|
||||||
|
_acme-challenge.gitea in zone wixur.ir.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
||||||
|
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
||||||
|
|
||||||
|
|
||||||
|
def auth_header():
|
||||||
|
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
||||||
|
if raw.lower().startswith("apikey "):
|
||||||
|
return "Apikey " + raw.split(None, 1)[1]
|
||||||
|
return "Apikey " + raw
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, url, body=None):
|
||||||
|
data = None if body is None else json.dumps(body).encode()
|
||||||
|
headers = {"Authorization": auth_header(), "Accept": "application/json"}
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||||
|
return resp.status, resp.read().decode()
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
return err.code, err.read().decode()
|
||||||
|
|
||||||
|
|
||||||
|
def zone_and_record(domain):
|
||||||
|
domain = domain.strip().rstrip(".")
|
||||||
|
override = os.environ.get("ARVAN_ZONE", "").strip().rstrip(".")
|
||||||
|
labels = domain.split(".")
|
||||||
|
if override:
|
||||||
|
zone = override
|
||||||
|
elif len(labels) > 2:
|
||||||
|
zone = ".".join(labels[-2:])
|
||||||
|
else:
|
||||||
|
zone = domain
|
||||||
|
if domain == zone:
|
||||||
|
name = "_acme-challenge"
|
||||||
|
elif domain.endswith("." + zone):
|
||||||
|
prefix = domain[: -(len(zone) + 1)]
|
||||||
|
name = "_acme-challenge." + prefix
|
||||||
|
else:
|
||||||
|
raise SystemExit("CERTBOT_DOMAIN is not in the Arvan zone")
|
||||||
|
fqdn = name + "." + zone
|
||||||
|
return zone, name, fqdn
|
||||||
|
|
||||||
|
|
||||||
|
def record_names_match(got, name, fqdn):
|
||||||
|
if not isinstance(got, str):
|
||||||
|
return False
|
||||||
|
got = got.strip().rstrip(".").lower()
|
||||||
|
return got in (name.lower(), fqdn.lower())
|
||||||
|
|
||||||
|
|
||||||
|
def walk(node):
|
||||||
|
if isinstance(node, list):
|
||||||
|
for item in node:
|
||||||
|
yield from walk(item)
|
||||||
|
elif isinstance(node, dict):
|
||||||
|
if "id" in node and "type" in node:
|
||||||
|
yield node
|
||||||
|
for value in node.values():
|
||||||
|
yield from walk(value)
|
||||||
|
|
||||||
|
|
||||||
|
def txt_text(record):
|
||||||
|
raw_value = record.get("value")
|
||||||
|
if isinstance(raw_value, dict):
|
||||||
|
return str(raw_value.get("text", ""))
|
||||||
|
if isinstance(raw_value, str):
|
||||||
|
return raw_value
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def list_txt(zone):
|
||||||
|
status, body = request(
|
||||||
|
"GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, zone)
|
||||||
|
)
|
||||||
|
if status < 200 or status >= 300:
|
||||||
|
raise SystemExit("Arvan DNS list failed: HTTP {}".format(status))
|
||||||
|
return list(walk(json.loads(body)))
|
||||||
|
|
||||||
|
|
||||||
|
def delete_record(zone, record_id):
|
||||||
|
status, _body = request(
|
||||||
|
"DELETE", "{}/{}/dns-records/{}".format(API, zone, record_id)
|
||||||
|
)
|
||||||
|
if status not in (200, 204, 404):
|
||||||
|
raise SystemExit("Arvan DNS delete failed: HTTP {}".format(status))
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_txt(zone, name, value):
|
||||||
|
status, body = request(
|
||||||
|
"POST",
|
||||||
|
"{}/{}/dns-records".format(API, zone),
|
||||||
|
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
||||||
|
)
|
||||||
|
if 200 <= status < 300:
|
||||||
|
return
|
||||||
|
if status == 422 and "duplicate" in body.lower():
|
||||||
|
for record in list_txt(zone):
|
||||||
|
if str(record.get("type", "")).lower() != "txt":
|
||||||
|
continue
|
||||||
|
if not record_names_match(record.get("name"), name, name + "." + zone):
|
||||||
|
continue
|
||||||
|
if value and value in txt_text(record):
|
||||||
|
return
|
||||||
|
delete_record(zone, record["id"])
|
||||||
|
status, _body = request(
|
||||||
|
"POST",
|
||||||
|
"{}/{}/dns-records".format(API, zone),
|
||||||
|
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
||||||
|
)
|
||||||
|
if 200 <= status < 300 or (status == 422 and "duplicate" in _body.lower()):
|
||||||
|
return
|
||||||
|
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||||
|
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
||||||
|
|
||||||
|
|
||||||
|
def txt_visible(fqdn, value):
|
||||||
|
urls = (
|
||||||
|
"https://dns.google/resolve?name={}&type=TXT".format(fqdn),
|
||||||
|
"https://cloudflare-dns.com/dns-query?name={}&type=TXT".format(fqdn),
|
||||||
|
)
|
||||||
|
for url in urls:
|
||||||
|
req = urllib.request.Request(url, headers={"Accept": "application/dns-json"})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||||
|
payload = json.loads(resp.read().decode())
|
||||||
|
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
||||||
|
continue
|
||||||
|
for answer in payload.get("Answer") or []:
|
||||||
|
data = answer.get("data", "").strip('"')
|
||||||
|
if value in data:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
@@ -14,10 +14,11 @@ if [ ! -s "$KEY" ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
docker cp "$KEY" dyolink_certbot_prod:/etc/letsencrypt/arvan-api-key
|
docker cp "$KEY" dyolink_certbot_prod:/etc/letsencrypt/arvan-api-key
|
||||||
|
docker cp "$SCRIPT_DIR/arvan_dns.py" dyolink_certbot_prod:/etc/letsencrypt/arvan_dns.py
|
||||||
docker cp "$SCRIPT_DIR/arvan-dns-auth.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-auth.py
|
docker cp "$SCRIPT_DIR/arvan-dns-auth.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-auth.py
|
||||||
docker cp "$SCRIPT_DIR/arvan-dns-cleanup.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-cleanup.py
|
docker cp "$SCRIPT_DIR/arvan-dns-cleanup.py" dyolink_certbot_prod:/etc/letsencrypt/arvan-dns-cleanup.py
|
||||||
docker exec dyolink_certbot_prod chmod 600 /etc/letsencrypt/arvan-api-key
|
docker exec dyolink_certbot_prod chmod 600 /etc/letsencrypt/arvan-api-key
|
||||||
docker exec dyolink_certbot_prod chmod 755 /etc/letsencrypt/arvan-dns-auth.py /etc/letsencrypt/arvan-dns-cleanup.py
|
docker exec dyolink_certbot_prod chmod 755 /etc/letsencrypt/arvan_dns.py /etc/letsencrypt/arvan-dns-auth.py /etc/letsencrypt/arvan-dns-cleanup.py
|
||||||
|
|
||||||
docker exec -i dyolink_certbot_prod python3 - <<'PY'
|
docker exec -i dyolink_certbot_prod python3 - <<'PY'
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|||||||
204
infrastructure/scripts/renew-wixur-cert.ps1
Normal file
204
infrastructure/scripts/renew-wixur-cert.ps1
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
# Issue or renew the wixur.ir certificate with an Arvan DNS check, copy it onto
|
||||||
|
# the PEM files Windows nginx already uses, and reload nginx.
|
||||||
|
# Requires Docker Desktop. The Arvan API key is one line in
|
||||||
|
# C:\dyolink\secrets\arvan-api-key and is not printed.
|
||||||
|
# -Register also schedules this script daily at 03:15.
|
||||||
|
|
||||||
|
param(
|
||||||
|
[switch]$Register
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$KeyFile = 'C:\dyolink\secrets\arvan-api-key'
|
||||||
|
$LeDir = 'C:\dyolink\letsencrypt'
|
||||||
|
$NginxHome = 'C:\tools\nginx-1.29.5'
|
||||||
|
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
$TaskName = 'Dyolink renew wixur certificate'
|
||||||
|
$Names = @('wixur.ir', 'www.wixur.ir', 'gitea.wixur.ir', 'errors.wixur.ir')
|
||||||
|
|
||||||
|
function Convert-DockerPath {
|
||||||
|
param([string]$Path)
|
||||||
|
$full = [IO.Path]::GetFullPath($Path)
|
||||||
|
if ($full -match '^([A-Za-z]):\\(.*)$') {
|
||||||
|
return '/' + $Matches[1].ToLower() + '/' + ($Matches[2] -replace '\\', '/')
|
||||||
|
}
|
||||||
|
return ($full -replace '\\', '/')
|
||||||
|
}
|
||||||
|
|
||||||
|
function Register-RenewTask {
|
||||||
|
param([string]$ScriptPath)
|
||||||
|
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$ScriptPath`""
|
||||||
|
$trigger = New-ScheduledTaskTrigger -Daily -At '03:15'
|
||||||
|
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd
|
||||||
|
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Highest
|
||||||
|
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
|
||||||
|
Write-Host "Scheduled $TaskName daily at 03:15."
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-NginxText {
|
||||||
|
param([string]$Path, [int]$Depth = 0)
|
||||||
|
if ($Depth -gt 5 -or -not (Test-Path -LiteralPath $Path)) { return '' }
|
||||||
|
$dir = Split-Path -Parent $Path
|
||||||
|
$raw = Get-Content -LiteralPath $Path -Raw
|
||||||
|
$included = [regex]::Replace($raw, '(?m)^\s*include\s+([^;]+);', {
|
||||||
|
param($match)
|
||||||
|
$spec = $match.Groups[1].Value.Trim().Trim('"').Trim("'")
|
||||||
|
$full = $spec
|
||||||
|
if ($spec -notmatch '^[A-Za-z]:\\' -and -not $spec.StartsWith('\\')) {
|
||||||
|
$full = Join-Path $dir ($spec -replace '/', '\')
|
||||||
|
}
|
||||||
|
$chunks = @()
|
||||||
|
foreach ($file in @(Get-Item -Path $full -ErrorAction SilentlyContinue)) {
|
||||||
|
$chunks += Get-NginxText -Path $file.FullName -Depth ($Depth + 1)
|
||||||
|
}
|
||||||
|
$chunks -join "`n"
|
||||||
|
})
|
||||||
|
return $included
|
||||||
|
}
|
||||||
|
|
||||||
|
function Split-ServerBlocks {
|
||||||
|
param([string]$Text)
|
||||||
|
$blocks = @()
|
||||||
|
$idx = 0
|
||||||
|
while ($true) {
|
||||||
|
$start = $Text.IndexOf('server', $idx)
|
||||||
|
if ($start -lt 0) { break }
|
||||||
|
$brace = $Text.IndexOf('{', $start)
|
||||||
|
if ($brace -lt 0) { break }
|
||||||
|
$depth = 0
|
||||||
|
$end = -1
|
||||||
|
for ($i = $brace; $i -lt $Text.Length; $i++) {
|
||||||
|
$ch = $Text[$i]
|
||||||
|
if ($ch -eq '{') { $depth++ }
|
||||||
|
elseif ($ch -eq '}') {
|
||||||
|
$depth--
|
||||||
|
if ($depth -eq 0) { $end = $i; break }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($end -lt 0) { break }
|
||||||
|
$blocks += $Text.Substring($start, $end - $start + 1)
|
||||||
|
$idx = $end + 1
|
||||||
|
}
|
||||||
|
return $blocks
|
||||||
|
}
|
||||||
|
|
||||||
|
function Resolve-NginxPath {
|
||||||
|
param([string]$Relative)
|
||||||
|
$clean = $Relative.Trim().Trim('"').Trim("'")
|
||||||
|
if ($clean -match '^[A-Za-z]:\\' -or $clean.StartsWith('\\')) { return $clean }
|
||||||
|
$rel = $clean -replace '/', '\'
|
||||||
|
$candidates = @(
|
||||||
|
(Join-Path $NginxHome $rel),
|
||||||
|
(Join-Path $NginxHome (Join-Path 'conf' $rel))
|
||||||
|
)
|
||||||
|
foreach ($candidate in $candidates) {
|
||||||
|
if (Test-Path -LiteralPath $candidate) { return $candidate }
|
||||||
|
}
|
||||||
|
return $candidates[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-CertTargets {
|
||||||
|
$conf = Join-Path $NginxHome 'conf\nginx.conf'
|
||||||
|
$text = Get-NginxText -Path $conf
|
||||||
|
$targets = @()
|
||||||
|
foreach ($block in (Split-ServerBlocks -Text $text)) {
|
||||||
|
$serverNames = @()
|
||||||
|
foreach ($match in [regex]::Matches($block, '(?m)^\s*server_name\s+([^;]+);')) {
|
||||||
|
$serverNames += ($match.Groups[1].Value -split '\s+')
|
||||||
|
}
|
||||||
|
$hit = $false
|
||||||
|
foreach ($name in $serverNames) {
|
||||||
|
if ($Names -contains $name.Trim()) { $hit = $true }
|
||||||
|
}
|
||||||
|
if (-not $hit) { continue }
|
||||||
|
$chain = [regex]::Match($block, '(?m)^\s*ssl_certificate\s+(\S+)\s*;')
|
||||||
|
$key = [regex]::Match($block, '(?m)^\s*ssl_certificate_key\s+(\S+)\s*;')
|
||||||
|
if (-not $chain.Success -or -not $key.Success) { continue }
|
||||||
|
$targets += [pscustomobject]@{
|
||||||
|
Chain = Resolve-NginxPath $chain.Groups[1].Value
|
||||||
|
Key = Resolve-NginxPath $key.Groups[1].Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($targets.Count -eq 0) {
|
||||||
|
$ssl = Join-Path $NginxHome 'conf\ssl'
|
||||||
|
$targets = @(
|
||||||
|
[pscustomobject]@{ Chain = Join-Path $ssl 'wixur-chain.pem'; Key = Join-Path $ssl 'wixur-key.pem' },
|
||||||
|
[pscustomobject]@{ Chain = Join-Path $ssl 'gitea-chain.pem'; Key = Join-Path $ssl 'gitea-key.pem' },
|
||||||
|
[pscustomobject]@{ Chain = Join-Path $ssl 'errors-chain.pem'; Key = Join-Path $ssl 'errors-key.pem' }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return $targets
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($Register) {
|
||||||
|
Register-RenewTask -ScriptPath $PSCommandPath
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $KeyFile)) {
|
||||||
|
throw "Missing $KeyFile"
|
||||||
|
}
|
||||||
|
foreach ($hook in @('arvan_dns.py', 'arvan-dns-auth.py', 'arvan-dns-cleanup.py')) {
|
||||||
|
if (-not (Test-Path -LiteralPath (Join-Path $ScriptDir $hook))) {
|
||||||
|
throw "Missing $hook next to this script"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force -Path $LeDir | Out-Null
|
||||||
|
$hookDir = Join-Path $LeDir 'hooks'
|
||||||
|
New-Item -ItemType Directory -Force -Path $hookDir | Out-Null
|
||||||
|
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan_dns.py') -Destination (Join-Path $hookDir 'arvan_dns.py')
|
||||||
|
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan-dns-auth.py') -Destination (Join-Path $hookDir 'arvan-dns-auth.py')
|
||||||
|
Copy-Item -Force -Path (Join-Path $ScriptDir 'arvan-dns-cleanup.py') -Destination (Join-Path $hookDir 'arvan-dns-cleanup.py')
|
||||||
|
Copy-Item -Force -Path $KeyFile -Destination (Join-Path $LeDir 'arvan-api-key')
|
||||||
|
|
||||||
|
$renewal = Join-Path $LeDir 'renewal\wixur.ir.conf'
|
||||||
|
$emailArgs = '--register-unsafely-without-email'
|
||||||
|
if ($env:LETSENCRYPT_EMAIL) {
|
||||||
|
$emailArgs = "--email $env:LETSENCRYPT_EMAIL --no-eff-email"
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Test-Path -LiteralPath $renewal) {
|
||||||
|
$certbotCmd = "chmod 755 /etc/letsencrypt/hooks/*.py; chmod 600 /etc/letsencrypt/arvan-api-key; certbot renew --cert-name wixur.ir --non-interactive"
|
||||||
|
} else {
|
||||||
|
$certbotCmd = "chmod 755 /etc/letsencrypt/hooks/*.py; chmod 600 /etc/letsencrypt/arvan-api-key; certbot certonly --manual --preferred-challenges dns --manual-auth-hook /etc/letsencrypt/hooks/arvan-dns-auth.py --manual-cleanup-hook /etc/letsencrypt/hooks/arvan-dns-cleanup.py --cert-name wixur.ir -d wixur.ir -d www.wixur.ir -d gitea.wixur.ir -d errors.wixur.ir --agree-tos --non-interactive $emailArgs"
|
||||||
|
}
|
||||||
|
|
||||||
|
$leMount = Convert-DockerPath $LeDir
|
||||||
|
Write-Host 'Requesting the certificate.'
|
||||||
|
docker run --rm --entrypoint sh -v "${leMount}:/etc/letsencrypt" certbot/certbot -c $certbotCmd
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "certbot failed ($LASTEXITCODE)" }
|
||||||
|
|
||||||
|
$exportCmd = 'cp -L /etc/letsencrypt/live/wixur.ir/fullchain.pem /etc/letsencrypt/export-fullchain.pem && cp -L /etc/letsencrypt/live/wixur.ir/privkey.pem /etc/letsencrypt/export-privkey.pem'
|
||||||
|
docker run --rm --entrypoint sh -v "${leMount}:/etc/letsencrypt" certbot/certbot -c $exportCmd
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "could not read the new certificate ($LASTEXITCODE)" }
|
||||||
|
|
||||||
|
$chainSrc = Join-Path $LeDir 'export-fullchain.pem'
|
||||||
|
$keySrc = Join-Path $LeDir 'export-privkey.pem'
|
||||||
|
$seen = @{}
|
||||||
|
foreach ($target in (Get-CertTargets)) {
|
||||||
|
$dir = Split-Path -Parent $target.Chain
|
||||||
|
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||||
|
if (-not $seen.ContainsKey($target.Chain)) {
|
||||||
|
Copy-Item -Force -Path $chainSrc -Destination $target.Chain
|
||||||
|
Write-Host "Updated $($target.Chain)"
|
||||||
|
$seen[$target.Chain] = $true
|
||||||
|
}
|
||||||
|
if (-not $seen.ContainsKey($target.Key)) {
|
||||||
|
Copy-Item -Force -Path $keySrc -Destination $target.Key
|
||||||
|
Write-Host "Updated $($target.Key)"
|
||||||
|
$seen[$target.Key] = $true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Remove-Item -Force -ErrorAction SilentlyContinue $chainSrc, $keySrc
|
||||||
|
|
||||||
|
Push-Location $NginxHome
|
||||||
|
try {
|
||||||
|
& .\nginx.exe -t
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'nginx -t failed' }
|
||||||
|
& .\nginx.exe -s reload
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'nginx reload failed' }
|
||||||
|
} finally {
|
||||||
|
Pop-Location
|
||||||
|
}
|
||||||
|
Write-Host 'Nginx reloaded.'
|
||||||
Reference in New Issue
Block a user