chore(home): mirror from kalinamall (b0abf99) with papatramp URLs

This commit is contained in:
2026-07-14 20:43:55 +10:00
commit 10704e0f88
40 changed files with 7253 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
#!/bin/bash
# Автогенерация release/manifest-VERSION.json при bump версии (version.txt / SSH_MONITOR_VERSION).
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
_staged() {
git diff --cached --name-only -- "$@"
}
_version_bump_staged() {
if _staged version.txt | grep -q .; then
return 0
fi
if _staged ssh-monitor | grep -q .; then
if git diff --cached -- ssh-monitor | grep -qE '^[+-].*SSH_MONITOR_VERSION='; then
return 0
fi
fi
return 1
}
_agent_files_staged() {
local f
for f in ssh-monitor sac-client.sh update_ssh_monitor.sh ssh-monitor-watchdog ssh-monitor-perms.sh; do
if _staged "$f" | grep -q .; then
return 0
fi
done
return 1
}
_version_bump_staged || _agent_files_staged || exit 0
_find_python() {
local c
for c in python3 python; do
if command -v "$c" >/dev/null 2>&1 && "$c" -c 'import sys' >/dev/null 2>&1; then
echo "$c"
return 0
fi
done
return 1
}
PY="$(_find_python)" || {
echo "pre-commit: python нужен для manifest (рабочий python/python3 не найден)" >&2
exit 1
}
"$PY" "$ROOT/contrib/manifest/generate.py"
VER="$(tr -d '\r\n' <"$ROOT/version.txt")"
[ -n "$VER" ] || {
echo "pre-commit: version.txt пуст — не могу добавить manifest" >&2
exit 1
}
MANIFEST="release/manifest-${VER}.json"
if [ ! -f "$MANIFEST" ]; then
echo "pre-commit: не создан $MANIFEST" >&2
exit 1
fi
git add "$MANIFEST"
echo "pre-commit: обновлён $MANIFEST (версия $VER)"
+54
View File
@@ -0,0 +1,54 @@
# Install git hooks + local manifest wrappers (not committed to git).
# Run from repo root: .\contrib\install-git-hooks.ps1
$ErrorActionPreference = "Stop"
$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$HookSrc = Join-Path $Root "contrib\hooks\pre-commit"
$HookDst = Join-Path $Root ".git\hooks\pre-commit"
$LocalDir = Join-Path $Root ".local"
$LocalScript = Join-Path $LocalDir "build-release-manifest.ps1"
$LocalScriptSh = Join-Path $LocalDir "build-release-manifest.sh"
if (-not (Test-Path (Join-Path $Root ".git"))) {
throw "Not a git repository: $Root"
}
if (-not (Test-Path $HookSrc)) {
throw "Missing hook file: $HookSrc"
}
New-Item -ItemType Directory -Force -Path (Split-Path $HookDst) | Out-Null
Copy-Item -Force $HookSrc $HookDst
New-Item -ItemType Directory -Force -Path $LocalDir | Out-Null
@'
# Local manifest wrapper (gitignored). Manual generation on Windows.
$ErrorActionPreference = "Stop"
$Root = git -C "$PSScriptRoot\.." rev-parse --show-toplevel 2>$null
if (-not $Root) {
$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
}
$py = Get-Command python -ErrorAction SilentlyContinue
if (-not $py) { $py = Get-Command python3 -ErrorAction SilentlyContinue }
if (-not $py) { throw "python not found in PATH" }
& $py.Source (Join-Path $Root "contrib\manifest\generate.py") @args
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
'@ | Set-Content -Path $LocalScript -Encoding UTF8
@'
#!/bin/bash
# Local manifest wrapper (gitignored). Git Bash.
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
exec python3 "$ROOT/contrib/manifest/generate.py" "$@"
'@ | Set-Content -Path $LocalScriptSh -Encoding ASCII -NoNewline
Add-Content -Path $LocalScriptSh -Value "`n" -NoNewline
Write-Host "OK: pre-commit hook -> $HookDst"
Write-Host "OK: manual script (PS) -> $LocalScript"
Write-Host "OK: manual script (sh) -> $LocalScriptSh"
Write-Host ""
Write-Host "Manual: .\.local\build-release-manifest.ps1"
Write-Host " python contrib\manifest\generate.py"
Write-Host "Pre-commit runs on version bump (python required in PATH)."
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
# Установка git hooks и локального скрипта ручной генерации manifest (не в git).
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOOK_SRC="$ROOT/contrib/hooks/pre-commit"
HOOK_DST="$ROOT/.git/hooks/pre-commit"
LOCAL_DIR="$ROOT/.local"
LOCAL_SCRIPT="$LOCAL_DIR/build-release-manifest.sh"
if [ ! -d "$ROOT/.git" ]; then
echo "ERROR: не git-репозиторий: $ROOT" >&2
exit 1
fi
mkdir -p "$LOCAL_DIR"
cat >"$LOCAL_SCRIPT" <<'EOF'
#!/bin/bash
# Локальный wrapper (не коммитится). Ручная генерация manifest.
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
exec python3 "$ROOT/contrib/manifest/generate.py" "$@"
EOF
chmod +x "$LOCAL_SCRIPT"
cp "$HOOK_SRC" "$HOOK_DST"
chmod +x "$HOOK_DST"
echo "OK: pre-commit hook → $HOOK_DST"
echo "OK: ручной скрипт → $LOCAL_SCRIPT (в .gitignore, не уйдёт в Gitea/GitHub)"
echo "После clone: ./contrib/install-git-hooks.sh или .\\contrib\\install-git-hooks.ps1 (Windows)"
+19
View File
@@ -0,0 +1,19 @@
# Пример для /etc/logrotate.d/ssh-monitor
# Установка: sudo cp contrib/logrotate.d/ssh-monitor /etc/logrotate.d/ssh-monitor
# Пути должны совпадать с LOG_FILE и WATCHDOG_LOG_FILE в /etc/ssh-monitor.conf
/var/log/ssh_monitor.log
/var/log/ssh_monitor_watchdog.log {
weekly
rotate 12
compress
delaycompress
missingok
notifempty
create 0640 root root
sharedscripts
postrotate
# При необходимости отправьте сигнал процессу (если добавите обработку HUP)
/bin/true
endscript
}
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Генерация release/manifest-VERSION.json (SHA256 git blob = checkout на Linux)."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import subprocess
import sys
from pathlib import Path
MANIFEST_FILES = (
"ssh-monitor",
"sac-client.sh",
"update_ssh_monitor.sh",
"ssh-monitor-watchdog",
"ssh-monitor-perms.sh",
)
def repo_root() -> Path:
return Path(
subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip()
)
def read_version(root: Path, explicit: str | None) -> str:
if explicit:
return explicit.strip()
vt = root / "version.txt"
if vt.is_file():
v = vt.read_text(encoding="utf-8").strip()
if v:
return v
ssh = root / "ssh-monitor"
if ssh.is_file():
for line in ssh.read_text(encoding="utf-8", errors="replace").splitlines():
if line.strip().startswith("SSH_MONITOR_VERSION="):
v = line.split("=", 1)[1].strip().strip("\"'")
if v:
return v
raise SystemExit("ERROR: укажите VERSION или заполните version.txt / SSH_MONITOR_VERSION")
def file_bytes_from_git(root: Path, name: str) -> bytes | None:
for ref in (f":{name}", f"HEAD:{name}"):
try:
return subprocess.check_output(["git", "-C", str(root), "show", ref])
except subprocess.CalledProcessError:
continue
return None
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sha256_release_file(root: Path, name: str) -> str:
blob = file_bytes_from_git(root, name)
if blob is not None:
return sha256_bytes(blob)
path = root / name
if not path.is_file():
raise SystemExit(f"ERROR: нет файла {name} (ни в git index/HEAD, ни на диске)")
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def main() -> None:
parser = argparse.ArgumentParser(description="Сгенерировать release/manifest-VERSION.json")
parser.add_argument("version", nargs="?", help="Версия (по умолчанию из version.txt)")
parser.add_argument(
"--pin-commit",
action="store_true",
help="Записать git_commit=HEAD (после коммита; в pre-commit не используется)",
)
args = parser.parse_args()
root = repo_root()
version = read_version(root, args.version)
for name in MANIFEST_FILES:
if file_bytes_from_git(root, name) is None and not (root / name).is_file():
raise SystemExit(f"ERROR: нет файла {name}")
git_commit = ""
if args.pin_commit:
try:
git_commit = subprocess.check_output(
["git", "-C", str(root), "rev-parse", "HEAD"], text=True
).strip()
except subprocess.CalledProcessError:
pass
manifest = {
"version": version,
"git_commit": git_commit,
"files": {name: f"sha256:{sha256_release_file(root, name)}" for name in MANIFEST_FILES},
}
out = root / "release" / f"manifest-{version}.json"
out.parent.mkdir(parents=True, exist_ok=True)
with out.open("w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2, ensure_ascii=False)
f.write("\n")
pin = git_commit[:12] if git_commit else "(empty)"
print(f"Wrote {out.relative_to(root)} git_commit={pin}")
if __name__ == "__main__":
main()
+50
View File
@@ -0,0 +1,50 @@
#!/bin/bash
# Smoke-test safe config parser (no network). Run from repo root.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# shellcheck source=ssh-monitor-perms.sh
source "$ROOT/ssh-monitor-perms.sh"
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT
cfg="$tmpdir/test.conf"
cat >"$cfg" <<'EOF'
# comment
TELEGRAM_BOT_TOKEN="tok"
UseSAC="exclusive"
SAC_URL="https://sac.example.test"
WHITELIST_IPS="127.0.0.1,10.0.0.5"
WHITELIST_SUBNETS="10.0.0.0/24"
BACKUP_WEBHOOK_URL="https://hooks.example/legacy"
UNKNOWN_KEY="ignored"
EOF
ssh_monitor_config_load_file "$cfg"
[ "${TELEGRAM_BOT_TOKEN:-}" = "tok" ] || {
echo "FAIL: TELEGRAM_BOT_TOKEN" >&2
exit 1
}
[ "${UseSAC:-}" = "exclusive" ] || {
echo "FAIL: UseSAC" >&2
exit 1
}
ips_csv="${WHITELIST_IPS:-}"
subs_csv="${WHITELIST_SUBNETS:-}"
WHITELIST_IPS=()
WHITELIST_SUBNETS=()
IFS=',' read -r -a WHITELIST_IPS <<<"$ips_csv"
IFS=',' read -r -a WHITELIST_SUBNETS <<<"$subs_csv"
ssh_monitor_validate_config_values || {
echo "FAIL: validate_config_values" >&2
exit 1
}
printf 'EVIL="$(id)"\n' >"$tmpdir/bad.conf"
if ssh_monitor_config_load_file "$tmpdir/bad.conf" 2>/dev/null; then
echo "OK: config parser smoke test passed"
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# Smoke-test sac-fail.count suppress on shutdown flag. Run from repo root.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT
write_log() { :; }
ssh_monitor_secure_file() { :; }
ssh_monitor_secure_dir() { mkdir -p "$1"; }
# shellcheck source=sac-client.sh
source "$ROOT/sac-client.sh"
export SAC_FAIL_COUNT_FILE="${tmpdir}/sac-fail.count"
sac_write_fail_count 0
sac_increment_fail_count
[ "$(sac_read_fail_count)" = "1" ] || {
echo "FAIL: expected count 1 after increment" >&2
exit 1
}
SAC_SUPPRESS_FAIL_COUNT=1
sac_increment_fail_count || true
[ "$(sac_read_fail_count)" = "1" ] || {
echo "FAIL: count changed under SAC_SUPPRESS_FAIL_COUNT" >&2
exit 1
}
echo "OK sac-fail.count suppress"