#!/usr/bin/env python3 """Idempotent founding `binky` admin credential bootstrap (WP-0011-T01). If no active binky credential exists, issues one labeled ``founding-admin`` with admin rights and prints the token once to stdout (and optionally writes it to TRF_BOOTSTRAP_TOKEN_FILE). Re-runs are no-ops when a credential already exists — they print the existing label, not a new token. """ from __future__ import annotations import os import sys import psycopg from target_revenue import registry def main() -> None: dsn = os.environ.get("TRF_DATABASE_URL") if not dsn: print("TRF_DATABASE_URL is required", file=sys.stderr) sys.exit(1) label = os.environ.get("TRF_BOOTSTRAP_LABEL", "founding-admin") with psycopg.connect(dsn) as conn: row = conn.execute( """ SELECT token, credential_label, rights FROM licensors WHERE licensor_id = 'binky' AND revoked_at IS NULL ORDER BY created_at ASC LIMIT 1 """ ).fetchone() if row is not None: token, existing_label, rights = row print( f"binky already has active credential label={existing_label!r} " f"rights={rights!r} — bootstrap no-op (token not re-printed)" ) conn.commit() return cred = registry.issue_sub_credential( conn, licensor_id="binky", credential_label=label, rights="admin", issued_by="bootstrap_binky", ) conn.commit() print(f"issued binky credential label={cred.credential_label!r}") print(f"TOKEN={cred.token}") out = os.environ.get("TRF_BOOTSTRAP_TOKEN_FILE") if out: with open(out, "w", encoding="utf-8") as f: f.write(cred.token) print(f"wrote token to {out}") if __name__ == "__main__": main()