jwt-sessions 0.1.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.
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ node_modules/
7
+ dist/
8
+ *.egg-info/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nassim Kaddouri
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.5
2
+ Name: jwt-sessions
3
+ Version: 0.1.0
4
+ Summary: First-party JWT auth for FastAPI with rotating, reuse-detecting refresh tokens.
5
+ Project-URL: Repository, https://github.com/Aegyptiacus11/jwt-sessions
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: auth,fastapi,jwt,refresh-token,session
9
+ Classifier: Framework :: FastAPI
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Internet :: WWW/HTTP :: Session
12
+ Classifier: Topic :: Security
13
+ Requires-Python: >=3.11
14
+ Requires-Dist: pwdlib[argon2]>=0.2
15
+ Requires-Dist: pyjwt>=2.8
16
+ Provides-Extra: fastapi
17
+ Requires-Dist: fastapi>=0.110; extra == 'fastapi'
18
+ Provides-Extra: sqlalchemy
19
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'sqlalchemy'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # jwt-sessions
23
+
24
+ First-party authentication for FastAPI: email and password sign-in,
25
+ short-lived access tokens, and refresh tokens that rotate on every use and
26
+ give themselves away when stolen.
27
+
28
+ It is for applications that own their users and do not want an identity
29
+ provider. Authorization - who may do what - is deliberately not here; it
30
+ belongs to the application.
31
+
32
+ > Status: 0.1.0, the first release, extracted from a production application; the
33
+ > API may still change before 1.0. MIT licensed.
34
+
35
+ ## Installing
36
+
37
+ ```bash
38
+ uv add "jwt-sessions[fastapi,sqlalchemy]"
39
+ ```
40
+
41
+ (or `pip install`, with the same argument). The extras are the FastAPI router and the
42
+ SQLAlchemy refresh store.
43
+
44
+ ## Using it
45
+
46
+ ```python
47
+ from jwt_sessions import AccessTokens, Auth, RefreshTokens
48
+ from jwt_sessions.fastapi import auth_router, bearer_claims
49
+ from jwt_sessions.sqlalchemy_store import SQLAlchemyRefreshStore, refresh_tables
50
+
51
+ families, tokens = refresh_tables(Base.metadata) # on your own metadata
52
+ auth = Auth(
53
+ users=MyUsers(), # by_login / by_id -> AuthUser
54
+ access=AccessTokens(settings.jwt_secret),
55
+ refresh=RefreshTokens(SQLAlchemyRefreshStore(sessionmaker, families, tokens)),
56
+ )
57
+ app.include_router(auth_router(auth), prefix="/api/v1")
58
+ current_claims = bearer_claims(auth) # a dependency: the verified claims
59
+ ```
60
+
61
+ `examples/demo_app.py` is a complete, runnable one:
62
+ `uv run uvicorn examples.demo_app:app`.
63
+
64
+ ## The contract
65
+
66
+ | | Request | Response |
67
+ |---|---|---|
68
+ | `POST /auth/login` | `{"email", "password"}` | `{"access_token", "token_type"}` + the refresh cookie |
69
+ | `POST /auth/refresh` | the refresh cookie | a new access token + the rotated cookie |
70
+ | `POST /auth/logout` | the refresh cookie | `204`; that session is revoked, the cookie cleared |
71
+ | `POST /auth/logout-all` | `Authorization: Bearer` | `204`; every session of the user is revoked |
72
+
73
+ - **The access token** is a JWT (HS256, 15 minutes by default), sent as
74
+ `Authorization: Bearer`. It is never in a cookie, so no request is authorised
75
+ by a cookie alone.
76
+ - **The refresh token** is an opaque random value that only ever travels in an
77
+ `httpOnly`, `SameSite=Lax` cookie scoped to the auth endpoints. JavaScript
78
+ never sees it, so a script injected into the page cannot take it away.
79
+
80
+ ### What a client has to do
81
+
82
+ A browser client is small - there is no client library, and the contract is
83
+ all it needs:
84
+
85
+ - Keep the access token in memory, not in storage.
86
+ - Call the auth endpoints with `credentials: "include"`, so the cookie travels.
87
+ - On load, `POST /auth/refresh` to restore a session; a 401 means signed out.
88
+ - On a 401 from the API, refresh **once** and retry; if the refresh fails, the
89
+ session is gone.
90
+ - Never run two refreshes at once from one page: the server spends a refresh
91
+ token on use, and the second would look like a replay (see below). Share one
92
+ in-flight refresh between everything that needs a token.
93
+ - Renewing a minute before the access token's `exp` saves the first request
94
+ after an idle spell a round trip.
95
+
96
+ ## What happens to a stolen refresh token
97
+
98
+ A sign-in starts a **family** of refresh tokens. Each refresh spends the
99
+ token presented and issues its successor. A spent token presented again means
100
+ two parties hold it - the user and whoever copied it - so the whole family is
101
+ revoked: both are signed out, and the copy is dead.
102
+
103
+ A stateless refresh JWT, the usual alternative, can do none of this: a copied
104
+ one keeps working until it expires, however often its owner refreshes, and
105
+ signing out only deletes the owner's copy.
106
+
107
+ Two tabs refreshing at the same instant would look like a replay, so a spent
108
+ token presented again within `reuse_grace_seconds` (10 s by default; 0 turns it
109
+ off) gets a successor instead. That window is open to a thief as well, if they
110
+ replay within those seconds of the real refresh.
111
+
112
+ Only the SHA-256 of a refresh token is stored, so a copy of the table holds
113
+ nothing that can be presented.
114
+
115
+ ## Also
116
+
117
+ - Signing in with an unknown email costs the same argon2 verification as a
118
+ wrong password, so response time does not say which addresses have accounts.
119
+ - Passwords over 1 KB are refused before hashing.
120
+ - The signing secret must be at least 32 bytes, and the JWT algorithm is pinned
121
+ on verification, never read from the token.
122
+ - A deactivated account's session ends at its next refresh; its current access
123
+ token runs out within the access TTL. `Auth.logout_everywhere` ends every
124
+ session at once - call it on deactivation and on a password change.
125
+ - `RefreshStore.purge` drops expired tokens; run it now and then (on start-up
126
+ is enough for most applications).
127
+
128
+ ## Development
129
+
130
+ ```bash
131
+ uv run pytest
132
+ uv run ruff check . && uv run ruff format --check .
133
+ ```
@@ -0,0 +1,112 @@
1
+ # jwt-sessions
2
+
3
+ First-party authentication for FastAPI: email and password sign-in,
4
+ short-lived access tokens, and refresh tokens that rotate on every use and
5
+ give themselves away when stolen.
6
+
7
+ It is for applications that own their users and do not want an identity
8
+ provider. Authorization - who may do what - is deliberately not here; it
9
+ belongs to the application.
10
+
11
+ > Status: 0.1.0, the first release, extracted from a production application; the
12
+ > API may still change before 1.0. MIT licensed.
13
+
14
+ ## Installing
15
+
16
+ ```bash
17
+ uv add "jwt-sessions[fastapi,sqlalchemy]"
18
+ ```
19
+
20
+ (or `pip install`, with the same argument). The extras are the FastAPI router and the
21
+ SQLAlchemy refresh store.
22
+
23
+ ## Using it
24
+
25
+ ```python
26
+ from jwt_sessions import AccessTokens, Auth, RefreshTokens
27
+ from jwt_sessions.fastapi import auth_router, bearer_claims
28
+ from jwt_sessions.sqlalchemy_store import SQLAlchemyRefreshStore, refresh_tables
29
+
30
+ families, tokens = refresh_tables(Base.metadata) # on your own metadata
31
+ auth = Auth(
32
+ users=MyUsers(), # by_login / by_id -> AuthUser
33
+ access=AccessTokens(settings.jwt_secret),
34
+ refresh=RefreshTokens(SQLAlchemyRefreshStore(sessionmaker, families, tokens)),
35
+ )
36
+ app.include_router(auth_router(auth), prefix="/api/v1")
37
+ current_claims = bearer_claims(auth) # a dependency: the verified claims
38
+ ```
39
+
40
+ `examples/demo_app.py` is a complete, runnable one:
41
+ `uv run uvicorn examples.demo_app:app`.
42
+
43
+ ## The contract
44
+
45
+ | | Request | Response |
46
+ |---|---|---|
47
+ | `POST /auth/login` | `{"email", "password"}` | `{"access_token", "token_type"}` + the refresh cookie |
48
+ | `POST /auth/refresh` | the refresh cookie | a new access token + the rotated cookie |
49
+ | `POST /auth/logout` | the refresh cookie | `204`; that session is revoked, the cookie cleared |
50
+ | `POST /auth/logout-all` | `Authorization: Bearer` | `204`; every session of the user is revoked |
51
+
52
+ - **The access token** is a JWT (HS256, 15 minutes by default), sent as
53
+ `Authorization: Bearer`. It is never in a cookie, so no request is authorised
54
+ by a cookie alone.
55
+ - **The refresh token** is an opaque random value that only ever travels in an
56
+ `httpOnly`, `SameSite=Lax` cookie scoped to the auth endpoints. JavaScript
57
+ never sees it, so a script injected into the page cannot take it away.
58
+
59
+ ### What a client has to do
60
+
61
+ A browser client is small - there is no client library, and the contract is
62
+ all it needs:
63
+
64
+ - Keep the access token in memory, not in storage.
65
+ - Call the auth endpoints with `credentials: "include"`, so the cookie travels.
66
+ - On load, `POST /auth/refresh` to restore a session; a 401 means signed out.
67
+ - On a 401 from the API, refresh **once** and retry; if the refresh fails, the
68
+ session is gone.
69
+ - Never run two refreshes at once from one page: the server spends a refresh
70
+ token on use, and the second would look like a replay (see below). Share one
71
+ in-flight refresh between everything that needs a token.
72
+ - Renewing a minute before the access token's `exp` saves the first request
73
+ after an idle spell a round trip.
74
+
75
+ ## What happens to a stolen refresh token
76
+
77
+ A sign-in starts a **family** of refresh tokens. Each refresh spends the
78
+ token presented and issues its successor. A spent token presented again means
79
+ two parties hold it - the user and whoever copied it - so the whole family is
80
+ revoked: both are signed out, and the copy is dead.
81
+
82
+ A stateless refresh JWT, the usual alternative, can do none of this: a copied
83
+ one keeps working until it expires, however often its owner refreshes, and
84
+ signing out only deletes the owner's copy.
85
+
86
+ Two tabs refreshing at the same instant would look like a replay, so a spent
87
+ token presented again within `reuse_grace_seconds` (10 s by default; 0 turns it
88
+ off) gets a successor instead. That window is open to a thief as well, if they
89
+ replay within those seconds of the real refresh.
90
+
91
+ Only the SHA-256 of a refresh token is stored, so a copy of the table holds
92
+ nothing that can be presented.
93
+
94
+ ## Also
95
+
96
+ - Signing in with an unknown email costs the same argon2 verification as a
97
+ wrong password, so response time does not say which addresses have accounts.
98
+ - Passwords over 1 KB are refused before hashing.
99
+ - The signing secret must be at least 32 bytes, and the JWT algorithm is pinned
100
+ on verification, never read from the token.
101
+ - A deactivated account's session ends at its next refresh; its current access
102
+ token runs out within the access TTL. `Auth.logout_everywhere` ends every
103
+ session at once - call it on deactivation and on a password change.
104
+ - `RefreshStore.purge` drops expired tokens; run it now and then (on start-up
105
+ is enough for most applications).
106
+
107
+ ## Development
108
+
109
+ ```bash
110
+ uv run pytest
111
+ uv run ruff check . && uv run ruff format --check .
112
+ ```
File without changes
@@ -0,0 +1,70 @@
1
+ """The smallest application using jwt-sessions.
2
+
3
+ uv run uvicorn examples.demo_app:app --port 8000
4
+
5
+ One user, ada@example.com / correct-horse, kept in memory. A real
6
+ application keeps users in its database (`UserStore`) and refresh tokens in
7
+ it too (`SQLAlchemyRefreshStore`).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from typing import Any
14
+
15
+ from fastapi import Depends, FastAPI
16
+
17
+ from jwt_sessions import (
18
+ AccessTokens,
19
+ Auth,
20
+ AuthUser,
21
+ InMemoryRefreshStore,
22
+ RefreshTokens,
23
+ hash_password,
24
+ )
25
+ from jwt_sessions.fastapi import CookieSettings, auth_router, bearer_claims
26
+
27
+ USERS = {
28
+ "ada@example.com": AuthUser(
29
+ id="u-ada",
30
+ password_hash=hash_password("correct-horse"),
31
+ claims={"role": "admin"},
32
+ )
33
+ }
34
+
35
+
36
+ class Users:
37
+ async def by_login(self, login: str) -> AuthUser | None:
38
+ return USERS.get(login.strip().lower())
39
+
40
+ async def by_id(self, user_id: str) -> AuthUser | None:
41
+ return next((u for u in USERS.values() if u.id == user_id), None)
42
+
43
+
44
+ auth = Auth(
45
+ users=Users(),
46
+ access=AccessTokens(
47
+ os.environ.get("DEMO_SECRET", "demo-secret-only-for-the-demo-app-000000")
48
+ ),
49
+ refresh=RefreshTokens(
50
+ InMemoryRefreshStore(),
51
+ reuse_grace_seconds=int(os.environ.get("DEMO_REUSE_GRACE", "10")),
52
+ ),
53
+ )
54
+ current = bearer_claims(auth)
55
+
56
+ app = FastAPI(title="jwt-sessions demo")
57
+ # Plain HTTP on localhost: a Secure cookie would never be sent back.
58
+ app.include_router(
59
+ auth_router(auth, cookie=CookieSettings(secure=False)), prefix="/api"
60
+ )
61
+
62
+
63
+ @app.get("/api/me")
64
+ async def me(claims: dict[str, Any] = Depends(current)) -> dict[str, Any]:
65
+ user = await Users().by_id(claims["sub"])
66
+ return {
67
+ "id": claims["sub"],
68
+ "email": next(k for k, v in USERS.items() if v is user),
69
+ "roles": [claims["role"]],
70
+ }
@@ -0,0 +1,68 @@
1
+ [project]
2
+ name = "jwt-sessions"
3
+ version = "0.1.0"
4
+ description = "First-party JWT auth for FastAPI with rotating, reuse-detecting refresh tokens."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ keywords = ["jwt", "auth", "session", "refresh-token", "fastapi"]
10
+ classifiers = [
11
+ "Framework :: FastAPI",
12
+ "Programming Language :: Python :: 3",
13
+ "Topic :: Security",
14
+ "Topic :: Internet :: WWW/HTTP :: Session",
15
+ ]
16
+ dependencies = [
17
+ "pyjwt>=2.8",
18
+ "pwdlib[argon2]>=0.2",
19
+ ]
20
+
21
+ [project.urls]
22
+ Repository = "https://github.com/Aegyptiacus11/jwt-sessions"
23
+
24
+ [project.optional-dependencies]
25
+ fastapi = ["fastapi>=0.110"]
26
+ sqlalchemy = ["sqlalchemy[asyncio]>=2.0"]
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "fastapi>=0.110",
31
+ "httpx>=0.27",
32
+ "sqlalchemy[asyncio]>=2.0",
33
+ "aiosqlite>=0.20",
34
+ "pytest>=8",
35
+ "pytest-asyncio>=0.24",
36
+ "ruff>=0.6",
37
+ "uvicorn>=0.54.0",
38
+ ]
39
+
40
+ [build-system]
41
+ requires = ["hatchling"]
42
+ build-backend = "hatchling.build"
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["src/jwt_sessions"]
46
+
47
+ [tool.hatch.build.targets.sdist]
48
+ only-include = ["src", "tests", "examples", "README.md", "LICENSE", "pyproject.toml"]
49
+
50
+ [tool.pytest.ini_options]
51
+ asyncio_mode = "auto"
52
+ asyncio_default_fixture_loop_scope = "function"
53
+ testpaths = ["tests"]
54
+ pythonpath = ["."]
55
+
56
+ [tool.ruff]
57
+ target-version = "py311"
58
+
59
+ [tool.ruff.lint]
60
+ select = ["E", "F", "I", "B", "UP", "S", "SIM"]
61
+ ignore = ["S101"]
62
+
63
+ [tool.ruff.lint.flake8-bugbear]
64
+ # FastAPI's dependency idiom.
65
+ extend-immutable-calls = ["fastapi.Depends"]
66
+
67
+ [tool.ruff.lint.per-file-ignores]
68
+ "tests/*" = ["S105", "S106"]
@@ -0,0 +1,24 @@
1
+ """First-party JWT auth with rotating, reuse-detecting refresh tokens."""
2
+
3
+ from jwt_sessions.core import Auth, AuthUser, InvalidCredentials, Session, UserStore
4
+ from jwt_sessions.memory import InMemoryRefreshStore
5
+ from jwt_sessions.passwords import check_password, hash_password, needs_rehash
6
+ from jwt_sessions.refresh import RefreshRejected, RefreshStore, RefreshTokens
7
+ from jwt_sessions.tokens import AccessTokens, InvalidToken
8
+
9
+ __all__ = [
10
+ "AccessTokens",
11
+ "Auth",
12
+ "AuthUser",
13
+ "InMemoryRefreshStore",
14
+ "InvalidCredentials",
15
+ "InvalidToken",
16
+ "RefreshRejected",
17
+ "RefreshStore",
18
+ "RefreshTokens",
19
+ "Session",
20
+ "UserStore",
21
+ "check_password",
22
+ "hash_password",
23
+ "needs_rehash",
24
+ ]
@@ -0,0 +1,96 @@
1
+ """The session lifecycle: sign in, refresh, sign out - in terms of the two
2
+ things an application supplies, where its users are (`UserStore`) and where
3
+ refresh tokens are kept (`RefreshStore`).
4
+
5
+ Framework-free; `jwt_sessions.fastapi` puts it behind HTTP.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+ from datetime import datetime
13
+ from typing import Any, Protocol
14
+
15
+ from jwt_sessions.passwords import check_password
16
+ from jwt_sessions.refresh import RefreshRejected, RefreshTokens
17
+ from jwt_sessions.tokens import AccessTokens
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class AuthUser:
22
+ """What the library needs to know about a user."""
23
+
24
+ id: str
25
+ password_hash: str
26
+ active: bool = True
27
+ #: Extra claims for the access token - a role, say. Read again on every
28
+ #: refresh, so a changed role reaches the token within one access TTL.
29
+ claims: Mapping[str, Any] = field(default_factory=dict)
30
+
31
+
32
+ class UserStore(Protocol):
33
+ async def by_login(self, login: str) -> AuthUser | None:
34
+ """The user signing in as `login` (an email, usually). Normalise case
35
+ here if logins are case-insensitive."""
36
+ ...
37
+
38
+ async def by_id(self, user_id: str) -> AuthUser | None: ...
39
+
40
+
41
+ class InvalidCredentials(Exception):
42
+ """Wrong login or password, or an inactive account - deliberately one
43
+ error, so the response does not say which."""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Session:
48
+ access_token: str
49
+ refresh_token: str
50
+ user_id: str
51
+
52
+
53
+ @dataclass
54
+ class Auth:
55
+ users: UserStore
56
+ access: AccessTokens
57
+ refresh: RefreshTokens
58
+
59
+ async def login(
60
+ self, login: str, password: str, *, now: datetime | None = None
61
+ ) -> Session:
62
+ user = await self.users.by_login(login)
63
+ # Always one argon2 verification, account or not - see passwords.py.
64
+ ok = check_password(password, user.password_hash if user else None)
65
+ if user is None or not ok or not user.active:
66
+ raise InvalidCredentials
67
+ refresh_token = await self.refresh.start(user.id, now=now)
68
+ return Session(
69
+ access_token=self.access.issue(user.id, user.claims, now=now),
70
+ refresh_token=refresh_token,
71
+ user_id=user.id,
72
+ )
73
+
74
+ async def renew(
75
+ self, refresh_token: str, *, now: datetime | None = None
76
+ ) -> Session:
77
+ """A new access token and the refresh token's successor; RefreshRejected
78
+ otherwise. An account deactivated since sign-in ends the session."""
79
+ rotated = await self.refresh.rotate(refresh_token, now=now)
80
+ user = await self.users.by_id(rotated.user_id)
81
+ if user is None or not user.active:
82
+ await self.refresh.revoke(rotated.token, now=now)
83
+ raise RefreshRejected("inactive")
84
+ return Session(
85
+ access_token=self.access.issue(user.id, user.claims, now=now),
86
+ refresh_token=rotated.token,
87
+ user_id=user.id,
88
+ )
89
+
90
+ async def logout(self, refresh_token: str, *, now: datetime | None = None) -> None:
91
+ await self.refresh.revoke(refresh_token, now=now)
92
+
93
+ async def logout_everywhere(
94
+ self, user_id: str, *, now: datetime | None = None
95
+ ) -> int:
96
+ return await self.refresh.revoke_user(user_id, now=now)