Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_setup.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_setup.py · 8.2 KB · 197 lines
1"""First-owner setup for a server installed by someone else's button.
2
3A one-click install (GitStable's "Install on DigitalOcean", 2026-11-23) puts
4a fresh object server on the public internet with nobody signed up. Someone
5has 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
12What it does instead. The installer (GitStable) makes a one-time setup code,
13shows it only to the person who pressed the button, on their own install
14page, 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
17and the box's disk hold only the hash. The person opens
18``https://<box>/setup#code=...`` -- the code after ``#`` never leaves their
19browser in a request -- and chooses their own email and password. Their
20password never passes through the installer or the cloud provider.
21
22While the code file is there and no admin exists, the server is *waiting*:
23every route but ``/health`` and ``/setup`` is refused (object_server gates it),
24so nothing on the box can be read or changed before it has an owner. Setup
25is a claim, not a write: the code file is renamed away before the admin is
26created, so of two setups at once exactly one gets the box (the other finds
27the file gone). Then the file is deleted and setup is closed for good.
28
29A code is ``CODE_LENGTH`` characters of Crockford base32 (100 bits), so the
30hash needs no salt or slow KDF: there is nothing to guess with a dictionary.
31Typing it is forgiving: case, spaces and dashes are ignored, and the letters
32base32 leaves out (I, L, O) are read as the digits they look like.
33
34If the code is lost the box stays waiting, harmlessly. Its owner can still
35SSH in and run ``object_identity_cli.py create-superuser``: once an admin
36exists the box is no longer waiting, whatever file is left.
37"""
38
39from __future__ import annotations
40
41import hashlib
42import hmac
43import os
44import re
45import secrets
46from pathlib import Path
47from typing import Any
48
49import object_credentials
50import object_identity
51import object_ids
52from object_versions import DEFAULT_DATA_DIR
53
54SETUP_PATH = "/setup"
55CODE_FILE = "setup_code.sha256"
56CODE_LENGTH = 20
57ADMIN_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
63class SetupError(ValueError):
64 """Something the person at the form can fix; the message is shown to them."""
65
66
67def code_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
68 return Path(base_dir) / object_identity.IDENTITY_DIR / CODE_FILE
69
70
71def 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
77def 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
82def 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
87def 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
93def _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
101def _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
109def _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
123def 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
130def 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
190def _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