lenapi 0.1.4.5__tar.gz → 0.1.4.7__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.
Files changed (54) hide show
  1. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/PKG-INFO +16 -14
  2. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/README.md +15 -13
  3. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/__init__.py +1 -1
  4. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/auth.py +2 -12
  5. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/cli.py +62 -75
  6. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi.egg-info/PKG-INFO +16 -14
  7. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/pyproject.toml +1 -1
  8. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_security_patch.py +42 -0
  9. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/LICENSE +0 -0
  10. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/admin.py +0 -0
  11. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/application.py +0 -0
  12. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/authentication.py +0 -0
  13. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/authorization.py +0 -0
  14. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/background.py +0 -0
  15. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/concurrency.py +0 -0
  16. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/database.py +0 -0
  17. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/dependencies.py +0 -0
  18. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/docs_guard.py +0 -0
  19. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/logging.py +0 -0
  20. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/middleware.py +0 -0
  21. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/migration_render.py +0 -0
  22. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/model.py +0 -0
  23. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/models.py +0 -0
  24. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/mongodb.py +0 -0
  25. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/openapi.py +0 -0
  26. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/parameters.py +0 -0
  27. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/project.py +0 -0
  28. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/request.py +0 -0
  29. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/response.py +0 -0
  30. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/security.py +0 -0
  31. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/security_store.py +0 -0
  32. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/sentinels.py +0 -0
  33. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/service.py +0 -0
  34. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/throttling.py +0 -0
  35. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi/transaction.py +0 -0
  36. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi.egg-info/SOURCES.txt +0 -0
  37. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi.egg-info/dependency_links.txt +0 -0
  38. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi.egg-info/entry_points.txt +0 -0
  39. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi.egg-info/requires.txt +0 -0
  40. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi.egg-info/top_level.txt +0 -0
  41. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/lenapi_bootstrap.py +0 -0
  42. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/setup.cfg +0 -0
  43. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_admin_console.py +0 -0
  44. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_cli_settings_recovery.py +0 -0
  45. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_docs_guard.py +0 -0
  46. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_framework_features.py +0 -0
  47. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_media_upload.py +0 -0
  48. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_migration_render.py +0 -0
  49. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_mongodb.py +0 -0
  50. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_platform_services.py +0 -0
  51. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_project_isolation.py +0 -0
  52. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_sentinels.py +0 -0
  53. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_throttle.py +0 -0
  54. {lenapi-0.1.4.5 → lenapi-0.1.4.7}/tests/test_user_model_extension.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lenapi
3
- Version: 0.1.4.5
3
+ Version: 0.1.4.7
4
4
  Summary: A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation.
5
5
  Author: Maekandex Communication Limitation
6
6
  Author-email: "Ifeanyi M. Onovo" <ifeanyi@maekandex.com.ng>
@@ -1474,7 +1474,6 @@ def oidc_profile(identity=Depends(provider_auth)):
1474
1474
  # settings.py — replace with the exact origin serving your frontend.
1475
1475
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1476
1476
  SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1477
- FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1478
1477
 
1479
1478
  # main.py
1480
1479
  from lenapi import LENAPI
@@ -1500,12 +1499,14 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1500
1499
 
1501
1500
  The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1502
1501
 
1503
- To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1502
+ To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. The webhook must return JSON containing `redirect_url`; LenAPI redirects the browser to that URL and forwards any `Set-Cookie` headers from the webhook response. Redirect URLs must use HTTPS; HTTP is accepted only for localhost development. Query parameters are allowed so the webhook can include a short-lived, single-use exchange code; URL fragments are rejected. Do not put a bearer token or provider access token in the redirect URL. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1504
1503
 
