confsync-server 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- confsync_server/__init__.py +3 -0
- confsync_server/__main__.py +3 -0
- confsync_server/app.py +693 -0
- confsync_server/auth.py +77 -0
- confsync_server/cli.py +91 -0
- confsync_server/config.py +80 -0
- confsync_server/crypto.py +69 -0
- confsync_server/db.py +337 -0
- confsync_server/service.py +69 -0
- confsync_server-0.1.0.dist-info/METADATA +20 -0
- confsync_server-0.1.0.dist-info/RECORD +13 -0
- confsync_server-0.1.0.dist-info/WHEEL +4 -0
- confsync_server-0.1.0.dist-info/entry_points.txt +2 -0
confsync_server/auth.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""GitHub OAuth flow and token/API-key generation helpers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import secrets
|
|
5
|
+
import string
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize"
|
|
10
|
+
GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token"
|
|
11
|
+
GITHUB_USER_URL = "https://api.github.com/user"
|
|
12
|
+
|
|
13
|
+
_KEY_ALPHABET = string.ascii_letters + string.digits
|
|
14
|
+
KEY_PREFIX = "cs_"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def generate_api_key() -> str:
|
|
18
|
+
"""New API key: ``cs_`` + 48 random base62 chars. Plaintext is shown to
|
|
19
|
+
the user once; only its sha256 is stored server-side."""
|
|
20
|
+
return KEY_PREFIX + "".join(secrets.choice(_KEY_ALPHABET) for _ in range(48))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def generate_session_token() -> str:
|
|
24
|
+
return secrets.token_urlsafe(32)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def generate_oauth_state() -> str:
|
|
28
|
+
return secrets.token_urlsafe(24)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_authorize_url(client_id: str, redirect_uri: str, state: str) -> str:
|
|
32
|
+
return (
|
|
33
|
+
f"{GITHUB_AUTHORIZE_URL}?client_id={client_id}"
|
|
34
|
+
f"&redirect_uri={redirect_uri}&state={state}&scope=read:user"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def exchange_code(client_id: str, client_secret: str, code: str,
|
|
39
|
+
redirect_uri: str) -> str:
|
|
40
|
+
"""Exchange an OAuth code for a GitHub access token."""
|
|
41
|
+
async with httpx.AsyncClient(timeout=20) as client:
|
|
42
|
+
resp = await client.post(
|
|
43
|
+
GITHUB_TOKEN_URL,
|
|
44
|
+
data={
|
|
45
|
+
"client_id": client_id,
|
|
46
|
+
"client_secret": client_secret,
|
|
47
|
+
"code": code,
|
|
48
|
+
"redirect_uri": redirect_uri,
|
|
49
|
+
},
|
|
50
|
+
headers={"Accept": "application/json"},
|
|
51
|
+
)
|
|
52
|
+
data = resp.json()
|
|
53
|
+
token = data.get("access_token")
|
|
54
|
+
if not token:
|
|
55
|
+
raise ValueError(f"GitHub token exchange failed: {data.get('error_description') or data}")
|
|
56
|
+
return token
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def fetch_github_user(access_token: str) -> dict:
|
|
60
|
+
"""Return the GitHub profile: {id, login, name, avatar_url}."""
|
|
61
|
+
async with httpx.AsyncClient(timeout=20) as client:
|
|
62
|
+
resp = await client.get(
|
|
63
|
+
GITHUB_USER_URL,
|
|
64
|
+
headers={
|
|
65
|
+
"Authorization": f"Bearer {access_token}",
|
|
66
|
+
"Accept": "application/vnd.github+json",
|
|
67
|
+
},
|
|
68
|
+
)
|
|
69
|
+
if resp.status_code != 200:
|
|
70
|
+
raise ValueError(f"GitHub user fetch failed: HTTP {resp.status_code}")
|
|
71
|
+
data = resp.json()
|
|
72
|
+
return {
|
|
73
|
+
"id": int(data["id"]),
|
|
74
|
+
"login": str(data["login"]),
|
|
75
|
+
"name": str(data.get("name") or ""),
|
|
76
|
+
"avatar_url": str(data.get("avatar_url") or ""),
|
|
77
|
+
}
|
confsync_server/cli.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""confsync-server CLI: serve / service."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from confsync_server import __version__
|
|
8
|
+
from confsync_server.config import load_settings
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def cmd_serve(args: argparse.Namespace) -> None:
|
|
12
|
+
import uvicorn
|
|
13
|
+
|
|
14
|
+
from confsync_server.app import create_app
|
|
15
|
+
|
|
16
|
+
settings = load_settings()
|
|
17
|
+
if args.host:
|
|
18
|
+
settings.host = args.host
|
|
19
|
+
if args.port:
|
|
20
|
+
settings.port = args.port
|
|
21
|
+
app = create_app(settings)
|
|
22
|
+
print(f"confsync-server {__version__} listening on {settings.host}:{settings.port}")
|
|
23
|
+
print(f"home: {settings.home} db: {settings.db_path}")
|
|
24
|
+
if settings.external_url:
|
|
25
|
+
print(f"external url: {settings.external_url}")
|
|
26
|
+
uvicorn.run(app, host=settings.host, port=settings.port, log_level="info")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def cmd_service(args: argparse.Namespace) -> None:
|
|
30
|
+
from confsync_server import service
|
|
31
|
+
|
|
32
|
+
action = args.action
|
|
33
|
+
if action == "install":
|
|
34
|
+
service.install()
|
|
35
|
+
elif action == "uninstall":
|
|
36
|
+
service.uninstall()
|
|
37
|
+
else:
|
|
38
|
+
service.control(action)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cmd_bootstrap(args: argparse.Namespace) -> None:
|
|
42
|
+
from confsync_server import auth, db
|
|
43
|
+
|
|
44
|
+
settings = load_settings()
|
|
45
|
+
conn = db.connect(settings.db_path)
|
|
46
|
+
try:
|
|
47
|
+
user = db.create_bootstrap_user(conn, args.login)
|
|
48
|
+
key = auth.generate_api_key()
|
|
49
|
+
db.create_api_key(conn, user["id"], args.name, key)
|
|
50
|
+
finally:
|
|
51
|
+
conn.close()
|
|
52
|
+
print(f"User '{args.login}' ready (admin={bool(user['is_admin'])}).")
|
|
53
|
+
print(f"API key (shown once): {key}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main() -> None:
|
|
57
|
+
parser = argparse.ArgumentParser(
|
|
58
|
+
prog="confsync-server",
|
|
59
|
+
description="confsync server — encrypted config document store",
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
62
|
+
sub = parser.add_subparsers(dest="group")
|
|
63
|
+
|
|
64
|
+
serve = sub.add_parser("serve", help="Run the server in the foreground")
|
|
65
|
+
serve.add_argument("--host", help="Override configured listen host")
|
|
66
|
+
serve.add_argument("--port", type=int, help="Override configured listen port")
|
|
67
|
+
|
|
68
|
+
svc = sub.add_parser("service", help="Manage the systemd user service (bare-metal)")
|
|
69
|
+
svc.add_argument("action",
|
|
70
|
+
choices=["install", "start", "stop", "restart", "status", "uninstall"])
|
|
71
|
+
|
|
72
|
+
boot = sub.add_parser(
|
|
73
|
+
"bootstrap",
|
|
74
|
+
help="Create a user + API key without GitHub OAuth (adopts real GitHub id on first login)")
|
|
75
|
+
boot.add_argument("--login", required=True, help="GitHub login name of the user")
|
|
76
|
+
boot.add_argument("--name", default="bootstrap", help="API key name")
|
|
77
|
+
|
|
78
|
+
args = parser.parse_args()
|
|
79
|
+
if args.group == "serve":
|
|
80
|
+
cmd_serve(args)
|
|
81
|
+
elif args.group == "service":
|
|
82
|
+
cmd_service(args)
|
|
83
|
+
elif args.group == "bootstrap":
|
|
84
|
+
cmd_bootstrap(args)
|
|
85
|
+
else:
|
|
86
|
+
parser.print_help()
|
|
87
|
+
sys.exit(0)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if __name__ == "__main__":
|
|
91
|
+
main()
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Server settings: file ($CONFSYNC_HOME/server.yaml) + env overrides."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
DEFAULT_PORT = 8930
|
|
8
|
+
|
|
9
|
+
HOME_ENV = "CONFSYNC_HOME"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def get_home() -> str:
|
|
13
|
+
"""Server home dir: $CONFSYNC_HOME, default ~/.confsync-server."""
|
|
14
|
+
env = os.environ.get(HOME_ENV, "").strip()
|
|
15
|
+
if env:
|
|
16
|
+
return env
|
|
17
|
+
return os.path.expanduser("~/.confsync-server")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class ServerSettings:
|
|
22
|
+
host: str = "127.0.0.1"
|
|
23
|
+
port: int = DEFAULT_PORT
|
|
24
|
+
external_url: str = "" # e.g. https://confsync.example.com (OAuth callback base)
|
|
25
|
+
github_client_id: str = ""
|
|
26
|
+
github_client_secret: str = ""
|
|
27
|
+
allowed_users: list[str] = field(default_factory=list) # GitHub logins
|
|
28
|
+
home: str = ""
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def db_path(self) -> str:
|
|
32
|
+
return os.path.join(self.home, "server.db")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_settings(home: str | None = None) -> ServerSettings:
|
|
36
|
+
"""Load settings from $CONFSYNC_HOME/server.yaml with env overrides.
|
|
37
|
+
|
|
38
|
+
Env overrides: CONFSYNC_HOST, CONFSYNC_PORT, CONFSYNC_EXTERNAL_URL,
|
|
39
|
+
CONFSYNC_GITHUB_CLIENT_ID, CONFSYNC_GITHUB_CLIENT_SECRET,
|
|
40
|
+
CONFSYNC_ALLOWED_USERS (comma-separated).
|
|
41
|
+
"""
|
|
42
|
+
import yaml
|
|
43
|
+
|
|
44
|
+
home = home or get_home()
|
|
45
|
+
raw: dict = {}
|
|
46
|
+
path = os.path.join(home, "server.yaml")
|
|
47
|
+
if os.path.exists(path):
|
|
48
|
+
with open(path) as f:
|
|
49
|
+
loaded = yaml.safe_load(f)
|
|
50
|
+
if loaded is not None and not isinstance(loaded, dict):
|
|
51
|
+
raise ValueError(f"{path} must be a YAML mapping")
|
|
52
|
+
raw = loaded or {}
|
|
53
|
+
|
|
54
|
+
gh = raw.get("github", {}) or {}
|
|
55
|
+
|
|
56
|
+
s = ServerSettings(
|
|
57
|
+
host=str(raw.get("host", "127.0.0.1")),
|
|
58
|
+
port=int(raw.get("port", DEFAULT_PORT)),
|
|
59
|
+
external_url=str(raw.get("external_url", "")).rstrip("/"),
|
|
60
|
+
github_client_id=str(gh.get("client_id", "")),
|
|
61
|
+
github_client_secret=str(gh.get("client_secret", "")),
|
|
62
|
+
allowed_users=[str(u) for u in (raw.get("allowed_users", []) or [])],
|
|
63
|
+
home=home,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
env = os.environ
|
|
67
|
+
if env.get("CONFSYNC_HOST"):
|
|
68
|
+
s.host = env["CONFSYNC_HOST"]
|
|
69
|
+
if env.get("CONFSYNC_PORT"):
|
|
70
|
+
s.port = int(env["CONFSYNC_PORT"])
|
|
71
|
+
if env.get("CONFSYNC_EXTERNAL_URL"):
|
|
72
|
+
s.external_url = env["CONFSYNC_EXTERNAL_URL"].rstrip("/")
|
|
73
|
+
if env.get("CONFSYNC_GITHUB_CLIENT_ID"):
|
|
74
|
+
s.github_client_id = env["CONFSYNC_GITHUB_CLIENT_ID"]
|
|
75
|
+
if env.get("CONFSYNC_GITHUB_CLIENT_SECRET"):
|
|
76
|
+
s.github_client_secret = env["CONFSYNC_GITHUB_CLIENT_SECRET"]
|
|
77
|
+
if env.get("CONFSYNC_ALLOWED_USERS"):
|
|
78
|
+
s.allowed_users = [u.strip() for u in env["CONFSYNC_ALLOWED_USERS"].split(",") if u.strip()]
|
|
79
|
+
|
|
80
|
+
return s
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""AES-256-GCM encryption for stored documents.
|
|
2
|
+
|
|
3
|
+
The master key (32 bytes) lives only on the server: it is auto-generated on
|
|
4
|
+
first run into ``$CONFSYNC_HOME/master.key`` (mode 0600), or supplied via the
|
|
5
|
+
``CONFSYNC_MASTER_KEY`` environment variable (base64).
|
|
6
|
+
|
|
7
|
+
Every document is encrypted with a fresh random 12-byte nonce. The document
|
|
8
|
+
identity (``user_id/app/name``) is bound as AAD so a ciphertext cannot be
|
|
9
|
+
replayed under a different document name. Storage format: ``nonce || ct || tag``.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import os
|
|
15
|
+
import secrets
|
|
16
|
+
|
|
17
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
18
|
+
|
|
19
|
+
MASTER_KEY_ENV = "CONFSYNC_MASTER_KEY"
|
|
20
|
+
|
|
21
|
+
_NONCE_LEN = 12
|
|
22
|
+
_KEY_LEN = 32
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def load_or_create_master_key(home: str) -> bytes:
|
|
26
|
+
"""Load the master key from env or $CONFSYNC_HOME/master.key.
|
|
27
|
+
|
|
28
|
+
Generates and persists a new key (mode 0600) when neither exists.
|
|
29
|
+
"""
|
|
30
|
+
env = os.environ.get(MASTER_KEY_ENV, "").strip()
|
|
31
|
+
if env:
|
|
32
|
+
key = base64.b64decode(env)
|
|
33
|
+
if len(key) != _KEY_LEN:
|
|
34
|
+
raise ValueError(f"{MASTER_KEY_ENV} must decode to 32 bytes, got {len(key)}")
|
|
35
|
+
return key
|
|
36
|
+
|
|
37
|
+
path = os.path.join(home, "master.key")
|
|
38
|
+
if os.path.exists(path):
|
|
39
|
+
with open(path, "rb") as f:
|
|
40
|
+
key = base64.b64decode(f.read().strip())
|
|
41
|
+
if len(key) != _KEY_LEN:
|
|
42
|
+
raise ValueError(f"{path} does not contain a valid 32-byte key")
|
|
43
|
+
return key
|
|
44
|
+
|
|
45
|
+
os.makedirs(home, exist_ok=True)
|
|
46
|
+
key = secrets.token_bytes(_KEY_LEN)
|
|
47
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
48
|
+
try:
|
|
49
|
+
os.write(fd, base64.b64encode(key) + b"\n")
|
|
50
|
+
finally:
|
|
51
|
+
os.close(fd)
|
|
52
|
+
return key
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def document_aad(user_id: int, app: str, name: str) -> bytes:
|
|
56
|
+
"""AAD binding a ciphertext to its document identity."""
|
|
57
|
+
return f"{user_id}/{app}/{name}".encode()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def encrypt(key: bytes, plaintext: bytes, aad: bytes) -> bytes:
|
|
61
|
+
nonce = secrets.token_bytes(_NONCE_LEN)
|
|
62
|
+
ct = AESGCM(key).encrypt(nonce, plaintext, aad)
|
|
63
|
+
return nonce + ct
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def decrypt(key: bytes, blob: bytes, aad: bytes) -> bytes:
|
|
67
|
+
if len(blob) < _NONCE_LEN + 16:
|
|
68
|
+
raise ValueError("ciphertext blob too short")
|
|
69
|
+
return AESGCM(key).decrypt(blob[:_NONCE_LEN], blob[_NONCE_LEN:], aad)
|
confsync_server/db.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""SQLite data layer: users, sessions, API keys, encrypted documents.
|
|
2
|
+
|
|
3
|
+
Secrets at rest: only sha256 hashes of session tokens and API keys are stored;
|
|
4
|
+
document contents are AES-256-GCM ciphertexts (see crypto.py).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import os
|
|
10
|
+
import sqlite3
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
SCHEMA = """\
|
|
14
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
15
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
16
|
+
github_id INTEGER NOT NULL UNIQUE,
|
|
17
|
+
login TEXT NOT NULL UNIQUE,
|
|
18
|
+
name TEXT NOT NULL DEFAULT '',
|
|
19
|
+
avatar_url TEXT NOT NULL DEFAULT '',
|
|
20
|
+
is_admin INTEGER NOT NULL DEFAULT 0,
|
|
21
|
+
created_at REAL NOT NULL
|
|
22
|
+
);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS allowed_logins (
|
|
24
|
+
login TEXT PRIMARY KEY
|
|
25
|
+
);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
27
|
+
token_hash TEXT PRIMARY KEY,
|
|
28
|
+
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
29
|
+
expires_at REAL NOT NULL
|
|
30
|
+
);
|
|
31
|
+
CREATE TABLE IF NOT EXISTS api_keys (
|
|
32
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
33
|
+
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
34
|
+
name TEXT NOT NULL DEFAULT '',
|
|
35
|
+
key_hash TEXT NOT NULL UNIQUE,
|
|
36
|
+
prefix TEXT NOT NULL,
|
|
37
|
+
created_at REAL NOT NULL,
|
|
38
|
+
last_used_at REAL,
|
|
39
|
+
revoked INTEGER NOT NULL DEFAULT 0
|
|
40
|
+
);
|
|
41
|
+
CREATE TABLE IF NOT EXISTS documents (
|
|
42
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
43
|
+
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
44
|
+
app TEXT NOT NULL,
|
|
45
|
+
name TEXT NOT NULL,
|
|
46
|
+
ciphertext BLOB NOT NULL,
|
|
47
|
+
version INTEGER NOT NULL,
|
|
48
|
+
updated_at REAL NOT NULL,
|
|
49
|
+
UNIQUE (user_id, app, name)
|
|
50
|
+
);
|
|
51
|
+
CREATE TABLE IF NOT EXISTS document_history (
|
|
52
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
53
|
+
user_id INTEGER NOT NULL,
|
|
54
|
+
app TEXT NOT NULL,
|
|
55
|
+
name TEXT NOT NULL,
|
|
56
|
+
version INTEGER NOT NULL,
|
|
57
|
+
ciphertext BLOB NOT NULL,
|
|
58
|
+
saved_at REAL NOT NULL
|
|
59
|
+
);
|
|
60
|
+
CREATE INDEX IF NOT EXISTS idx_history_doc ON document_history (user_id, app, name, version);
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
SESSION_TTL = 30 * 24 * 3600 # 30 days
|
|
64
|
+
HISTORY_KEEP = 20
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def hash_token(token: str) -> str:
|
|
68
|
+
return hashlib.sha256(token.encode()).hexdigest()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def connect(db_path: str) -> sqlite3.Connection:
|
|
72
|
+
os.makedirs(os.path.dirname(os.path.abspath(db_path)), exist_ok=True)
|
|
73
|
+
conn = sqlite3.connect(db_path)
|
|
74
|
+
conn.row_factory = sqlite3.Row
|
|
75
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
76
|
+
conn.execute("PRAGMA foreign_keys=ON")
|
|
77
|
+
conn.executescript(SCHEMA)
|
|
78
|
+
return conn
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# ── users / allowlist ─────────────────────────────────────────────
|
|
82
|
+
|
|
83
|
+
def get_user_by_github_id(conn: sqlite3.Connection, github_id: int) -> sqlite3.Row | None:
|
|
84
|
+
return conn.execute("SELECT * FROM users WHERE github_id = ?", (github_id,)).fetchone()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def get_user_by_id(conn: sqlite3.Connection, user_id: int) -> sqlite3.Row | None:
|
|
88
|
+
return conn.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def count_users(conn: sqlite3.Connection) -> int:
|
|
92
|
+
return conn.execute("SELECT COUNT(*) AS n FROM users").fetchone()["n"]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def seed_allowed_logins(conn: sqlite3.Connection, logins: list[str]) -> None:
|
|
96
|
+
"""Seed the allowlist from config (idempotent; never removes entries)."""
|
|
97
|
+
for login in logins:
|
|
98
|
+
conn.execute("INSERT OR IGNORE INTO allowed_logins (login) VALUES (?)", (login,))
|
|
99
|
+
conn.commit()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def is_login_allowed(conn: sqlite3.Connection, login: str) -> bool:
|
|
103
|
+
"""Allowed when the users table is empty (bootstrap: first login becomes
|
|
104
|
+
admin) or when the login is on the allowlist."""
|
|
105
|
+
if count_users(conn) == 0:
|
|
106
|
+
return True
|
|
107
|
+
row = conn.execute("SELECT login FROM allowed_logins WHERE login = ?", (login,)).fetchone()
|
|
108
|
+
return row is not None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def upsert_user(conn: sqlite3.Connection, github_id: int, login: str,
|
|
112
|
+
name: str, avatar_url: str) -> sqlite3.Row:
|
|
113
|
+
"""Insert or refresh a user from their GitHub profile. The very first
|
|
114
|
+
user becomes admin and is added to the allowlist."""
|
|
115
|
+
existing = get_user_by_github_id(conn, github_id)
|
|
116
|
+
now = time.time()
|
|
117
|
+
if existing:
|
|
118
|
+
conn.execute(
|
|
119
|
+
"UPDATE users SET login = ?, name = ?, avatar_url = ? WHERE id = ?",
|
|
120
|
+
(login, name, avatar_url, existing["id"]),
|
|
121
|
+
)
|
|
122
|
+
conn.commit()
|
|
123
|
+
return get_user_by_id(conn, existing["id"])
|
|
124
|
+
# A CLI-bootstrapped user (placeholder negative github_id) adopts its real
|
|
125
|
+
# GitHub id on first OAuth login, keeping its documents and API keys.
|
|
126
|
+
by_login = conn.execute("SELECT * FROM users WHERE login = ?", (login,)).fetchone()
|
|
127
|
+
if by_login is not None and by_login["github_id"] < 0:
|
|
128
|
+
conn.execute(
|
|
129
|
+
"UPDATE users SET github_id = ?, name = ?, avatar_url = ? WHERE id = ?",
|
|
130
|
+
(github_id, name, avatar_url, by_login["id"]),
|
|
131
|
+
)
|
|
132
|
+
conn.commit()
|
|
133
|
+
return get_user_by_id(conn, by_login["id"])
|
|
134
|
+
is_admin = 1 if count_users(conn) == 0 else 0
|
|
135
|
+
cur = conn.execute(
|
|
136
|
+
"INSERT INTO users (github_id, login, name, avatar_url, is_admin, created_at)"
|
|
137
|
+
" VALUES (?, ?, ?, ?, ?, ?)",
|
|
138
|
+
(github_id, login, name, avatar_url, is_admin, now),
|
|
139
|
+
)
|
|
140
|
+
if is_admin:
|
|
141
|
+
conn.execute("INSERT OR IGNORE INTO allowed_logins (login) VALUES (?)", (login,))
|
|
142
|
+
conn.commit()
|
|
143
|
+
return get_user_by_id(conn, cur.lastrowid)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def create_bootstrap_user(conn: sqlite3.Connection, login: str) -> sqlite3.Row:
|
|
147
|
+
"""Create a CLI-only user (placeholder negative github_id) so an API key
|
|
148
|
+
can be issued before GitHub OAuth is set up. On first OAuth login the row
|
|
149
|
+
adopts the real github_id (see upsert_user)."""
|
|
150
|
+
import secrets
|
|
151
|
+
|
|
152
|
+
existing = conn.execute("SELECT * FROM users WHERE login = ?", (login,)).fetchone()
|
|
153
|
+
if existing is not None:
|
|
154
|
+
return existing
|
|
155
|
+
is_admin = 1 if count_users(conn) == 0 else 0
|
|
156
|
+
cur = conn.execute(
|
|
157
|
+
"INSERT INTO users (github_id, login, name, avatar_url, is_admin, created_at)"
|
|
158
|
+
" VALUES (?, ?, '', '', ?, ?)",
|
|
159
|
+
(-(secrets.randbelow(2**62) + 1), login, is_admin, time.time()),
|
|
160
|
+
)
|
|
161
|
+
conn.execute("INSERT OR IGNORE INTO allowed_logins (login) VALUES (?)", (login,))
|
|
162
|
+
conn.commit()
|
|
163
|
+
return get_user_by_id(conn, cur.lastrowid)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def allow_login(conn: sqlite3.Connection, login: str) -> None:
|
|
167
|
+
conn.execute("INSERT OR IGNORE INTO allowed_logins (login) VALUES (?)", (login,))
|
|
168
|
+
conn.commit()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def disallow_login(conn: sqlite3.Connection, login: str) -> None:
|
|
172
|
+
conn.execute("DELETE FROM allowed_logins WHERE login = ?", (login,))
|
|
173
|
+
conn.commit()
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def list_allowed_logins(conn: sqlite3.Connection) -> list[str]:
|
|
177
|
+
rows = conn.execute("SELECT login FROM allowed_logins ORDER BY login").fetchall()
|
|
178
|
+
return [r["login"] for r in rows]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# ── web sessions ──────────────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
def create_session(conn: sqlite3.Connection, user_id: int, token: str) -> None:
|
|
184
|
+
conn.execute(
|
|
185
|
+
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, ?)",
|
|
186
|
+
(hash_token(token), user_id, time.time() + SESSION_TTL),
|
|
187
|
+
)
|
|
188
|
+
conn.commit()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def get_session_user(conn: sqlite3.Connection, token: str) -> sqlite3.Row | None:
|
|
192
|
+
row = conn.execute(
|
|
193
|
+
"SELECT user_id, expires_at FROM sessions WHERE token_hash = ?",
|
|
194
|
+
(hash_token(token),),
|
|
195
|
+
).fetchone()
|
|
196
|
+
if row is None:
|
|
197
|
+
return None
|
|
198
|
+
if row["expires_at"] < time.time():
|
|
199
|
+
conn.execute("DELETE FROM sessions WHERE token_hash = ?", (hash_token(token),))
|
|
200
|
+
conn.commit()
|
|
201
|
+
return None
|
|
202
|
+
return get_user_by_id(conn, row["user_id"])
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def delete_session(conn: sqlite3.Connection, token: str) -> None:
|
|
206
|
+
conn.execute("DELETE FROM sessions WHERE token_hash = ?", (hash_token(token),))
|
|
207
|
+
conn.commit()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ── API keys ──────────────────────────────────────────────────────
|
|
211
|
+
|
|
212
|
+
def create_api_key(conn: sqlite3.Connection, user_id: int, name: str,
|
|
213
|
+
plaintext_key: str) -> None:
|
|
214
|
+
conn.execute(
|
|
215
|
+
"INSERT INTO api_keys (user_id, name, key_hash, prefix, created_at)"
|
|
216
|
+
" VALUES (?, ?, ?, ?, ?)",
|
|
217
|
+
(user_id, name, hash_token(plaintext_key), plaintext_key[:8], time.time()),
|
|
218
|
+
)
|
|
219
|
+
conn.commit()
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def get_user_by_api_key(conn: sqlite3.Connection, plaintext_key: str) -> sqlite3.Row | None:
|
|
223
|
+
row = conn.execute(
|
|
224
|
+
"SELECT id, user_id, revoked FROM api_keys WHERE key_hash = ?",
|
|
225
|
+
(hash_token(plaintext_key),),
|
|
226
|
+
).fetchone()
|
|
227
|
+
if row is None or row["revoked"]:
|
|
228
|
+
return None
|
|
229
|
+
conn.execute("UPDATE api_keys SET last_used_at = ? WHERE id = ?", (time.time(), row["id"]))
|
|
230
|
+
conn.commit()
|
|
231
|
+
return get_user_by_id(conn, row["user_id"])
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def list_api_keys(conn: sqlite3.Connection, user_id: int) -> list[sqlite3.Row]:
|
|
235
|
+
return conn.execute(
|
|
236
|
+
"SELECT id, name, prefix, created_at, last_used_at, revoked FROM api_keys"
|
|
237
|
+
" WHERE user_id = ? ORDER BY id",
|
|
238
|
+
(user_id,),
|
|
239
|
+
).fetchall()
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def revoke_api_key(conn: sqlite3.Connection, user_id: int, key_id: int) -> bool:
|
|
243
|
+
cur = conn.execute(
|
|
244
|
+
"UPDATE api_keys SET revoked = 1 WHERE id = ? AND user_id = ?",
|
|
245
|
+
(key_id, user_id),
|
|
246
|
+
)
|
|
247
|
+
conn.commit()
|
|
248
|
+
return cur.rowcount > 0
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# ── documents ─────────────────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
def put_document(conn: sqlite3.Connection, user_id: int, app: str, name: str,
|
|
254
|
+
ciphertext: bytes) -> int:
|
|
255
|
+
"""Insert or replace a document; archives the previous version. Returns
|
|
256
|
+
the new version number."""
|
|
257
|
+
now = time.time()
|
|
258
|
+
row = conn.execute(
|
|
259
|
+
"SELECT version, ciphertext FROM documents WHERE user_id = ? AND app = ? AND name = ?",
|
|
260
|
+
(user_id, app, name),
|
|
261
|
+
).fetchone()
|
|
262
|
+
if row is None:
|
|
263
|
+
new_version = 1
|
|
264
|
+
conn.execute(
|
|
265
|
+
"INSERT INTO documents (user_id, app, name, ciphertext, version, updated_at)"
|
|
266
|
+
" VALUES (?, ?, ?, ?, ?, ?)",
|
|
267
|
+
(user_id, app, name, ciphertext, new_version, now),
|
|
268
|
+
)
|
|
269
|
+
else:
|
|
270
|
+
new_version = row["version"] + 1
|
|
271
|
+
conn.execute(
|
|
272
|
+
"INSERT INTO document_history (user_id, app, name, version, ciphertext, saved_at)"
|
|
273
|
+
" VALUES (?, ?, ?, ?, ?, ?)",
|
|
274
|
+
(user_id, app, name, row["version"], row["ciphertext"], now),
|
|
275
|
+
)
|
|
276
|
+
conn.execute(
|
|
277
|
+
"UPDATE documents SET ciphertext = ?, version = ?, updated_at = ?"
|
|
278
|
+
" WHERE user_id = ? AND app = ? AND name = ?",
|
|
279
|
+
(ciphertext, new_version, now, user_id, app, name),
|
|
280
|
+
)
|
|
281
|
+
# prune history beyond HISTORY_KEEP
|
|
282
|
+
conn.execute(
|
|
283
|
+
"DELETE FROM document_history WHERE user_id = ? AND app = ? AND name = ?"
|
|
284
|
+
" AND version NOT IN ("
|
|
285
|
+
" SELECT version FROM document_history"
|
|
286
|
+
" WHERE user_id = ? AND app = ? AND name = ?"
|
|
287
|
+
" ORDER BY version DESC LIMIT ?"
|
|
288
|
+
" )",
|
|
289
|
+
(user_id, app, name, user_id, app, name, HISTORY_KEEP),
|
|
290
|
+
)
|
|
291
|
+
conn.commit()
|
|
292
|
+
return new_version
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def get_document(conn: sqlite3.Connection, user_id: int, app: str, name: str) -> sqlite3.Row | None:
|
|
296
|
+
return conn.execute(
|
|
297
|
+
"SELECT * FROM documents WHERE user_id = ? AND app = ? AND name = ?",
|
|
298
|
+
(user_id, app, name),
|
|
299
|
+
).fetchone()
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def list_documents(conn: sqlite3.Connection, user_id: int) -> list[sqlite3.Row]:
|
|
303
|
+
return conn.execute(
|
|
304
|
+
"SELECT app, name, version, updated_at, length(ciphertext) AS size"
|
|
305
|
+
" FROM documents WHERE user_id = ? ORDER BY app, name",
|
|
306
|
+
(user_id,),
|
|
307
|
+
).fetchall()
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def delete_document(conn: sqlite3.Connection, user_id: int, app: str, name: str) -> bool:
|
|
311
|
+
cur = conn.execute(
|
|
312
|
+
"DELETE FROM documents WHERE user_id = ? AND app = ? AND name = ?",
|
|
313
|
+
(user_id, app, name),
|
|
314
|
+
)
|
|
315
|
+
conn.execute(
|
|
316
|
+
"DELETE FROM document_history WHERE user_id = ? AND app = ? AND name = ?",
|
|
317
|
+
(user_id, app, name),
|
|
318
|
+
)
|
|
319
|
+
conn.commit()
|
|
320
|
+
return cur.rowcount > 0
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def list_history(conn: sqlite3.Connection, user_id: int, app: str, name: str) -> list[sqlite3.Row]:
|
|
324
|
+
return conn.execute(
|
|
325
|
+
"SELECT version, saved_at, length(ciphertext) AS size FROM document_history"
|
|
326
|
+
" WHERE user_id = ? AND app = ? AND name = ? ORDER BY version DESC",
|
|
327
|
+
(user_id, app, name),
|
|
328
|
+
).fetchall()
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def get_history_version(conn: sqlite3.Connection, user_id: int, app: str, name: str,
|
|
332
|
+
version: int) -> sqlite3.Row | None:
|
|
333
|
+
return conn.execute(
|
|
334
|
+
"SELECT * FROM document_history"
|
|
335
|
+
" WHERE user_id = ? AND app = ? AND name = ? AND version = ?",
|
|
336
|
+
(user_id, app, name, version),
|
|
337
|
+
).fetchone()
|