lupaxa-token-decoder 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,24 @@
1
+ # OS
2
+ .DS_Store
3
+
4
+ # Cursor
5
+ .cursor/
6
+ .superpowers/
7
+ .worktrees/
8
+ cursor-docs
9
+
10
+ # Make
11
+ .makefiles/
12
+
13
+ # MkDocs
14
+ site/
15
+
16
+ # Python
17
+ .venv/
18
+ __pycache__/
19
+ .mypy_cache/
20
+ .ruff_cache/
21
+ .pytest_cache/
22
+ dist/
23
+ build/
24
+ *.egg-info/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) The Lupaxa Project
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,124 @@
1
+ Metadata-Version: 2.5
2
+ Name: lupaxa-token-decoder
3
+ Version: 0.1.0
4
+ Summary: Decode and inspect JWTs and other common token formats.
5
+ Project-URL: Homepage, https://github.com/lupaxa-security-toolbox/token-decoder
6
+ Project-URL: Repository, https://github.com/lupaxa-security-toolbox/token-decoder
7
+ Project-URL: Issues, https://github.com/lupaxa-security-toolbox/token-decoder/issues
8
+ Author: The Lupaxa Project
9
+ License: MIT License
10
+
11
+ Copyright (c) The Lupaxa Project
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENCE
31
+ Keywords: cli,decoder,jwt,security,token
32
+ Classifier: Development Status :: 3 - Alpha
33
+ Classifier: Environment :: Console
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: MacOS
36
+ Classifier: Operating System :: Microsoft :: Windows
37
+ Classifier: Operating System :: POSIX :: Linux
38
+ Classifier: Programming Language :: Python :: 3
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Programming Language :: Python :: 3.14
43
+ Classifier: Topic :: Security
44
+ Classifier: Topic :: Utilities
45
+ Requires-Python: >=3.11
46
+ Provides-Extra: dev
47
+ Requires-Dist: bump-my-version>=1.2.0; extra == 'dev'
48
+ Requires-Dist: mypy>=1.12.0; extra == 'dev'
49
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
50
+ Requires-Dist: pytest>=8.0; extra == 'dev'
51
+ Requires-Dist: ruff>=0.6.0; extra == 'dev'
52
+ Provides-Extra: test
53
+ Requires-Dist: pytest-cov>=5.0; extra == 'test'
54
+ Requires-Dist: pytest>=8.0; extra == 'test'
55
+ Description-Content-Type: text/markdown
56
+
57
+ <p align="center">
58
+ <a href="https://github.com/lupaxa-security-toolbox">
59
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/organisations/security-toolbox/readme-logo.png" alt="Security Toolbox" />
60
+ </a>
61
+ </p>
62
+
63
+ <h1 align="center">Token Decoder</h1>
64
+
65
+ Token Decoder inspects a JWT or another common token and prints a JSON report. It does not verify signatures and it does not decrypt JWE payloads.
66
+
67
+ The library import is `lupaxa.token_decoder`. The command is `token-decoder`.
68
+
69
+ ## Install
70
+
71
+ Python 3.11 or newer. There are no runtime dependencies.
72
+
73
+ ```bash
74
+ pip install lupaxa-token-decoder
75
+ ```
76
+
77
+ ## Quick Start
78
+
79
+ Pass a token, or pipe one line on stdin:
80
+
81
+ ```bash
82
+ token-decoder "$TOKEN"
83
+ printf '%s\n' "$TOKEN" | token-decoder
84
+ ```
85
+
86
+ With no argument, a terminal prompts on stderr. The JSON report is written to stdout.
87
+
88
+ > **Note:** A token passed as an argument can be stored in your shell history. Pipe it on stdin when that matters. `signature_verified` is always false. This tool never checks a signature and never decrypts a JWE.
89
+
90
+ ## Library
91
+
92
+ ```python
93
+ from lupaxa.token_decoder import decode_token
94
+
95
+ print(decode_token(token)["type"])
96
+ ```
97
+
98
+ `lupaxa` is a namespace package. There is no `lupaxa/__init__.py`.
99
+
100
+ ## What it Decodes
101
+
102
+ | Type | When |
103
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------ |
104
+ | JWT | Three segments whose header is JSON and contains `alg`. `exp`, `iat`, and `nbf` gain a UTC reading beside the raw value. |
105
+ | JWE | Five segments whose header is JSON and contains `enc`. The ciphertext is reported, not decrypted. |
106
+ | JSON | The token itself is a JSON document. |
107
+ | Hexadecimal | An even-length hex string. UTF-8 text is included when the bytes decode. |
108
+ | Base64 / Base64URL | Standard or URL-safe Base64 that decodes to UTF-8. JSON text is parsed. |
109
+ | Opaque / Unknown | None of the formats above. |
110
+
111
+ A leading `Bearer` prefix is ignored. Line wrapping is removed except inside a JSON document.
112
+
113
+ ## Command Line Options
114
+
115
+ | Option | Meaning |
116
+ | -------------- | ----------------------------------- |
117
+ | `TOKEN` | Token to decode. |
118
+ | `-` | Read one line from stdin. |
119
+ | `--help`, `-h` | Print the command summary and exit. |
120
+ | `--version` | Print the version and exit. |
121
+
122
+ <a href="https://github.com/the-lupaxa-project">
123
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/components/footer-for-child-orgs.svg" alt="The Lupaxa Project Footer" width="100%" />
124
+ </a>
@@ -0,0 +1,68 @@
1
+ <p align="center">
2
+ <a href="https://github.com/lupaxa-security-toolbox">
3
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/organisations/security-toolbox/readme-logo.png" alt="Security Toolbox" />
4
+ </a>
5
+ </p>
6
+
7
+ <h1 align="center">Token Decoder</h1>
8
+
9
+ Token Decoder inspects a JWT or another common token and prints a JSON report. It does not verify signatures and it does not decrypt JWE payloads.
10
+
11
+ The library import is `lupaxa.token_decoder`. The command is `token-decoder`.
12
+
13
+ ## Install
14
+
15
+ Python 3.11 or newer. There are no runtime dependencies.
16
+
17
+ ```bash
18
+ pip install lupaxa-token-decoder
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ Pass a token, or pipe one line on stdin:
24
+
25
+ ```bash
26
+ token-decoder "$TOKEN"
27
+ printf '%s\n' "$TOKEN" | token-decoder
28
+ ```
29
+
30
+ With no argument, a terminal prompts on stderr. The JSON report is written to stdout.
31
+
32
+ > **Note:** A token passed as an argument can be stored in your shell history. Pipe it on stdin when that matters. `signature_verified` is always false. This tool never checks a signature and never decrypts a JWE.
33
+
34
+ ## Library
35
+
36
+ ```python
37
+ from lupaxa.token_decoder import decode_token
38
+
39
+ print(decode_token(token)["type"])
40
+ ```
41
+
42
+ `lupaxa` is a namespace package. There is no `lupaxa/__init__.py`.
43
+
44
+ ## What it Decodes
45
+
46
+ | Type | When |
47
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------ |
48
+ | JWT | Three segments whose header is JSON and contains `alg`. `exp`, `iat`, and `nbf` gain a UTC reading beside the raw value. |
49
+ | JWE | Five segments whose header is JSON and contains `enc`. The ciphertext is reported, not decrypted. |
50
+ | JSON | The token itself is a JSON document. |
51
+ | Hexadecimal | An even-length hex string. UTF-8 text is included when the bytes decode. |
52
+ | Base64 / Base64URL | Standard or URL-safe Base64 that decodes to UTF-8. JSON text is parsed. |
53
+ | Opaque / Unknown | None of the formats above. |
54
+
55
+ A leading `Bearer` prefix is ignored. Line wrapping is removed except inside a JSON document.
56
+
57
+ ## Command Line Options
58
+
59
+ | Option | Meaning |
60
+ | -------------- | ----------------------------------- |
61
+ | `TOKEN` | Token to decode. |
62
+ | `-` | Read one line from stdin. |
63
+ | `--help`, `-h` | Print the command summary and exit. |
64
+ | `--version` | Print the version and exit. |
65
+
66
+ <a href="https://github.com/the-lupaxa-project">
67
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/components/footer-for-child-orgs.svg" alt="The Lupaxa Project Footer" width="100%" />
68
+ </a>
@@ -0,0 +1,23 @@
1
+ <p align="center">
2
+ <a href="https://github.com/lupaxa-security-toolbox">
3
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/organisations/security-toolbox/readme-logo.png" alt="Organisation Logo" />
4
+ </a>
5
+ </p>
6
+
7
+ <h1 align="center">Core Documentation</h1>
8
+
9
+ The following documents define the standards that apply across **The Lupaxa Project**:
10
+
11
+ | Document | Purpose |
12
+ | :------------------------------------ | :---------------------------------------------------------------- |
13
+ | [Code of Conduct](CODE_OF_CONDUCT.md) | Expected behaviour and reporting procedures. |
14
+ | [How to Contribute](CONTRIBUTING.md) | Development workflow, coding standards, and contribution process. |
15
+ | [Governance](GOVERNANCE.md) | Project governance, roles, and decision-making. |
16
+ | [Maintainers](MAINTAINERS.md) | Maintainer responsibilities and expectations. |
17
+ | [Projects Overview](PROJECTS.md) | Overview of organisations, repositories, and project structure. |
18
+ | [Security Policy](SECURITY.md) | Responsible disclosure and secure development practices. |
19
+ | [Support Guide](SUPPORT.md) | How to obtain help and support. |
20
+
21
+ <a href="https://github.com/the-lupaxa-project">
22
+ <img src="https://raw.githubusercontent.com/the-lupaxa-project/brand-assets/master/logos/components/footer-for-child-orgs.svg" alt="The Lupaxa Project Footer" width="100%" />
23
+ </a>
@@ -0,0 +1,138 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.18"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lupaxa-token-decoder"
7
+ dynamic = ["version"]
8
+ description = "Decode and inspect JWTs and other common token formats."
9
+ readme = "README.md"
10
+ license = { file = "LICENCE" }
11
+ requires-python = ">=3.11"
12
+ authors = [
13
+ { name = "The Lupaxa Project" },
14
+ ]
15
+ keywords = [
16
+ "jwt",
17
+ "token",
18
+ "decoder",
19
+ "cli",
20
+ "security",
21
+ ]
22
+ dependencies = []
23
+ classifiers = [
24
+ "Development Status :: 3 - Alpha",
25
+ "Environment :: Console",
26
+ "License :: OSI Approved :: MIT License",
27
+ "Operating System :: MacOS",
28
+ "Operating System :: Microsoft :: Windows",
29
+ "Operating System :: POSIX :: Linux",
30
+ "Programming Language :: Python :: 3",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Programming Language :: Python :: 3.14",
35
+ "Topic :: Security",
36
+ "Topic :: Utilities",
37
+ ]
38
+ [project.urls]
39
+ Homepage = "https://github.com/lupaxa-security-toolbox/token-decoder"
40
+ Repository = "https://github.com/lupaxa-security-toolbox/token-decoder"
41
+ Issues = "https://github.com/lupaxa-security-toolbox/token-decoder/issues"
42
+
43
+ [project.scripts]
44
+ token-decoder = "lupaxa.token_decoder.cli:main"
45
+
46
+ [project.optional-dependencies]
47
+ dev = [
48
+ "bump-my-version>=1.2.0",
49
+ "mypy>=1.12.0",
50
+ "pytest>=8.0",
51
+ "pytest-cov>=5.0",
52
+ "ruff>=0.6.0",
53
+ ]
54
+ test = [
55
+ "pytest>=8.0",
56
+ "pytest-cov>=5.0",
57
+ ]
58
+
59
+ [tool.hatch.version]
60
+ path = "src/lupaxa/token_decoder/version.py"
61
+
62
+ [tool.hatch.build.targets.sdist]
63
+ include = [
64
+ "src/**",
65
+ "README.md",
66
+ "LICENCE",
67
+ ]
68
+
69
+ [tool.hatch.build.targets.wheel]
70
+ packages = ["src/lupaxa"]
71
+
72
+ [tool.ruff]
73
+ line-length = 120
74
+ target-version = "py311"
75
+ src = ["src", "tests"]
76
+
77
+ [tool.ruff.lint]
78
+ select = [
79
+ "E",
80
+ "F",
81
+ "I",
82
+ "B",
83
+ "S",
84
+ "UP",
85
+ "SIM",
86
+ "C4",
87
+ "ISC",
88
+ "D",
89
+ "ANN",
90
+ "PT",
91
+ ]
92
+ ignore = [
93
+ "D100",
94
+ "D104",
95
+ "D107",
96
+ "D200",
97
+ "D201",
98
+ "D202",
99
+ "D203",
100
+ "D204",
101
+ "D205",
102
+ "D206",
103
+ "D207",
104
+ "D208",
105
+ "D209",
106
+ "D210",
107
+ "D211",
108
+ "D212",
109
+ "D213",
110
+ ]
111
+
112
+ [tool.ruff.lint.per-file-ignores]
113
+ "tests/**" = ["S101", "S105", "S106", "ANN001", "ANN201", "D101", "D102", "D103", "D105"]
114
+
115
+ [tool.ruff.lint.pydocstyle]
116
+ convention = "numpy"
117
+
118
+ [tool.basedpyright]
119
+ pythonVersion = "3.11"
120
+ typeCheckingMode = "standard"
121
+
122
+ [tool.mypy]
123
+ python_version = "3.11"
124
+ warn_unused_configs = true
125
+ warn_return_any = true
126
+ warn_unused_ignores = true
127
+ disallow_untyped_defs = true
128
+ follow_imports = "normal"
129
+ ignore_missing_imports = true
130
+ packages = ["lupaxa.token_decoder"]
131
+ mypy_path = "src"
132
+ explicit_package_bases = true
133
+ namespace_packages = true
134
+
135
+ [tool.pytest.ini_options]
136
+ addopts = "-ra --disable-warnings"
137
+ testpaths = ["tests"]
138
+ pythonpath = ["src"]
@@ -0,0 +1,6 @@
1
+ """Decode and inspect JWTs and other common token formats."""
2
+
3
+ from lupaxa.token_decoder.decode import decode_token
4
+ from lupaxa.token_decoder.version import __version__, get_version
5
+
6
+ __all__ = ["__version__", "decode_token", "get_version"]
@@ -0,0 +1,6 @@
1
+ """python -m lupaxa.token_decoder."""
2
+
3
+ from lupaxa.token_decoder.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,70 @@
1
+ """Slim command-line interface for token-decoder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from typing import TextIO
9
+
10
+ from lupaxa.token_decoder.decode import decode_token
11
+ from lupaxa.token_decoder.version import __version__
12
+
13
+
14
+ def build_parser() -> argparse.ArgumentParser:
15
+ """Return the command-line parser."""
16
+ parser = argparse.ArgumentParser(
17
+ prog="token-decoder",
18
+ description="Decode JWTs and other token formats. Signatures are not verified.",
19
+ )
20
+ parser.add_argument(
21
+ "token",
22
+ nargs="?",
23
+ help="Token to decode. Omit to read stdin, or to prompt when stdin is a terminal. Use - for stdin.",
24
+ )
25
+ parser.add_argument("--version", action="version", version=__version__)
26
+ return parser
27
+
28
+
29
+ def _is_tty(stream: TextIO) -> bool:
30
+ isatty = getattr(stream, "isatty", None)
31
+ if not callable(isatty):
32
+ return False
33
+ return bool(isatty())
34
+
35
+
36
+ def read_token(argument: str | None, stdin: TextIO) -> str:
37
+ """Return the token argument, or one line from stdin.
38
+
39
+ The prompt is written to stderr so a piped JSON report stays clean.
40
+
41
+ Parameters
42
+ ----------
43
+ argument:
44
+ The positional argument, or ``None`` when it was omitted.
45
+ stdin:
46
+ Stream to read when the argument is missing or is ``-``.
47
+ """
48
+ if argument is not None and argument != "-":
49
+ return argument
50
+ if _is_tty(stdin):
51
+ print("Token: ", end="", file=sys.stderr, flush=True)
52
+ return stdin.readline()
53
+
54
+
55
+ def main(argv: list[str] | None = None, stdin: TextIO | None = None) -> int:
56
+ """Decode one token and print a JSON report.
57
+
58
+ Parameters
59
+ ----------
60
+ argv:
61
+ Arguments to parse. Defaults to the process arguments.
62
+ stdin:
63
+ Token source when the argument is omitted. Defaults to ``sys.stdin``.
64
+ """
65
+ args = build_parser().parse_args(argv)
66
+ source = sys.stdin if stdin is None else stdin
67
+ report = decode_token(read_token(args.token, source))
68
+ json.dump(report, sys.stdout, indent=2, ensure_ascii=False)
69
+ sys.stdout.write("\n")
70
+ return 0
@@ -0,0 +1,314 @@
1
+ """Detect and decode JWTs and other common token formats.
2
+
3
+ Signatures are never verified. Compact JWE tokens are recognised and are
4
+ not decrypted.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import binascii
11
+ import json
12
+ import re
13
+ from contextlib import suppress
14
+ from datetime import UTC, datetime
15
+ from typing import Literal, TypeAlias, TypedDict, cast
16
+
17
+ Json: TypeAlias = dict[str, "Json"] | list["Json"] | str | int | float | bool | None
18
+
19
+
20
+ class JwtReport(TypedDict):
21
+ """Decoded compact JWT. The signature is not verified."""
22
+
23
+ type: Literal["JWT"]
24
+ header: dict[str, Json]
25
+ payload: Json | str
26
+ signature: str
27
+ signature_verified: Literal[False]
28
+
29
+
30
+ class JweReport(TypedDict):
31
+ """Recognised compact JWE. The payload is not decrypted."""
32
+
33
+ type: Literal["JWE"]
34
+ header: dict[str, Json]
35
+ encrypted_key: str
36
+ initialization_vector: str
37
+ ciphertext: str
38
+ authentication_tag: str
39
+ decrypted: Literal[False]
40
+
41
+
42
+ class JsonReport(TypedDict):
43
+ """A token that is itself a JSON document."""
44
+
45
+ type: Literal["JSON"]
46
+ data: Json
47
+
48
+
49
+ class HexReport(TypedDict):
50
+ """An even-length hexadecimal token."""
51
+
52
+ type: Literal["Hexadecimal"]
53
+ decoded: str | None
54
+ bytes: int
55
+
56
+
57
+ class Base64Report(TypedDict):
58
+ """Standard or URL-safe Base64 that decodes as UTF-8."""
59
+
60
+ type: Literal["Base64 / Base64URL"]
61
+ decoded: Json
62
+
63
+
64
+ class EmptyReport(TypedDict):
65
+ """A blank token."""
66
+
67
+ type: Literal["Empty token"]
68
+
69
+
70
+ class OpaqueReport(TypedDict):
71
+ """A token that matched none of the known formats."""
72
+
73
+ type: Literal["Opaque / Unknown"]
74
+ length: int
75
+ note: str
76
+
77
+
78
+ Report = JwtReport | JweReport | JsonReport | HexReport | Base64Report | EmptyReport | OpaqueReport
79
+
80
+ _TIMESTAMP_CLAIMS = ("exp", "iat", "nbf")
81
+ _HEX = re.compile(r"[0-9a-fA-F]+\Z")
82
+ _B64 = re.compile(r"[A-Za-z0-9_+/=-]+\Z")
83
+
84
+
85
+ def decode_base64(value: str) -> bytes:
86
+ """Decode standard or URL-safe Base64, adding padding when it is missing.
87
+
88
+ ``altchars`` translates ``-`` and ``_`` to ``+`` and ``/`` before
89
+ validation, so one call accepts both alphabets.
90
+
91
+ Parameters
92
+ ----------
93
+ value:
94
+ A Base64 or Base64url string, with or without padding.
95
+
96
+ Returns
97
+ -------
98
+ bytes
99
+ The decoded bytes.
100
+ """
101
+ padded = value + ("=" * (-len(value) % 4))
102
+ return base64.b64decode(padded, altchars=b"-_", validate=True)
103
+
104
+
105
+ def format_timestamp(value: Json) -> Json:
106
+ """Convert a Unix timestamp to an ISO-8601 UTC string.
107
+
108
+ Booleans are returned unchanged. ``bool`` is a subclass of ``int``,
109
+ so a claim such as ``true`` must not be treated as a timestamp.
110
+ Values that are not numbers, or that cannot be converted, are also
111
+ returned unchanged.
112
+
113
+ Parameters
114
+ ----------
115
+ value:
116
+ A claim value that might be a Unix timestamp in seconds.
117
+ """
118
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
119
+ return value
120
+ try:
121
+ moment = datetime.fromtimestamp(value, tz=UTC)
122
+ except (ValueError, OverflowError, OSError):
123
+ return value
124
+ return moment.isoformat()
125
+
126
+
127
+ def _as_json(value: object) -> Json:
128
+ """Return ``value`` as a JSON document.
129
+
130
+ Parameters
131
+ ----------
132
+ value:
133
+ An object produced by ``json.loads``.
134
+
135
+ Raises
136
+ ------
137
+ ValueError
138
+ If ``value`` is not a JSON object, array, string, number, boolean,
139
+ or null.
140
+ """
141
+ if isinstance(value, dict):
142
+ pairs = cast("dict[object, object]", value)
143
+ document: dict[str, Json] = {}
144
+ for key, item in pairs.items():
145
+ document[str(key)] = _as_json(item)
146
+ return document
147
+ if isinstance(value, list):
148
+ items = cast("list[object]", value)
149
+ return [_as_json(item) for item in items]
150
+ if isinstance(value, (str, int, float, bool)) or value is None:
151
+ return value
152
+ message = "JSON value is not a document"
153
+ raise ValueError(message)
154
+
155
+
156
+ def _json_value(raw: str | bytes) -> Json:
157
+ return _as_json(cast("object", json.loads(raw)))
158
+
159
+
160
+ def decode_jwt(token: str) -> Report | None:
161
+ """Decode a compact JWT without verifying its signature.
162
+
163
+ Parameters
164
+ ----------
165
+ token:
166
+ A candidate compact JWT (``header.payload.signature``).
167
+
168
+ Returns
169
+ -------
170
+ dict or None
171
+ A report when the header is a JSON object that contains ``alg``.
172
+ ``None`` when ``token`` is not a JWT.
173
+ """
174
+ parts = token.split(".")
175
+ if len(parts) != 3 or parts[0] == "" or parts[1] == "":
176
+ return None
177
+ try:
178
+ header = _json_value(decode_base64(parts[0]))
179
+ except (ValueError, binascii.Error, UnicodeDecodeError):
180
+ return None
181
+ if not isinstance(header, dict) or "alg" not in header:
182
+ return None
183
+
184
+ try:
185
+ payload: Json | str = _json_value(decode_base64(parts[1]))
186
+ except (ValueError, binascii.Error, UnicodeDecodeError):
187
+ payload = "<Non-JSON or encrypted payload>"
188
+
189
+ if isinstance(payload, dict):
190
+ stamped: dict[str, Json] = dict(payload)
191
+ for key in _TIMESTAMP_CLAIMS:
192
+ if key in stamped:
193
+ raw_value = stamped[key]
194
+ stamped[key] = {"raw": raw_value, "utc": format_timestamp(raw_value)}
195
+ payload = stamped
196
+
197
+ return {
198
+ "type": "JWT",
199
+ "header": header,
200
+ "payload": payload,
201
+ "signature": parts[2],
202
+ "signature_verified": False,
203
+ }
204
+
205
+
206
+ def decode_jwe(token: str) -> Report | None:
207
+ """Recognise a compact JWE without decrypting it.
208
+
209
+ Parameters
210
+ ----------
211
+ token:
212
+ A candidate compact JWE of five dot-separated segments.
213
+
214
+ Returns
215
+ -------
216
+ dict or None
217
+ A report when the header is a JSON object that contains ``enc``.
218
+ ``None`` when ``token`` is not a compact JWE.
219
+ """
220
+ parts = token.split(".")
221
+ if len(parts) != 5 or parts[0] == "":
222
+ return None
223
+ try:
224
+ header = _json_value(decode_base64(parts[0]))
225
+ except (ValueError, binascii.Error, UnicodeDecodeError):
226
+ return None
227
+ if not isinstance(header, dict) or "enc" not in header:
228
+ return None
229
+ return {
230
+ "type": "JWE",
231
+ "header": header,
232
+ "encrypted_key": parts[1],
233
+ "initialization_vector": parts[2],
234
+ "ciphertext": parts[3],
235
+ "authentication_tag": parts[4],
236
+ "decrypted": False,
237
+ }
238
+
239
+
240
+ def _without_bearer(token: str) -> str:
241
+ stripped = token.strip()
242
+ match = re.match(r"bearer(?:\s+|$)", stripped, flags=re.IGNORECASE)
243
+ if match is None:
244
+ return stripped
245
+ return stripped[match.end() :].strip()
246
+
247
+
248
+ def _unwrap(token: str) -> str:
249
+ """Drop wrapping whitespace without flattening a JSON document."""
250
+ if any(character.isspace() for character in token) and not token.startswith(("{", "[", '"')):
251
+ return "".join(token.split())
252
+ return token
253
+
254
+
255
+ def decode_token(token: str) -> Report:
256
+ """Detect and decode one token.
257
+
258
+ A leading ``Bearer`` prefix is removed. Signatures are not checked.
259
+
260
+ Parameters
261
+ ----------
262
+ token:
263
+ A JWT, compact JWE, JSON document, hexadecimal string, Base64
264
+ string, or an unrecognised token.
265
+
266
+ Returns
267
+ -------
268
+ dict
269
+ A JSON-ready report. The ``type`` field names the format.
270
+ """
271
+ token = _unwrap(_without_bearer(token))
272
+ if not token:
273
+ return {"type": "Empty token"}
274
+
275
+ jwt = decode_jwt(token)
276
+ if jwt is not None:
277
+ return jwt
278
+
279
+ jwe = decode_jwe(token)
280
+ if jwe is not None:
281
+ return jwe
282
+
283
+ # A bare number is left for the hex and Base64 checks. Digit strings are
284
+ # common tokens; a JSON number is not.
285
+ if token[:1] in '{["' or token in {"true", "false", "null"}:
286
+ try:
287
+ return {"type": "JSON", "data": _json_value(token)}
288
+ except ValueError:
289
+ pass
290
+
291
+ if len(token) % 2 == 0 and _HEX.fullmatch(token):
292
+ raw = bytes.fromhex(token)
293
+ try:
294
+ decoded: str | None = raw.decode("utf-8")
295
+ except UnicodeDecodeError:
296
+ decoded = None
297
+ return {"type": "Hexadecimal", "decoded": decoded, "bytes": len(raw)}
298
+
299
+ if _B64.fullmatch(token):
300
+ try:
301
+ text = decode_base64(token).decode("utf-8")
302
+ except (ValueError, UnicodeDecodeError, binascii.Error):
303
+ pass
304
+ else:
305
+ decoded_value: Json = text
306
+ with suppress(ValueError):
307
+ decoded_value = _json_value(text)
308
+ return {"type": "Base64 / Base64URL", "decoded": decoded_value}
309
+
310
+ return {
311
+ "type": "Opaque / Unknown",
312
+ "length": len(token),
313
+ "note": "Token cannot be decoded using known formats.",
314
+ }
@@ -0,0 +1,8 @@
1
+ """Package version."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+
6
+ def get_version() -> str:
7
+ """Return the package version."""
8
+ return __version__