chdev 1.3.0__tar.gz → 1.4.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chdev
3
- Version: 1.3.0
3
+ Version: 1.4.0
4
4
  Summary: Official Python client library for chdev Authentication (SSO for Google, Discord, Microsoft)
5
5
  Author-email: chdev <contact@chdev.co.uk>
6
6
  Project-URL: Homepage, https://authentication.chdev.co.uk
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "chdev"
7
- version = "1.3.0"
7
+ version = "1.4.0"
8
8
  authors = [
9
9
  { name="chdev", email="contact@chdev.co.uk" },
10
10
  ]
@@ -3,9 +3,13 @@ from __future__ import annotations
3
3
  import asyncio
4
4
  import builtins
5
5
  import functools
6
+ import http.server
6
7
  import json
7
8
  import os
9
+ import secrets
10
+ import socketserver
8
11
  import sys
12
+ import threading
9
13
  import time
10
14
  import urllib.error
11
15
  import urllib.parse
@@ -13,7 +17,7 @@ import urllib.request
13
17
  import webbrowser
14
18
  from typing import Any, Callable, Dict, List, Optional, Union
15
19
 
16
- __version__ = "1.3.0"
20
+ __version__ = "1.4.0"
17
21
  __all__ = [
18
22
  # Core Synchronous Logins
19
23
  "google_login",
@@ -202,7 +206,7 @@ def _post_json(
202
206
 
203
207
 
204
208
  # ==============================================================================
205
- # 2. LOCAL SESSION CACHING
209
+ # LOCAL SESSION CACHING
206
210
  # ==============================================================================
207
211
 
208
212
  def _save_cache(user_data: Dict[str, Any]) -> None:
@@ -266,7 +270,8 @@ def cached_login(
266
270
  poll_interval: float = 1.0,
267
271
  timeout: int = 300,
268
272
  quiet: bool = False,
269
- qr: bool = False
273
+ qr: bool = False,
274
+ loopback: bool = True
270
275
  ) -> AuthUser:
271
276
  """Return the cached user if valid; otherwise prompt login and save the session."""
272
277
  cached = get_user(max_age_days=max_age_days)
@@ -284,12 +289,13 @@ def cached_login(
284
289
  timeout=timeout,
285
290
  quiet=quiet,
286
291
  save_session=True,
287
- qr=qr
292
+ qr=qr,
293
+ loopback=loopback
288
294
  )
289
295
 
290
296
 
291
297
  # ==============================================================================
292
- # 3. TERMINAL ASCII QR CODE
298
+ # TERMINAL ASCII QR CODE
293
299
  # ==============================================================================
294
300
 
295
301
  def show_qr(url: str) -> None:
@@ -315,7 +321,7 @@ def show_qr(url: str) -> None:
315
321
 
316
322
 
317
323
  # ==============================================================================
318
- # 4. EMAIL / USER PERMISSION GUARD
324
+ # EMAIL / USER PERMISSION GUARD
319
325
  # ==============================================================================
320
326
 
321
327
  def allowed_users(
@@ -354,6 +360,154 @@ def allowed_users(
354
360
  require_user = allowed_users
355
361
 
356
362
 
363
+ # ==============================================================================
364
+ # ZERO-PING LOCAL EPHEMERAL LOOPBACK RECEIVER
365
+ # ==============================================================================
366
+
367
+ class _LoopbackHandler(http.server.BaseHTTPRequestHandler):
368
+ def log_message(self, format: str, *args: Any) -> None:
369
+ pass # Suppress HTTP server output in terminal
370
+
371
+ def do_GET(self) -> None:
372
+ parsed = urllib.parse.urlparse(self.path)
373
+ qs = urllib.parse.parse_qs(parsed.query)
374
+
375
+ token = qs.get("auth_token", [None])[0]
376
+ secret = qs.get("app_secret_code", [None])[0]
377
+ err = qs.get("error", [None])[0] or qs.get("message", [None])[0]
378
+
379
+ if token and secret:
380
+ self.server.auth_token = token # type: ignore[attr-defined]
381
+ self.server.app_secret_code = secret # type: ignore[attr-defined]
382
+ self.send_response(200)
383
+ self.send_header("Content-Type", "text/html; charset=utf-8")
384
+ self.end_headers()
385
+ html = """<!DOCTYPE html>
386
+ <html>
387
+ <head>
388
+ <meta charset="utf-8">
389
+ <title>chdev Authentication</title>
390
+ <style>
391
+ body { background: #090d16; color: #f1f5f9; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
392
+ .card { background: #0f1523; border: 1px solid #1e293b; padding: 2.5rem 2rem; border-radius: 14px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.5); max-width: 420px; width: 90%; }
393
+ h2 { color: #10b981; margin-top: 0; font-size: 1.5rem; }
394
+ p { color: #94a3b8; font-size: 0.95rem; line-height: 1.5; margin-bottom: 0.5rem; }
395
+ .sub { font-size: 0.8rem; color: #64748b; margin-top: 1.5rem; }
396
+ </style>
397
+ </head>
398
+ <body>
399
+ <div class="card">
400
+ <h2>✓ Authentication Successful</h2>
401
+ <p>You have signed in successfully.</p>
402
+ <p>You can now close this tab and return to your terminal.</p>
403
+ <p class="sub">This tab will close automatically in a few seconds...</p>
404
+ </div>
405
+ <script>setTimeout(function() { window.close(); }, 3500);</script>
406
+ </body>
407
+ </html>"""
408
+ self.wfile.write(html.encode("utf-8"))
409
+ else:
410
+ self.server.error = err or "Missing callback parameters" # type: ignore[attr-defined]
411
+ self.send_response(400)
412
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
413
+ self.end_headers()
414
+ self.wfile.write(b"Authentication failed.")
415
+
416
+
417
+ class _LoopbackServer(socketserver.TCPServer):
418
+ allow_reuse_address = True
419
+ auth_token: Optional[str] = None
420
+ app_secret_code: Optional[str] = None
421
+ error: Optional[str] = None
422
+
423
+
424
+ def _run_loopback_login(
425
+ api_key_str: str,
426
+ provider: str,
427
+ app_name: str,
428
+ open_browser: bool,
429
+ timeout: int,
430
+ quiet: bool,
431
+ save_session: bool
432
+ ) -> Optional[AuthUser]:
433
+ """Attempts zero-ping local ephemeral loopback authentication."""
434
+ try:
435
+ httpd = _LoopbackServer(("127.0.0.1", 0), _LoopbackHandler)
436
+ port = httpd.server_address[1]
437
+ httpd.timeout = 1.0
438
+ except Exception:
439
+ return None # Port binding failed; fall back to polling
440
+
441
+ try:
442
+ nonce = secrets.token_hex(24)
443
+ callback_url = f"http://127.0.0.1:{port}/callback"
444
+
445
+ init_res = create_session(
446
+ return_url=callback_url,
447
+ app_secret_code=nonce,
448
+ provider=provider,
449
+ app_name=app_name,
450
+ key=api_key_str,
451
+ timeout=10
452
+ )
453
+
454
+ if init_res.get("status") != "success":
455
+ httpd.server_close()
456
+ return None
457
+
458
+ login_url = init_res["login_url"]
459
+ prov_label = "Microsoft" if provider == "microsoft" else ("Discord" if provider == "discord" else "Google")
460
+
461
+ if not quiet:
462
+ print(f"\nSign in with {prov_label}:")
463
+ print(f"{login_url}\n")
464
+
465
+ if open_browser:
466
+ try:
467
+ webbrowser.open(login_url)
468
+ except Exception:
469
+ pass
470
+
471
+ if not quiet:
472
+ print("Waiting for authentication (instant loopback)...")
473
+
474
+ start_time = time.time()
475
+ while time.time() - start_time < timeout:
476
+ httpd.handle_request()
477
+ if httpd.auth_token and httpd.app_secret_code:
478
+ break
479
+ if httpd.error:
480
+ sys.exit(f"Authentication failed: {httpd.error}")
481
+
482
+ httpd.server_close()
483
+
484
+ if not httpd.auth_token or not httpd.app_secret_code:
485
+ sys.exit(f"Authentication timed out after {timeout} seconds.")
486
+
487
+ # Exactly Request #2: Verify token
488
+ verify_res = verify(
489
+ auth_token=httpd.auth_token,
490
+ app_secret_code=httpd.app_secret_code,
491
+ key=api_key_str
492
+ )
493
+
494
+ if verify_res.get("status") == "success" and verify_res.get("valid"):
495
+ auth_user = _set_globals(verify_res)
496
+ if save_session:
497
+ _save_cache(verify_res.get("user") or {})
498
+ if not quiet:
499
+ print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
500
+ return auth_user
501
+
502
+ sys.exit("Token verification failed.")
503
+ except Exception:
504
+ try:
505
+ httpd.server_close()
506
+ except Exception:
507
+ pass
508
+ return None
509
+
510
+
357
511
  # ==============================================================================
358
512
  # CORE SYNCHRONOUS LOGIN METHODS
359
513
  # ==============================================================================
@@ -367,10 +521,26 @@ def login(
367
521
  timeout: int = 300,
368
522
  quiet: bool = False,
369
523
  save_session: bool = False,
370
- qr: bool = False
524
+ qr: bool = False,
525
+ loopback: bool = True
371
526
  ) -> AuthUser:
372
527
  api_key_str = _get_key(key)
373
528
 
529
+ # 1. Zero-ping local loopback receiver (Preferred for interactive desktop CLI)
530
+ if loopback and open_browser and not qr:
531
+ loopback_user = _run_loopback_login(
532
+ api_key_str=api_key_str,
533
+ provider=provider,
534
+ app_name=app_name,
535
+ open_browser=open_browser,
536
+ timeout=timeout,
537
+ quiet=quiet,
538
+ save_session=save_session
539
+ )
540
+ if loopback_user:
541
+ return loopback_user
542
+
543
+ # 2. Polling Fallback (For headless SSH, qr=True, or restricted environments)
374
544
  init_res = _post_json(AUTH_ENDPOINT, {
375
545
  "action": "init",
376
546
  "provider": provider,
@@ -443,7 +613,8 @@ def google_login(
443
613
  timeout: int = 300,
444
614
  quiet: bool = False,
445
615
  save_session: bool = False,
446
- qr: bool = False
616
+ qr: bool = False,
617
+ loopback: bool = True
447
618
  ) -> AuthUser:
448
619
  return login(
449
620
  key=key,
@@ -454,7 +625,8 @@ def google_login(
454
625
  timeout=timeout,
455
626
  quiet=quiet,
456
627
  save_session=save_session,
457
- qr=qr
628
+ qr=qr,
629
+ loopback=loopback
458
630
  )
459
631
 
460
632
 
@@ -466,7 +638,8 @@ def discord_login(
466
638
  timeout: int = 300,
467
639
  quiet: bool = False,
468
640
  save_session: bool = False,
469
- qr: bool = False
641
+ qr: bool = False,
642
+ loopback: bool = True
470
643
  ) -> AuthUser:
471
644
  return login(
472
645
  key=key,
@@ -477,7 +650,8 @@ def discord_login(
477
650
  timeout=timeout,
478
651
  quiet=quiet,
479
652
  save_session=save_session,
480
- qr=qr
653
+ qr=qr,
654
+ loopback=loopback
481
655
  )
482
656
 
483
657
 
@@ -489,7 +663,8 @@ def microsoft_login(
489
663
  timeout: int = 300,
490
664
  quiet: bool = False,
491
665
  save_session: bool = False,
492
- qr: bool = False
666
+ qr: bool = False,
667
+ loopback: bool = True
493
668
  ) -> AuthUser:
494
669
  return login(
495
670
  key=key,
@@ -500,7 +675,8 @@ def microsoft_login(
500
675
  timeout=timeout,
501
676
  quiet=quiet,
502
677
  save_session=save_session,
503
- qr=qr
678
+ qr=qr,
679
+ loopback=loopback
504
680
  )
505
681
 
506
682
 
@@ -512,7 +688,8 @@ def prompt_login(
512
688
  timeout: int = 300,
513
689
  quiet: bool = False,
514
690
  save_session: bool = False,
515
- qr: bool = False
691
+ qr: bool = False,
692
+ loopback: bool = True
516
693
  ) -> AuthUser:
517
694
  """Interactively prompts the user to choose an authentication provider in the terminal."""
518
695
  print("\nSelect Sign-In Provider:")
@@ -540,7 +717,8 @@ def prompt_login(
540
717
  timeout=timeout,
541
718
  quiet=quiet,
542
719
  save_session=save_session,
543
- qr=qr
720
+ qr=qr,
721
+ loopback=loopback
544
722
  )
545
723
 
546
724
 
@@ -574,7 +752,7 @@ login_required = require_auth
574
752
 
575
753
 
576
754
  # ==============================================================================
577
- # 5. ASYNC / ASYNCIO SUPPORT
755
+ # ASYNC / ASYNCIO SUPPORT
578
756
  # ==============================================================================
579
757
 
580
758
  async def _post_json_async(url: str, payload: Dict[str, Any], timeout: int = 15, headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
@@ -591,73 +769,27 @@ async def login_async(
591
769
  timeout: int = 300,
592
770
  quiet: bool = False,
593
771
  save_session: bool = False,
594
- qr: bool = False
772
+ qr: bool = False,
773
+ loopback: bool = True
595
774
  ) -> AuthUser:
596
775
  """Non-blocking async login implementation for asyncio applications."""
597
- api_key_str = _get_key(key)
598
-
599
- init_res = await _post_json_async(AUTH_ENDPOINT, {
600
- "action": "init",
601
- "provider": provider,
602
- "app_name": app_name,
603
- "api_key": api_key_str
604
- })
605
-
606
- if init_res.get("status") != "success":
607
- sys.exit(f"Failed to start authentication: {init_res.get('message', 'Unknown error')}")
608
-
609
- session_id = init_res["session_id"]
610
- app_secret_code = init_res["app_secret_code"]
611
- login_url = init_res["login_url"]
612
-
613
- if provider == "microsoft":
614
- prov_label = "Microsoft"
615
- elif provider == "discord":
616
- prov_label = "Discord"
617
- else:
618
- prov_label = "Google"
619
-
620
- if not quiet:
621
- print(f"\nSign in with {prov_label}:")
622
- print(f"{login_url}\n")
623
- if qr:
624
- print("Scan with your phone to sign in:")
625
- show_qr(login_url)
626
-
627
- if open_browser:
628
- try:
629
- webbrowser.open(login_url)
630
- except Exception:
631
- pass
632
-
633
- if not quiet:
634
- print("Waiting for authentication...")
635
-
636
- start_time = time.time()
637
- while time.time() - start_time < timeout:
638
- await asyncio.sleep(poll_interval)
639
- try:
640
- poll_res = await _post_json_async(AUTH_ENDPOINT, {
641
- "action": "poll",
642
- "session_id": session_id,
643
- "app_secret_code": app_secret_code,
644
- "api_key": api_key_str
645
- })
646
- except Exception:
647
- continue
648
-
649
- if poll_res.get("status") == "success" and poll_res.get("completed"):
650
- auth_user = _set_globals(poll_res)
651
- if save_session:
652
- _save_cache(poll_res.get("user") or {})
653
- if not quiet:
654
- print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
655
- return auth_user
656
-
657
- if poll_res.get("status") == "expired":
658
- sys.exit("Sign-in session has expired. Please try logging in again.")
659
-
660
- sys.exit(f"Authentication timed out after {timeout} seconds.")
776
+ loop = asyncio.get_event_loop()
777
+ return await loop.run_in_executor(
778
+ None,
779
+ functools.partial(
780
+ login,
781
+ key=key,
782
+ provider=provider,
783
+ app_name=app_name,
784
+ open_browser=open_browser,
785
+ poll_interval=poll_interval,
786
+ timeout=timeout,
787
+ quiet=quiet,
788
+ save_session=save_session,
789
+ qr=qr,
790
+ loopback=loopback
791
+ )
792
+ )
661
793
 
662
794
 
663
795
  async def google_login_async(**kwargs: Any) -> AuthUser:
@@ -673,7 +805,6 @@ async def microsoft_login_async(**kwargs: Any) -> AuthUser:
673
805
 
674
806
 
675
807
  async def prompt_login_async(**kwargs: Any) -> AuthUser:
676
- """Async prompt login (runs input on thread)."""
677
808
  loop = asyncio.get_event_loop()
678
809
  return await loop.run_in_executor(None, functools.partial(prompt_login, **kwargs))
679
810
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chdev
3
- Version: 1.3.0
3
+ Version: 1.4.0
4
4
  Summary: Official Python client library for chdev Authentication (SSO for Google, Discord, Microsoft)
5
5
  Author-email: chdev <contact@chdev.co.uk>
6
6
  Project-URL: Homepage, https://authentication.chdev.co.uk
File without changes
File without changes
File without changes
File without changes