jwt-toolkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jwt_toolkit/__init__.py +0 -0
- jwt_toolkit/cli/__init__.py +110 -0
- jwt_toolkit/cli/algorithms.py +66 -0
- jwt_toolkit/cli/banner.py +277 -0
- jwt_toolkit/cli/console.py +35 -0
- jwt_toolkit/cli/decoding.py +83 -0
- jwt_toolkit/cli/panels.py +28 -0
- jwt_toolkit/commands/__init__.py +0 -0
- jwt_toolkit/commands/audit.py +269 -0
- jwt_toolkit/commands/crack.py +322 -0
- jwt_toolkit/commands/decode.py +54 -0
- jwt_toolkit/commands/download_wordlists.py +216 -0
- jwt_toolkit/commands/forge.py +133 -0
- jwt_toolkit/commands/generate_secret.py +72 -0
- jwt_toolkit/commands/sign.py +146 -0
- jwt_toolkit/commands/verify.py +290 -0
- jwt_toolkit/core/__init__.py +0 -0
- jwt_toolkit/core/auditor.py +602 -0
- jwt_toolkit/core/crypto.py +229 -0
- jwt_toolkit/core/decoder.py +70 -0
- jwt_toolkit/core/encoding.py +22 -0
- jwt_toolkit/core/errors.py +25 -0
- jwt_toolkit/core/forge.py +260 -0
- jwt_toolkit/core/jwks.py +197 -0
- jwt_toolkit-0.1.0.dist-info/METADATA +116 -0
- jwt_toolkit-0.1.0.dist-info/RECORD +29 -0
- jwt_toolkit-0.1.0.dist-info/WHEEL +4 -0
- jwt_toolkit-0.1.0.dist-info/entry_points.txt +2 -0
- jwt_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
jwt_toolkit/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
3
|
+
|
|
4
|
+
import click
|
|
5
|
+
|
|
6
|
+
from jwt_toolkit.cli.banner import render_banner, render_help
|
|
7
|
+
from jwt_toolkit.commands.audit import audit
|
|
8
|
+
from jwt_toolkit.commands.crack import crack
|
|
9
|
+
from jwt_toolkit.commands.decode import decode
|
|
10
|
+
from jwt_toolkit.commands.download_wordlists import download_wordlists
|
|
11
|
+
from jwt_toolkit.commands.forge import forge
|
|
12
|
+
from jwt_toolkit.commands.generate_secret import generate_secret
|
|
13
|
+
from jwt_toolkit.commands.sign import sign
|
|
14
|
+
from jwt_toolkit.commands.verify import verify
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
__version__ = version("jwt-toolkit")
|
|
18
|
+
except PackageNotFoundError:
|
|
19
|
+
__version__ = "0.0.0"
|
|
20
|
+
|
|
21
|
+
CLI_HELP = """\
|
|
22
|
+
JWT Toolkit — a command-line toolkit for inspecting, verifying, cracking,
|
|
23
|
+
and securing JSON Web Tokens.
|
|
24
|
+
|
|
25
|
+
Built to expose how JWT signing works and where it breaks. Use it to audit
|
|
26
|
+
tokens for misconfigurations, verify signatures and standard claims,
|
|
27
|
+
brute-force weak HMAC secrets against a wordlist, and generate
|
|
28
|
+
cryptographically strong secrets.
|
|
29
|
+
|
|
30
|
+
\b
|
|
31
|
+
Commands:
|
|
32
|
+
decode Decode a JWT and pretty-print its header and payload.
|
|
33
|
+
sign Mint a new JWT from a payload and HMAC secret.
|
|
34
|
+
audit Static security analysis of a JWT (no key required).
|
|
35
|
+
verify Verify the signature and standard claims of a JWT.
|
|
36
|
+
forge Emit defensive attack-shaped variants of a JWT for self-audit.
|
|
37
|
+
crack Brute-force a weak HMAC secret using a wordlist.
|
|
38
|
+
generate-secret Emit a cryptographically strong random secret.
|
|
39
|
+
download-wordlists Fetch the latest common-secrets wordlist.
|
|
40
|
+
|
|
41
|
+
\b
|
|
42
|
+
Examples:
|
|
43
|
+
jwt-toolkit decode <token>
|
|
44
|
+
jwt-toolkit sign --payload '{"sub":"1"}' --secret mysecret
|
|
45
|
+
jwt-toolkit audit <token>
|
|
46
|
+
jwt-toolkit audit <token> --strict --json
|
|
47
|
+
jwt-toolkit verify <token> --secret <secret> --issuer auth.example.com
|
|
48
|
+
jwt-toolkit verify <token> --jwks-url https://auth.example/.well-known/jwks.json
|
|
49
|
+
jwt-toolkit forge <token> --public-key key.pub.pem
|
|
50
|
+
jwt-toolkit crack <token> wordlists/common-secrets.txt --threads 8
|
|
51
|
+
jwt-toolkit generate-secret --bits 256 --encoding base64
|
|
52
|
+
jwt-toolkit download-wordlists --output-dir wordlists
|
|
53
|
+
|
|
54
|
+
Run `jwt-toolkit COMMAND --help` for command-specific options.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@click.group(
|
|
59
|
+
invoke_without_command=True,
|
|
60
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
61
|
+
help=CLI_HELP,
|
|
62
|
+
)
|
|
63
|
+
@click.version_option(
|
|
64
|
+
version=__version__,
|
|
65
|
+
prog_name="jwt-toolkit",
|
|
66
|
+
message="%(prog)s %(version)s",
|
|
67
|
+
)
|
|
68
|
+
@click.option(
|
|
69
|
+
"--no-banner",
|
|
70
|
+
is_flag=True,
|
|
71
|
+
envvar="JWT_TOOLKIT_NO_BANNER",
|
|
72
|
+
help="Suppress the startup banner (also: JWT_TOOLKIT_NO_BANNER=1).",
|
|
73
|
+
)
|
|
74
|
+
@click.option(
|
|
75
|
+
"--quiet",
|
|
76
|
+
is_flag=True,
|
|
77
|
+
envvar="JWT_TOOLKIT_QUIET",
|
|
78
|
+
help="Suppress banner and non-essential output; useful for scripting.",
|
|
79
|
+
)
|
|
80
|
+
@click.option(
|
|
81
|
+
"--no-color",
|
|
82
|
+
is_flag=True,
|
|
83
|
+
envvar="NO_COLOR",
|
|
84
|
+
help="Disable color output (also: NO_COLOR=1).",
|
|
85
|
+
)
|
|
86
|
+
@click.pass_context
|
|
87
|
+
def cli(ctx: click.Context, no_banner: bool, quiet: bool, no_color: bool):
|
|
88
|
+
# Set env vars before the lazy console is first used by any subcommand.
|
|
89
|
+
if no_color:
|
|
90
|
+
os.environ["NO_COLOR"] = "1"
|
|
91
|
+
if quiet:
|
|
92
|
+
os.environ["JWT_TOOLKIT_QUIET"] = "1"
|
|
93
|
+
|
|
94
|
+
# The banner is only rendered for the bare `jwt-toolkit` invocation.
|
|
95
|
+
# Printing it for every subcommand would corrupt --json output and noisily
|
|
96
|
+
# prefix Click's usage errors, so it stays out of the subcommand path.
|
|
97
|
+
if ctx.invoked_subcommand is None:
|
|
98
|
+
if not (no_banner or quiet):
|
|
99
|
+
render_banner()
|
|
100
|
+
render_help()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
cli.add_command(decode)
|
|
104
|
+
cli.add_command(sign)
|
|
105
|
+
cli.add_command(audit)
|
|
106
|
+
cli.add_command(generate_secret)
|
|
107
|
+
cli.add_command(verify)
|
|
108
|
+
cli.add_command(forge)
|
|
109
|
+
cli.add_command(crack)
|
|
110
|
+
cli.add_command(download_wordlists)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from jwt_toolkit.core.crypto import (
|
|
2
|
+
ALL_SIGNING_ALGORITHMS,
|
|
3
|
+
ASYMMETRIC_ALGORITHMS,
|
|
4
|
+
SUPPORTED_ALGORITHMS,
|
|
5
|
+
)
|
|
6
|
+
from jwt_toolkit.core.errors import UnsupportedAlgorithmError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def ensure_hmac_algorithm(header: dict, *, action: str) -> str:
|
|
10
|
+
# Validates that the token's alg is one we can sign/verify with HMAC.
|
|
11
|
+
# `action` is the verb used in error copy — "verify"/"crack"/etc.
|
|
12
|
+
alg = str(header.get("alg", "")).upper()
|
|
13
|
+
if alg == "NONE":
|
|
14
|
+
raise UnsupportedAlgorithmError(
|
|
15
|
+
title="Verification Error" if action == "verify" else "Cannot Crack",
|
|
16
|
+
headline=(
|
|
17
|
+
"Token uses alg: none, it has no signature to verify"
|
|
18
|
+
if action == "verify"
|
|
19
|
+
else "Token uses alg: none — there is no signature to crack"
|
|
20
|
+
),
|
|
21
|
+
details=(
|
|
22
|
+
(
|
|
23
|
+
"This token is completely unsigned and trivially forgeable"
|
|
24
|
+
if action == "verify"
|
|
25
|
+
else "An unsigned token can be forged without any secret"
|
|
26
|
+
),
|
|
27
|
+
),
|
|
28
|
+
)
|
|
29
|
+
if alg not in SUPPORTED_ALGORITHMS:
|
|
30
|
+
raise UnsupportedAlgorithmError(
|
|
31
|
+
title="Verification Error" if action == "verify" else "Cannot Crack",
|
|
32
|
+
headline=f"Unsupported algorithm: {alg}",
|
|
33
|
+
details=(
|
|
34
|
+
f"Supported : {', '.join(SUPPORTED_ALGORITHMS)}"
|
|
35
|
+
if action == "verify"
|
|
36
|
+
else f"crack only works on HMAC tokens: {', '.join(SUPPORTED_ALGORITHMS)}",
|
|
37
|
+
),
|
|
38
|
+
)
|
|
39
|
+
return alg
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def ensure_signing_algorithm(header: dict) -> str:
|
|
43
|
+
# Validates that the token's alg is any signing algorithm we can verify
|
|
44
|
+
# (HMAC or asymmetric). Returns the canonical uppercase alg name.
|
|
45
|
+
alg = str(header.get("alg", "")).upper()
|
|
46
|
+
if alg == "NONE":
|
|
47
|
+
raise UnsupportedAlgorithmError(
|
|
48
|
+
title="Verification Error",
|
|
49
|
+
headline="Token uses alg: none, it has no signature to verify",
|
|
50
|
+
details=("This token is completely unsigned and trivially forgeable",),
|
|
51
|
+
)
|
|
52
|
+
if alg not in ALL_SIGNING_ALGORITHMS:
|
|
53
|
+
raise UnsupportedAlgorithmError(
|
|
54
|
+
title="Verification Error",
|
|
55
|
+
headline=f"Unsupported algorithm: {alg}",
|
|
56
|
+
details=(f"Supported: {', '.join(sorted(ALL_SIGNING_ALGORITHMS))}",),
|
|
57
|
+
)
|
|
58
|
+
return alg
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_asymmetric(alg: str) -> bool:
|
|
62
|
+
return alg.upper() in ASYMMETRIC_ALGORITHMS
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def is_hmac(alg: str) -> bool:
|
|
66
|
+
return alg.upper() in SUPPORTED_ALGORITHMS
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import random
|
|
5
|
+
import shutil
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
9
|
+
|
|
10
|
+
from rich.align import Align
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.padding import Padding
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
from rich.text import Text
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from pyfiglet import Figlet, FontNotFound # type: ignore
|
|
18
|
+
|
|
19
|
+
_HAS_FIGLET = True
|
|
20
|
+
except ImportError:
|
|
21
|
+
_HAS_FIGLET = False
|
|
22
|
+
|
|
23
|
+
from jwt_toolkit.cli.console import console as _shared_console
|
|
24
|
+
|
|
25
|
+
# Banner — startup splash for `jwt-toolkit` with no subcommand.
|
|
26
|
+
# The banner is intentionally only shown for the bare invocation. Printing it
|
|
27
|
+
# for every subcommand would corrupt --json output and pollute Click's usage
|
|
28
|
+
# errors, so subcommands stay clean.
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _get_version() -> str:
|
|
32
|
+
try:
|
|
33
|
+
return version("jwt-toolkit")
|
|
34
|
+
except PackageNotFoundError:
|
|
35
|
+
return "0.0.0"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Three figlet fonts at full width, plus narrower fallbacks for small terminals.
|
|
39
|
+
# One is picked at random each invocation so the splash doesn't feel static.
|
|
40
|
+
_FONTS_WIDE = ("slant", "ansi_shadow", "small_slant")
|
|
41
|
+
_FONTS_NARROW = ("small", "standard", "mini")
|
|
42
|
+
|
|
43
|
+
# Cool cyan→violet gradient applied line-by-line to the ASCII art.
|
|
44
|
+
_GRADIENT = ("#22d3ee", "#06b6d4", "#3b82f6", "#6366f1", "#8b5cf6")
|
|
45
|
+
|
|
46
|
+
_ACCENT = "bright_cyan"
|
|
47
|
+
_DIM = "grey50"
|
|
48
|
+
|
|
49
|
+
_SUBTITLE = "JWT Security Toolkit"
|
|
50
|
+
_TAGLINE = "Decode · Sign · Audit · Verify · Forge · Crack · Generate"
|
|
51
|
+
_REPO_URL = "https://github.com/KhaledSaeed18/jwt-toolkit"
|
|
52
|
+
|
|
53
|
+
# Plain-ASCII fallback shown when pyfiglet is unavailable or every font is
|
|
54
|
+
# wider than the terminal. Kept narrow on purpose (~60 cols).
|
|
55
|
+
_PLAIN_FALLBACK = r"""
|
|
56
|
+
_ _ _ _____ _____ _ _ _ _
|
|
57
|
+
| | | | |_ _| |_ _|__ ___ | | | _(_) |_
|
|
58
|
+
| | |/\| | | | | |/ _ \ / _ \| | |/ / | __|
|
|
59
|
+
_/ | /\ | | | | (_) | (_) | | <| | |_
|
|
60
|
+
|__/|__/ \__|_| |_|\___/ \___/|_|_|\_\_|\__|
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _is_animation_safe() -> bool:
|
|
65
|
+
"""Disable animation in non-interactive contexts (pipes, CI, NO_COLOR)."""
|
|
66
|
+
if not sys.stdout.isatty():
|
|
67
|
+
return False
|
|
68
|
+
if os.environ.get("CI"):
|
|
69
|
+
return False
|
|
70
|
+
if os.environ.get("NO_COLOR"):
|
|
71
|
+
return False
|
|
72
|
+
return os.environ.get("TERM") != "dumb"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _terminal_width(default: int = 80) -> int:
|
|
76
|
+
return shutil.get_terminal_size((default, 20)).columns
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _pick_art(width: int) -> tuple[str, bool]:
|
|
80
|
+
"""Render the title via pyfiglet; return (art, used_figlet)."""
|
|
81
|
+
if not _HAS_FIGLET:
|
|
82
|
+
return _PLAIN_FALLBACK.strip("\n"), False
|
|
83
|
+
|
|
84
|
+
fonts = _FONTS_WIDE if width >= 78 else _FONTS_NARROW
|
|
85
|
+
candidates = list(fonts)
|
|
86
|
+
random.shuffle(candidates)
|
|
87
|
+
|
|
88
|
+
for font in candidates:
|
|
89
|
+
try:
|
|
90
|
+
fig = Figlet(font=font, width=max(width, 40))
|
|
91
|
+
art = fig.renderText("JWT Toolkit").rstrip("\n")
|
|
92
|
+
except (FontNotFound, Exception):
|
|
93
|
+
continue
|
|
94
|
+
max_line = max((len(line) for line in art.splitlines()), default=0)
|
|
95
|
+
if max_line <= width:
|
|
96
|
+
return art, True
|
|
97
|
+
|
|
98
|
+
return _PLAIN_FALLBACK.strip("\n"), False
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _colorize_line(line: str, line_index: int, total_lines: int) -> Text:
|
|
102
|
+
idx = 0 if total_lines <= 1 else int((line_index / (total_lines - 1)) * (len(_GRADIENT) - 1))
|
|
103
|
+
return Text(line, style=_GRADIENT[idx])
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _info_line(ver: str) -> Text:
|
|
107
|
+
line = Text()
|
|
108
|
+
line.append("v", style=_DIM)
|
|
109
|
+
line.append(ver, style=_ACCENT)
|
|
110
|
+
line.append(" · ", style=_DIM)
|
|
111
|
+
line.append("python ", style=_DIM)
|
|
112
|
+
line.append(f"{sys.version_info.major}.{sys.version_info.minor}", style=_ACCENT)
|
|
113
|
+
line.append(" · ", style=_DIM)
|
|
114
|
+
line.append(_REPO_URL, style=f"underline {_DIM}")
|
|
115
|
+
return line
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def render_banner(
|
|
119
|
+
*,
|
|
120
|
+
console: Console | None = None,
|
|
121
|
+
animate: bool | None = None,
|
|
122
|
+
) -> None:
|
|
123
|
+
"""Render the startup banner.
|
|
124
|
+
|
|
125
|
+
The banner reveals line-by-line in a fast (~120ms) cascade when running in
|
|
126
|
+
an interactive terminal, and falls back to a single-shot render in pipes,
|
|
127
|
+
CI, or when NO_COLOR / TERM=dumb is set.
|
|
128
|
+
"""
|
|
129
|
+
console = console or _shared_console
|
|
130
|
+
if animate is None:
|
|
131
|
+
animate = _is_animation_safe()
|
|
132
|
+
|
|
133
|
+
width = _terminal_width()
|
|
134
|
+
art, _ = _pick_art(width)
|
|
135
|
+
lines = art.splitlines()
|
|
136
|
+
total = len(lines)
|
|
137
|
+
|
|
138
|
+
# Top breathing room
|
|
139
|
+
console.print()
|
|
140
|
+
|
|
141
|
+
for i, line in enumerate(lines):
|
|
142
|
+
console.print(Align.center(_colorize_line(line, i, total)))
|
|
143
|
+
if animate:
|
|
144
|
+
time.sleep(0.012)
|
|
145
|
+
|
|
146
|
+
console.print()
|
|
147
|
+
console.print(Align.center(Text(_SUBTITLE, style=f"bold {_ACCENT}")))
|
|
148
|
+
console.print(Align.center(Text(_TAGLINE, style=_DIM)))
|
|
149
|
+
|
|
150
|
+
divider_width = min(max(width - 8, 20), 60)
|
|
151
|
+
console.print(Align.center(Text("─" * divider_width, style=_DIM)))
|
|
152
|
+
console.print(Align.center(_info_line(_get_version())))
|
|
153
|
+
console.print()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# help layout
|
|
157
|
+
_COMMANDS: tuple[tuple[str, str], ...] = (
|
|
158
|
+
("decode", "Decode a JWT and pretty-print its header and payload."),
|
|
159
|
+
("sign", "Mint a new JWT from a payload and HMAC or asymmetric key."),
|
|
160
|
+
("audit", "Static security analysis of a JWT — no key required."),
|
|
161
|
+
("verify", "Verify a JWT's signature and standard claims."),
|
|
162
|
+
("forge", "Emit defensive attack-shaped variants of a JWT for self-audit."),
|
|
163
|
+
("crack", "Brute-force a weak HMAC secret using a wordlist."),
|
|
164
|
+
("generate-secret", "Emit a cryptographically strong random secret."),
|
|
165
|
+
("download-wordlists", "Fetch the latest common-secrets wordlist."),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
_EXAMPLES: tuple[tuple[str, str], ...] = (
|
|
169
|
+
("decode a token", "jwt-toolkit decode <token>"),
|
|
170
|
+
("mint a new token", 'jwt-toolkit sign --payload \'{"sub":"1"}\' --secret <secret>'),
|
|
171
|
+
("audit a token", "jwt-toolkit audit <token>"),
|
|
172
|
+
("strict + JSON report", "jwt-toolkit audit <token> --strict --json"),
|
|
173
|
+
(
|
|
174
|
+
"verify signature & claims",
|
|
175
|
+
"jwt-toolkit verify <token> --secret <secret> --issuer auth.example.com",
|
|
176
|
+
),
|
|
177
|
+
(
|
|
178
|
+
"verify against a JWKS",
|
|
179
|
+
"jwt-toolkit verify <token> --jwks-url https://auth.example/.well-known/jwks.json",
|
|
180
|
+
),
|
|
181
|
+
(
|
|
182
|
+
"forge defensive test cases",
|
|
183
|
+
"jwt-toolkit forge <token> --public-key key.pub.pem",
|
|
184
|
+
),
|
|
185
|
+
(
|
|
186
|
+
"crack a weak HMAC secret",
|
|
187
|
+
"jwt-toolkit crack <token> wordlists/common-secrets.txt --threads 8",
|
|
188
|
+
),
|
|
189
|
+
("generate a 256-bit secret", "jwt-toolkit generate-secret --bits 256 --encoding base64"),
|
|
190
|
+
("refresh the wordlist", "jwt-toolkit download-wordlists --output-dir wordlists"),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
_OPTIONS: tuple[tuple[str, str], ...] = (
|
|
194
|
+
("--version", "Show the version and exit."),
|
|
195
|
+
("--no-banner", "Suppress the startup banner (env: JWT_TOOLKIT_NO_BANNER)."),
|
|
196
|
+
("-h, --help", "Show this message and exit."),
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _section_header(title: str) -> Text:
|
|
201
|
+
header = Text()
|
|
202
|
+
header.append("▌ ", style=f"bold {_ACCENT}")
|
|
203
|
+
header.append(title, style=f"bold {_ACCENT}")
|
|
204
|
+
return header
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _two_col_table(
|
|
208
|
+
rows: tuple[tuple[str, str], ...],
|
|
209
|
+
*,
|
|
210
|
+
key_style: str,
|
|
211
|
+
value_style: str = "white",
|
|
212
|
+
key_prefix: str = "",
|
|
213
|
+
) -> Table:
|
|
214
|
+
table = Table(show_header=False, box=None, padding=(0, 3), pad_edge=False)
|
|
215
|
+
table.add_column(style=key_style, no_wrap=True)
|
|
216
|
+
table.add_column(style=value_style, overflow="fold")
|
|
217
|
+
for key, value in rows:
|
|
218
|
+
table.add_row(f"{key_prefix}{key}", value)
|
|
219
|
+
return table
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def render_help(console: Console | None = None) -> None:
|
|
223
|
+
"""Render a polished, sectioned help screen for the bare invocation."""
|
|
224
|
+
console = console or _shared_console
|
|
225
|
+
|
|
226
|
+
# ABOUT
|
|
227
|
+
about = Text(
|
|
228
|
+
"A command-line toolkit for inspecting, verifying, cracking, and securing "
|
|
229
|
+
"JSON Web Tokens — built to expose how JWT signing works and where it breaks.",
|
|
230
|
+
style="white",
|
|
231
|
+
)
|
|
232
|
+
console.print(_section_header("ABOUT"))
|
|
233
|
+
console.print(Padding(about, (0, 4, 1, 4)))
|
|
234
|
+
|
|
235
|
+
# USAGE
|
|
236
|
+
usage = Text()
|
|
237
|
+
usage.append("$ ", style=_DIM)
|
|
238
|
+
usage.append("jwt-toolkit ", style="bold white")
|
|
239
|
+
usage.append("[OPTIONS] ", style=_ACCENT)
|
|
240
|
+
usage.append("COMMAND ", style="bold magenta")
|
|
241
|
+
usage.append("[ARGS]...", style=_DIM)
|
|
242
|
+
|
|
243
|
+
console.print(_section_header("USAGE"))
|
|
244
|
+
console.print(Padding(usage, (0, 0, 1, 4)))
|
|
245
|
+
|
|
246
|
+
# COMMANDS
|
|
247
|
+
console.print(_section_header("COMMANDS"))
|
|
248
|
+
console.print(
|
|
249
|
+
Padding(
|
|
250
|
+
_two_col_table(_COMMANDS, key_style="bold cyan"),
|
|
251
|
+
(0, 0, 1, 2),
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
# EXAMPLES — dim "# label" comment beside a green command line
|
|
256
|
+
console.print(_section_header("EXAMPLES"))
|
|
257
|
+
console.print(
|
|
258
|
+
Padding(
|
|
259
|
+
_two_col_table(_EXAMPLES, key_style=_DIM, value_style="bright_green", key_prefix="# "),
|
|
260
|
+
(0, 0, 1, 2),
|
|
261
|
+
)
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
# OPTIONS
|
|
265
|
+
console.print(_section_header("OPTIONS"))
|
|
266
|
+
console.print(
|
|
267
|
+
Padding(
|
|
268
|
+
_two_col_table(_OPTIONS, key_style="yellow"),
|
|
269
|
+
(0, 0, 1, 2),
|
|
270
|
+
)
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
hint = Text("Run ", style=_DIM)
|
|
274
|
+
hint.append("jwt-toolkit COMMAND --help", style=f"bold {_ACCENT}")
|
|
275
|
+
hint.append(" for command-specific options.", style=_DIM)
|
|
276
|
+
console.print(Padding(hint, (0, 0, 0, 2)))
|
|
277
|
+
console.print()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from rich.console import Console
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class _ConsoleProxy:
|
|
9
|
+
"""Lazy proxy so --no-color and --quiet env vars are set before Console is created."""
|
|
10
|
+
|
|
11
|
+
def __init__(self) -> None:
|
|
12
|
+
self._inner: Console | None = None
|
|
13
|
+
|
|
14
|
+
def _get(self) -> Console:
|
|
15
|
+
if self._inner is None:
|
|
16
|
+
self._inner = Console(
|
|
17
|
+
no_color=bool(os.environ.get("NO_COLOR")),
|
|
18
|
+
quiet=bool(os.environ.get("JWT_TOOLKIT_QUIET")),
|
|
19
|
+
)
|
|
20
|
+
return self._inner
|
|
21
|
+
|
|
22
|
+
def __getattr__(self, name: str):
|
|
23
|
+
return getattr(self._get(), name)
|
|
24
|
+
|
|
25
|
+
# Rich internals (Live, Progress) use the console as a context manager.
|
|
26
|
+
# Python looks up dunder methods on the type, not the instance, so
|
|
27
|
+
# __getattr__ alone is not enough — we must forward them explicitly.
|
|
28
|
+
def __enter__(self):
|
|
29
|
+
return self._get().__enter__()
|
|
30
|
+
|
|
31
|
+
def __exit__(self, *args):
|
|
32
|
+
return self._get().__exit__(*args)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
console = _ConsoleProxy()
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import sys
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import click
|
|
7
|
+
|
|
8
|
+
from jwt_toolkit.cli.panels import print_error
|
|
9
|
+
from jwt_toolkit.core.decoder import DecodedToken, decode_token
|
|
10
|
+
from jwt_toolkit.core.errors import TokenDecodeError, UnsupportedAlgorithmError
|
|
11
|
+
|
|
12
|
+
# Stable schema version shared by every command that emits --json errors.
|
|
13
|
+
JSON_SCHEMA_VERSION = "0.1"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def resolve_token(raw: str) -> str:
|
|
17
|
+
"""Resolve the token string from a raw CLI argument.
|
|
18
|
+
|
|
19
|
+
Accepts three forms:
|
|
20
|
+
- read from stdin
|
|
21
|
+
@<path> read from a file
|
|
22
|
+
<token> use as-is
|
|
23
|
+
"""
|
|
24
|
+
if raw == "-":
|
|
25
|
+
return sys.stdin.read().strip()
|
|
26
|
+
if raw.startswith("@"):
|
|
27
|
+
path = raw[1:]
|
|
28
|
+
try:
|
|
29
|
+
with Path(path).open() as fh:
|
|
30
|
+
return fh.read().strip()
|
|
31
|
+
except OSError as exc:
|
|
32
|
+
click.echo(f"Cannot read token from {path!r}: {exc}", err=True)
|
|
33
|
+
raise SystemExit(2) from exc
|
|
34
|
+
return raw
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def safe_decode(
|
|
38
|
+
token: str,
|
|
39
|
+
*,
|
|
40
|
+
as_json: bool = False,
|
|
41
|
+
json_extra: Callable[[TokenDecodeError], dict] | None = None,
|
|
42
|
+
) -> DecodedToken:
|
|
43
|
+
# Decode a token, rendering a consistent error panel/JSON on failure and
|
|
44
|
+
# exiting with code 2. The caller never has to know about the exception types.
|
|
45
|
+
try:
|
|
46
|
+
return decode_token(token)
|
|
47
|
+
except TokenDecodeError as exc:
|
|
48
|
+
_emit_error(
|
|
49
|
+
code=exc.code,
|
|
50
|
+
title=exc.title,
|
|
51
|
+
headline=exc.headline,
|
|
52
|
+
details=exc.details,
|
|
53
|
+
as_json=as_json,
|
|
54
|
+
extra=json_extra(exc) if json_extra else None,
|
|
55
|
+
)
|
|
56
|
+
raise SystemExit(2) from exc
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def render_algorithm_error(exc: UnsupportedAlgorithmError) -> None:
|
|
60
|
+
print_error(exc.headline, *exc.details, title=exc.title)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _emit_error(
|
|
64
|
+
*,
|
|
65
|
+
code: str,
|
|
66
|
+
title: str,
|
|
67
|
+
headline: str,
|
|
68
|
+
details: tuple[str, ...],
|
|
69
|
+
as_json: bool,
|
|
70
|
+
extra: dict | None,
|
|
71
|
+
) -> None:
|
|
72
|
+
if as_json:
|
|
73
|
+
document = {
|
|
74
|
+
"schema_version": JSON_SCHEMA_VERSION,
|
|
75
|
+
"error": code,
|
|
76
|
+
"message": headline,
|
|
77
|
+
"detail": list(details),
|
|
78
|
+
}
|
|
79
|
+
if extra:
|
|
80
|
+
document.update(extra)
|
|
81
|
+
click.echo(json.dumps(document, indent=2))
|
|
82
|
+
return
|
|
83
|
+
print_error(headline, *details, title=title)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from collections.abc import Iterable
|
|
2
|
+
|
|
3
|
+
from rich.panel import Panel
|
|
4
|
+
|
|
5
|
+
from jwt_toolkit.cli.console import console
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def print_error(headline: str, *details: str, title: str) -> None:
|
|
9
|
+
body = f"[bold red]{headline}[/bold red]"
|
|
10
|
+
if details:
|
|
11
|
+
body += "\n\n" + "\n".join(f"[dim]{line}[/dim]" for line in details)
|
|
12
|
+
console.print(Panel(body, title=title, border_style="red"))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def print_success(
|
|
16
|
+
headline: str,
|
|
17
|
+
*details: str,
|
|
18
|
+
title: str,
|
|
19
|
+
headline_style: str = "bold green",
|
|
20
|
+
border_style: str = "green",
|
|
21
|
+
footer: Iterable[str] = (),
|
|
22
|
+
) -> None:
|
|
23
|
+
body = f"[{headline_style}]{headline}[/{headline_style}]"
|
|
24
|
+
if details:
|
|
25
|
+
body += "\n\n" + "\n".join(f"[dim]{line}[/dim]" for line in details)
|
|
26
|
+
if footer:
|
|
27
|
+
body += "\n\n" + "\n".join(footer)
|
|
28
|
+
console.print(Panel(body, title=title, border_style=border_style))
|
|
File without changes
|