logi-auth 1.0.1__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.
logi_auth/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """logi_auth — server-side "Sign in with logi" for Python / Django backends.
2
+
3
+ Confidential OAuth 2.0 code exchange + id_token (RS256) verification. Same
4
+ safety contract as the iOS/Android/Web/Flutter/Node/Ruby SDKs (shared golden
5
+ vectors).
6
+ """
7
+
8
+ from .errors import IdTokenError, LogiAuthError, ServerError
9
+ from .id_token_verifier import verify_id_token
10
+ from .server import LogiAuthServer, LogiSession
11
+
12
+ __version__ = "1.0.1"
13
+
14
+ __all__ = [
15
+ "LogiAuthServer",
16
+ "LogiSession",
17
+ "verify_id_token",
18
+ "LogiAuthError",
19
+ "IdTokenError",
20
+ "ServerError",
21
+ "__version__",
22
+ ]
logi_auth/errors.py ADDED
@@ -0,0 +1,39 @@
1
+ """Error types for logi_auth."""
2
+
3
+
4
+ class LogiAuthError(Exception):
5
+ """Base for all errors raised by this package."""
6
+
7
+
8
+ class IdTokenError(LogiAuthError):
9
+ """id_token verification failure.
10
+
11
+ ``code`` mirrors the Web verifier and the golden-vector strings exactly
12
+ (e.g. ``"bad_signature"``, ``"aud_mismatch"``).
13
+ """
14
+
15
+ CODES = (
16
+ "malformed",
17
+ "missing_kid",
18
+ "unknown_kid",
19
+ "bad_signature",
20
+ "iss_mismatch",
21
+ "aud_mismatch",
22
+ "expired",
23
+ "nonce_mismatch",
24
+ "missing_claim",
25
+ "at_hash_mismatch",
26
+ )
27
+
28
+ def __init__(self, code: str):
29
+ self.code = code
30
+ super().__init__(f"id_token verification failed: {code}")
31
+
32
+
33
+ class ServerError(LogiAuthError):
34
+ """OAuth / transport failure raised by :class:`LogiAuthServer`."""
35
+
36
+ def __init__(self, code: str, message: str, detail=None):
37
+ self.code = code
38
+ self.detail = detail
39
+ super().__init__(message)
@@ -0,0 +1,194 @@
1
+ """RS256 id_token verification.
2
+
3
+ Mirrors the server (server/app/lib/oauth/jwt_verifier.rb) and the other SDKs:
4
+ kid -> JWKS -> RS256 signature -> iss / aud / exp / iat / nonce / sub. Passes the
5
+ shared 4-SDK golden vectors (../../test-vectors).
6
+
7
+ Uses the standard ``cryptography`` library for the RSA primitive (Python has no
8
+ stdlib RSA verify, just as Dart uses pointycastle). The JWS parsing + claim
9
+ checks are implemented here, mirroring verify.ts.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import hashlib
16
+ import json
17
+ import time
18
+ from typing import Any
19
+
20
+ from cryptography.exceptions import InvalidSignature
21
+ from cryptography.hazmat.primitives import hashes
22
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
23
+
24
+ from .errors import IdTokenError
25
+
26
+
27
+ def verify_id_token(
28
+ id_token: str,
29
+ jwks: dict,
30
+ expected: dict,
31
+ now: int | None = None,
32
+ clock_skew_sec: int = 60,
33
+ access_token: str | None = None,
34
+ ) -> dict:
35
+ """Verify ``id_token`` and return ``{"sub", "claims"}``.
36
+
37
+ Raises :class:`IdTokenError` on any failure — never returns an unverified
38
+ subject. Claim order: signature -> iss -> aud -> exp -> iat -> nonce -> sub
39
+ -> at_hash.
40
+
41
+ ``expected`` is ``{"issuer", "client_id", "nonce"}`` (``nonce`` optional).
42
+ ``now`` is Unix seconds; defaults to now. Injectable for deterministic tests.
43
+
44
+ ``access_token`` binds the id_token to the access_token per OIDC §3.1.3.6:
45
+ when the payload carries ``at_hash`` **and** ``access_token`` is supplied, the
46
+ left-most 128 bits of ``SHA-256(access_token)`` (base64url, no padding) MUST
47
+ equal ``at_hash``. When either is absent the check is skipped (backward
48
+ compatible with callers that only verify the id_token).
49
+ """
50
+ now = int(time.time()) if now is None else now
51
+
52
+ parts = id_token.split(".")
53
+ if len(parts) != 3 or not all(parts):
54
+ raise IdTokenError("malformed")
55
+
56
+ header = _decode_json_segment(parts[0])
57
+ payload = _decode_json_segment(parts[1])
58
+ if header is None or payload is None:
59
+ raise IdTokenError("malformed")
60
+
61
+ # Only RS256 is accepted — never verify a token whose header declares another
62
+ # (or no) algorithm, even if the RSA signature happens to match.
63
+ if header.get("alg") != "RS256":
64
+ raise IdTokenError("bad_signature")
65
+
66
+ kid = header.get("kid")
67
+ if not isinstance(kid, str) or not kid:
68
+ raise IdTokenError("missing_kid")
69
+
70
+ # Select the signing key by kid, but only among RSA keys usable for RS256
71
+ # signatures. Filtering on kty/use/alg keeps verification robust if the JWKS
72
+ # later mixes in EC (or encryption) keys: we still pick the correct RSA key
73
+ # instead of tripping over an unrelated one that happens to share a kid.
74
+ jwk = next(
75
+ (
76
+ k
77
+ for k in jwks.get("keys", [])
78
+ if k.get("kid") == kid
79
+ and k.get("kty") == "RSA"
80
+ and k.get("use") in (None, "sig")
81
+ and k.get("alg") in (None, "RS256")
82
+ ),
83
+ None,
84
+ )
85
+ if jwk is None:
86
+ raise IdTokenError("unknown_kid")
87
+
88
+ signature = _b64url_decode(parts[2])
89
+ if signature is None or not _verify_rs256(f"{parts[0]}.{parts[1]}".encode(), signature, jwk):
90
+ raise IdTokenError("bad_signature")
91
+
92
+ if payload.get("iss") != expected["issuer"]:
93
+ raise IdTokenError("iss_mismatch")
94
+
95
+ aud = payload.get("aud")
96
+ if not _audience_matches(aud, expected["client_id"]):
97
+ raise IdTokenError("aud_mismatch")
98
+ # OIDC 3.1.3.7: with multiple audiences an ``azp`` MUST be present; whenever
99
+ # ``azp`` is present it MUST equal our client_id.
100
+ azp = payload.get("azp")
101
+ if isinstance(aud, list) and len(aud) > 1:
102
+ if azp != expected["client_id"]:
103
+ raise IdTokenError("aud_mismatch")
104
+ elif azp is not None:
105
+ if azp != expected["client_id"]:
106
+ raise IdTokenError("aud_mismatch")
107
+
108
+ exp = _numeric(payload.get("exp"))
109
+ if exp is None or exp <= now - clock_skew_sec:
110
+ raise IdTokenError("expired")
111
+
112
+ iat = _numeric(payload.get("iat"))
113
+ # iat missing or in the future -> malformed (mirrors the other verifiers).
114
+ if iat is None or iat > now + clock_skew_sec:
115
+ raise IdTokenError("malformed")
116
+
117
+ expected_nonce = expected.get("nonce")
118
+ if expected_nonce is not None and payload.get("nonce") != expected_nonce:
119
+ raise IdTokenError("nonce_mismatch")
120
+
121
+ sub = payload.get("sub")
122
+ if not isinstance(sub, str) or not sub:
123
+ raise IdTokenError("missing_claim")
124
+
125
+ # OIDC 3.1.3.6 at_hash: present-only binding. Checked last, after every other
126
+ # claim has been validated and only when the caller supplies the matching
127
+ # access_token, so id_token-only callers keep their existing behaviour.
128
+ at_hash = payload.get("at_hash")
129
+ if isinstance(at_hash, str) and access_token is not None:
130
+ if _at_hash(access_token) != at_hash:
131
+ raise IdTokenError("at_hash_mismatch")
132
+
133
+ return {"sub": sub, "claims": payload}
134
+
135
+
136
+ def _at_hash(access_token: str) -> str:
137
+ # base64url(no padding) of the left-most 128 bits of SHA-256(access_token).
138
+ digest = hashlib.sha256(access_token.encode("utf-8")).digest()[:16]
139
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
140
+
141
+
142
+ def _verify_rs256(signing_input: bytes, signature: bytes, jwk: dict) -> bool:
143
+ n_bytes = _b64url_decode(jwk.get("n", ""))
144
+ e_bytes = _b64url_decode(jwk.get("e", ""))
145
+ if n_bytes is None or e_bytes is None:
146
+ return False
147
+ try:
148
+ public_key = rsa.RSAPublicNumbers(
149
+ int.from_bytes(e_bytes, "big"),
150
+ int.from_bytes(n_bytes, "big"),
151
+ ).public_key()
152
+ except (ValueError, TypeError):
153
+ return False
154
+ try:
155
+ public_key.verify(signature, signing_input, padding.PKCS1v15(), hashes.SHA256())
156
+ return True
157
+ except InvalidSignature:
158
+ return False
159
+
160
+
161
+ def _decode_json_segment(segment: str) -> dict | None:
162
+ raw = _b64url_decode(segment)
163
+ if raw is None:
164
+ return None
165
+ try:
166
+ parsed = json.loads(raw)
167
+ except (json.JSONDecodeError, UnicodeDecodeError):
168
+ return None
169
+ return parsed if isinstance(parsed, dict) else None
170
+
171
+
172
+ def _audience_matches(aud: Any, client_id: str) -> bool:
173
+ if isinstance(aud, str):
174
+ return aud == client_id
175
+ if isinstance(aud, list):
176
+ return client_id in aud
177
+ return False
178
+
179
+
180
+ def _numeric(value: Any) -> int | None:
181
+ if isinstance(value, bool):
182
+ return None
183
+ if isinstance(value, (int, float)):
184
+ return int(value)
185
+ return None
186
+
187
+
188
+ def _b64url_decode(segment: str) -> bytes | None:
189
+ if not isinstance(segment, str):
190
+ return None
191
+ try:
192
+ return base64.urlsafe_b64decode(segment + "=" * ((-len(segment)) % 4))
193
+ except (ValueError, TypeError):
194
+ return None
logi_auth/server.py ADDED
@@ -0,0 +1,226 @@
1
+ """Server-side "Sign in with logi" for Python / Django backends.
2
+
3
+ Confidential-client OAuth 2.0 code exchange + id_token (RS256) verification.
4
+
5
+ Why this exists: a backend RP that skips the id_token ``aud`` check can be
6
+ tricked into accepting a token minted for a DIFFERENT client (cross-client
7
+ account takeover). :meth:`LogiAuthServer.exchange_code_and_verify` ALWAYS
8
+ verifies signature + iss + aud + exp + nonce before returning ``sub``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from dataclasses import dataclass
19
+ from typing import Any
20
+
21
+ from .errors import IdTokenError, ServerError
22
+ from .id_token_verifier import verify_id_token
23
+
24
+
25
+ @dataclass
26
+ class LogiSession:
27
+ """A verified session. ``sub`` is set only after the id_token checks pass."""
28
+
29
+ sub: str
30
+ email: str | None
31
+ id_token: str
32
+ access_token: str
33
+ refresh_token: str | None
34
+ expires_at: int | None
35
+ scope: str | None
36
+ claims: dict
37
+
38
+
39
+ class LogiAuthServer:
40
+ def __init__(
41
+ self,
42
+ *,
43
+ client_id: str,
44
+ redirect_uri: str,
45
+ client_secret: str | None = None,
46
+ issuer: str = "https://api.1pass.dev",
47
+ token_issuer: str = "https://api.1pass.dev",
48
+ scopes: list[str] | None = None,
49
+ jwks_cache_ttl: int = 3600,
50
+ ):
51
+ if not client_id:
52
+ raise ValueError("client_id is required")
53
+ if not redirect_uri:
54
+ raise ValueError("redirect_uri is required")
55
+ self.client_id = client_id
56
+ self.redirect_uri = redirect_uri
57
+ self.client_secret = client_secret
58
+ self.issuer = issuer.rstrip("/")
59
+ self.token_issuer = token_issuer
60
+ self.default_scopes = scopes or ["openid", "profile:basic", "email"]
61
+ self.jwks_cache_ttl = jwks_cache_ttl
62
+ self._jwks_cache: dict | None = None
63
+ self._jwks_fetched_at = 0.0
64
+
65
+ def authorization_url(
66
+ self,
67
+ *,
68
+ state: str,
69
+ nonce: str,
70
+ scopes: list[str] | None = None,
71
+ code_challenge: str | None = None,
72
+ prompt: str | None = None,
73
+ ) -> str:
74
+ params = {
75
+ "response_type": "code",
76
+ "client_id": self.client_id,
77
+ "redirect_uri": self.redirect_uri,
78
+ "scope": " ".join(scopes or self.default_scopes),
79
+ "state": state,
80
+ "nonce": nonce,
81
+ }
82
+ if code_challenge:
83
+ params["code_challenge"] = code_challenge
84
+ params["code_challenge_method"] = "S256"
85
+ if prompt:
86
+ params["prompt"] = prompt
87
+ return f"{self.issuer}/oauth/authorize?{urllib.parse.urlencode(params)}"
88
+
89
+ def exchange_code_and_verify(
90
+ self, *, code: str, nonce: str, code_verifier: str | None = None
91
+ ) -> LogiSession:
92
+ # The server flow always issued a nonce in authorization_url, so a
93
+ # missing nonce here (e.g. an expired session) is a bug — never proceed
94
+ # with the nonce check silently disabled.
95
+ if not nonce:
96
+ raise ServerError(
97
+ "invalid_nonce", "nonce is required — the sign-in session may have expired"
98
+ )
99
+
100
+ form = {
101
+ "grant_type": "authorization_code",
102
+ "code": code,
103
+ "redirect_uri": self.redirect_uri,
104
+ "client_id": self.client_id,
105
+ }
106
+ if self.client_secret:
107
+ form["client_secret"] = self.client_secret
108
+ if code_verifier:
109
+ form["code_verifier"] = code_verifier
110
+
111
+ status, body = self._post(f"{self.issuer}/oauth/token", form)
112
+ if not 200 <= status < 300:
113
+ raise ServerError(
114
+ "token_exchange_failed",
115
+ f"Token exchange failed (HTTP {status})",
116
+ detail=body[:2048],
117
+ )
118
+
119
+ tokens = self._parse_token_body(body)
120
+ id_token = tokens.get("id_token")
121
+ if not isinstance(id_token, str) or not id_token:
122
+ raise ServerError(
123
+ "missing_id_token",
124
+ "Token response had no id_token — was `openid` in the scopes?",
125
+ )
126
+
127
+ # _parse_token_body guarantees access_token is a non-empty str, so the
128
+ # at_hash binding is always exercised when the id_token carries at_hash.
129
+ verified = self._verify_with_rotation_retry(id_token, nonce, tokens["access_token"])
130
+ email = verified["claims"].get("email")
131
+ expires_in = tokens.get("expires_in")
132
+
133
+ return LogiSession(
134
+ sub=verified["sub"],
135
+ email=email if isinstance(email, str) else None,
136
+ id_token=id_token,
137
+ access_token=tokens.get("access_token"),
138
+ refresh_token=tokens.get("refresh_token"),
139
+ expires_at=(
140
+ int(time.time()) + int(expires_in)
141
+ if isinstance(expires_in, (int, float)) and not isinstance(expires_in, bool)
142
+ else None
143
+ ),
144
+ scope=tokens.get("scope"),
145
+ claims=verified["claims"],
146
+ )
147
+
148
+ # -- internals -----------------------------------------------------------
149
+
150
+ def _verify_with_rotation_retry(self, id_token: str, nonce: str, access_token: str) -> dict:
151
+ expected = {"issuer": self.token_issuer, "client_id": self.client_id, "nonce": nonce}
152
+ jwks, from_cache = self._fetch_jwks(force=False)
153
+ try:
154
+ return verify_id_token(id_token, jwks, expected, access_token=access_token)
155
+ except IdTokenError as err:
156
+ # Key rotation within the cache TTL — bust + refetch once.
157
+ if err.code == "unknown_kid" and from_cache:
158
+ fresh, _ = self._fetch_jwks(force=True)
159
+ try:
160
+ return verify_id_token(id_token, fresh, expected, access_token=access_token)
161
+ except IdTokenError as retry_err:
162
+ raise self._as_id_token_invalid(retry_err) from retry_err
163
+ raise self._as_id_token_invalid(err) from err
164
+
165
+ @staticmethod
166
+ def _as_id_token_invalid(err: IdTokenError) -> ServerError:
167
+ return ServerError(
168
+ "id_token_invalid", f"id_token verification failed ({err.code})", detail=err.code
169
+ )
170
+
171
+ def _fetch_jwks(self, force: bool) -> tuple[dict, bool]:
172
+ if (
173
+ not force
174
+ and self._jwks_cache is not None
175
+ and (time.time() - self._jwks_fetched_at) < self.jwks_cache_ttl
176
+ ):
177
+ return self._jwks_cache, True
178
+
179
+ status, body = self._get(f"{self.issuer}/.well-known/jwks.json")
180
+ if not 200 <= status < 300:
181
+ raise ServerError("jwks_fetch_failed", f"JWKS fetch failed (HTTP {status})")
182
+ try:
183
+ jwks = json.loads(body)
184
+ if not isinstance(jwks, dict) or not isinstance(jwks.get("keys"), list):
185
+ raise ValueError("missing keys")
186
+ except (json.JSONDecodeError, ValueError) as err:
187
+ raise ServerError("jwks_fetch_failed", "JWKS response was malformed", detail=str(err)) from err
188
+
189
+ self._jwks_cache = jwks
190
+ self._jwks_fetched_at = time.time()
191
+ return jwks, False
192
+
193
+ def _parse_token_body(self, body: str) -> dict:
194
+ try:
195
+ tokens = json.loads(body)
196
+ except json.JSONDecodeError as err:
197
+ raise ServerError(
198
+ "token_exchange_failed", "Token response was not valid JSON", detail=str(err)
199
+ ) from err
200
+ if not isinstance(tokens, dict) or not isinstance(tokens.get("access_token"), str):
201
+ raise ServerError("token_exchange_failed", "Token response was missing access_token")
202
+ return tokens
203
+
204
+ def _post(self, url: str, form: dict[str, str]) -> tuple[int, str]:
205
+ data = urllib.parse.urlencode(form).encode()
206
+ request = urllib.request.Request(
207
+ url,
208
+ data=data,
209
+ method="POST",
210
+ headers={"Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"},
211
+ )
212
+ return self._perform(request)
213
+
214
+ def _get(self, url: str) -> tuple[int, str]:
215
+ request = urllib.request.Request(url, method="GET", headers={"Accept": "application/json"})
216
+ return self._perform(request)
217
+
218
+ def _perform(self, request: urllib.request.Request) -> tuple[int, str]:
219
+ try:
220
+ with urllib.request.urlopen(request, timeout=15) as resp: # noqa: S310 (fixed https scheme)
221
+ return resp.status, resp.read().decode("utf-8", "replace")
222
+ except urllib.error.HTTPError as err:
223
+ # Non-2xx: return status + body so the caller handles it uniformly.
224
+ return err.code, err.read().decode("utf-8", "replace")
225
+ except urllib.error.URLError as err:
226
+ raise ServerError("network_error", f"Network error: {err.reason}", detail=str(err)) from err
@@ -0,0 +1,210 @@
1
+ Metadata-Version: 2.4
2
+ Name: logi-auth
3
+ Version: 1.0.1
4
+ Summary: Server-side "Sign in with logi" for Python/Django — confidential OAuth 2.0 + id_token (RS256) verification.
5
+ Author: Dcode
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/dcode-co/logi-auth-python
8
+ Project-URL: Issues, https://github.com/dcode-co/logi-auth-python/issues
9
+ Keywords: logi,1pass,oauth,oidc,django,auth,openid,id-token
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Requires-Dist: cryptography>=41.0
15
+ Dynamic: license-file
16
+
17
+ # logi-auth (Python)
18
+
19
+ Server-side **"Sign in with logi"** for Python / Django backends — confidential
20
+ OAuth 2.0 Authorization Code exchange + **id_token (RS256) verification**. Only
21
+ dependency: `cryptography` (no HTTP client dependency — stdlib `urllib`).
22
+
23
+ This is the **confidential / backend** counterpart to the public-client SDKs
24
+ (browser, iOS, Android, Flutter). If your RP has a backend, verify on the
25
+ server with this package — do **not** rely on a client-side check.
26
+
27
+ > **Why it matters:** a backend that skips the id_token `aud` check can be
28
+ > tricked into accepting a token minted for a *different* client (cross-client
29
+ > account takeover — the launchcrew/krx incident). `exchange_code_and_verify`
30
+ > always verifies signature + iss + aud + exp + nonce before returning `sub`.
31
+
32
+ ## Supported versions
33
+
34
+ | Requirement | Version |
35
+ |-------------|---------|
36
+ | **Python** | **>= 3.9** |
37
+ | **Django** | any — the package is framework-agnostic; use it from any view |
38
+ | Flask / FastAPI / etc. | any |
39
+ | Dependencies | `cryptography >= 41.0` |
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install logi-auth
45
+ ```
46
+
47
+ ## Django view example
48
+
49
+ ```python
50
+ # settings.py (or a dedicated logi_auth.py config module)
51
+ import os
52
+ from logi_auth import LogiAuthServer
53
+
54
+ LOGI = LogiAuthServer(
55
+ client_id=os.environ["LOGI_CLIENT_ID"],
56
+ client_secret=os.environ["LOGI_CLIENT_SECRET"], # confidential client
57
+ redirect_uri="https://app.example.com/auth/logi/callback",
58
+ )
59
+ ```
60
+
61
+ ```python
62
+ # views.py
63
+ import secrets
64
+
65
+ from django.http import HttpResponseBadRequest
66
+ from django.shortcuts import redirect
67
+
68
+ from logi_auth import ServerError
69
+
70
+ from .settings import LOGI
71
+ from .models import User
72
+
73
+
74
+ def logi_start(request):
75
+ state = secrets.token_hex(16)
76
+ nonce = secrets.token_hex(16)
77
+ request.session["logi_state"] = state
78
+ request.session["logi_nonce"] = nonce
79
+ return redirect(LOGI.authorization_url(state=state, nonce=nonce))
80
+
81
+
82
+ def logi_callback(request):
83
+ if request.GET.get("state") != request.session.pop("logi_state", None):
84
+ return HttpResponseBadRequest("state mismatch")
85
+
86
+ # The provider may redirect back with ?error=access_denied (user cancelled)
87
+ # and no `code` — handle that before the exchange instead of 500-ing.
88
+ if request.GET.get("error"):
89
+ return redirect(f"/login?error={request.GET['error']}")
90
+ code = request.GET.get("code")
91
+ if not code:
92
+ return HttpResponseBadRequest("missing authorization code")
93
+
94
+ try:
95
+ result = LOGI.exchange_code_and_verify(
96
+ code=code,
97
+ nonce=request.session.pop("logi_nonce", None),
98
+ )
99
+ except ServerError as e:
100
+ # result.sub is only ever set after signature+iss+aud+exp+nonce all pass.
101
+ return redirect(f"/login?error={e.code}")
102
+
103
+ # result.sub is the verified pairwise subject — key your User record on it.
104
+ user, _ = User.objects.get_or_create(logi_sub=result.sub, defaults={"email": result.email})
105
+ request.session["user_id"] = user.id
106
+ return redirect("/")
107
+ ```
108
+
109
+ Identity claims (email/name) are **not** guaranteed on the id_token — fetch
110
+ them from `GET {issuer}/oauth/userinfo` with the returned `access_token` as a
111
+ Bearer token if you need more than `sub`/`email`.
112
+
113
+ ## Public client (PKCE, no secret)
114
+
115
+ Omit `client_secret` and pass a `code_challenge` / `code_verifier`:
116
+
117
+ ```python
118
+ logi = LogiAuthServer(client_id=client_id, redirect_uri=redirect_uri) # no secret
119
+ url = logi.authorization_url(state=state, nonce=nonce, code_challenge=code_challenge)
120
+ result = logi.exchange_code_and_verify(code=code, nonce=nonce, code_verifier=code_verifier)
121
+ ```
122
+
123
+ ## API
124
+
125
+ ```python
126
+ from logi_auth import LogiAuthServer, LogiSession, verify_id_token, LogiAuthError, IdTokenError, ServerError
127
+ ```
128
+
129
+ ### `LogiAuthServer(...)`
130
+
131
+ ```python
132
+ LogiAuthServer(
133
+ *,
134
+ client_id: str,
135
+ redirect_uri: str,
136
+ client_secret: str | None = None,
137
+ issuer: str = "https://api.1pass.dev",
138
+ token_issuer: str = "https://api.1pass.dev",
139
+ scopes: list[str] | None = None, # default: ["openid", "profile:basic", "email"]
140
+ jwks_cache_ttl: int = 3600,
141
+ )
142
+ ```
143
+
144
+ - **`.authorization_url(*, state, nonce, scopes=None, code_challenge=None, prompt=None) -> str`**
145
+ Builds the `/oauth/authorize` redirect URL.
146
+ - **`.exchange_code_and_verify(*, code, nonce, code_verifier=None) -> LogiSession`**
147
+ Exchanges the authorization `code` for tokens, then verifies the returned
148
+ `id_token` (signature via JWKS + `iss` + `aud` + `exp` + `nonce`, with a
149
+ transparent single JWKS refetch on key rotation) before returning a
150
+ `LogiSession`.
151
+
152
+ ### `LogiSession`
153
+
154
+ Returned only once id_token verification has fully passed:
155
+
156
+ | Field | Type |
157
+ |-------|------|
158
+ | `sub` | `str` — verified pairwise subject |
159
+ | `email` | `str \| None` |
160
+ | `id_token` | `str` |
161
+ | `access_token` | `str` |
162
+ | `refresh_token` | `str \| None` |
163
+ | `expires_at` | `int \| None` — unix timestamp |
164
+ | `scope` | `str \| None` |
165
+ | `claims` | `dict` — full verified id_token claim set |
166
+
167
+ ## Error handling
168
+
169
+ Both error types carry a `.code` string for programmatic branching (same
170
+ codes as the Ruby/Node/Web SDKs and the shared golden vectors).
171
+
172
+ `ServerError.code`:
173
+
174
+ | Code | Meaning |
175
+ |------|---------|
176
+ | `invalid_nonce` | Missing nonce — the sign-in session likely expired |
177
+ | `token_exchange_failed` | `/oauth/token` returned a non-2xx status or malformed body |
178
+ | `missing_id_token` | Token response had no `id_token` (was `openid` in scopes?) |
179
+ | `id_token_invalid` | id_token failed verification — `.detail` carries the underlying `IdTokenError.code` |
180
+ | `jwks_fetch_failed` | JWKS endpoint unreachable or returned a malformed document |
181
+ | `network_error` | Transport-level failure talking to the issuer |
182
+
183
+ `IdTokenError.code` (raised by `verify_id_token` directly, or wrapped into
184
+ `ServerError("id_token_invalid", ...)` by `exchange_code_and_verify`):
185
+
186
+ `malformed`, `missing_kid`, `unknown_kid`, `bad_signature`, `iss_mismatch`,
187
+ `aud_mismatch`, `expired`, `nonce_mismatch`, `missing_claim`, `at_hash_mismatch`.
188
+
189
+ ```python
190
+ from logi_auth import ServerError
191
+
192
+ try:
193
+ result = LOGI.exchange_code_and_verify(code=code, nonce=nonce)
194
+ except ServerError as e:
195
+ logger.warning("logi sign-in failed: %s (%s)", e.code, e.detail)
196
+ return redirect(f"/login?error={e.code}")
197
+ ```
198
+
199
+ ## Security
200
+
201
+ `exchange_code_and_verify` performs the full id_token verification —
202
+ signature against the issuer's JWKS, `iss`, `aud` (against your `client_id`),
203
+ `exp`, and `nonce` — **before** it ever returns a `sub`. Verifying on the
204
+ server, not just trusting a client-supplied token, is what closes the
205
+ cross-client account-takeover class of bug: a frontend alone cannot prove that
206
+ an id_token it received was actually minted for *your* `client_id`.
207
+
208
+ ## License
209
+
210
+ Apache-2.0
@@ -0,0 +1,10 @@
1
+ logi_auth/__init__.py,sha256=6Dh8c0s46nlv34V9phSq2n13c6hLE4nvHgphhRYUhC4,584
2
+ logi_auth/errors.py,sha256=fx9jrszRzxyzp9r4bMlI97QOhoZDoYmLk_yaKUn0jrs,977
3
+ logi_auth/id_token_verifier.py,sha256=3VExJ-P4Y8fXv6TyK-2tL2J0rVWuEpqThvCsQh1ICvg,6838
4
+ logi_auth/server.py,sha256=EIeQWXGxH_6hZkfHiQcF4kIYRpvnfWbfR3uDd__Z9lQ,8833
5
+ logi_auth-1.0.1.dist-info/licenses/LICENSE,sha256=tB_InTlU319nHTGhdTphEI_xs39XDxEZsRltktjWXSU,10359
6
+ logi_auth-1.0.1.dist-info/licenses/NOTICE,sha256=8nV26-gmMBmUUyb8tZh215SlbvAMlNSTEKSTDeeizBo,100
7
+ logi_auth-1.0.1.dist-info/METADATA,sha256=7XUglRAIqpMA7FnIKw1dmLOf8SgRmdWqCzRO67hSlcw,7334
8
+ logi_auth-1.0.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
9
+ logi_auth-1.0.1.dist-info/top_level.txt,sha256=__nvIQqjp6LD7CIuBEMrxuco3OrRwW-lfTa_ydZp5N8,10
10
+ logi_auth-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,80 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following
60
+ boilerplate notice, with the fields enclosed by brackets "[]"
61
+ replaced with your own identifying information. (Don't include
62
+ the brackets!) The text should be enclosed in the appropriate
63
+ comment syntax for the file format. We also recommend that a
64
+ file or class name and description of purpose be included on the
65
+ same "printed page" as the copyright notice for easier
66
+ identification within third-party archives.
67
+
68
+ Copyright 2026 Dcode
69
+
70
+ Licensed under the Apache License, Version 2.0 (the "License");
71
+ you may not use this file except in compliance with the License.
72
+ You may obtain a copy of the License at
73
+
74
+ http://www.apache.org/licenses/LICENSE-2.0
75
+
76
+ Unless required by applicable law or agreed to in writing, software
77
+ distributed under the License is distributed on an "AS IS" BASIS,
78
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
79
+ See the License for the specific language governing permissions and
80
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ logi auth SDK
2
+ Copyright 2026 Dcode
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
@@ -0,0 +1 @@
1
+ logi_auth