askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_setup.py · 8.2 KB · 197 lines
| 1 | """First-owner setup for a server installed by someone else's button. |
| 2 | |
| 3 | A one-click install (GitStable's "Install on DigitalOcean", 2026-11-23) puts |
| 4 | a fresh object server on the public internet with nobody signed up. Someone |
| 5 | has to become its first admin, and the obvious ways are all wrong: |
| 6 | |
| 7 | - a default login and password: the same on every box, so known to everyone; |
| 8 | - the installer generating a password and the box serving it at a URL: the |
| 9 | box can't tell its owner from the first stranger who asks; |
| 10 | - "SSH in and run create-superuser": right for an operator, not one click. |
| 11 | |
| 12 | What it does instead. The installer (GitStable) makes a one-time setup code, |
| 13 | shows it only to the person who pressed the button, on their own install |
| 14 | page, and sends the box only its SHA-256 (as the cloud-init file |
| 15 | /etc/dbbasic-setup-code.sha256, which scripts/one-click-install.sh moves to |
| 16 | ``identity/setup_code.sha256`` in the data directory). DigitalOcean's metadata |
| 17 | and the box's disk hold only the hash. The person opens |
| 18 | ``https://<box>/setup#code=...`` -- the code after ``#`` never leaves their |
| 19 | browser in a request -- and chooses their own email and password. Their |
| 20 | password never passes through the installer or the cloud provider. |
| 21 | |
| 22 | While the code file is there and no admin exists, the server is *waiting*: |
| 23 | every route but ``/health`` and ``/setup`` is refused (object_server gates it), |
| 24 | so nothing on the box can be read or changed before it has an owner. Setup |
| 25 | is a claim, not a write: the code file is renamed away before the admin is |
| 26 | created, so of two setups at once exactly one gets the box (the other finds |
| 27 | the file gone). Then the file is deleted and setup is closed for good. |
| 28 | |
| 29 | A code is ``CODE_LENGTH`` characters of Crockford base32 (100 bits), so the |
| 30 | hash needs no salt or slow KDF: there is nothing to guess with a dictionary. |
| 31 | Typing it is forgiving: case, spaces and dashes are ignored, and the letters |
| 32 | base32 leaves out (I, L, O) are read as the digits they look like. |
| 33 | |
| 34 | If the code is lost the box stays waiting, harmlessly. Its owner can still |
| 35 | SSH in and run ``object_identity_cli.py create-superuser``: once an admin |
| 36 | exists the box is no longer waiting, whatever file is left. |
| 37 | """ |
| 38 | |
| 39 | from __future__ import annotations |
| 40 | |
| 41 | import hashlib |
| 42 | import hmac |
| 43 | import os |
| 44 | import re |
| 45 | import secrets |
| 46 | from pathlib import Path |
| 47 | from typing import Any |
| 48 | |
| 49 | import object_credentials |
| 50 | import object_identity |
| 51 | import object_ids |
| 52 | from object_versions import DEFAULT_DATA_DIR |
| 53 | |
| 54 | SETUP_PATH = "/setup" |
| 55 | CODE_FILE = "setup_code.sha256" |
| 56 | CODE_LENGTH = 20 |
| 57 | ADMIN_ROLES = frozenset({"admin", "superuser"}) |
| 58 | _ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" # Crockford base32 |
| 59 | _READ_AS = str.maketrans({"I": "1", "L": "1", "O": "0"}) |
| 60 | _HASH_RE = re.compile(r"^sha256:([0-9a-f]{64})$") |
| 61 | |
| 62 | |
| 63 | class SetupError(ValueError): |
| 64 | """Something the person at the form can fix; the message is shown to them.""" |
| 65 | |
| 66 | |
| 67 | def code_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 68 | return Path(base_dir) / object_identity.IDENTITY_DIR / CODE_FILE |
| 69 | |
| 70 | |
| 71 | def normalize_code(value: str | None) -> str: |
| 72 | """The code as it was made: upper case, no spaces or dashes, I/L/O read as 1/1/0.""" |
| 73 | text = re.sub(r"[\s-]+", "", str(value or "")).upper().translate(_READ_AS) |
| 74 | return text if len(text) == CODE_LENGTH and all(c in _ALPHABET for c in text) else "" |
| 75 | |
| 76 | |
| 77 | def code_hash(code: str) -> str: |
| 78 | """What the box keeps: ``sha256:<hex>`` of the normalized code.""" |
| 79 | return "sha256:" + hashlib.sha256(normalize_code(code).encode("ascii")).hexdigest() |
| 80 | |
| 81 | |
| 82 | def new_code() -> str: |
| 83 | """A fresh code, for tests and for an operator making one by hand. GitStable makes its own.""" |
| 84 | return "".join(secrets.choice(_ALPHABET) for _ in range(CODE_LENGTH)) |
| 85 | |
| 86 | |
| 87 | def display(code: str) -> str: |
| 88 | """XXXXX-XXXXX-XXXXX-XXXXX, for reading aloud or typing.""" |
| 89 | plain = normalize_code(code) |
| 90 | return "-".join(plain[i:i + 5] for i in range(0, len(plain), 5)) |
| 91 | |
| 92 | |
| 93 | def _stored_hash(base_dir: Path | str) -> str | None: |
| 94 | try: |
| 95 | text = code_path(base_dir).read_text(encoding="ascii").strip() |
| 96 | except (OSError, UnicodeDecodeError): |
| 97 | return None |
| 98 | return text if _HASH_RE.match(text) else None |
| 99 | |
| 100 | |
| 101 | def _admin_exists(base_dir: Path | str) -> bool: |
| 102 | try: |
| 103 | users = object_identity.list_users(base_dir=base_dir) |
| 104 | except ValueError: |
| 105 | return True # an identity store we can't read is not an empty one: don't hand the box out |
| 106 | return any(ADMIN_ROLES.intersection(user.get("roles") or ()) for user in users) |
| 107 | |
| 108 | |
| 109 | def _readable_id(email: str, base_dir: Path | str) -> str: |
| 110 | """The email's name part ("owner" for owner@example.org) when it makes a valid, unused id, so pages say |
| 111 | "signed in as owner" rather than a long random id (seen on the first test box). Else a random one.""" |
| 112 | name = re.sub(r"[^a-z0-9_.-]", "", email.split("@", 1)[0].lower())[:40] |
| 113 | if name and name[0].isalnum(): |
| 114 | try: |
| 115 | object_identity.get_user(name, base_dir=base_dir) |
| 116 | except LookupError: |
| 117 | return name |
| 118 | except ValueError: |
| 119 | pass |
| 120 | return object_ids.new_uuid4() |
| 121 | |
| 122 | |
| 123 | def waiting(base_dir: Path | str = DEFAULT_DATA_DIR) -> bool: |
| 124 | """True while this box has a setup code and no admin: only /health and /setup may answer.""" |
| 125 | if not code_path(base_dir).exists(): |
| 126 | return False |
| 127 | return not _admin_exists(base_dir) |
| 128 | |
| 129 | |
| 130 | def complete( |
| 131 | code: str | None, |
| 132 | email: str | None, |
| 133 | password: str | None, |
| 134 | display_name: str | None = None, |
| 135 | *, |
| 136 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 137 | ) -> dict[str, Any] | None: |
| 138 | """Make the first admin. Returns the user, or None when the code is wrong or setup is already done. |
| 139 | |
| 140 | Raises SetupError for a bad email or password, before anything is claimed, so the person can fix it |
| 141 | and the code still works.""" |
| 142 | from object_signup import SignupError, check_password, normalize_email # the same rules as signup |
| 143 | |
| 144 | try: |
| 145 | email = normalize_email(email) |
| 146 | password = check_password(password) |
| 147 | except SignupError as exc: |
| 148 | raise SetupError(str(exc)) from exc |
| 149 | name = " ".join(str(display_name or "").split())[:100] |
| 150 | |
| 151 | if not waiting(base_dir): |
| 152 | return None |
| 153 | stored = _stored_hash(base_dir) |
| 154 | given = normalize_code(code) |
| 155 | if stored is None or not given or not hmac.compare_digest(code_hash(given), stored): |
| 156 | return None |
| 157 | |
| 158 | path = code_path(base_dir) |
| 159 | claimed = path.with_name(f"{CODE_FILE}.claimed-{os.getpid()}-{secrets.token_hex(4)}") |
| 160 | try: |
| 161 | os.rename(path, claimed) # the claim: of two setups at once, one rename finds nothing |
| 162 | except FileNotFoundError: |
| 163 | return None |
| 164 | if _admin_exists(base_dir): # made from the shell meanwhile: setup is over |
| 165 | claimed.unlink(missing_ok=True) |
| 166 | return None |
| 167 | # The password first, then the user: an admin that exists is what ends "waiting", so it must never |
| 168 | # exist without the password that lets its owner in. |
| 169 | user_id = _readable_id(email, base_dir) |
| 170 | try: |
| 171 | try: |
| 172 | # set_password also ends any sessions left under this id; if that fails it raises after the |
| 173 | # credential is written, so the password is taken back here too, not only when create_user fails |
| 174 | object_credentials.set_password(user_id, password, base_dir=base_dir) |
| 175 | user = object_identity.create_user( |
| 176 | {"user_id": user_id, "email": email, "display_name": name, "roles": ["admin"]}, |
| 177 | base_dir=base_dir, |
| 178 | # the row under this id is the one set_password wrote just now (it replaced any leftover) |
| 179 | leftover_password=object_identity.LEFTOVER_PASSWORD_KEEP) |
| 180 | except Exception: |
| 181 | _take_back_password(user_id, base_dir) |
| 182 | raise |
| 183 | except Exception: |
| 184 | os.rename(claimed, path) # nothing was made: the code still works |
| 185 | raise |
| 186 | claimed.unlink(missing_ok=True) |
| 187 | return user |
| 188 | |
| 189 | |
| 190 | def _take_back_password(user_id: str, base_dir: Path | str) -> None: |
| 191 | """Remove the password a failed setup wrote. remove_password deletes the row before it ends sessions, |
| 192 | so when ending them fails again the row is gone all the same; no user row was made, so no session of |
| 193 | this id can have been signed in with it.""" |
| 194 | try: |
| 195 | object_credentials.remove_password(user_id, base_dir=base_dir) |
| 196 | except object_credentials.SessionRevocationError: |
| 197 | pass |