summaryrefslogtreecommitdiff
path: root/hetzner-admin/app.py
blob: a9377a84bec143f69fe4b577dcfa93896a525ab9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import functools
import hmac
import json
import os
import secrets
import time
from datetime import timedelta

import paramiko
from flask import Flask, redirect, render_template_string, request, session
from webauthn import (
    generate_authentication_options,
    generate_registration_options,
    options_to_json,
    verify_authentication_response,
    verify_registration_response,
)
from webauthn.helpers import base64url_to_bytes, bytes_to_base64url
from webauthn.helpers.structs import (
    AuthenticatorSelectionCriteria,
    PublicKeyCredentialDescriptor,
    ResidentKeyRequirement,
)

ADMIN_USER = os.environ["ADMIN_USER"]
ADMIN_PASS = os.environ["ADMIN_PASS"]
SSH_HOST = os.environ.get("SSH_HOST", "host.docker.internal")
SSH_PORT = int(os.environ.get("SSH_PORT", "22"))
SSH_USER = os.environ.get("SSH_USER", "root")
SSH_KEY_PATH = os.environ.get("SSH_KEY_PATH", "/app/id_rsa")
RP_ID = os.environ.get("RP_ID", "hetzner-admin.yyamashita.com")
ORIGIN = f"https://{RP_ID}"
DATA_DIR = os.environ.get("DATA_DIR", "/app/data")
PASSKEYS_PATH = os.path.join(DATA_DIR, "passkeys.json")
SECRET_PATH = os.path.join(DATA_DIR, "secret_key")


def load_secret():
    os.makedirs(DATA_DIR, exist_ok=True)
    if not os.path.exists(SECRET_PATH):
        with open(SECRET_PATH, "w") as f:
            f.write(secrets.token_hex(32))
    with open(SECRET_PATH) as f:
        return f.read().strip()


app = Flask(__name__)
app.secret_key = load_secret()
app.config.update(
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE="Lax",
    PERMANENT_SESSION_LIFETIME=timedelta(days=30),
)

COMMANDS = [
    ("Docker Status", "docker ps"),
    ("Restart Caddy", "docker compose -f /app/infra/caddy/docker-compose.yml restart"),
    ("Restart Mail", "docker compose -f /app/infra/mail/docker-compose.yml restart"),
    ("Restart cgit", "docker compose -f /app/infra/cgit/docker-compose.yml restart"),
    ("Restart Admin", "docker compose -f /app/infra/hetzner-admin/docker-compose.yml restart"),
    ("Restart Claude Sessions", "bash /app/infra/claude/restart-sessions.sh"),
    ("Reboot Server", "reboot"),
]

COMMAND_MAP = {label: cmd for label, cmd in COMMANDS}

# 個別に停止・起動できるサービス(run-command.sh の SERVICES と status/targets.txt の名前に合わせる)
SERVICES = ["golive", "whoisband", "blog", "todo", "git", "vpn", "ntfy", "mail", "code"]

# ブラウザ側: JSON ⇔ WebAuthn の変換はブラウザ組み込みの
# parseCreationOptionsFromJSON / parseRequestOptionsFromJSON / toJSON に任せる
PASSKEY_JS = """<script>
async function passkey(kind) {
  try {
    const opts = await (await fetch('/passkey/' + kind + '/options', {method: 'POST'})).json();
    const cred = kind === 'register'
      ? await navigator.credentials.create({publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(opts)})
      : await navigator.credentials.get({publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(opts)});
    const res = await fetch('/passkey/' + kind + '/verify', {
      method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(cred.toJSON())});
    const msg = await res.text();
    if (!res.ok) throw new Error(msg);
    if (kind === 'login') location.href = '/'; else alert(msg);
  } catch (e) {
    alert('Passkey error: ' + e.message);
  }
}
</script>"""

