vercel-oidc 0.6.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,128 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+
5
+ # C extensions
6
+ *.so
7
+
8
+ # Distribution / packaging
9
+ .Python
10
+ build/
11
+ develop-eggs/
12
+ dist/
13
+ downloads/
14
+ eggs/
15
+ .eggs/
16
+ lib/
17
+ lib64/
18
+ parts/
19
+ sdist/
20
+ var/
21
+ wheels/
22
+ share/python-wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+ MANIFEST
27
+
28
+ # PyInstallerhave
29
+ *.manifest
30
+ *.spec
31
+
32
+ # Installer logs
33
+ pip-log.txt
34
+ pip-delete-this-directory.txt
35
+
36
+ # Unit test / coverage reports
37
+ htmlcov/
38
+ .tox/
39
+ .nox/
40
+ .coverage
41
+ .coverage.*
42
+ .cache
43
+ nosetests.xml
44
+ coverage.xml
45
+ *.cover
46
+ *.py,cover
47
+ .hypothesis/
48
+ .pytest_cache/
49
+ .ruff_cache/
50
+
51
+ # Translations
52
+ *.mo
53
+ *.pot
54
+
55
+ # Scrapy
56
+ .scrapy
57
+
58
+ # Sphinx documentation
59
+ docs/_build/
60
+
61
+ # PyBuilder
62
+ target/
63
+
64
+ # Jupyter Notebook
65
+ .ipynb_checkpoints
66
+
67
+ # IPython
68
+ profile_default/
69
+ ipython_config.py
70
+
71
+ # pyenv
72
+ .python-version
73
+
74
+ # pipenv
75
+ Pipfile.lock
76
+
77
+ # poetry
78
+ poetry.lock
79
+
80
+ # PDM
81
+ pdm.lock
82
+ .pdm.toml
83
+
84
+ # Hatch
85
+ .hatch/
86
+
87
+ # pyright/mypy
88
+ .mypy_cache/
89
+ .dmypy.json
90
+ dmypy.json
91
+
92
+ # pyre
93
+ .pyre/
94
+
95
+ # pytype
96
+ .pytype/
97
+
98
+ # Caches
99
+ __pypackages__/
100
+
101
+ # Editor/project files
102
+ .DS_Store
103
+ .idea/
104
+ .vscode/
105
+ *.swp
106
+ *.swo
107
+
108
+ # Virtual environments
109
+ .env
110
+ .venv
111
+ .venv.*
112
+ env/
113
+ venv/
114
+ **/.env
115
+ **/.venv
116
+ **/.venv.*
117
+ **/env/
118
+ **/venv/
119
+ ENV/
120
+ env.bak/
121
+ venv.bak/
122
+
123
+ # dotenv anywhere
124
+ **/.env
125
+ **/.env.*
126
+ **/*.env
127
+
128
+ .claude
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vercel, Inc.
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,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: vercel-oidc
3
+ Version: 0.6.0
4
+ Summary: OIDC helpers for Vercel Python applications
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: httpx<1,>=0.27.0
9
+ Requires-Dist: vercel-headers>=0.6.0
10
+ Description-Content-Type: text/markdown
11
+
12
+ # OIDC
13
+
14
+ `vercel.oidc` retrieves and decodes Vercel OIDC tokens.
15
+
16
+ ## Async Token Lookup
17
+
18
+ ```python
19
+ from vercel.oidc import decode_oidc_payload
20
+ from vercel.headers import set_headers
21
+ from vercel.oidc.aio import get_vercel_oidc_token
22
+
23
+
24
+ async def main() -> None:
25
+ token = await get_vercel_oidc_token()
26
+ payload = decode_oidc_payload(token)
27
+ project_id = payload.get("project_id")
28
+ ```
29
+
30
+ Token lookup prefers the `x-vercel-oidc-token` request header registered with
31
+ `vercel.headers.set_headers()`, then `VERCEL_OIDC_TOKEN`. The compatibility
32
+ alias `vercel.oidc.set_headers()` updates the same header context. In local development,
33
+ you can load a short-lived token dynamically:
34
+
35
+ ```bash
36
+ VERCEL_OIDC_TOKEN=$(vc project token some-project) some-command
37
+ ```
38
+
39
+ Use `vercel.oidc.get_vercel_oidc_token()` for synchronous code.
@@ -0,0 +1,28 @@
1
+ # OIDC
2
+
3
+ `vercel.oidc` retrieves and decodes Vercel OIDC tokens.
4
+
5
+ ## Async Token Lookup
6
+
7
+ ```python
8
+ from vercel.oidc import decode_oidc_payload
9
+ from vercel.headers import set_headers
10
+ from vercel.oidc.aio import get_vercel_oidc_token
11
+
12
+
13
+ async def main() -> None:
14
+ token = await get_vercel_oidc_token()
15
+ payload = decode_oidc_payload(token)
16
+ project_id = payload.get("project_id")
17
+ ```
18
+
19
+ Token lookup prefers the `x-vercel-oidc-token` request header registered with
20
+ `vercel.headers.set_headers()`, then `VERCEL_OIDC_TOKEN`. The compatibility
21
+ alias `vercel.oidc.set_headers()` updates the same header context. In local development,
22
+ you can load a short-lived token dynamically:
23
+
24
+ ```bash
25
+ VERCEL_OIDC_TOKEN=$(vc project token some-project) some-command
26
+ ```
27
+
28
+ Use `vercel.oidc.get_vercel_oidc_token()` for synchronous code.
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27.0,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "vercel-oidc"
7
+ dynamic = ["version"]
8
+ description = "OIDC helpers for Vercel Python applications"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE", "LICENSE.*"]
13
+ dependencies = [
14
+ "httpx>=0.27.0,<1",
15
+ "vercel-headers>=0.6.0",
16
+ ]
17
+
18
+ [tool.uv.sources]
19
+ vercel-headers = { workspace = true }
20
+
21
+ [tool.hatch.version]
22
+ path = "vercel/oidc/version.py"
23
+
24
+ [tool.hatch.build.targets.sdist]
25
+ include = [
26
+ "/vercel/oidc/**/*.py",
27
+ "/README.md",
28
+ "/vercel/oidc/py.typed",
29
+ "/pyproject.toml",
30
+ "/LICENSE",
31
+ ]
32
+ exclude = [
33
+ "/**/__pycache__",
34
+ ]
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ dev-mode-dirs = ["."]
38
+ only-include = ["/vercel/oidc"]
39
+ exclude = [
40
+ "/**/__pycache__",
41
+ ]
@@ -0,0 +1,21 @@
1
+ from vercel.headers import set_headers
2
+
3
+ from .credentials import Credentials, get_credentials
4
+ from .token import (
5
+ VercelOidcTokenError,
6
+ decode_oidc_payload,
7
+ get_token_payload,
8
+ get_vercel_oidc_token,
9
+ get_vercel_oidc_token_sync,
10
+ )
11
+
12
+ __all__ = [
13
+ "VercelOidcTokenError",
14
+ "get_vercel_oidc_token",
15
+ "get_vercel_oidc_token_sync",
16
+ "get_token_payload",
17
+ "set_headers",
18
+ "Credentials",
19
+ "get_credentials",
20
+ "decode_oidc_payload",
21
+ ]
@@ -0,0 +1,7 @@
1
+ from .token import (
2
+ fetch_vercel_oidc_token_async as fetch_vercel_oidc_token,
3
+ get_vercel_oidc_token_async as get_vercel_oidc_token,
4
+ refresh_token_async as refresh_token,
5
+ )
6
+
7
+ __all__ = ["get_vercel_oidc_token", "refresh_token", "fetch_vercel_oidc_token"]
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from .token import VercelOidcTokenError, decode_oidc_payload, get_vercel_oidc_token_from_context
6
+ from .types import Credentials
7
+
8
+
9
+ def get_credentials(
10
+ *,
11
+ token: str | None = None,
12
+ project_id: str | None = None,
13
+ team_id: str | None = None,
14
+ ) -> Credentials:
15
+ if token and project_id and team_id:
16
+ return Credentials(token=token, project_id=project_id, team_id=team_id)
17
+
18
+ # Resolve OIDC token from request headers (set by the runtime) or env var.
19
+ oidc: str | None = None
20
+ try:
21
+ oidc = get_vercel_oidc_token_from_context()
22
+ except VercelOidcTokenError:
23
+ pass
24
+
25
+ if oidc:
26
+ project = os.getenv("VERCEL_PROJECT_ID")
27
+ team = os.getenv("VERCEL_TEAM_ID")
28
+ if not (project and team):
29
+ try:
30
+ payload = decode_oidc_payload(oidc)
31
+ project = payload.get("project_id")
32
+ team = payload.get("owner_id")
33
+ except Exception:
34
+ pass
35
+ if project and team:
36
+ return Credentials(token=oidc, project_id=project, team_id=team)
37
+ raise RuntimeError(
38
+ "OIDC token present but could not determine VERCEL_PROJECT_ID and VERCEL_TEAM_ID"
39
+ )
40
+
41
+ token = token or os.getenv("VERCEL_TOKEN")
42
+ project_id = project_id or os.getenv("VERCEL_PROJECT_ID")
43
+ team_id = team_id or os.getenv("VERCEL_TEAM_ID")
44
+
45
+ if token and project_id and team_id:
46
+ return Credentials(token=token, project_id=project_id, team_id=team_id)
47
+
48
+ raise RuntimeError(
49
+ "Missing credentials. "
50
+ "For local development, run 'vercel link && vercel env pull'. "
51
+ "Otherwise, set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID."
52
+ )
File without changes
@@ -0,0 +1,200 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from collections.abc import Mapping
5
+
6
+ import httpx
7
+
8
+ from vercel.headers import get_headers
9
+
10
+ from .types import VercelTokenResponse
11
+ from .utils import (
12
+ find_project_info,
13
+ get_token_payload,
14
+ get_vercel_cli_token,
15
+ is_expired,
16
+ load_token,
17
+ save_token,
18
+ )
19
+
20
+ BASE_URL = "https://api.vercel.com/v1"
21
+
22
+
23
+ class VercelOidcTokenError(Exception):
24
+ def __init__(self, message: str, cause: Exception | None = None):
25
+ if cause is not None:
26
+ message = f"{message}: {cause}"
27
+ super().__init__(message)
28
+ self.cause = cause
29
+
30
+
31
+ def get_vercel_oidc_token_from_context() -> str:
32
+ # Prefer request header registered in the OIDC context,
33
+ # fall back to environment variable like the TypeScript SDK.
34
+ headers = get_headers()
35
+ if headers:
36
+ # Normalize headers to lowercase keys
37
+ lower_headers: dict[str, str] = {}
38
+ if isinstance(headers, Mapping):
39
+ for k, v in headers.items():
40
+ lower_headers[str(k).lower()] = v
41
+ elif isinstance(headers, (list, tuple)):
42
+ for item in headers:
43
+ if isinstance(item, (list, tuple)) and len(item) == 2:
44
+ k, v = item
45
+ lower_headers[str(k).lower()] = v
46
+ elif hasattr(headers, "keys") and hasattr(headers, "__getitem__"):
47
+ for k in headers.keys():
48
+ v = headers[k]
49
+ lower_headers[str(k).lower()] = v
50
+
51
+ token_from_header = lower_headers.get("x-vercel-oidc-token")
52
+ if token_from_header:
53
+ return token_from_header
54
+
55
+ token_from_env = os.getenv("VERCEL_OIDC_TOKEN")
56
+ if not token_from_env:
57
+ raise VercelOidcTokenError(
58
+ "The 'x-vercel-oidc-token' header is missing from the request. "
59
+ "Do you have the OIDC option enabled in the Vercel project settings?"
60
+ )
61
+ return token_from_env
62
+
63
+
64
+ # for TS parity
65
+ get_vercel_oidc_token_sync = get_vercel_oidc_token_from_context
66
+
67
+
68
+ def refresh_token() -> None:
69
+ project = find_project_info()
70
+ project_id: str = project["projectId"]
71
+ team_id = project.get("teamId")
72
+
73
+ maybe = load_token(project_id)
74
+ if not maybe or is_expired(get_token_payload(maybe.token)):
75
+ auth_token = get_vercel_cli_token()
76
+ if not auth_token:
77
+ raise VercelOidcTokenError("Failed to refresh OIDC token: login to vercel cli")
78
+ if not project_id:
79
+ raise VercelOidcTokenError("Failed to refresh OIDC token: project id not found")
80
+ new_token = fetch_vercel_oidc_token(auth_token, project_id, team_id)
81
+ if not new_token:
82
+ raise VercelOidcTokenError("Failed to refresh OIDC token")
83
+ save_token(new_token, project_id)
84
+ os.environ["VERCEL_OIDC_TOKEN"] = new_token.token
85
+ else:
86
+ os.environ["VERCEL_OIDC_TOKEN"] = maybe.token
87
+
88
+
89
+ async def refresh_token_async() -> None:
90
+ project = find_project_info()
91
+ project_id: str = project["projectId"]
92
+ team_id = project.get("teamId")
93
+
94
+ maybe = load_token(project_id)
95
+ if not maybe or is_expired(get_token_payload(maybe.token)):
96
+ auth_token = get_vercel_cli_token()
97
+ if not auth_token:
98
+ raise VercelOidcTokenError("Failed to refresh OIDC token: login to vercel cli")
99
+ if not project_id:
100
+ raise VercelOidcTokenError("Failed to refresh OIDC token: project id not found")
101
+ new_token = await fetch_vercel_oidc_token_async(auth_token, project_id, team_id)
102
+ if not new_token:
103
+ raise VercelOidcTokenError("Failed to refresh OIDC token")
104
+ save_token(new_token, project_id)
105
+ os.environ["VERCEL_OIDC_TOKEN"] = new_token.token
106
+ else:
107
+ os.environ["VERCEL_OIDC_TOKEN"] = maybe.token
108
+
109
+
110
+ def get_vercel_oidc_token() -> str:
111
+ token = ""
112
+ err: Exception | None = None
113
+ try:
114
+ token = get_vercel_oidc_token_from_context()
115
+ except Exception as e:
116
+ err = e
117
+ try:
118
+ if not token or is_expired(get_token_payload(token)):
119
+ # Only attempt refresh in environments that look like local dev with a .vercel folder
120
+ try:
121
+ _ = find_project_info()
122
+ except Exception as e:
123
+ # Preserve the original context error and surface an actionable message
124
+ if err and isinstance(err, Exception) and getattr(err, "message", None):
125
+ e.args = (f"{err}\n{e}",)
126
+ raise VercelOidcTokenError(
127
+ "Missing OIDC request header and no local project context (.vercel) available",
128
+ e,
129
+ ) from e
130
+ refresh_token()
131
+ token = get_vercel_oidc_token_from_context()
132
+ except Exception as e:
133
+ if err and isinstance(e, Exception) and getattr(err, "message", None):
134
+ e.args = (f"{err}\n{e}",)
135
+ raise VercelOidcTokenError("Failed to refresh OIDC token", e) from e
136
+ return token
137
+
138
+
139
+ async def get_vercel_oidc_token_async() -> str:
140
+ token = ""
141
+ err: Exception | None = None
142
+ try:
143
+ token = get_vercel_oidc_token_from_context()
144
+ except Exception as e:
145
+ err = e
146
+ try:
147
+ if not token or is_expired(get_token_payload(token)):
148
+ # Only attempt refresh in environments that look like local dev with a .vercel folder
149
+ try:
150
+ _ = find_project_info()
151
+ except Exception as e:
152
+ if err and isinstance(err, Exception) and getattr(err, "message", None):
153
+ e.args = (f"{err}\n{e}",)
154
+ raise VercelOidcTokenError(
155
+ "Missing OIDC request header and no local project context (.vercel) available",
156
+ e,
157
+ ) from e
158
+ await refresh_token_async()
159
+ token = get_vercel_oidc_token_from_context()
160
+ except Exception as e:
161
+ if err and isinstance(e, Exception) and getattr(err, "message", None):
162
+ e.args = (f"{err}\n{e}",)
163
+ raise VercelOidcTokenError("Failed to refresh OIDC token", e) from e
164
+ return token
165
+
166
+
167
+ def fetch_vercel_oidc_token(
168
+ auth_token: str, project_id: str, team_id: str | None
169
+ ) -> VercelTokenResponse | None:
170
+ url = f"{BASE_URL}/projects/{project_id}/token?source=vercel-oidc-refresh"
171
+ if team_id:
172
+ url += f"&teamId={team_id}"
173
+ with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
174
+ r = client.post(url, headers={"authorization": f"Bearer {auth_token}"})
175
+ if not (200 <= r.status_code < 300):
176
+ raise RuntimeError(f"Failed to refresh OIDC token: {r.status_code} {r.reason_phrase}")
177
+ data = r.json()
178
+ if not isinstance(data, dict) or not isinstance(data.get("token"), str):
179
+ raise TypeError("Expected a string-valued token property")
180
+ return VercelTokenResponse(token=data["token"])
181
+
182
+
183
+ async def fetch_vercel_oidc_token_async(
184
+ auth_token: str, project_id: str, team_id: str | None
185
+ ) -> VercelTokenResponse | None:
186
+ url = f"{BASE_URL}/projects/{project_id}/token?source=vercel-oidc-refresh"
187
+ if team_id:
188
+ url += f"&teamId={team_id}"
189
+ async with httpx.AsyncClient(timeout=httpx.Timeout(30.0)) as client:
190
+ r = await client.post(url, headers={"authorization": f"Bearer {auth_token}"})
191
+ if not (200 <= r.status_code < 300):
192
+ raise RuntimeError(f"Failed to refresh OIDC token: {r.status_code} {r.reason_phrase}")
193
+ data = r.json()
194
+ if not isinstance(data, dict) or not isinstance(data.get("token"), str):
195
+ raise TypeError("Expected a string-valued token property")
196
+ return VercelTokenResponse(token=data["token"])
197
+
198
+
199
+ def decode_oidc_payload(token: str) -> dict:
200
+ return get_token_payload(token)
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TypedDict
5
+
6
+
7
+ class ProjectInfo(TypedDict):
8
+ projectId: str
9
+ teamId: str | None
10
+
11
+
12
+ @dataclass
13
+ class VercelTokenResponse:
14
+ token: str
15
+
16
+
17
+ @dataclass
18
+ class Credentials:
19
+ token: str
20
+ project_id: str
21
+ team_id: str
@@ -0,0 +1,145 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import os
6
+ import sys
7
+ from typing import Any
8
+
9
+ from .types import ProjectInfo, VercelTokenResponse
10
+
11
+
12
+ def _user_data_dir() -> str | None:
13
+ try:
14
+ home = os.path.expanduser("~")
15
+ if sys.platform.startswith("win"):
16
+ # Prefer LOCALAPPDATA for application data storage on Windows
17
+ return os.environ.get("LOCALAPPDATA")
18
+ if sys.platform == "darwin":
19
+ return os.path.join(home, "Library", "Application Support")
20
+ # linux and others
21
+ xdg_data_home = os.environ.get("XDG_DATA_HOME")
22
+ return xdg_data_home or os.path.join(home, ".local", "share")
23
+ except Exception:
24
+ return None
25
+
26
+
27
+ def get_vercel_data_dir() -> str | None:
28
+ base = _user_data_dir()
29
+ if not base:
30
+ return None
31
+ return os.path.join(base, "com.vercel.cli")
32
+
33
+
34
+ def get_vercel_cli_token() -> str | None:
35
+ data_dir = get_vercel_data_dir()
36
+ if not data_dir:
37
+ return None
38
+ token_path = os.path.join(data_dir, "auth.json")
39
+ if not os.path.exists(token_path):
40
+ return None
41
+ try:
42
+ with open(token_path, encoding="utf-8") as f:
43
+ data = json.load(f)
44
+ token = data.get("token")
45
+ if isinstance(token, str) and token:
46
+ return token
47
+ return None
48
+ except Exception:
49
+ return None
50
+
51
+
52
+ def _find_root_dir(start: str | None = None) -> str | None:
53
+ # Walk up from start (or cwd) looking for a .vercel folder (align with TS SDK)
54
+ current = os.path.abspath(start or os.getcwd())
55
+ while True:
56
+ vercel_dir = os.path.join(current, ".vercel")
57
+ if os.path.isdir(vercel_dir):
58
+ return current
59
+ parent = os.path.dirname(current)
60
+ if parent == current:
61
+ return None
62
+ current = parent
63
+
64
+
65
+ def find_project_info() -> ProjectInfo:
66
+ root = _find_root_dir()
67
+ if not root:
68
+ raise RuntimeError("Unable to find root directory")
69
+ prj_path = os.path.join(root, ".vercel", "project.json")
70
+ if not os.path.exists(prj_path):
71
+ raise RuntimeError("project.json not found")
72
+ try:
73
+ with open(prj_path, encoding="utf-8") as f:
74
+ prj = json.load(f)
75
+ project_id = prj.get("projectId")
76
+ team_id = prj.get("orgId") if isinstance(prj.get("orgId"), str) else None
77
+ if not isinstance(project_id, str):
78
+ raise TypeError("Expected a string-valued projectId property")
79
+ return {"projectId": project_id, "teamId": team_id}
80
+ except Exception as e:
81
+ raise RuntimeError("Unable to find project ID") from e
82
+
83
+
84
+ def _token_store_dir() -> str | None:
85
+ base = _user_data_dir()
86
+ if not base:
87
+ return None
88
+ return os.path.join(base, "com.vercel.token")
89
+
90
+
91
+ def save_token(token: VercelTokenResponse, project_id: str) -> None:
92
+ directory = _token_store_dir()
93
+ if not directory:
94
+ raise RuntimeError("Unable to find user data directory")
95
+ try:
96
+ os.makedirs(directory, mode=0o700, exist_ok=True)
97
+ token_path = os.path.join(directory, f"{project_id}.json")
98
+ with open(token_path, "w", encoding="utf-8") as f:
99
+ json.dump({"token": token.token}, f)
100
+ try:
101
+ os.chmod(token_path, 0o600)
102
+ except Exception:
103
+ pass
104
+ except Exception as e:
105
+ raise RuntimeError("Failed to save token") from e
106
+
107
+
108
+ def load_token(project_id: str) -> VercelTokenResponse | None:
109
+ directory = _token_store_dir()
110
+ if not directory:
111
+ return None
112
+ token_path = os.path.join(directory, f"{project_id}.json")
113
+ if not os.path.exists(token_path):
114
+ return None
115
+ try:
116
+ with open(token_path, encoding="utf-8") as f:
117
+ data = json.load(f)
118
+ token = data.get("token")
119
+ if isinstance(token, str):
120
+ return VercelTokenResponse(token=token)
121
+ return None
122
+ except Exception as e:
123
+ raise RuntimeError("Failed to load token") from e
124
+
125
+
126
+ def get_token_payload(token: str) -> dict[str, Any]:
127
+ parts = token.split(".")
128
+ if len(parts) != 3:
129
+ raise ValueError("Invalid token")
130
+ base64_part = parts[1].replace("-", "+").replace("_", "/")
131
+ padded = base64_part + "=" * ((4 - (len(base64_part) % 4)) % 4)
132
+ decoded = base64.b64decode(padded)
133
+ return json.loads(decoded.decode("utf-8"))
134
+
135
+
136
+ def is_expired(payload: dict[str, Any]) -> bool:
137
+ # Consider token expired if it will expire within the next 15 minutes
138
+ exp = payload.get("exp")
139
+ if not isinstance(exp, (int, float)):
140
+ return True
141
+ import time
142
+
143
+ fifteen_minutes_ms = 15 * 60 * 1000
144
+ now_ms = int(time.time() * 1000)
145
+ return int(exp * 1000) < now_ms + fifteen_minutes_ms
@@ -0,0 +1 @@
1
+ __version__ = "0.6.0"