1505
1504
  ```python
1506
1505
  # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1507
1506
  from lenapi import JSONResponse, LENAPI, Request
1508
- import settings
1507
+ import hashlib
1508
+ import secrets
1509
+ from urllib.parse import urlencode
1509
1510
 
1510
1511
  app = LENAPI()
1511
1512
 
@@ -1515,19 +1516,20 @@ async def social_success(request: Request):
1515
1516
  identity = data["identity"]
1516
1517
  user_id = data.get("user_id")
1517
1518
 
1518
- # Implement your own account rules and issue your own session/JWT here.
1519
+ # Apply your own account rules, then store a short-lived, single-use code.
1519
1520
  user = await find_or_create_user(identity, user_id)
1520
- session_id = await create_session(user)
1521
-
1522
- response = JSONResponse({"accepted": True})
1523
- response.set_cookie(
1524
- "session_id", session_id, max_age=3600, path="/",
1525
- httponly=True, secure=True, samesite="lax",
1521
+ code = secrets.token_urlsafe(32)
1522
+ code_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
1523
+ await app.cache.set(
1524
+ f"social_login:{code_hash}", {"user_id": str(user.id)}, ttl=400
1526
1525
  )
1527
- return response
1526
+ redirect_url = "https://app.example.com/login/success?" + urlencode({"code": code})
1527
+ return JSONResponse({"redirect_url": redirect_url})
1528
1528
  ```
1529
1529
 
1530
- The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1530
+ The frontend should immediately POST the code to a separate backend exchange route. That route hashes the submitted code, retrieves and deletes its cache entry, and only then issues your bearer token or session. Do not place an access token in the redirect URL.
1531
+
1532
+ The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the webhook's `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1531
1533
 
1532
1534
  `allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
1533
1535
 
@@ -2049,7 +2051,7 @@ python lenora.py migrate
2049
2051
  python lenora.py showmigrations
2050
2052
  ```
2051
2053
 
2052
- `repair-migrations` repairs only migration history. It compares the live SQL schema with the current models, then stamps the local head only when they match; it preserves schema and data and refuses mismatches. If a revision file is missing, restore it when possible; use repair only after confirming the live schema matches current model metadata. On an empty database with no revisions, use `migration` to create a new initial revision instead. MongoDB has no Alembic history and does not support this repair command.
2054
+ `repair-migrations` rebuilds SQL migration history from the live database schema and the current models. It removes this project's local revision files and Alembic version table, then generates and applies a fresh migration. Application tables and rows are preserved; existing tables or columns no longer represented by models are retained rather than dropped. Back up the database before running it. MongoDB has no Alembic history and does not support this repair command.
2053
2055
 
2054
2056
  ```bash
2055
2057
  python lenora.py repair-migrations
@@ -1422,7 +1422,6 @@ def oidc_profile(identity=Depends(provider_auth)):
1422
1422
  # settings.py — replace with the exact origin serving your frontend.
1423
1423
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1424
1424
  SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1425
- FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1426
1425
 
1427
1426
  # main.py
1428
1427
  from lenapi import LENAPI
@@ -1448,12 +1447,14 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1448
1447
 
1449
1448
  The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1450
1449
 
1451
- To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1450
+ To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. The webhook must return JSON containing `redirect_url`; LenAPI redirects the browser to that URL and forwards any `Set-Cookie` headers from the webhook response. Redirect URLs must use HTTPS; HTTP is accepted only for localhost development. Query parameters are allowed so the webhook can include a short-lived, single-use exchange code; URL fragments are rejected. Do not put a bearer token or provider access token in the redirect URL. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1452
1451
 
1453
1452
  ```python
1454
1453
  # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1455
1454
  from lenapi import JSONResponse, LENAPI, Request
1456
- import settings
1455
+ import hashlib
1456
+ import secrets
1457
+ from urllib.parse import urlencode
1457
1458
 
1458
1459
  app = LENAPI()
1459
1460
 
@@ -1463,19 +1464,20 @@ async def social_success(request: Request):
1463
1464
  identity = data["identity"]
1464
1465
  user_id = data.get("user_id")
1465
1466
 
1466
- # Implement your own account rules and issue your own session/JWT here.
1467
+ # Apply your own account rules, then store a short-lived, single-use code.
1467
1468
  user = await find_or_create_user(identity, user_id)
