Files
yaris-obd/server/scripts/create_device.py
T
Mathieu MoranandCopilot a114939914 fix: authenticate device config sync like upload client
- send X-Device-Name and X-Api-Key to /api/device-config
- require YARIS_DEVICE_NAME alongside shared upload creds
- fix server create_device output to match actual Pi env names
- document shared upload/config sync credential requirements

Co-authored-by: Copilot <[email protected]>
2026-08-10 17:42:40 -04:00

52 lines
1.5 KiB
Python

#!/usr/bin/env python3
"""Register a new device (e.g. the Pi) and print its API key.
Run this INSIDE the api container so it shares the same DB connection env
vars already configured by docker-compose, e.g.:
docker compose exec api python3 scripts/create_device.py yaris-2013
The raw API key is only ever shown once here - copy it into the Pi's
upload-client config immediately. Only its sha256 hash is stored server-side.
"""
import hashlib
import secrets
import sys
sys.path.insert(0, "/app")
from modules import db # noqa: E402
def main():
if len(sys.argv) != 2:
print(f"usage: {sys.argv[0]} <device-name>", file=sys.stderr)
sys.exit(1)
device_name = sys.argv[1]
raw_key = secrets.token_urlsafe(32)
key_hash = hashlib.sha256(raw_key.encode("utf-8")).hexdigest()
with db.get_cursor(commit=True) as cur:
cur.execute(
"""
INSERT INTO devices (name, api_key_hash) VALUES (%s, %s)
ON CONFLICT (name) DO UPDATE SET api_key_hash = EXCLUDED.api_key_hash
RETURNING id
""",
(device_name, key_hash),
)
device_id = cur.fetchone()[0]
print(f"Device '{device_name}' registered (id={device_id}).")
print()
print("Save these on the Pi (e.g. in db/upload_creds.env, gitignored):")
print(f" YARIS_DEVICE_NAME={device_name}")
print(f" YARIS_API_KEY={raw_key}")
print()
print("This key will not be shown again - only its hash is stored server-side.")
if __name__ == "__main__":
main()