LOGIN_HTML = """<!DOCTYPE html>
<html>
<head><title>Server Admin</title><meta name="viewport" content="width=device-width"></head>
<body>
<h3>Server Admin</h3>
<p><button onclick="passkey('login')">Login with Passkey</button></p>
<form method="post" action="/login">
  <input name="username" placeholder="user" autocomplete="username">
  <input name="password" type="password" placeholder="password" autocomplete="current-password">
  <button>Login</button>
</form>
{% if error %}<p style="color:red">{{ error }}</p>{% endif %}
""" + PASSKEY_JS + """
</body>
</html>"""

HTML = """<!DOCTYPE html>
<html>
<head><title>Server Admin</title><meta name="viewport" content="width=device-width"></head>
<body>
<h3>Server Admin</h3>
<p><a href="https://status.yyamashita.com">Status</a></p>
<h4>Services</h4>
{% if services is string %}
<p style="color:red">{{ services }}</p>
{% else %}
<table>
{% for name, state in services %}
<tr>
  <td>{{ name }}</td>
  <td style="color:{{ 'green' if state == 'running' else 'gray' }}">{{ state }}</td>
  <td>
    <form method="post" action="/service" style="margin:0">
      <input type="hidden" name="name" value="{{ name }}">
      {% if state == "running" %}
      <button name="action" value="stop" onclick="return confirm('Stop {{ name }}?')">Stop</button>
      {% else %}
      <button name="action" value="start">Start</button>
      {% endif %}
    </form>
  </td>
</tr>
{% endfor %}
</table>
{% endif %}
<h4>Commands</h4>
{% for label, _ in commands %}
<form method="post" action="/run" style="display:block;margin-bottom:8px">
  <input type="hidden" name="cmd" value="{{ label }}">
  {% if label == "Reboot Server" %}
  <button onclick="return confirm('Really reboot?')">{{ label }}</button>
  {% else %}
  <button>{{ label }}</button>
  {% endif %}
</form>
{% endfor %}
{% if output is not none %}
<h4>Output:</h4>
<pre>{{ output }}</pre>
{% endif %}
<hr>
<p>
  Passkeys registered: {{ passkey_count }}
  <button onclick="passkey('register')">Register this device's passkey</button>
  <a href="/logout">Logout</a>
</p>
""" + PASSKEY_JS + """
</body>
</html>"""


def load_passkeys():
    try:
        with open(PASSKEYS_PATH) as f:
            return json.load(f)
    except FileNotFoundError:
        return []


def save_passkeys(keys):
    tmp = PASSKEYS_PATH + ".tmp"
    with open(tmp, "w") as f:
        json.dump(keys, f, indent=2)
    os.replace(tmp, PASSKEYS_PATH)


def requires_auth(f):
    @functools.wraps(f)
    def decorated(*args, **kwargs):
        if not session.get("auth"):
            return redirect("/login")
        return f(*args, **kwargs)

    return decorated


def log_in():
    session.clear()
    session.permanent = True
    session["auth"] = True


def run_ssh(command):
    key = paramiko.RSAKey.from_private_key_file(SSH_KEY_PATH)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(SSH_HOST, port=SSH_PORT, username=SSH_USER, pkey=key, timeout=10)
    try:
        _, stdout, stderr = client.exec_command(command, timeout=30)
        out = stdout.read().decode(errors="replace")
        err = stderr.read().decode(errors="replace")
        return (out + err).strip() or "(no output)"
    finally:
        client.close()


def load_services():
    """[(name, "running"|"stopped"), ...]。取得できなければエラーメッセージ(str)"""
    try:
        out = run_ssh("services")
    except Exception as e:
        return f"Error loading services: {e}"
    states = dict(line.split(None, 1) for line in out.splitlines() if len(line.split()) == 2)
    return [(name, states.get(name, "unknown")) for name in SERVICES]


def render_index(output=None):
    return render_template_string(
        HTML,
        commands=COMMANDS,
        services=load_services(),
        output=output,
        passkey_count=len(load_passkeys()),
    )


@app.route("/login", methods=["GET", "POST"])
def login():
    error = None
    if request.method == "POST":
        user_ok = hmac.compare_digest(request.form.get("username", ""), ADMIN_USER)
        pass_ok = hmac.compare_digest(request.form.get("password", ""), ADMIN_PASS)
        if user_ok and pass_ok:
            log_in()
            return redirect("/")
        error = "Wrong user or password"
    return render_template_string(LOGIN_HTML, error=error)


@app.route("/logout")
def logout():
    session.clear()
    return redirect("/login")


@app.route("/passkey/register/options", methods=["POST"])
@requires_auth
def passkey_register_options():
    opts = generate_registration_options(
        rp_id=RP_ID,
        rp_name="Server Admin",
        user_name=ADMIN_USER,
        user_id=ADMIN_USER.encode(),
        authenticator_selection=AuthenticatorSelectionCriteria(
            resident_key=ResidentKeyRequirement.REQUIRED
        ),
        exclude_credentials=[
            PublicKeyCredentialDescriptor(id=base64url_to_bytes(k["id"]))
            for k in load_passkeys()
        ],
    )
    session["challenge"] = bytes_to_base64url(opts.challenge)
    return app.response_class(options_to_json(opts), mimetype="application/json")


@app.route("/passkey/register/verify", methods=["POST"])
@requires_auth
def passkey_register_verify():
    challenge = session.pop("challenge", None)
    if not challenge:
        return "No challenge", 400
    try:
        v = verify_registration_response(
            credential=request.get_data(as_text=True),
            expected_challenge=base64url_to_bytes(challenge),
            expected_rp_id=RP_ID,
            expected_origin=ORIGIN,
        )
    except Exception as e:
        return f"Registration failed: {e}", 400
    keys = load_passkeys()
    keys.append(
        {
            "id": bytes_to_base64url(v.credential_id),
            "public_key": bytes_to_base64url(v.credential_public_key),
            "sign_count": v.sign_count,
            "created": time.strftime("%Y-%m-%d %H:%M:%S"),
            "user_agent": request.headers.get("User-Agent", ""),
        }
    )
    save_passkeys(keys)
    return "Passkey registered"


@app.route("/passkey/login/options", methods=["POST"])
def passkey_login_options():
    # allow_credentials を空にしてブラウザ側で保存済みパスキーを選ばせる
    opts = generate_authentication_options(rp_id=RP_ID)
    session["challenge"] = bytes_to_base64url(opts.challenge)
    return app.response_class(options_to_json(opts), mimetype="application/json")


@app.route("/passkey/login/verify", methods=["POST"])
def passkey_login_verify():
    challenge = session.pop("challenge", None)
    if not challenge:
        return "No challenge", 400
    cred = request.get_json(silent=True) or {}
    keys = load_passkeys()
    key = next((k for k in keys if k["id"] == cred.get("id")), None)
    if not key:
        return "Unknown passkey (register it first after password login)", 400
    try:
        v = verify_authentication_response(
            credential=cred,
            expected_challenge=base64url_to_bytes(challenge),
            expected_rp_id=RP_ID,
            expected_origin=ORIGIN,
            credential_public_key=base64url_to_bytes(key["public_key"]),
            credential_current_sign_count=key["sign_count"],
        )
    except Exception as e:
        return f"Login failed: {e}", 400
    key["sign_count"] = v.new_sign_count
    save_passkeys(keys)
    log_in()
    return "OK"


@app.route("/")
@requires_auth
def index():
    return render_index()


@app.route("/run", methods=["POST"])
@requires_auth
def run():
    label = request.form.get("cmd", "")
    command = COMMAND_MAP.get(label)
    if not command:
        output = f"Unknown command: {label}"
    else:
        try:
            output = run_ssh(command)
        except Exception as e:
            output = f"Error: {e}"
    return render_index(output)


@app.route("/service", methods=["POST"])
@requires_auth
def service():
    name = request.form.get("name", "")
    action = request.form.get("action", "")
    if name not in SERVICES or action not in ("stop", "start"):
        return render_index(f"Unknown service action: {action} {name}")
    try:
        output = run_ssh(f"{action} {name}")
    except Exception as e:
        output = f"Error: {e}"
    return render_index(output)