1468
- session_id = await create_session(user)
1469
-
1470
- response = JSONResponse({"accepted": True})
1471
- response.set_cookie(
1472
- "session_id", session_id, max_age=3600, path="/",
1473
- httponly=True, secure=True, samesite="lax",
1469
+ code = secrets.token_urlsafe(32)
1470
+ code_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
1471
+ await app.cache.set(
1472
+ f"social_login:{code_hash}", {"user_id": str(user.id)}, ttl=400
1474
1473
  )
1475
- return response
1474
+ redirect_url = "https://app.example.com/login/success?" + urlencode({"code": code})
1475
+ return JSONResponse({"redirect_url": redirect_url})
1476
1476
  ```
1477
1477
 
1478
- The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1478
+ The frontend should immediately POST the code to a separate backend exchange route. That route hashes the submitted code, retrieves and deletes its cache entry, and only then issues your bearer token or session. Do not place an access token in the redirect URL.
1479
+
1480
+ The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the webhook's `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1479
1481
 
1480
1482
  `allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
1481
1483
 
@@ -1997,7 +1999,7 @@ python lenora.py migrate
1997
1999
  python lenora.py showmigrations
1998
2000
  ```
1999
2001
 
2000
- `repair-migrations` repairs only migration history. It compares the live SQL schema with the current models, then stamps the local head only when they match; it preserves schema and data and refuses mismatches. If a revision file is missing, restore it when possible; use repair only after confirming the live schema matches current model metadata. On an empty database with no revisions, use `migration` to create a new initial revision instead. MongoDB has no Alembic history and does not support this repair command.
2002
+ `repair-migrations` rebuilds SQL migration history from the live database schema and the current models. It removes this project's local revision files and Alembic version table, then generates and applies a fresh migration. Application tables and rows are preserved; existing tables or columns no longer represented by models are retained rather than dropped. Back up the database before running it. MongoDB has no Alembic history and does not support this repair command.
2001
2003
 
2002
2004
  ```bash
2003
2005
  python lenora.py repair-migrations
@@ -8,7 +8,7 @@ if sys.version_info < (3, 11):
8
8
  "on 2026-10-01 and is no longer supported."
9
9
  )
10
10
 
11
- __version__ = "0.1.4.5"
11
+ __version__ = "0.1.4.7"
12
12
 
13
13
  from .application import Application, LENAPI, Router
14
14
  from .background import BackgroundQueue, BackgroundTasks
@@ -43,7 +43,6 @@ class SocialAuth:
43
43
  user_model=None,
44
44
  allowed_origins=None,
45
45
  success_callback: str | None = None,
46
- frontend_redirect_uri: str | None = None,
47
46
  ) -> None:
48
47
  if isinstance(providers, str):
49
48
  raise TypeError("providers must be a list or tuple of provider names")
@@ -74,13 +73,6 @@ class SocialAuth:
74
73
  if success_callback is None:
75
74
  success_callback = getattr(self.settings, "SOCIAL_AUTH_SUCCESS_CALLBACK", "") or None
76
75
  self.success_callback = self._validate_success_callback(success_callback)
77
- if frontend_redirect_uri is None:
78
- frontend_redirect_uri = getattr(self.settings, "FRONTEND_REDIRECT_URI", "") or None
79
- self.frontend_redirect_uri = (
80
- self._validate_success_redirect(frontend_redirect_uri)
81
- if frontend_redirect_uri
82
- else None
83
- )
84
76
  if allowed_origins is None:
85
77
  allowed_origins = getattr(self.settings, "SOCIAL_AUTH_ALLOWED_ORIGINS", ())
86
78
  self.allowed_origins = self._normalize_origins(allowed_origins)
@@ -118,7 +110,6 @@ class SocialAuth:
118
110
  or not parsed.hostname
119
111
  or parsed.username is not None
120
112
  or parsed.password is not None
121
- or parsed.query
122
113
  or parsed.fragment
123
114
  ):
124
115
  raise ValueError("Social login success callback returned an invalid redirect URL")
@@ -360,11 +351,10 @@ class SocialAuth:
360
351
  parsed_result = {}
361
352
  if isinstance(parsed_result, dict):
362
353
  result = parsed_result
363
- redirect_url = result.get("redirect_url") or self.frontend_redirect_uri
354
+ redirect_url = result.get("redirect_url")
364
355
  if not redirect_url:
365
356
  raise ValueError(
366
- "Social login needs a frontend redirect URL in the webhook response "
367
- "or FRONTEND_REDIRECT_URI setting"
357
+ "Social login success callback must return a redirect_url"
368
358
  )
369
359
  redirect_url = self._validate_success_redirect(redirect_url)
370
360
  cookies = response.headers.get_list("set-cookie")
@@ -104,8 +104,6 @@ SOCIAL_AUTH_ALLOWED_ORIGINS = []
104
104
  # Optional server-to-server endpoint for application-owned social login/session handling.
105
105
  # Use HTTPS when enabling it.
106
106
  SOCIAL_AUTH_SUCCESS_CALLBACK = ""
107
- # Browser destination after the social-auth webhook succeeds.
108
- FRONTEND_REDIRECT_URI = ""
109
107
  # Keep this generated key private. Rotate it to invalidate existing tokens.
110
108
  SECRET_KEY = "__LENAPI_GENERATED_SECRET_KEY__"
111
109
  TOKEN = {
@@ -475,7 +473,7 @@ def _main() -> None:
475
473
  showmigrations = commands.add_parser("showmigrations", help="show local and applied database migration history")
476
474
  showmigrations.add_argument("--app", default=DEFAULT_APP, help=f"ASGI app import string (default: {DEFAULT_APP})")
477
475
  repair_migrations = commands.add_parser(
478
- "repair-migrations", help="repair a missing database revision when the schema matches current models"
476
+ "repair-migrations", help="rebuild migration history from the live schema and current models while preserving application data"
479
477
  )
480
478
  repair_migrations.add_argument("--app", default=DEFAULT_APP, help=f"ASGI app import string (default: {DEFAULT_APP})")
481
479
  clear_migrations = commands.add_parser(
@@ -1030,7 +1028,7 @@ def test_http_endpoint_is_registered_and_documented(method, path):
1030
1028
 
1031
1029
  engine = app.database.engine
1032
1030
  revisions = Path.cwd() / "migrations" / "versions"
1033
- if namespace and args.command != "delete_migrations":
1031
+ if namespace and args.command not in {"delete_migrations", "repair-migrations"}:
1034
1032
  # Never read or adopt the legacy global alembic_version table: it may
1035
1033
  # belong to another project using the same database. Also refuse to
1036
1034
  # replay a pre-namespace local chain into the shared database.
@@ -1098,7 +1096,22 @@ def test_http_endpoint_is_registered_and_documented(method, path):
1098
1096
  name for name in inspector.get_view_names()
1099
1097
  if namespace and name.startswith(f"{namespace}_")
1100
1098
  }
1101
- if args.command in {"migration", "migrate", "repair-migrations"}:
1099
+ if args.command == "repair-migrations":
1100
+ # A repair rebases only migration metadata. Keep every application
1101
+ # table, view, and row; autogenerate a new revision against the live
1102
+ # schema below so the resulting migration contains only forward diffs.
1103
+ revisions.mkdir(parents=True, exist_ok=True)
1104
+ with engine.begin() as connection:
1105
+ if version_table in inspect(connection).get_table_names():
1106
+ quoted_version = connection.dialect.identifier_preparer.quote(version_table)
1107
+ connection.exec_driver_sql(f"DROP TABLE {quoted_version}")
1108
+ for path in revisions.glob("*.py"):
1109
+ if path.name != "__init__.py":
1110
+ path.unlink()
1111
+ logger.info(
1112
+ "Reset local migration revisions and the project Alembic version table; application data was preserved."
1113
+ )
1114
+ if args.command in {"migration", "migrate"}:
1102
1115
  confirm_project_orphans(orphaned_tables | owned_views, "database tables/views")
1103
1116
  if orphaned_tables or owned_views:
1104
1117
  dialect = engine.dialect.name
@@ -1280,72 +1293,6 @@ def test_http_endpoint_is_registered_and_documented(method, path):
1280
1293
  print("Database migration state: " + ", ".join(sorted(current_heads)))
1281
1294
  return
1282
1295
 
1283
- if args.command == "repair-migrations":
1284
- script = ScriptDirectory.from_config(config)
1285
- with engine.connect() as connection:
1286
- table_names = set(inspect(connection).get_table_names())
1287
- differences = compare_metadata(
1288
- MigrationContext.configure(
1289
- connection,
1290
- opts={"compare_type": True, "include_object": include_migration_object,
1291
- "version_table": version_table},
1292
- ),
1293
- Model.metadata,
1294
- )
1295
- if differences:
1296
- parser.error(
1297
- "database schema does not match current models; refusing to change migration history. "
1298
- "Restore the missing revision file or reconcile the schema first. "
1299
- "If the database is empty, run python lenora.py migration instead."
1300
- )
1301
- local_revisions = [
1302
- path for path in revisions.glob("*.py") if path.name != "__init__.py"
1303
- ]
1304
- if not local_revisions:
1305
- if not table_names:
1306
- parser.error("database is empty; run python lenora.py migration to create the initial revision")
1307
- from alembic.autogenerate import render_python_code
1308
- from alembic.operations.ops import CreateIndexOp, CreateTableOp, UpgradeOps
1309
- from alembic.util import rev_id
1310
-
1311
- revision_id = rev_id()
1312
- operations = []
1313
- tables = list(Model.metadata.sorted_tables)
1314
- for table in tables:
1315
- operations.append(CreateTableOp.from_table(table))
1316
- for table in tables:
1317
- operations.extend(
1318
- CreateIndexOp.from_index(index)
1319
- for index in sorted(table.indexes, key=lambda index: index.name or "")
1320
- )
1321
- upgrade_code = render_python_code(UpgradeOps(ops=operations))
1322
- downgrade_code = "\n".join(
1323
- f" op.drop_table({table.name!r})" for table in reversed(tables)
1324
- ) or " pass"
1325
- revisions.mkdir(parents=True, exist_ok=True)
1326
- baseline = revisions / f"{revision_id}_baseline.py"
1327
- baseline.write_text(
1328
- '"""Baseline schema captured from the current model metadata.\n\n'
1329
- f"Revision ID: {revision_id}\nRevises: None\n\n\n"
1330
- '"""\nfrom alembic import op\nimport sqlalchemy as sa\n\n'
1331
- f"revision = {revision_id!r}\ndown_revision = None\n"
1332
- "branch_labels = None\ndepends_on = None\n\n\n"
1333
- "def upgrade():\n"
1334
- f"{upgrade_code}\n\n\n"
1335
- "def downgrade():\n"
1336
- f"{downgrade_code}\n",
1337
- encoding="utf-8",
1338
- )
1339
- logger.info("Created baseline migration %s from current models.", baseline.name)
1340
- head = revision_id
1341
- else:
1342
- head = script.get_current_head()
1343
- if head is None:
1344
- parser.error("no migration head found; inspect showmigrations and restore missing revision files")
1345
- command.stamp(config, "head")
1346
- logger.info("Migration history repaired to %s; schema and data were preserved.", head)
1347
- return
1348
-
1349
1296
  if args.command == "clear_migrations":
1350
1297
  with engine.connect() as connection:
1351
1298
  table_names = set(inspect(connection).get_table_names())
@@ -1356,7 +1303,7 @@ def test_http_endpoint_is_registered_and_documented(method, path):
1356
1303
  if application_tables:
1357
1304
  parser.error(
1358
1305
  "refusing to clear migrations because the database contains application tables; "
1359
- "use `python lenora.py repair-migrations` for a missing revision when its schema matches models"
1306
+ "use `python lenora.py repair-migrations` to rebuild migration history while preserving application tables and data"
1360
1307
  )
1361
1308
  if version_table in table_names:
1362
1309
  with engine.begin() as connection:
@@ -1369,13 +1316,19 @@ def test_http_endpoint_is_registered_and_documented(method, path):
1369
1316
  logger.info("Cleared migration files and database history; no application tables existed.")
1370
1317
  return
1371
1318
 
1372
- schema_generation = args.command in {"migration", "background-worker"}
1319
+ schema_generation = args.command in {"migration", "background-worker", "repair-migrations"}
1373
1320
  if schema_generation:
1374
1321
  existing_revisions = [
1375
1322
  path for path in revisions.glob("*.py") if path.name != "__init__.py"
1376
1323
  ]
1377
1324
  revisions_before_autogenerate = {path.resolve() for path in existing_revisions}
1378
- config.attributes["lenapi_initial_revision"] = not existing_revisions
1325
+ # Repair autogeneration must compare against the real database even
1326
+ # for SQLite. The normal initial-migration path uses an empty temporary
1327
+ # database to generate a create-all baseline, which would overwrite
1328
+ # the meaning of an existing schema during repair.
1329
+ config.attributes["lenapi_initial_revision"] = (
1330
+ not existing_revisions and args.command != "repair-migrations"
1331
+ )
1379
1332
 
1380
1333
  script = ScriptDirectory.from_config(config)
1381
1334
 
@@ -1527,6 +1480,36 @@ def test_http_endpoint_is_registered_and_documented(method, path):
1527
1480
  temporary_engine.dispose()
1528
1481
 
1529
1482
  def skip_empty_revision(migration_context, revision, directives):
1483
+ if args.command == "repair-migrations":
1484
+ # Preserve existing database data: an autogenerate diff must
1485
+ # never remove a table or column simply because its model was
1486
+ # removed or renamed. Keep the remaining forward changes.
1487
+ from alembic.operations import ops
1488
+
1489
+ def keep_data_operations(container):
1490
+ kept = []
1491
+ for operation in container.ops:
1492
+ if isinstance(operation, (ops.DropTableOp, ops.DropColumnOp)):
1493
+ preserved_name = getattr(operation, "table_name", "table")
1494
+ if isinstance(operation, ops.DropColumnOp):
1495
+ preserved_name = f"{preserved_name}.{operation.column_name}"
1496
+ logger.warning(
1497
+ "Keeping existing database data in %s; model removal was not applied.",
1498
+ preserved_name,
1499
+ )
1500
+ continue
1501
+ nested = getattr(operation, "ops", None)
1502
+ if nested is not None:
1503
+ keep_data_operations(operation)
1504
+ kept.append(operation)
1505
+ container.ops = kept
1506
+
1507
+ for directive in directives or ():
1508
+ for upgrade_ops in directive.upgrade_ops_list:
1509
+ keep_data_operations(upgrade_ops)
1510
+ # Unlike an ordinary migration, an empty repair revision is
1511
+ # useful: it records the new baseline after a history reset.
1512
+ return
1530
1513
  if directives and directives[0].upgrade_ops.is_empty():
1531
1514
  directives.clear()
1532
1515
 
@@ -1645,7 +1628,11 @@ def test_http_endpoint_is_registered_and_documented(method, path):
1645
1628
  name for name in table_names
1646
1629
  if namespace and name.startswith(f"{namespace}_") and name != version_table
1647
1630
  }
1648
- if existing_tables and version_table not in table_names:
1631
+ if (
1632
+ existing_tables
1633
+ and version_table not in table_names
1634
+ and args.command != "repair-migrations"
1635
+ ):
1649
1636
  differences = compare_metadata(
1650
1637
  MigrationContext.configure(
1651
1638
  connection,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lenapi
3
- Version: 0.1.4.5
3
+ Version: 0.1.4.7
4
4
  Summary: A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation.
5
5
  Author: Maekandex Communication Limitation
6
6
  Author-email: "Ifeanyi M. Onovo" <ifeanyi@maekandex.com.ng>
@@ -1474,7 +1474,6 @@ def oidc_profile(identity=Depends(provider_auth)):
1474
1474
  # settings.py — replace with the exact origin serving your frontend.
1475
1475
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1476
1476
  SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1477
- FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1478
1477
 
1479
1478
  # main.py
1480
1479
  from lenapi import LENAPI
@@ -1500,12 +1499,14 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1500
1499
 
1501
1500
  The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1502
1501
 
1503
- To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1502
+ To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. The webhook must return JSON containing `redirect_url`; LenAPI redirects the browser to that URL and forwards any `Set-Cookie` headers from the webhook response. Redirect URLs must use HTTPS; HTTP is accepted only for localhost development. Query parameters are allowed so the webhook can include a short-lived, single-use exchange code; URL fragments are rejected. Do not put a bearer token or provider access token in the redirect URL. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1504
1503
 
1505
1504
  ```python
1506
1505
  # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1507
1506
  from lenapi import JSONResponse, LENAPI, Request
1508
- import settings
1507
+ import hashlib
1508
+ import secrets
1509
+ from urllib.parse import urlencode
1509
1510
 
1510
1511
  app = LENAPI()
1511
1512
 
@@ -1515,19 +1516,20 @@ async def social_success(request: Request):
1515
1516
  identity = data["identity"]
1516
1517
  user_id = data.get("user_id")
1517
1518
 
1518
- # Implement your own account rules and issue your own session/JWT here.
1519
+ # Apply your own account rules, then store a short-lived, single-use code.
1519
1520
  user = await find_or_create_user(identity, user_id)
1520
- session_id = await create_session(user)
1521
-
1522
- response = JSONResponse({"accepted": True})
1523
- response.set_cookie(
1524
- "session_id", session_id, max_age=3600, path="/",
1525
- httponly=True, secure=True, samesite="lax",
1521
+ code = secrets.token_urlsafe(32)
1522
+ code_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
1523
+ await app.cache.set(
1524
+ f"social_login:{code_hash}", {"user_id": str(user.id)}, ttl=400
1526
1525
  )
1527
- return response
1526
+ redirect_url = "https://app.example.com/login/success?" + urlencode({"code": code})
1527
+ return JSONResponse({"redirect_url": redirect_url})
1528
1528
  ```
1529
1529
 
1530
- The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1530
+ The frontend should immediately POST the code to a separate backend exchange route. That route hashes the submitted code, retrieves and deletes its cache entry, and only then issues your bearer token or session. Do not place an access token in the redirect URL.
1531
+
1532
+ The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the webhook's `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1531
1533
 
1532
1534
  `allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
1533
1535
 
@@ -2049,7 +2051,7 @@ python lenora.py migrate
2049
2051
  python lenora.py showmigrations
2050
2052
  ```
2051
2053
 
2052
- `repair-migrations` repairs only migration history. It compares the live SQL schema with the current models, then stamps the local head only when they match; it preserves schema and data and refuses mismatches. If a revision file is missing, restore it when possible; use repair only after confirming the live schema matches current model metadata. On an empty database with no revisions, use `migration` to create a new initial revision instead. MongoDB has no Alembic history and does not support this repair command.
2054
+ `repair-migrations` rebuilds SQL migration history from the live database schema and the current models. It removes this project's local revision files and Alembic version table, then generates and applies a fresh migration. Application tables and rows are preserved; existing tables or columns no longer represented by models are retained rather than dropped. Back up the database before running it. MongoDB has no Alembic history and does not support this repair command.
2053
2055
 
2054
2056
  ```bash
2055
2057
  python lenora.py repair-migrations
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "lenapi"
7
- version = "0.1.4.5"
7
+ version = "0.1.4.7"
8
8
  description = "A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation."
9
9
  authors = [
10
10
  {name = "Ifeanyi M. Onovo", email = "ifeanyi@maekandex.com.ng"},
@@ -208,6 +208,48 @@ def test_social_auth_success_callback_redirects_without_exposing_identity():
208
208
  assert delivered["identity"]["sub"] == "provider-user-1"
209
209
 
210
210
 
211
+ def test_social_auth_uses_webhook_redirect_with_query_parameters(monkeypatch):
212
+ import httpx
213
+
214
+ settings = SimpleNamespace(
215
+ SOCIAL_AUTH_SUCCESS_CALLBACK="https://backend.example/auth/social/success",
216
+ )
217
+ auth = SocialAuth(["google"], settings=settings)
218
+
219
+ class CallbackResponse:
220
+ is_success = True
221
+ content = b'{"redirect_url": "https://frontend.example/login/success?code=one-time-code"}'
222
+ headers = httpx.Headers([
223
+ ("set-cookie", "session_id=opaque-session; Path=/; HttpOnly; Secure; SameSite=None")
224
+ ])
225
+
226
+ @staticmethod
227
+ def json():
228
+ return {"redirect_url": "https://frontend.example/login/success?code=one-time-code"}
229
+
230
+ class CallbackClient:
231
+ def __init__(self, **kwargs):
232
+ pass
233
+
234
+ async def __aenter__(self):
235
+ return self
236
+
237
+ async def __aexit__(self, *_args):
238
+ return False
239
+
240
+ async def post(self, url, **kwargs):
241
+ assert url == settings.SOCIAL_AUTH_SUCCESS_CALLBACK
242
+ return CallbackResponse()
243
+
244
+ monkeypatch.setattr(httpx, "AsyncClient", CallbackClient)
245
+ redirect_url, cookies = asyncio.run(
246
+ auth._deliver_success("google", {"sub": "provider-user"}, None)
247
+ )
248
+
249
+ assert redirect_url == "https://frontend.example/login/success?code=one-time-code"
250
+ assert cookies == [
251
+ "session_id=opaque-session; Path=/; HttpOnly; Secure; SameSite=None"
252
+ ]
211
253
  def test_social_auth_origin_configuration_is_normalized_and_validated():
212
254
  auth = SocialAuth(
213
255
  ["google"],
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes