vercel-oidc-bundle 0.7.1__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,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,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: vercel-oidc-bundle
3
+ Version: 0.7.1
4
+ Summary: OIDC helpers for Vercel Python applications
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: vercel-headers-bundle>=0.7.1
9
+ Requires-Dist: vercel-internal-shared-vendored-deps>=0.1.0
10
+ Description-Content-Type: text/markdown
11
+
12
+ # vercel-oidc-bundle
13
+
14
+ This is a version of `vercel-oidc` with third-party dependencies bundled. For normal use, install the unbundled `vercel-oidc` package instead: https://pypi.org/project/vercel-oidc/
15
+
16
+ # OIDC
17
+
18
+ `vercel.oidc` retrieves and decodes Vercel OIDC tokens.
19
+
20
+ ## Async Token Lookup
21
+
22
+ ```python
23
+ from vercel.oidc import decode_oidc_payload
24
+ from vercel.headers import set_headers
25
+ from vercel.oidc.aio import get_vercel_oidc_token
26
+
27
+
28
+ async def main() -> None:
29
+ token = await get_vercel_oidc_token()
30
+ payload = decode_oidc_payload(token)
31
+ project_id = payload.get("project_id")
32
+ ```
33
+
34
+ Token lookup prefers the `x-vercel-oidc-token` request header registered with
35
+ `vercel.headers.set_headers()`, then `VERCEL_OIDC_TOKEN`. The compatibility
36
+ alias `vercel.oidc.set_headers()` updates the same header context. In local development,
37
+ you can load a short-lived token dynamically:
38
+
39
+ ```bash
40
+ VERCEL_OIDC_TOKEN=$(vc project token some-project) some-command
41
+ ```
42
+
43
+ Use `vercel.oidc.get_vercel_oidc_token()` for synchronous code.
@@ -0,0 +1,32 @@
1
+ # vercel-oidc-bundle
2
+
3
+ This is a version of `vercel-oidc` with third-party dependencies bundled. For normal use, install the unbundled `vercel-oidc` package instead: https://pypi.org/project/vercel-oidc/
4
+
5
+ # OIDC
6
+
7
+ `vercel.oidc` retrieves and decodes Vercel OIDC tokens.
8
+
9
+ ## Async Token Lookup
10
+
11
+ ```python
12
+ from vercel.oidc import decode_oidc_payload
13
+ from vercel.headers import set_headers
14
+ from vercel.oidc.aio import get_vercel_oidc_token
15
+
16
+
17
+ async def main() -> None:
18
+ token = await get_vercel_oidc_token()
19
+ payload = decode_oidc_payload(token)
20
+ project_id = payload.get("project_id")
21
+ ```
22
+
23
+ Token lookup prefers the `x-vercel-oidc-token` request header registered with
24
+ `vercel.headers.set_headers()`, then `VERCEL_OIDC_TOKEN`. The compatibility
25
+ alias `vercel.oidc.set_headers()` updates the same header context. In local development,
26
+ you can load a short-lived token dynamically:
27
+
28
+ ```bash
29
+ VERCEL_OIDC_TOKEN=$(vc project token some-project) some-command
30
+ ```
31
+
32
+ Use `vercel.oidc.get_vercel_oidc_token()` for synchronous code.
@@ -0,0 +1,116 @@
1
+ """Hatch metadata hook for publish-time workspace dependency bounds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
10
+ from packaging.requirements import Requirement
11
+
12
+ try:
13
+ import tomllib
14
+ except ModuleNotFoundError: # pragma: no cover - Python < 3.11
15
+ import tomli as tomllib # type: ignore[no-redef]
16
+
17
+
18
+ class WorkspaceDependenciesMetadataHook(MetadataHookInterface):
19
+ """Generate package dependencies from the repo-owned dependency table."""
20
+
21
+ def update(self, metadata: dict[str, Any]) -> None:
22
+ """Populate dynamic dependencies for Hatchling metadata generation."""
23
+ pyproject = _load_pyproject(Path(self.root))
24
+ release = pyproject.get("tool", {}).get("vercel", {}).get("release", {})
25
+ dependency_table = release.get("dependencies", {})
26
+ workspace_sources = pyproject.get("tool", {}).get("uv", {}).get("sources", {})
27
+ workspace_names = {
28
+ name for name, source in workspace_sources.items() if source.get("workspace") is True
29
+ }
30
+ workspace_root = _find_workspace_root(Path(self.root))
31
+
32
+ metadata["dependencies"] = [
33
+ _rewrite_dependency(requirement, workspace_names, workspace_root)
34
+ for requirement in dependency_table.get("dependencies", [])
35
+ ]
36
+
37
+
38
+ def _load_pyproject(path: Path) -> dict[str, Any]:
39
+ with (path / "pyproject.toml").open("rb") as fp:
40
+ return tomllib.load(fp)
41
+
42
+
43
+ def _find_workspace_root(start: Path) -> Path | None:
44
+ for path in [start, *start.parents]:
45
+ pyproject = path / "pyproject.toml"
46
+ if not pyproject.exists():
47
+ continue
48
+ data = _load_pyproject(path)
49
+ if "workspace" in data.get("tool", {}).get("uv", {}):
50
+ return path
51
+ return None
52
+
53
+
54
+ def _rewrite_dependency(
55
+ requirement: str,
56
+ workspace_names: set[str],
57
+ workspace_root: Path | None,
58
+ ) -> str:
59
+ parsed = Requirement(requirement)
60
+ normalized = parsed.name.lower().replace("_", "-")
61
+ if normalized not in workspace_names or workspace_root is None:
62
+ return requirement
63
+ return _with_lower_bound(parsed, _read_workspace_version(workspace_root, normalized))
64
+
65
+
66
+ def _with_lower_bound(requirement: Requirement, version: str) -> str:
67
+ extras = f"[{','.join(sorted(requirement.extras))}]" if requirement.extras else ""
68
+ specifiers = [
69
+ str(specifier) for specifier in requirement.specifier if specifier.operator != ">="
70
+ ]
71
+ specifier_text = ",".join([f">={version}", *specifiers])
72
+ marker = f" ; {requirement.marker}" if requirement.marker else ""
73
+ return f"{requirement.name}{extras}{specifier_text}{marker}"
74
+
75
+
76
+ def _read_workspace_version(workspace_root: Path, package_name: str) -> str:
77
+ for pattern in ("src/*/pyproject.toml", "integrations/*/pyproject.toml"):
78
+ for pyproject_path in workspace_root.glob(pattern):
79
+ version = _version_from_pyproject(pyproject_path, package_name)
80
+ if version is not None:
81
+ return version
82
+ raise RuntimeError(f"unknown workspace dependency {package_name!r}")
83
+
84
+
85
+ def _version_from_pyproject(pyproject_path: Path, package_name: str) -> str | None:
86
+ data = _load_pyproject(pyproject_path.parent)
87
+ if data.get("project", {}).get("name") != package_name:
88
+ return None
89
+ version_path = pyproject_path.parent / data["tool"]["hatch"]["version"]["path"]
90
+ module = ast.parse(version_path.read_text(encoding="utf-8"), filename=str(version_path))
91
+ for node in module.body:
92
+ value = _version_value(node)
93
+ if value is None:
94
+ continue
95
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
96
+ return value.value
97
+ raise RuntimeError(f"could not find __version__ in {version_path}")
98
+
99
+
100
+ def _version_value(node: ast.stmt) -> ast.expr | None:
101
+ if isinstance(node, ast.Assign) and any(
102
+ isinstance(target, ast.Name) and target.id == "__version__" for target in node.targets
103
+ ):
104
+ return node.value
105
+ if (
106
+ isinstance(node, ast.AnnAssign)
107
+ and isinstance(node.target, ast.Name)
108
+ and node.target.id == "__version__"
109
+ ):
110
+ return node.value
111
+ return None
112
+
113
+
114
+ def get_metadata_hook() -> type[MetadataHookInterface]:
115
+ """Return the hook class used by Hatchling's custom hook loader."""
116
+ return WorkspaceDependenciesMetadataHook
@@ -0,0 +1,29 @@
1
+ """Load the shared Vercel Hatch metadata hook."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.util import module_from_spec, spec_from_file_location
6
+ from pathlib import Path
7
+ from types import ModuleType
8
+
9
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
10
+
11
+
12
+ def get_metadata_hook() -> type[MetadataHookInterface]:
13
+ """Return the shared workspace dependency metadata hook."""
14
+ return _load_shared_hook().get_metadata_hook()
15
+
16
+
17
+ def _load_shared_hook() -> ModuleType:
18
+ root = Path(__file__).resolve().parent
19
+ candidates = [root / "../../scripts/hatch_build.py", root / "_vercel_hatch_build.py"]
20
+ for candidate in candidates:
21
+ path = candidate.resolve()
22
+ if path.exists():
23
+ spec = spec_from_file_location("_vercel_hatch_build", path)
24
+ if spec is None or spec.loader is None:
25
+ raise RuntimeError(f"could not load Hatch hook from {path}")
26
+ module = module_from_spec(spec)
27
+ spec.loader.exec_module(module)
28
+ return module
29
+ raise RuntimeError("could not find shared Vercel Hatch metadata hook")
@@ -0,0 +1,79 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27.0,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "vercel-oidc-bundle"
7
+ dynamic = ["version", "dependencies"]
8
+ description = "OIDC helpers for Vercel Python applications"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = [
13
+ "LICENSE",
14
+ "LICENSE.*",
15
+ "vercel/oidc/_vendor/LICEN[CS]E*",
16
+ ]
17
+
18
+ [tool.hatch.metadata.hooks.custom]
19
+ path = "hatch_build.py"
20
+
21
+ [tool.vercel.release.dependencies]
22
+ dependencies = [
23
+ "vercel-headers-bundle>=0.7.1",
24
+ "vercel-internal-shared-vendored-deps>=0.1.0",
25
+ ]
26
+
27
+ [tool.uv.sources]
28
+ vercel-headers = { workspace = true }
29
+
30
+ [tool.hatch.version]
31
+ path = "vercel/oidc/version.py"
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ force-include = { "_vercel_hatch_build.py" = "/_vercel_hatch_build.py" }
35
+ include = [
36
+ "/vercel/oidc/**/*.py",
37
+ "/README.md",
38
+ "/vercel/oidc/py.typed",
39
+ "/pyproject.toml",
40
+ "/hatch_build.py",
41
+ "/LICENSE",
42
+ "/vercel/oidc/_vendor/LICEN[CS]E*",
43
+ ]
44
+ exclude = [
45
+ "/**/__pycache__",
46
+ ]
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ dev-mode-dirs = ["."]
50
+ only-include = ["/vercel/oidc"]
51
+ exclude = [
52
+ "/**/__pycache__",
53
+ ]
54
+
55
+ [tool.poe]
56
+ include = "../../scripts/poe/poe.toml"
57
+ verbosity = -1
58
+
59
+ [tool.poe.tasks.typecheck]
60
+ cmd = "$MYPY"
61
+
62
+ [tool.poe.tasks.test]
63
+ cmd = "python -c \"pass\""
64
+
65
+ [tool.vendoring]
66
+ destination = "vercel/oidc/_vendor/"
67
+ requirements = "vercel/oidc/_vendor/vendor.txt"
68
+ namespace = "vercel.oidc._vendor"
69
+ protected-files = [
70
+ "__init__.py",
71
+ "vendor.txt",
72
+ ]
73
+
74
+ [tool.vendoring.transformations]
75
+ drop = [
76
+ "*.so",
77
+ "*/tests/",
78
+ "*/__pycache__/",
79
+ ]
@@ -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 @@
1
+ """Generated vendored dependencies for vercel-oidc-bundle."""
@@ -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,275 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import threading
5
+ import time
6
+ from collections.abc import Mapping
7
+ from typing import Any
8
+
9
+ from vercel.internal._vendor import httpx
10
+
11
+ from vercel.headers import get_headers
12
+
13
+ from .types import VercelTokenResponse
14
+ from .utils import (
15
+ find_project_info,
16
+ get_token_payload,
17
+ get_vercel_cli_token,
18
+ is_expired,
19
+ load_token,
20
+ save_token,
21
+ )
22
+
23
+ BASE_URL = "https://api.vercel.com/v1"
24
+ _cached_oidc_token_lock = threading.Lock()
25
+ _cached_oidc_token: str | None = None
26
+ _cached_oidc_payload: dict[str, Any] | None = None
27
+
28
+
29
+ class VercelOidcTokenError(Exception):
30
+ def __init__(self, message: str, cause: Exception | None = None):
31
+ if cause is not None:
32
+ message = f"{message}: {cause}"
33
+ super().__init__(message)
34
+ self.cause = cause
35
+
36
+
37
+ def get_vercel_oidc_token_from_context() -> str:
38
+ # Prefer request header registered in the OIDC context,
39
+ # fall back to environment variable like the TypeScript SDK.
40
+ token_from_header = _token_from_headers(get_headers())
41
+ if token_from_header:
42
+ token = _select_header_or_cached_token(token_from_header)
43
+ if token is not None:
44
+ return token
45
+ else:
46
+ token_from_cache = _get_cached_unexpired_token()
47
+ if token_from_cache is not None:
48
+ return token_from_cache
49
+
50
+ token_from_env = os.getenv("VERCEL_OIDC_TOKEN")
51
+ if not token_from_env:
52
+ raise VercelOidcTokenError(
53
+ "The 'x-vercel-oidc-token' header is missing from the request. "
54
+ "Do you have the OIDC option enabled in the Vercel project settings?"
55
+ )
56
+ return token_from_env
57
+
58
+
59
+ def _token_from_headers(headers: object) -> str | None:
60
+ if not headers:
61
+ return None
62
+ lower_headers: dict[str, str] = {}
63
+ if isinstance(headers, Mapping):
64
+ for k, v in headers.items():
65
+ lower_headers[str(k).lower()] = v
66
+ elif isinstance(headers, (list, tuple)):
67
+ for item in headers:
68
+ if isinstance(item, (list, tuple)) and len(item) == 2:
69
+ k, v = item
70
+ lower_headers[str(k).lower()] = v
71
+ elif hasattr(headers, "keys") and hasattr(headers, "__getitem__"):
72
+ for k in headers.keys():
73
+ v = headers[k]
74
+ lower_headers[str(k).lower()] = v
75
+ return lower_headers.get("x-vercel-oidc-token")
76
+
77
+
78
+ def _select_header_or_cached_token(token: str) -> str | None:
79
+ try:
80
+ payload = get_token_payload(token)
81
+ except Exception:
82
+ return token
83
+ if _is_past_expiration(payload):
84
+ return _get_cached_unexpired_token()
85
+
86
+ with _cached_oidc_token_lock:
87
+ global _cached_oidc_payload, _cached_oidc_token
88
+ if _cached_oidc_token is None or _cached_oidc_payload is None:
89
+ _cached_oidc_token = token
90
+ _cached_oidc_payload = payload
91
+ return token
92
+ if _is_past_expiration(_cached_oidc_payload):
93
+ _cached_oidc_token = token
94
+ _cached_oidc_payload = payload
95
+ return token
96
+ if _expires_after(payload, _cached_oidc_payload):
97
+ _cached_oidc_token = token
98
+ _cached_oidc_payload = payload
99
+ return token
100
+ return _cached_oidc_token
101
+
102
+
103
+ def _get_cached_unexpired_token() -> str | None:
104
+ with _cached_oidc_token_lock:
105
+ global _cached_oidc_payload, _cached_oidc_token
106
+ if _cached_oidc_token is None or _cached_oidc_payload is None:
107
+ return None
108
+ if _is_past_expiration(_cached_oidc_payload):
109
+ _cached_oidc_token = None
110
+ _cached_oidc_payload = None
111
+ return None
112
+ return _cached_oidc_token
113
+
114
+
115
+ def _is_past_expiration(payload: dict[str, Any]) -> bool:
116
+ exp = payload.get("exp")
117
+ if not isinstance(exp, (int, float)):
118
+ return True
119
+ return exp <= time.time()
120
+
121
+
122
+ def _expires_after(left: dict[str, Any], right: dict[str, Any]) -> bool:
123
+ left_exp = left.get("exp")
124
+ right_exp = right.get("exp")
125
+ if not isinstance(left_exp, (int, float)):
126
+ return False
127
+ if not isinstance(right_exp, (int, float)):
128
+ return True
129
+ return left_exp > right_exp
130
+
131
+
132
+ def _clear_cached_oidc_token() -> None:
133
+ with _cached_oidc_token_lock:
134
+ global _cached_oidc_payload, _cached_oidc_token
135
+ _cached_oidc_token = None
136
+ _cached_oidc_payload = None
137
+
138
+
139
+ # for TS parity
140
+ get_vercel_oidc_token_sync = get_vercel_oidc_token_from_context
141
+
142
+
143
+ def refresh_token() -> None:
144
+ project = find_project_info()
145
+ project_id: str = project["projectId"]
146
+ team_id = project.get("teamId")
147
+
148
+ maybe = load_token(project_id)
149
+ if not maybe or is_expired(get_token_payload(maybe.token)):
150
+ auth_token = get_vercel_cli_token()
151
+ if not auth_token:
152
+ raise VercelOidcTokenError("Failed to refresh OIDC token: login to vercel cli")
153
+ if not project_id:
154
+ raise VercelOidcTokenError("Failed to refresh OIDC token: project id not found")
155
+ new_token = fetch_vercel_oidc_token(auth_token, project_id, team_id)
156
+ if not new_token:
157
+ raise VercelOidcTokenError("Failed to refresh OIDC token")
158
+ save_token(new_token, project_id)
159
+ os.environ["VERCEL_OIDC_TOKEN"] = new_token.token
160
+ else:
161
+ os.environ["VERCEL_OIDC_TOKEN"] = maybe.token
162
+
163
+
164
+ async def refresh_token_async() -> None:
165
+ project = find_project_info()
166
+ project_id: str = project["projectId"]
167
+ team_id = project.get("teamId")
168
+
169
+ maybe = load_token(project_id)
170
+ if not maybe or is_expired(get_token_payload(maybe.token)):
171
+ auth_token = get_vercel_cli_token()
172
+ if not auth_token:
173
+ raise VercelOidcTokenError("Failed to refresh OIDC token: login to vercel cli")
174
+ if not project_id:
175
+ raise VercelOidcTokenError("Failed to refresh OIDC token: project id not found")
176
+ new_token = await fetch_vercel_oidc_token_async(auth_token, project_id, team_id)
177
+ if not new_token:
178
+ raise VercelOidcTokenError("Failed to refresh OIDC token")
179
+ save_token(new_token, project_id)
180
+ os.environ["VERCEL_OIDC_TOKEN"] = new_token.token
181
+ else:
182
+ os.environ["VERCEL_OIDC_TOKEN"] = maybe.token
183
+
184
+
185
+ def get_vercel_oidc_token() -> str:
186
+ token = ""
187
+ err: Exception | None = None
188
+ try:
189
+ token = get_vercel_oidc_token_from_context()
190
+ except Exception as e:
191
+ err = e
192
+ try:
193
+ if not token or is_expired(get_token_payload(token)):
194
+ # Only attempt refresh in environments that look like local dev with a .vercel folder
195
+ try:
196
+ _ = find_project_info()
197
+ except Exception as e:
198
+ # Preserve the original context error and surface an actionable message
199
+ if err and isinstance(err, Exception) and getattr(err, "message", None):
200
+ e.args = (f"{err}\n{e}",)
201
+ raise VercelOidcTokenError(
202
+ "Missing OIDC request header and no local project context (.vercel) available",
203
+ e,
204
+ ) from e
205
+ refresh_token()
206
+ token = get_vercel_oidc_token_from_context()
207
+ except Exception as e:
208
+ if err and isinstance(e, Exception) and getattr(err, "message", None):
209
+ e.args = (f"{err}\n{e}",)
210
+ raise VercelOidcTokenError("Failed to refresh OIDC token", e) from e
211
+ return token
212
+
213
+
214
+ async def get_vercel_oidc_token_async() -> str:
215
+ token = ""
216
+ err: Exception | None = None
217
+ try:
218
+ token = get_vercel_oidc_token_from_context()
219
+ except Exception as e:
220
+ err = e
221
+ try:
222
+ if not token or is_expired(get_token_payload(token)):
223
+ # Only attempt refresh in environments that look like local dev with a .vercel folder
224
+ try:
225
+ _ = find_project_info()
226
+ except Exception as e:
227
+ if err and isinstance(err, Exception) and getattr(err, "message", None):
228
+ e.args = (f"{err}\n{e}",)
229
+ raise VercelOidcTokenError(
230
+ "Missing OIDC request header and no local project context (.vercel) available",
231
+ e,
232
+ ) from e
233
+ await refresh_token_async()
234
+ token = get_vercel_oidc_token_from_context()
235
+ except Exception as e:
236
+ if err and isinstance(e, Exception) and getattr(err, "message", None):
237
+ e.args = (f"{err}\n{e}",)
238
+ raise VercelOidcTokenError("Failed to refresh OIDC token", e) from e
239
+ return token
240
+
241
+
242
+ def fetch_vercel_oidc_token(
243
+ auth_token: str, project_id: str, team_id: str | None
244
+ ) -> VercelTokenResponse | None:
245
+ url = f"{BASE_URL}/projects/{project_id}/token?source=vercel-oidc-refresh"
246
+ if team_id:
247
+ url += f"&teamId={team_id}"
248
+ with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
249
+ r = client.post(url, headers={"authorization": f"Bearer {auth_token}"})
250
+ if not (200 <= r.status_code < 300):
251
+ raise RuntimeError(f"Failed to refresh OIDC token: {r.status_code} {r.reason_phrase}")
252
+ data = r.json()
253
+ if not isinstance(data, dict) or not isinstance(data.get("token"), str):
254
+ raise TypeError("Expected a string-valued token property")
255
+ return VercelTokenResponse(token=data["token"])
256
+
257
+
258
+ async def fetch_vercel_oidc_token_async(
259
+ auth_token: str, project_id: str, team_id: str | None
260
+ ) -> VercelTokenResponse | None:
261
+ url = f"{BASE_URL}/projects/{project_id}/token?source=vercel-oidc-refresh"
262
+ if team_id:
263
+ url += f"&teamId={team_id}"
264
+ async with httpx.AsyncClient(timeout=httpx.Timeout(30.0)) as client:
265
+ r = await client.post(url, headers={"authorization": f"Bearer {auth_token}"})
266
+ if not (200 <= r.status_code < 300):
267
+ raise RuntimeError(f"Failed to refresh OIDC token: {r.status_code} {r.reason_phrase}")
268
+ data = r.json()
269
+ if not isinstance(data, dict) or not isinstance(data.get("token"), str):
270
+ raise TypeError("Expected a string-valued token property")
271
+ return VercelTokenResponse(token=data["token"])
272
+
273
+
274
+ def decode_oidc_payload(token: str) -> dict:
275
+ 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.7.1"