From 9a57e497da8a7d68a5b0146d629f499eda154af7 Mon Sep 17 00:00:00 2001 From: rameen Date: Mon, 9 Nov 2026 14:47:18 +0330 Subject: [PATCH 1/2] Add a separate nudentic.com release tag. vX.Y.Z-com builds and deploys only the international server, and the Iran workflow skips those tags before any build or SSH. Co-authored-by: Cursor --- .gitea/workflows/prod-com-tag-deploy.yml | 329 +++++++++++++++++++++++ .gitea/workflows/prod-tag-deploy.yml | 37 ++- README.md | 4 + infrastructure/DEPLOY.md | 17 +- 4 files changed, 384 insertions(+), 3 deletions(-) create mode 100644 .gitea/workflows/prod-com-tag-deploy.yml diff --git a/.gitea/workflows/prod-com-tag-deploy.yml b/.gitea/workflows/prod-com-tag-deploy.yml new file mode 100644 index 0000000..6745df8 --- /dev/null +++ b/.gitea/workflows/prod-com-tag-deploy.yml @@ -0,0 +1,329 @@ +# International production: build images for https://nudentic.com, push :vX.Y.Z-com +# to Gitea (not :latest and not the bare :vX.Y.Z tag — that tag is nudentic.ir), +# then SSH only to the international server. +# +# The Iran workflow (.gitea/workflows/prod-tag-deploy.yml) and PROD_* secrets stay as they are. +# This file runs only on tags named vX.Y.Z-com. A normal vX.Y.Z tag does not start it. +# +# Variables: +# REGISTRY_HOST Windows Docker push host, e.g. host.docker.internal:3000 +# REGISTRY_OWNER Gitea user/org for packages +# CLONE_HOST git clone, e.g. 127.0.0.1:3000 +# COM_PUBLIC_BASE_URL https://nudentic.com (required; no trailing slash) +# NEXT_PUBLIC_SENTRY_DSN GlitchTip frontend project DSN +# NODE_IMAGE_SOURCE extra base-image ref(s) for seed/resolve +# NPM_REGISTRY default http://host.docker.internal:4873 +# PROD_REGISTRY_HOST Linux pull host, e.g. wixur.ir:3000 +# COM_INFRA_DIR /opt/dyolink/infrastructure +# +# Secrets (in addition to REGISTRY_USERNAME / REGISTRY_PASSWORD): +# COM_SSH_HOST 46.225.98.149 +# COM_SSH_USER nudentic +# COM_SSH_KEY OpenSSH private key (full PEM) +# COM_SSH_PORT optional, default 22 +# +# Do not set these to the Iran server. See infrastructure/DEPLOY.md. + +name: Production international — nudentic.com + +on: + push: + tags: + - 'v*.*.*-com' + workflow_dispatch: + inputs: + tag: + description: 'International git tag to build and deploy (e.g. v1.0.25-com).' + required: true + +defaults: + run: + shell: powershell + +jobs: + build-and-push: + runs-on: windows + steps: + - name: Resolve nudentic.com image tag + run: | + $ErrorActionPreference = 'Stop' + $dispatchTag = '${{ github.event.inputs.tag }}'.Trim() + if (-not [string]::IsNullOrWhiteSpace($dispatchTag)) { + $tag = $dispatchTag + } else { + $tag = "${{ github.ref_name }}" + } + if ($tag -notmatch '^v\d+\.\d+\.\d+-com$') { + Write-Host "International tag must be vMAJOR.MINOR.PATCH-com (got: $tag)" + exit 1 + } + Write-Host "image_tag=$tag" + [System.IO.File]::AppendAllText($env:GITHUB_ENV, "COM_GIT_TAG=$tag`n") + [System.IO.File]::AppendAllText($env:GITHUB_ENV, "COM_IMAGE_TAG=$tag`n") + + - name: Checkout (this Gitea) + run: | + $ErrorActionPreference = 'Stop' + $cloneHost = '${{ vars.CLONE_HOST }}'.Trim() + if ([string]::IsNullOrWhiteSpace($cloneHost)) { + $Server = "${{ github.server_url }}".TrimEnd('/') + } elseif ($cloneHost -match '^https?://') { + $Server = $cloneHost.TrimEnd('/') + } else { + $Server = 'http://' + $cloneHost + } + $Repo = "${{ github.repository }}" + $Branch = $env:COM_GIT_TAG + $Token = "${{ github.token }}" + $Actor = "${{ github.actor }}" + $hp = $Server -replace '^https?://', '' + if ($Server.StartsWith('https')) { + $cloneUrl = 'https://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git' + } else { + $cloneUrl = 'http://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git' + } + $env:GIT_TERMINAL_PROMPT = '0' + git clone --depth 1 --branch $Branch $cloneUrl . + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Log in to container registry + run: | + $ErrorActionPreference = 'Stop' + $pass = @' + ${{ secrets.REGISTRY_PASSWORD }} + '@ + $pass.Trim() | docker login "${{ vars.REGISTRY_HOST }}" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Seed Gitea base images (node, postgres, nginx, certbot, verdaccio) + run: | + $ErrorActionPreference = 'Stop' + $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim() + $extra = '${{ vars.NODE_IMAGE_SOURCE }}'.Trim() + if ($extra -like '*NODE_IMAGE_SOURCE*') { $extra = '' } + $scriptArgs = @{ RegistryPrefix = $prefix } + if (-not [string]::IsNullOrWhiteSpace($extra)) { $scriptArgs['ExtraSources'] = $extra } + & .\infrastructure\scripts\seed-gitea-base-images.ps1 @scriptArgs + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Resolve npm registry (Verdaccio on Windows host) + run: | + $ErrorActionPreference = 'Stop' + $reg = '${{ vars.NPM_REGISTRY }}'.Trim() + if ($reg -like '*NPM_REGISTRY*') { $reg = '' } + $scriptArgs = @{} + if (-not [string]::IsNullOrWhiteSpace($reg)) { $scriptArgs['Registry'] = $reg } + & .\infrastructure\scripts\ci-resolve-npm-registry.ps1 @scriptArgs + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Resolve dyolink-node (Gitea, then mirrors, Hub last) + run: | + $ErrorActionPreference = 'Stop' + $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim() + $extra = '${{ vars.NODE_IMAGE_SOURCE }}'.Trim() + if ($extra -like '*NODE_IMAGE_SOURCE*') { $extra = '' } + $scriptArgs = @{ RegistryPrefix = $prefix } + if (-not [string]::IsNullOrWhiteSpace($extra)) { $scriptArgs['ExtraSources'] = $extra } + & .\infrastructure\scripts\ci-resolve-node-image.ps1 @scriptArgs + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Build and push backend (:tag-com only) + run: | + $ErrorActionPreference = 'Stop' + $tag = $env:COM_IMAGE_TAG + $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim() + $nodeImage = ([System.IO.File]::ReadAllText((Join-Path (Get-Location) '.ci-node-image'))).Trim() + if ([string]::IsNullOrWhiteSpace($nodeImage)) { + Write-Host "Missing .ci-node-image" + exit 1 + } + $npmReg = ([System.IO.File]::ReadAllText((Join-Path (Get-Location) '.ci-npm-registry'))).Trim() + if ([string]::IsNullOrWhiteSpace($npmReg)) { + Write-Host "Missing .ci-npm-registry" + exit 1 + } + if (Test-Path '.ci-use-legacy-builder') { $env:DOCKER_BUILDKIT = '0' } + Write-Host "Building $prefix/dyolink-backend:$tag (NODE_IMAGE=$nodeImage NPM_REGISTRY=$npmReg)" + $ok = $false + for ($i = 1; $i -le 3; $i++) { + Write-Host "docker build attempt $i/3" + docker build ` + --add-host "host.docker.internal:host-gateway" ` + --build-arg "NODE_IMAGE=$nodeImage" ` + --build-arg "NPM_REGISTRY=$npmReg" ` + -t "$prefix/dyolink-backend:$tag" ./backend + if ($LASTEXITCODE -eq 0) { $ok = $true; break } + if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) } + } + if (-not $ok) { exit 1 } + docker push "$prefix/dyolink-backend:$tag" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Build and push frontend (nudentic.com baked in) + env: + COM_PUBLIC_BASE_URL: ${{ vars.COM_PUBLIC_BASE_URL }} + NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }} + run: | + $ErrorActionPreference = 'Stop' + $tag = $env:COM_IMAGE_TAG + $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim() + $nodeImage = ([System.IO.File]::ReadAllText((Join-Path (Get-Location) '.ci-node-image'))).Trim() + if ([string]::IsNullOrWhiteSpace($nodeImage)) { + Write-Host "Missing .ci-node-image" + exit 1 + } + $npmReg = ([System.IO.File]::ReadAllText((Join-Path (Get-Location) '.ci-npm-registry'))).Trim() + if ([string]::IsNullOrWhiteSpace($npmReg)) { + Write-Host "Missing .ci-npm-registry" + exit 1 + } + if (Test-Path '.ci-use-legacy-builder') { $env:DOCKER_BUILDKIT = '0' } + $base = $env:COM_PUBLIC_BASE_URL.Trim() + if ($base -ne 'https://nudentic.com') { + Write-Host "Set variable COM_PUBLIC_BASE_URL=https://nudentic.com (got: '$base')" + exit 1 + } + Write-Host "Building $prefix/dyolink-frontend:$tag (NODE_IMAGE=$nodeImage NPM_REGISTRY=$npmReg)" + $ok = $false + for ($i = 1; $i -le 3; $i++) { + Write-Host "docker build attempt $i/3" + docker build ` + --add-host "host.docker.internal:host-gateway" ` + --build-arg "NEXT_PUBLIC_API_URL=$base/api" ` + --build-arg "NEXT_PUBLIC_APP_URL=$base" ` + --build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" ` + --build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" ` + --build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=production" ` + --build-arg "NODE_IMAGE=$nodeImage" ` + --build-arg "NPM_REGISTRY=$npmReg" ` + -t "$prefix/dyolink-frontend:$tag" ` + ./frontend + if ($LASTEXITCODE -eq 0) { $ok = $true; break } + if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) } + } + if (-not $ok) { exit 1 } + docker push "$prefix/dyolink-frontend:$tag" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + deploy: + needs: build-and-push + runs-on: windows + steps: + - name: Resolve nudentic.com image tag + run: | + $ErrorActionPreference = 'Stop' + $dispatchTag = '${{ github.event.inputs.tag }}'.Trim() + if (-not [string]::IsNullOrWhiteSpace($dispatchTag)) { + $tag = $dispatchTag + } else { + $tag = "${{ github.ref_name }}" + } + if ($tag -notmatch '^v\d+\.\d+\.\d+-com$') { + Write-Host "International tag must be vMAJOR.MINOR.PATCH-com (got: $tag)" + exit 1 + } + Write-Host "image_tag=$tag" + [System.IO.File]::AppendAllText($env:GITHUB_ENV, "COM_GIT_TAG=$tag`n") + [System.IO.File]::AppendAllText($env:GITHUB_ENV, "COM_IMAGE_TAG=$tag`n") + + - name: Checkout (tagged tree for compose file) + run: | + $ErrorActionPreference = 'Stop' + $cloneHost = '${{ vars.CLONE_HOST }}'.Trim() + if ([string]::IsNullOrWhiteSpace($cloneHost)) { + $Server = "${{ github.server_url }}".TrimEnd('/') + } elseif ($cloneHost -match '^https?://') { + $Server = $cloneHost.TrimEnd('/') + } else { + $Server = 'http://' + $cloneHost + } + $Repo = "${{ github.repository }}" + $Branch = $env:COM_GIT_TAG + $Token = "${{ github.token }}" + $Actor = "${{ github.actor }}" + $hp = $Server -replace '^https?://', '' + if ($Server.StartsWith('https')) { + $cloneUrl = 'https://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git' + } else { + $cloneUrl = 'http://' + $Actor + ':' + $Token + '@' + $hp + '/' + $Repo + '.git' + } + $env:GIT_TERMINAL_PROMPT = '0' + git clone --depth 1 --branch $Branch $cloneUrl . + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Write SSH key + run: | + $ErrorActionPreference = 'Stop' + $raw = @' + ${{ secrets.COM_SSH_KEY }} + '@ + $key = $raw.Trim() + if ($key -notmatch 'BEGIN') { + Write-Host "Set secret COM_SSH_KEY to an OpenSSH private key for the nudentic.com server" + exit 1 + } + $keyPath = Join-Path $env:RUNNER_TEMP 'com_ssh' + $normalized = $key.Replace("`r`n", "`n").TrimEnd() + "`n" + [System.IO.File]::WriteAllText($keyPath, $normalized) + $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value + icacls $keyPath /inheritance:r + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + icacls $keyPath /grant:r "*${sid}:(R)" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + [System.IO.File]::AppendAllText($env:GITHUB_ENV, "COM_SSH_KEY_PATH=$keyPath`n") + + - name: Copy compose + deploy script to Linux + run: | + $ErrorActionPreference = 'Stop' + $hostName = '${{ secrets.COM_SSH_HOST }}'.Trim() + $user = '${{ secrets.COM_SSH_USER }}'.Trim() + $port = '${{ secrets.COM_SSH_PORT }}'.Trim() + if ([string]::IsNullOrWhiteSpace($port)) { $port = '22' } + if ([string]::IsNullOrWhiteSpace($hostName) -or [string]::IsNullOrWhiteSpace($user)) { + Write-Host "Set secrets COM_SSH_HOST and COM_SSH_USER. Do not reuse PROD_SSH_*." + exit 1 + } + $infra = '${{ vars.COM_INFRA_DIR }}'.Trim() + if ([string]::IsNullOrWhiteSpace($infra)) { $infra = '/opt/dyolink/infrastructure' } + $ssh = @('-i', $env:COM_SSH_KEY_PATH, '-o', 'StrictHostKeyChecking=accept-new') + ssh.exe @ssh -p $port "${user}@${hostName}" "mkdir -p $infra/scripts $infra/nginx" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + scp.exe @ssh -P $port ` + infrastructure/docker-compose.prod.yml ` + "${user}@${hostName}:${infra}/docker-compose.prod.yml" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + scp.exe @ssh -P $port ` + infrastructure/scripts/prod-remote-deploy.sh ` + "${user}@${hostName}:${infra}/scripts/prod-remote-deploy.sh" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + scp.exe @ssh -P $port ` + infrastructure/scripts/render-nginx-ssl.sh ` + "${user}@${hostName}:${infra}/scripts/render-nginx-ssl.sh" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + scp.exe @ssh -P $port ` + infrastructure/nginx/nginx.ssl.conf.template ` + "${user}@${hostName}:${infra}/nginx/nginx.ssl.conf.template" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ssh.exe @ssh -p $port "${user}@${hostName}" "chmod +x $infra/scripts/prod-remote-deploy.sh $infra/scripts/render-nginx-ssl.sh" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + - name: Login on Linux and deploy tag-com + run: | + $ErrorActionPreference = 'Stop' + $hostName = '${{ secrets.COM_SSH_HOST }}'.Trim() + $user = '${{ secrets.COM_SSH_USER }}'.Trim() + $port = '${{ secrets.COM_SSH_PORT }}'.Trim() + if ([string]::IsNullOrWhiteSpace($port)) { $port = '22' } + $infra = '${{ vars.COM_INFRA_DIR }}'.Trim() + if ([string]::IsNullOrWhiteSpace($infra)) { $infra = '/opt/dyolink/infrastructure' } + $regHost = '${{ vars.PROD_REGISTRY_HOST }}'.Trim() + if ([string]::IsNullOrWhiteSpace($regHost)) { $regHost = 'wixur.ir:3000' } + $imageTag = $env:COM_IMAGE_TAG + $pass = @' + ${{ secrets.REGISTRY_PASSWORD }} + '@ + $regUser = '${{ secrets.REGISTRY_USERNAME }}' + $ssh = @('-i', $env:COM_SSH_KEY_PATH, '-o', 'StrictHostKeyChecking=accept-new') + $remote = "docker login $regHost -u $regUser --password-stdin && PROD_INFRA_DIR=$infra $infra/scripts/prod-remote-deploy.sh $imageTag" + $pass.Trim() | ssh.exe @ssh -p $port "${user}@${hostName}" $remote + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/.gitea/workflows/prod-tag-deploy.yml b/.gitea/workflows/prod-tag-deploy.yml index 4583c20..589d6ed 100644 --- a/.gitea/workflows/prod-tag-deploy.yml +++ b/.gitea/workflows/prod-tag-deploy.yml @@ -45,6 +45,9 @@ defaults: jobs: build-and-push: + # v1.0.25-com is the international tag. This filter also matches that name, + # so the job must not build or push it onto nudentic.ir. + if: ${{ !endsWith(github.ref_name, '-com') && !endsWith(github.event.inputs.tag, '-com') }} runs-on: windows steps: - name: Checkout (this Gitea) @@ -78,7 +81,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Resolve image tag (v*.*.* only) - id: meta + id: gate run: | $ErrorActionPreference = 'Stop' $dispatchTag = '${{ github.event.inputs.tag }}'.Trim() @@ -87,7 +90,13 @@ jobs: } else { $tag = "${{ github.ref_name }}" } - if ($tag -notmatch '^v\d+\.\d+\.\d+') { + if ($tag -match '-com$') { + Write-Host "Skipping Iran workflow for international tag $tag" + [System.IO.File]::AppendAllText($env:GITHUB_OUTPUT, "skip=true`n") + exit 0 + } + [System.IO.File]::AppendAllText($env:GITHUB_OUTPUT, "skip=false`n") + if ($tag -notmatch '^v\d+\.\d+\.\d+$') { Write-Host "Production images must be tagged vMAJOR.MINOR.PATCH (got: $tag)" exit 1 } @@ -95,6 +104,7 @@ jobs: Write-Host "image_tag=$tag REGISTRY_PREFIX=$prefix" - name: Log in to container registry + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $pass = @' @@ -104,6 +114,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Seed Gitea base images (node, postgres, nginx, certbot, verdaccio) + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim() @@ -115,6 +126,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Resolve npm registry (Verdaccio on Windows host) + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $reg = '${{ vars.NPM_REGISTRY }}'.Trim() @@ -125,6 +137,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Resolve dyolink-node (Gitea, then mirrors, Hub last) + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $prefix = "${{ vars.REGISTRY_HOST }}/${{ vars.REGISTRY_OWNER }}".Trim() @@ -137,6 +150,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Build and push backend (tag only, not :latest) + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $dispatchTag = '${{ github.event.inputs.tag }}'.Trim() @@ -170,6 +184,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Build and push frontend (nudentic.ir baked in) + if: steps.gate.outputs.skip != 'true' env: PROD_PUBLIC_BASE_URL: ${{ vars.PROD_PUBLIC_BASE_URL }} NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }} @@ -216,9 +231,24 @@ jobs: deploy: needs: build-and-push + if: ${{ !endsWith(github.ref_name, '-com') && !endsWith(github.event.inputs.tag, '-com') }} runs-on: windows steps: + - name: Skip international tags + id: gate + run: | + $ErrorActionPreference = 'Stop' + $dispatchTag = '${{ github.event.inputs.tag }}'.Trim() + if (-not [string]::IsNullOrWhiteSpace($dispatchTag)) { $tag = $dispatchTag } else { $tag = "${{ github.ref_name }}" } + if ($tag -match '-com$') { + Write-Host "Skipping Iran deploy for international tag $tag" + [System.IO.File]::AppendAllText($env:GITHUB_OUTPUT, "skip=true`n") + exit 0 + } + [System.IO.File]::AppendAllText($env:GITHUB_OUTPUT, "skip=false`n") + - name: Checkout (tagged tree for compose file) + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $cloneHost = '${{ vars.CLONE_HOST }}'.Trim() @@ -249,6 +279,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Write SSH key + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $raw = @' @@ -272,6 +303,7 @@ jobs: [System.IO.File]::AppendAllText($env:GITHUB_ENV, "PROD_SSH_KEY_PATH=$keyPath`n") - name: Copy compose + deploy script to Linux + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $hostName = '${{ secrets.PROD_SSH_HOST }}'.Trim() @@ -303,6 +335,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Login on Linux and deploy tag + if: steps.gate.outputs.skip != 'true' run: | $ErrorActionPreference = 'Stop' $hostName = '${{ secrets.PROD_SSH_HOST }}'.Trim() diff --git a/README.md b/README.md index 48ac4fd..11d7dd2 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,10 @@ Git tag **`v1.0.1`** → Gitea workflow [`.gitea/workflows/prod-tag-deploy.yml`] First-time SSL / Hub fallback: same `DEPLOY.md`. +## International production (`https://nudentic.com`) + +Tag `vX.Y.Z-com` runs [`.gitea/workflows/prod-com-tag-deploy.yml`](.gitea/workflows/prod-com-tag-deploy.yml). That workflow bakes `https://nudentic.com`, pushes that same tag, and deploys only to the international server. A normal `vX.Y.Z` tag still deploys `nudentic.ir` and does not start this workflow. + --- ## Staging deploy (`https://wixur.ir`) diff --git a/infrastructure/DEPLOY.md b/infrastructure/DEPLOY.md index 15e09a9..088793b 100644 --- a/infrastructure/DEPLOY.md +++ b/infrastructure/DEPLOY.md @@ -78,6 +78,20 @@ Check `https://nudentic.ir/api/health`. AdminJS is `https://nudentic.ir/admin`. --- +## International production (`https://nudentic.com`) + +Second Linux host (`46.225.98.149`). Apex only. Empty database. This does **not** change the Iran server, its DNS, or any `PROD_*` variable or secret. + +Its own tag runs [`.gitea/workflows/prod-com-tag-deploy.yml`](../.gitea/workflows/prod-com-tag-deploy.yml). `v1.0.25-com` pushes `dyolink-backend:v1.0.25-com` and `dyolink-frontend:v1.0.25-com` (frontend baked with `https://nudentic.com`) and SSHs only with `COM_SSH_*`. A normal `v1.0.25` tag does not start this workflow. The Iran workflow skips any tag that ends in `-com` before build or SSH. + +**Gitea variable:** `COM_PUBLIC_BASE_URL=https://nudentic.com`. **Secrets:** `COM_SSH_HOST=46.225.98.149`, `COM_SSH_USER=nudentic`, `COM_SSH_KEY`. Optional `COM_INFRA_DIR` (default `/opt/dyolink/infrastructure`) and `COM_SSH_PORT`. + +On that server, `.env` uses `DOMAIN=nudentic.com` and `secrets/backend.env` uses `FRONTEND_URL=https://nudentic.com`. First HTTPS is still `./scripts/deploy-prod.sh` (Let's Encrypt). Later tags call `prod-remote-deploy.sh vX.Y.Z-com`. + +The workflow file has to be on the tagged commit. A tag cut before this file is pushed does not run the international job. + +--- + ## Iran-local builds (international blackout) Production **build** still happens on the Windows Gitea runner. Linux only **pulls** from `wixur.ir:3000`. @@ -523,7 +537,8 @@ Database dump and restore (take a backup, copy it off the server, load it locall | `/opt/dyolink/infrastructure/nginx/generated/default.conf` | Auto-generated nginx SSL config | | `/opt/dyolink/infrastructure/scripts/prod-remote-deploy.sh` | Tag deploy (CI SSH) | | `/opt/dyolink/infrastructure/scripts/deploy-prod.sh` | First-time SSL + stack up | -| `.gitea/workflows/prod-tag-deploy.yml` | CI: Verdaccio + Gitea bases, push `:v*`, SSH deploy | +| `.gitea/workflows/prod-tag-deploy.yml` | CI: Verdaccio + Gitea bases, push `:v*`, SSH deploy to nudentic.ir | +| `.gitea/workflows/prod-com-tag-deploy.yml` | Same tag: push `:v*-com`, SSH deploy to nudentic.com only | --- -- 2.53.0.windows.1 From 97fcdc071f59597872a06e7867dc0b57df6aa6f8 Mon Sep 17 00:00:00 2001 From: rameen Date: Thu, 19 Nov 2026 14:47:42 +0330 Subject: [PATCH 2/2] Renew nudentic.ir through Arvan DNS when port 80 cannot be used. Let's Encrypt is redirected to a private address on port 80, so webroot renewal never replaces the certificate. The server scripts create the TXT record with an API key that stays on the server. --- infrastructure/DEPLOY.md | 2 + infrastructure/scripts/arvan-dns-auth.py | 79 +++++++++++++++++++ infrastructure/scripts/arvan-dns-cleanup.py | 71 +++++++++++++++++ infrastructure/scripts/install-arvan-renew.sh | 66 ++++++++++++++++ 4 files changed, 218 insertions(+) create mode 100755 infrastructure/scripts/arvan-dns-auth.py create mode 100755 infrastructure/scripts/arvan-dns-cleanup.py create mode 100755 infrastructure/scripts/install-arvan-renew.sh diff --git a/infrastructure/DEPLOY.md b/infrastructure/DEPLOY.md index 088793b..b606b65 100644 --- a/infrastructure/DEPLOY.md +++ b/infrastructure/DEPLOY.md @@ -109,6 +109,8 @@ CERTBOT_IMAGE=wixur.ir:3000//certbot:latest **During a blackout:** tag `v*` as usual. Do not prune Docker on Windows or Linux. Let's Encrypt **renew** needs public ACME — existing certs keep working until expiry. +`nudentic.ir` renews with a DNS TXT record at Arvan, not port 80. The API key stays on the server at `/opt/dyolink/secrets/arvan-api-key`. Install or repair that renewal with `scripts/install-arvan-renew.sh`. A daily cron reloads Nginx so the new file is served. Port 80 from outside Iran is redirected to a private address, so a webroot renew fails. + --- ## Architecture diff --git a/infrastructure/scripts/arvan-dns-auth.py b/infrastructure/scripts/arvan-dns-auth.py new file mode 100755 index 0000000..53983b4 --- /dev/null +++ b/infrastructure/scripts/arvan-dns-auth.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""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 time +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() + 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(): + domain = os.environ["CERTBOT_DOMAIN"] + value = os.environ["CERTBOT_VALIDATION"] + status, body = request( + "POST", + "{}/{}/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): + if txt_visible(fqdn, value): + print("TXT record is visible") + return + time.sleep(10) + raise SystemExit("TXT record was not visible in public DNS in time") + + +if __name__ == "__main__": + main() diff --git a/infrastructure/scripts/arvan-dns-cleanup.py b/infrastructure/scripts/arvan-dns-cleanup.py new file mode 100755 index 0000000..56aadb2 --- /dev/null +++ b/infrastructure/scripts/arvan-dns-cleanup.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Remove the _acme-challenge TXT record created for one Certbot attempt.""" +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): + 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(): + domain = os.environ["CERTBOT_DOMAIN"] + value = os.environ.get("CERTBOT_VALIDATION", "") + status, body = request("GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, domain)) + if status < 200 or status >= 300: + 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": + continue + if record.get("name") not in ("_acme-challenge", "_acme-challenge." + domain): + continue + text = "" + raw_value = record.get("value") + if isinstance(raw_value, dict): + text = str(raw_value.get("text", "")) + if value and value not in text: + continue + del_status, _ = request( + "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") + + +if __name__ == "__main__": + main() diff --git a/infrastructure/scripts/install-arvan-renew.sh b/infrastructure/scripts/install-arvan-renew.sh new file mode 100755 index 0000000..d538e7a --- /dev/null +++ b/infrastructure/scripts/install-arvan-renew.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Run on the nudentic.ir VPS as dyolink. +# Uses /opt/dyolink/secrets/arvan-api-key (one line, not in git). +# Points the existing nudentic.ir certificate at Arvan DNS-01 and reloads +# Nginx once a day so a renewed file is actually served. +set -euo pipefail + +KEY=/opt/dyolink/secrets/arvan-api-key +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +if [ ! -s "$KEY" ]; then + echo "Missing $KEY" >&2 + exit 1 +fi + +docker cp "$KEY" dyolink_certbot_prod:/etc/letsencrypt/arvan-api-key +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 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 -i dyolink_certbot_prod python3 - <<'PY' +from pathlib import Path +path = Path("/etc/letsencrypt/renewal/nudentic.ir.conf") +text = path.read_text().splitlines() +kept = [] +for line in text: + if line.startswith("manual_auth_hook ") or line.startswith("manual_cleanup_hook "): + continue + if line.startswith("webroot_path "): + continue + if line.startswith("authenticator "): + kept.append("authenticator = manual") + elif line.startswith("pref_challs "): + kept.append("pref_challs = dns-01,") + else: + kept.append(line) +hooks = [ + "manual_auth_hook = /etc/letsencrypt/arvan-dns-auth.py", + "manual_cleanup_hook = /etc/letsencrypt/arvan-dns-cleanup.py", +] +out = [] +inserted = False +for line in kept: + if line.startswith("[") and line != "[renewalparams]" and not inserted: + out.extend(hooks) + inserted = True + out.append(line) +if not inserted: + out.extend(hooks) +if not any(line.startswith("pref_challs ") for line in out): + out.append("pref_challs = dns-01,") +path.write_text("\n".join(out) + "\n") +print("renewal config updated") +PY + +docker exec dyolink_certbot_prod mkdir -p /etc/letsencrypt/renewal-disabled +if docker exec dyolink_certbot_prod test -f /etc/letsencrypt/renewal/wixur.ir.conf; then + docker exec dyolink_certbot_prod mv /etc/letsencrypt/renewal/wixur.ir.conf /etc/letsencrypt/renewal-disabled/wixur.ir.conf + echo "wixur.ir renewal disabled on this host" +fi + +CRON_LINE='15 3 * * * docker exec dyolink_nginx_prod nginx -s reload' +(crontab -l 2>/dev/null | grep -v 'dyolink_nginx_prod nginx -s reload' || true + echo "$CRON_LINE") | crontab - +echo "nginx reload scheduled daily at 03:15" -- 2.53.0.windows.1