tvkit 0.18.0__tar.gz → 0.18.2__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.
Files changed (120) hide show
  1. {tvkit-0.18.0/tvkit.egg-info → tvkit-0.18.2}/PKG-INFO +8 -6
  2. {tvkit-0.18.0 → tvkit-0.18.2}/README.md +2 -2
  3. {tvkit-0.18.0 → tvkit-0.18.2}/pyproject.toml +14 -5
  4. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_authentication.py +36 -2
  5. tvkit-0.18.2/tests/test_credential_safety.py +316 -0
  6. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_dependency_declarations.py +17 -0
  7. tvkit-0.18.2/tests/test_docs_markdown.py +86 -0
  8. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/__init__.py +1 -1
  9. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/services/message_service.py +13 -3
  10. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/utils/symbol_validator.py +2 -2
  11. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/auth_manager.py +7 -4
  12. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/cookie_provider.py +20 -2
  13. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/probe_cache.py +41 -6
  14. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/profile_parser.py +6 -2
  15. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/token_provider.py +52 -3
  16. {tvkit-0.18.0 → tvkit-0.18.2/tvkit.egg-info}/PKG-INFO +8 -6
  17. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit.egg-info/SOURCES.txt +2 -0
  18. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit.egg-info/requires.txt +3 -3
  19. {tvkit-0.18.0 → tvkit-0.18.2}/LICENSE +0 -0
  20. {tvkit-0.18.0 → tvkit-0.18.2}/setup.cfg +0 -0
  21. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_adjustment_enum.py +0 -0
  22. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_batch_downloader.py +0 -0
  23. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_connection_retry.py +0 -0
  24. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_connection_service.py +0 -0
  25. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_export_module.py +0 -0
  26. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_export_timestamp_format.py +0 -0
  27. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_export_validation.py +0 -0
  28. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_fundamentals_catalog.py +0 -0
  29. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_fundamentals_client.py +0 -0
  30. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_fundamentals_export.py +0 -0
  31. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_fundamentals_models.py +0 -0
  32. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_fundamentals_transport.py +0 -0
  33. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_futures_range_degradation.py +0 -0
  34. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_historical_ohlcv.py +0 -0
  35. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_indicator_service.py +0 -0
  36. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_interval_validation.py +0 -0
  37. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_ohlcv_models.py +0 -0
  38. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_ohlcv_range_filter.py +0 -0
  39. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_ohlcv_reconnect.py +0 -0
  40. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_ohlcv_symbol_integration.py +0 -0
  41. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_range_end_bounds.py +0 -0
  42. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_range_segmentation.py +0 -0
  43. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_realtime_models.py +0 -0
  44. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_retry_backoff.py +0 -0
  45. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_scanner_models.py +0 -0
  46. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_scanner_row_drop.py +0 -0
  47. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_segmented_fetch.py +0 -0
  48. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_series_errors.py +0 -0
  49. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_symbols_config.py +0 -0
  50. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_symbols_normalizer.py +0 -0
  51. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_timezone_utils.py +0 -0
  52. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_utils.py +0 -0
  53. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_validation_checks.py +0 -0
  54. {tvkit-0.18.0 → tvkit-0.18.2}/tests/test_validation_composite.py +0 -0
  55. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/__main__.py +0 -0
  56. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/__init__.py +0 -0
  57. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/__init__.py +0 -0
  58. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/exceptions.py +0 -0
  59. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/models/__init__.py +0 -0
  60. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/models/adjustment.py +0 -0
  61. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/models/ohlcv.py +0 -0
  62. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/models/realtime.py +0 -0
  63. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/models/stream_models.py +0 -0
  64. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/ohlcv.py +0 -0
  65. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/services/__init__.py +0 -0
  66. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/services/connection_service.py +0 -0
  67. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/services/segmented_fetch_service.py +0 -0
  68. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/chart/utils.py +0 -0
  69. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/fundamentals/__init__.py +0 -0
  70. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/fundamentals/catalog.py +0 -0
  71. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/fundamentals/client.py +0 -0
  72. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/fundamentals/exceptions.py +0 -0
  73. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/fundamentals/models.py +0 -0
  74. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/fundamentals/transport.py +0 -0
  75. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/scanner/__init__.py +0 -0
  76. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/scanner/markets.py +0 -0
  77. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/scanner/models/__init__.py +0 -0
  78. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/scanner/models/scanner.py +0 -0
  79. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/scanner/services/__init__.py +0 -0
  80. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/scanner/services/scanner_service.py +0 -0
  81. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/utils/__init__.py +0 -0
  82. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/utils/indicator_service.py +0 -0
  83. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/utils/models.py +0 -0
  84. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/utils/retry.py +0 -0
  85. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/api/utils/timestamp.py +0 -0
  86. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/__init__.py +0 -0
  87. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/capability_detector.py +0 -0
  88. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/credentials.py +0 -0
  89. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/exceptions.py +0 -0
  90. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/auth/models.py +0 -0
  91. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/batch/__init__.py +0 -0
  92. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/batch/downloader.py +0 -0
  93. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/batch/exceptions.py +0 -0
  94. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/batch/models.py +0 -0
  95. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/cli.py +0 -0
  96. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/__init__.py +0 -0
  97. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/data_exporter.py +0 -0
  98. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/formatters/__init__.py +0 -0
  99. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/formatters/base_formatter.py +0 -0
  100. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/formatters/csv_formatter.py +0 -0
  101. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/formatters/json_formatter.py +0 -0
  102. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/formatters/polars_formatter.py +0 -0
  103. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/export/models.py +0 -0
  104. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/helpers.py +0 -0
  105. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/py.typed +0 -0
  106. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/quickstart.py +0 -0
  107. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/symbols/__init__.py +0 -0
  108. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/symbols/exceptions.py +0 -0
  109. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/symbols/models.py +0 -0
  110. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/symbols/normalizer.py +0 -0
  111. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/time/__init__.py +0 -0
  112. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/time/conversion.py +0 -0
  113. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/time/exchange.py +0 -0
  114. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/validation/__init__.py +0 -0
  115. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/validation/checks.py +0 -0
  116. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/validation/exceptions.py +0 -0
  117. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/validation/models.py +0 -0
  118. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit/validation/validator.py +0 -0
  119. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit.egg-info/dependency_links.txt +0 -0
  120. {tvkit-0.18.0 → tvkit-0.18.2}/tvkit.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tvkit
3
- Version: 0.18.0
3
+ Version: 0.18.2
4
4
  Summary: tvkit is a Python library that fetches real-time stock data from TradingView, including price, market cap, P/E ratio, ROE, and more for stocks from multiple countries. Easily access and analyze financial metrics for global markets.
5
5
  Author-email: lumduan <b@candythink.com>
6
6
  License-Expression: MIT
@@ -15,6 +15,8 @@ Classifier: Programming Language :: Python :: 3
15
15
  Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
18
20
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
21
  Classifier: Topic :: Office/Business :: Financial
20
22
  Requires-Python: >=3.11
@@ -24,14 +26,14 @@ Requires-Dist: pydantic>=2.0.0
24
26
  Requires-Dist: pydantic-settings>=2.15.0
25
27
  Requires-Dist: websockets>=17.0.1
26
28
  Requires-Dist: httpx>=0.24.0
27
- Requires-Dist: polars>=1.44.0
28
- Requires-Dist: browser-cookie3>=0.20.1
29
+ Requires-Dist: polars>=1.44.1
30
+ Requires-Dist: browser-cookie3==0.20.1
29
31
  Requires-Dist: pyyaml>=6.0.3
30
32
  Provides-Extra: pandas
31
33
  Requires-Dist: pandas>=3.0.5; extra == "pandas"
32
34
  Requires-Dist: pyarrow>=25.0.1; extra == "pandas"
33
35
  Provides-Extra: dev
34
- Requires-Dist: ruff==0.16.4; extra == "dev"
36
+ Requires-Dist: ruff==0.17.6; extra == "dev"
35
37
  Requires-Dist: pytest>=9.1.1; extra == "dev"
36
38
  Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
37
39
  Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
@@ -110,8 +112,8 @@ asyncio.run(main())
110
112
  | 1786109400.0 | 2026-08-07 | 311.45 | 314.81 | 310.74 | 313.33 | 34,437,191 |
111
113
  | 1786368600.0 | 2026-08-10 | 306.83 | 308.26 | 304.61 | 308.26 | 44,812,503 |
112
114
 
113
- # 10 rows total, showing 5
114
- # `date` is derived — OHLCVBar has 6 fields: timestamp, open, high, low, close, volume
115
+ - 10 rows total, showing 5
116
+ - `date` is derived — OHLCVBar has 6 fields: timestamp, open, high, low, close, volume
115
117
 
116
118
  The `print()` above emits the first and sixth columns only: `1785850200.0 309.38`.
117
119
 
@@ -66,8 +66,8 @@ asyncio.run(main())
66
66
  | 1786109400.0 | 2026-08-07 | 311.45 | 314.81 | 310.74 | 313.33 | 34,437,191 |
67
67
  | 1786368600.0 | 2026-08-10 | 306.83 | 308.26 | 304.61 | 308.26 | 44,812,503 |
68
68
 
69
- # 10 rows total, showing 5
70
- # `date` is derived — OHLCVBar has 6 fields: timestamp, open, high, low, close, volume
69
+ - 10 rows total, showing 5
70
+ - `date` is derived — OHLCVBar has 6 fields: timestamp, open, high, low, close, volume
71
71
 
72
72
  The `print()` above emits the first and sixth columns only: `1785850200.0 309.38`.
73
73
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "tvkit"
3
- version = "0.18.0"
3
+ version = "0.18.2"
4
4
  description = "tvkit is a Python library that fetches real-time stock data from TradingView, including price, market cap, P/E ratio, ROE, and more for stocks from multiple countries. Easily access and analyze financial metrics for global markets."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -15,6 +15,8 @@ classifiers = [
15
15
  "Programming Language :: Python :: 3.11",
16
16
  "Programming Language :: Python :: 3.12",
17
17
  "Programming Language :: Python :: 3.13",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Programming Language :: Python :: 3.15",
18
20
  "Topic :: Software Development :: Libraries :: Python Modules",
19
21
  "Topic :: Office/Business :: Financial",
20
22
  ]
@@ -23,8 +25,12 @@ dependencies = [
23
25
  "pydantic-settings>=2.15.0",
24
26
  "websockets>=17.0.1",
25
27
  "httpx>=0.24.0",
26
- "polars>=1.44.0",
27
- "browser-cookie3>=0.20.1",
28
+ "polars>=1.44.1",
29
+ # Exact pin, on purpose. browser-cookie3 reads and decrypts the user's browser cookie
30
+ # stores, and upstream has been dormant since 2024-12 (last release 0.20.1, 2025-01-04).
31
+ # Without a pin, a new release (say after a takeover of the PyPI name) would install
32
+ # automatically. A bump is a reviewed decision; see SECURITY.md.
33
+ "browser-cookie3==0.20.1",
28
34
  "pyyaml>=6.0.3",
29
35
  ]
30
36
 
@@ -36,7 +42,7 @@ pandas = [
36
42
  "pyarrow>=25.0.1",
37
43
  ]
38
44
  dev = [
39
- "ruff==0.16.4",
45
+ "ruff==0.17.6",
40
46
  "pytest>=9.1.1",
41
47
  "pytest-asyncio>=0.23.0",
42
48
  "pytest-cov>=5.0.0",
@@ -106,6 +112,9 @@ indent-style = "space"
106
112
  [tool.pytest.ini_options]
107
113
  testpaths = ["tests"]
108
114
  asyncio_mode = "strict"
115
+ # Explicit, to silence pytest-asyncio's "unset" deprecation. tvkit has no async fixtures, so
116
+ # this changes no behaviour; "function" is also pytest-asyncio's announced future default.
117
+ asyncio_default_fixture_loop_scope = "function"
109
118
 
110
119
  [dependency-groups]
111
120
  dev = [
@@ -116,6 +125,6 @@ dev = [
116
125
  "pytest-asyncio>=1.1.0",
117
126
  "pytest-cov>=7.0.0",
118
127
  "rich>=15.0.0",
119
- "ruff>=0.16.4",
128
+ "ruff>=0.17.6",
120
129
  "twine>=7.0.0",
121
130
  ]
@@ -230,6 +230,19 @@ class TestProfileParser:
230
230
  profile = ProfileParser.parse(html)
231
231
  assert profile["id"] == 3
232
232
 
233
+ def test_script_end_tag_variants_are_recognised(self) -> None:
234
+ """`</script >` and `</SCRIPT\n>` close a script block too (CodeQL py/bad-tag-filter)."""
235
+ html = (
236
+ "<html><script>var a=1;</script >"
237
+ '<SCRIPT type="text/javascript">var b=2;</SCRIPT\n>'
238
+ "<script>var c=3;</scripts>still c</script></html>"
239
+ )
240
+ assert ProfileParser._extract_script_blocks(html) == [
241
+ "var a=1;",
242
+ "var b=2;",
243
+ "var c=3;</scripts>still c",
244
+ ]
245
+
233
246
  def test_balanced_brace_extract_basic(self) -> None:
234
247
  text = 'start {"key": "value", "nested": {"a": 1}} end'
235
248
  result = ProfileParser._balanced_brace_extract(text, 6)
@@ -370,13 +383,14 @@ class TestTradingViewAccount:
370
383
  # ---------------------------------------------------------------------------
371
384
 
372
385
 
373
- def _make_cookie_jar(cookies: dict[str, str]) -> list[MagicMock]:
374
- """Build a list of mock cookie objects from a name→value dict."""
386
+ def _make_cookie_jar(cookies: dict[str, str], domain: str = ".tradingview.com") -> list[MagicMock]:
387
+ """Build a list of mock cookie objects from a name→value dict, all on ``domain``."""
375
388
  jar = []
376
389
  for name, value in cookies.items():
377
390
  c = MagicMock()
378
391
  c.name = name
379
392
  c.value = value
393
+ c.domain = domain
380
394
  jar.append(c)
381
395
  return jar
382
396
 
@@ -1641,3 +1655,23 @@ class TestRealBrowserAuth:
1641
1655
  async with AuthManager() as auth:
1642
1656
  assert auth.auth_token == "unauthorized_user_token"
1643
1657
  assert auth.account is None
1658
+
1659
+
1660
+ def test_auth_token_guard_survives_python_O() -> None:
1661
+ """The guard raises under `python -O` too: it must not be an `assert` statement."""
1662
+ import subprocess
1663
+ import sys
1664
+
1665
+ code = (
1666
+ "from tvkit.auth import AuthManager, TradingViewCredentials\n"
1667
+ "try:\n"
1668
+ " AuthManager(TradingViewCredentials()).auth_token\n"
1669
+ "except AssertionError:\n"
1670
+ " print('raised')\n"
1671
+ "else:\n"
1672
+ " print('returned')\n"
1673
+ )
1674
+ out = subprocess.run(
1675
+ [sys.executable, "-O", "-c", code], capture_output=True, text=True, check=True
1676
+ ).stdout.strip()
1677
+ assert out == "raised"
@@ -0,0 +1,316 @@
1
+ """
2
+ Credential-safety guards: where tvkit's session credentials may and may not go.
3
+
4
+ Each class pins one leak path that existed before 0.18.1:
5
+
6
+ - ``TestAuthTokenNotLogged`` — ``MessageService.send_message`` logged every outgoing
7
+ frame at DEBUG, ``set_auth_token`` included, and the bug-report template asks users
8
+ to paste DEBUG output into a public issue.
9
+ - ``TestSessionCookieStaysOnTradingView`` — ``TokenProvider`` handed httpx a plain
10
+ cookie dict with ``follow_redirects=True``. httpx sends domain-less cookies to every
11
+ host, so a redirect off TradingView would have carried ``sessionid`` with it.
12
+ - ``TestLookalikeCookiesDropped`` — ``browser_cookie3`` matches ``%tradingview.com%``,
13
+ so cookies from look-alike hosts reached the flattened cookie dict.
14
+ - ``TestProbeCachePermissions`` — the cache directory was created with the umask's
15
+ mode (``0775`` under umask ``002``), and a malformed entry raised.
16
+ - ``TestCookieExportFileMode`` — ``scripts/export_tv_cookies.py`` wrote the session
17
+ cookies with ``Path.write_text`` (``0664`` under umask ``002``).
18
+
19
+ No network: httpx runs against ``httpx.MockTransport``.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import importlib.util
25
+ import json
26
+ import logging
27
+ import os
28
+ import stat
29
+ from collections.abc import Callable
30
+ from pathlib import Path
31
+ from types import ModuleType
32
+ from typing import Any
33
+ from unittest.mock import MagicMock, patch
34
+
35
+ import httpx
36
+ import pytest
37
+
38
+ from tvkit.api.chart.services.message_service import MessageService
39
+ from tvkit.auth import BrowserCookieError, CookieProvider, ProfileFetchError
40
+ from tvkit.auth import probe_cache as probe_cache_module
41
+ from tvkit.auth.probe_cache import ProbeCache
42
+ from tvkit.auth.token_provider import TokenProvider, _scoped_cookies
43
+
44
+ REPO_ROOT = Path(__file__).resolve().parents[1]
45
+
46
+ _TOKEN = "eyJSECRET.TOKEN.VALUE-0123456789"
47
+ _COOKIES = {"sessionid": "SESSION-SECRET", "sessionid_sign": "SIGN-SECRET"}
48
+ _PROFILE_HTML = (
49
+ '<html><body><script>var user = {"id":1,"username":"u",'
50
+ f'"auth_token":"{_TOKEN}","is_pro":false,"pro_plan":"","badges":[],'
51
+ '"is_broker":false};</script></body></html>'
52
+ )
53
+
54
+ posix_only = pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits")
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Auth token in DEBUG logs
59
+ # ---------------------------------------------------------------------------
60
+
61
+
62
+ class _FakeWebSocket:
63
+ def __init__(self) -> None:
64
+ self.sent: list[str] = []
65
+
66
+ async def send(self, message: str) -> None:
67
+ self.sent.append(message)
68
+
69
+
70
+ @pytest.mark.asyncio
71
+ class TestAuthTokenNotLogged:
72
+ async def test_set_auth_token_frame_is_redacted(self, caplog: pytest.LogCaptureFixture) -> None:
73
+ ws = _FakeWebSocket()
74
+ service = MessageService(ws) # type: ignore[arg-type]
75
+ with caplog.at_level(logging.DEBUG):
76
+ await service.send_message("set_auth_token", [_TOKEN])
77
+
78
+ assert _TOKEN in ws.sent[0], "the token must still be SENT — only the log is redacted"
79
+ assert _TOKEN not in caplog.text
80
+ assert "set_auth_token (parameters redacted" in caplog.text
81
+
82
+ async def test_other_frames_are_still_logged_verbatim(
83
+ self, caplog: pytest.LogCaptureFixture
84
+ ) -> None:
85
+ """Redaction is per-function, not a blanket mute of the debug log."""
86
+ service = MessageService(_FakeWebSocket()) # type: ignore[arg-type]
87
+ with caplog.at_level(logging.DEBUG):
88
+ await service.send_message("quote_add_symbols", ["qs_abc", "NASDAQ:AAPL"])
89
+ assert '"quote_add_symbols","p":["qs_abc","NASDAQ:AAPL"]' in caplog.text
90
+
91
+ async def test_logs_under_the_module_logger_not_root(
92
+ self, caplog: pytest.LogCaptureFixture
93
+ ) -> None:
94
+ """A module logger lets users silence tvkit's frame log without touching root."""
95
+ service = MessageService(_FakeWebSocket()) # type: ignore[arg-type]
96
+ with caplog.at_level(logging.DEBUG):
97
+ await service.send_message("set_locale", ["en", "US"])
98
+ names = {r.name for r in caplog.records if "Sending message" in r.getMessage()}
99
+ assert names == {"tvkit.api.chart.services.message_service"}
100
+
101
+
102
+ # ---------------------------------------------------------------------------
103
+ # Session cookies on redirect
104
+ # ---------------------------------------------------------------------------
105
+
106
+
107
+ def _client_factory(
108
+ handler: Callable[[httpx.Request], httpx.Response],
109
+ ) -> Callable[..., httpx.AsyncClient]:
110
+ """Patch target for ``httpx.AsyncClient`` that keeps tvkit's kwargs and adds a mock transport."""
111
+ real_client = httpx.AsyncClient
112
+
113
+ def factory(**kwargs: Any) -> httpx.AsyncClient:
114
+ return real_client(transport=httpx.MockTransport(handler), **kwargs)
115
+
116
+ return factory
117
+
118
+
119
+ def _redirecting_handler(
120
+ location: str, seen: list[tuple[str, str | None]]
121
+ ) -> Callable[[httpx.Request], httpx.Response]:
122
+ """www.tradingview.com redirects to ``location``; any other host serves the profile page."""
123
+
124
+ def handler(request: httpx.Request) -> httpx.Response:
125
+ seen.append((request.url.host, request.headers.get("cookie")))
126
+ if request.url.host == "www.tradingview.com" and request.url.scheme == "https":
127
+ return httpx.Response(302, headers={"location": location})
128
+ return httpx.Response(200, text=_PROFILE_HTML)
129
+
130
+ return handler
131
+
132
+
133
+ @pytest.mark.asyncio
134
+ class TestSessionCookieStaysOnTradingView:
135
+ @pytest.mark.parametrize(
136
+ "location",
137
+ [
138
+ "https://attacker.example/landing",
139
+ "https://nottradingview.com/",
140
+ "https://www.tradingview.com.attacker.example/",
141
+ "http://www.tradingview.com/", # scheme downgrade
142
+ ],
143
+ )
144
+ async def test_redirect_off_tradingview_is_refused_before_sending(self, location: str) -> None:
145
+ seen: list[tuple[str, str | None]] = []
146
+ factory = _client_factory(_redirecting_handler(location, seen))
147
+ with patch("tvkit.auth.token_provider.httpx.AsyncClient", side_effect=factory):
148
+ with pytest.raises(ProfileFetchError, match="Refusing to follow a redirect"):
149
+ await TokenProvider().fetch_profile(_COOKIES)
150
+
151
+ # Only the first request went out; the foreign hop was never sent at all.
152
+ assert [host for host, _ in seen] == ["www.tradingview.com"]
153
+
154
+ async def test_redirect_to_a_tradingview_subdomain_is_followed(self) -> None:
155
+ seen: list[tuple[str, str | None]] = []
156
+ factory = _client_factory(_redirecting_handler("https://th.tradingview.com/", seen))
157
+ with patch("tvkit.auth.token_provider.httpx.AsyncClient", side_effect=factory):
158
+ profile = await TokenProvider().fetch_profile(_COOKIES)
159
+
160
+ assert profile["auth_token"] == _TOKEN
161
+ assert [host for host, _ in seen] == ["www.tradingview.com", "th.tradingview.com"]
162
+ assert all(cookie and "sessionid=SESSION-SECRET" in cookie for _, cookie in seen)
163
+
164
+ async def test_scoped_jar_alone_withholds_cookies_from_another_host(self) -> None:
165
+ """Second line of defence: even without the hook, the jar is bound to TradingView."""
166
+ seen: list[tuple[str, str | None]] = []
167
+
168
+ def handler(request: httpx.Request) -> httpx.Response:
169
+ seen.append((request.url.host, request.headers.get("cookie")))
170
+ return httpx.Response(200)
171
+
172
+ async with httpx.AsyncClient(
173
+ cookies=_scoped_cookies(_COOKIES), transport=httpx.MockTransport(handler)
174
+ ) as client:
175
+ await client.get("https://www.tradingview.com/")
176
+ await client.get("https://attacker.example/")
177
+
178
+ assert seen[0][1] is not None and "sessionid=SESSION-SECRET" in seen[0][1]
179
+ assert seen[1] == ("attacker.example", None)
180
+
181
+ async def test_invalid_token_error_does_not_echo_the_token(self) -> None:
182
+ short = "xQ9zW" # shorter than the 10-char minimum
183
+ html = _PROFILE_HTML.replace(_TOKEN, short)
184
+ factory = _client_factory(lambda request: httpx.Response(200, text=html))
185
+ with patch("tvkit.auth.token_provider.httpx.AsyncClient", side_effect=factory):
186
+ with pytest.raises(ProfileFetchError) as excinfo:
187
+ await TokenProvider().fetch_profile(_COOKIES)
188
+ assert short not in str(excinfo.value)
189
+ assert "str of length 5" in str(excinfo.value)
190
+
191
+
192
+ # ---------------------------------------------------------------------------
193
+ # Look-alike cookie domains
194
+ # ---------------------------------------------------------------------------
195
+
196
+
197
+ def _cookie(name: str, value: str, domain: str) -> MagicMock:
198
+ c = MagicMock()
199
+ c.name, c.value, c.domain = name, value, domain
200
+ return c
201
+
202
+
203
+ def _provider_with_jar(jar: list[MagicMock]) -> tuple[CookieProvider, MagicMock]:
204
+ bc3 = MagicMock()
205
+ bc3.chrome.return_value = jar
206
+ return CookieProvider(), bc3
207
+
208
+
209
+ class TestLookalikeCookiesDropped:
210
+ def test_lookalike_sessionid_cannot_override_the_real_one(self) -> None:
211
+ jar = [
212
+ _cookie("sessionid", "REAL", ".tradingview.com"),
213
+ _cookie("device_t", "DT", "www.tradingview.com"),
214
+ _cookie("sessionid", "PLANTED", "nottradingview.com"),
215
+ _cookie("tracker", "T", ".tradingview.com.attacker.example"),
216
+ ]
217
+ provider, bc3 = _provider_with_jar(jar)
218
+ with patch("tvkit.auth.cookie_provider._get_browser_cookie3", return_value=bc3):
219
+ cookies = provider.extract("chrome")
220
+ assert cookies == {"sessionid": "REAL", "device_t": "DT"}
221
+
222
+ def test_sessionid_only_on_a_lookalike_host_is_treated_as_missing(self) -> None:
223
+ provider, bc3 = _provider_with_jar(
224
+ [_cookie("sessionid", "PLANTED", "evil-tradingview.com")]
225
+ )
226
+ with patch("tvkit.auth.cookie_provider._get_browser_cookie3", return_value=bc3):
227
+ with pytest.raises(BrowserCookieError, match="sessionid cookie not found"):
228
+ provider.extract("chrome")
229
+
230
+
231
+ # ---------------------------------------------------------------------------
232
+ # ProbeCache permissions and malformed entries
233
+ # ---------------------------------------------------------------------------
234
+
235
+
236
+ @posix_only
237
+ class TestProbeCachePermissions:
238
+ def test_new_cache_dir_is_0700_and_file_is_0600(self, tmp_path: Path) -> None:
239
+ old_umask = os.umask(0o002) # the umask that made settfex's directory group-writable
240
+ try:
241
+ path = tmp_path / "cachedir" / "capabilities.json"
242
+ ProbeCache(path=path).save(user_id=1, max_bars=5_000, plan="")
243
+ finally:
244
+ os.umask(old_umask)
245
+ assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
246
+ assert stat.S_IMODE(path.stat().st_mode) == 0o600
247
+
248
+ def test_loose_default_dir_is_tightened(
249
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
250
+ ) -> None:
251
+ default = tmp_path / "home-cache" / "tvkit" / "capabilities.json"
252
+ default.parent.mkdir(parents=True)
253
+ default.parent.chmod(0o775)
254
+ monkeypatch.setattr(probe_cache_module, "_CACHE_PATH", default)
255
+
256
+ ProbeCache().save(user_id=1, max_bars=5_000, plan="")
257
+
258
+ assert stat.S_IMODE(default.parent.stat().st_mode) == 0o700
259
+
260
+ def test_existing_caller_dir_is_left_alone(self, tmp_path: Path) -> None:
261
+ shared = tmp_path / "shared"
262
+ shared.mkdir()
263
+ shared.chmod(0o775)
264
+ ProbeCache(path=shared / "caps.json").save(user_id=1, max_bars=5_000, plan="")
265
+ assert stat.S_IMODE(shared.stat().st_mode) == 0o775
266
+
267
+
268
+ class TestProbeCacheMalformedEntry:
269
+ @pytest.mark.parametrize(
270
+ "entry",
271
+ [
272
+ ["not", "a", "dict"],
273
+ {"timestamp": 9e18}, # no max_bars
274
+ {"timestamp": "yesterday", "max_bars": 5000},
275
+ {"timestamp": 9e18, "max_bars": None},
276
+ ],
277
+ )
278
+ def test_malformed_entry_is_a_miss_not_a_crash(self, tmp_path: Path, entry: object) -> None:
279
+ path = tmp_path / "caps.json"
280
+ path.write_text(json.dumps({"1": entry}))
281
+ assert ProbeCache(path=path).load(user_id=1) is None
282
+
283
+
284
+ # ---------------------------------------------------------------------------
285
+ # scripts/export_tv_cookies.py file mode
286
+ # ---------------------------------------------------------------------------
287
+
288
+
289
+ def _load_export_script() -> ModuleType:
290
+ spec = importlib.util.spec_from_file_location(
291
+ "export_tv_cookies", REPO_ROOT / "scripts" / "export_tv_cookies.py"
292
+ )
293
+ assert spec is not None and spec.loader is not None
294
+ module = importlib.util.module_from_spec(spec)
295
+ spec.loader.exec_module(module)
296
+ return module
297
+
298
+
299
+ @posix_only
300
+ class TestCookieExportFileMode:
301
+ def test_new_file_is_0600(self, tmp_path: Path) -> None:
302
+ old_umask = os.umask(0o002)
303
+ try:
304
+ dest = tmp_path / "tv_cookies.json"
305
+ _load_export_script()._write_private(dest, json.dumps(_COOKIES))
306
+ finally:
307
+ os.umask(old_umask)
308
+ assert stat.S_IMODE(dest.stat().st_mode) == 0o600
309
+ assert json.loads(dest.read_text()) == _COOKIES
310
+
311
+ def test_existing_loose_file_is_tightened(self, tmp_path: Path) -> None:
312
+ dest = tmp_path / "tv_cookies.json"
313
+ dest.write_text("{}")
314
+ dest.chmod(0o664)
315
+ _load_export_script()._write_private(dest, json.dumps(_COOKIES))
316
+ assert stat.S_IMODE(dest.stat().st_mode) == 0o600
@@ -224,3 +224,20 @@ def test_lazy_and_type_checking_imports_are_scanned() -> None:
224
224
  # lazy, inside _get_browser_cookie3()
225
225
  assert "browser_cookie3" in modules
226
226
  assert any("tvkit/auth/cookie_provider.py" in site for site in modules["browser_cookie3"])
227
+
228
+
229
+ def test_browser_cookie3_is_pinned_exactly() -> None:
230
+ """browser-cookie3 stays on an exact pin: a supply-chain hold, not an oversight.
231
+
232
+ It reads and decrypts the user's browser cookie stores, and upstream has been dormant
233
+ since 2024-12. With an open range, a new release (for example after a takeover of the
234
+ PyPI name) would install automatically for every user. Bumping the pin is a reviewed
235
+ decision (SECURITY.md). This test makes sure it is never silently loosened back to ``>=``.
236
+ """
237
+ pyproject = tomllib.loads(PYPROJECT.read_text(encoding="utf-8"))
238
+ specs = [
239
+ r
240
+ for r in pyproject["project"]["dependencies"]
241
+ if _normalize(re.split(r"[<>=!~;\[ ]", r)[0]) == "browser-cookie3"
242
+ ]
243
+ assert specs == ["browser-cookie3==0.20.1"], specs
@@ -0,0 +1,86 @@
1
+ """
2
+ Guard against Markdown that renders at the wrong size on GitHub and PyPI.
3
+
4
+ This exists because of a real defect. The docs style guide told writers to annotate
5
+ output with a comment line such as ``# 250 rows total, showing 5``. That is correct
6
+ inside a fenced ``text`` block. Under a Markdown table, or after the closing fence of an
7
+ output block, the same line is an ATX level-1 heading, so every such note rendered in the
8
+ page's largest type. It had spread to 42 note runs across 21 files, including the
9
+ README that PyPI shows on the project page.
10
+
11
+ The check is structural: a page has at most one level-1 heading (its title). Every other
12
+ ``# `` line outside a fence is almost certainly a stray note. Notes outside a fence
13
+ belong in a ``-`` bullet list (``docs/reference/_style.md``, Style Rule 11).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import pathlib
19
+ import re
20
+
21
+ import pytest
22
+
23
+ REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
24
+
25
+ PAGES: list[pathlib.Path] = sorted(
26
+ [REPO_ROOT / "README.md", *(REPO_ROOT / "docs").rglob("*.md")],
27
+ )
28
+
29
+ # An ATX level-1 heading: up to three spaces of indent, one '#', then a space or end of line.
30
+ _ATX_H1 = re.compile(r"^ {0,3}#(?:[ \t]|$)")
31
+ # A setext level-1 underline: up to three spaces of indent, then only '=' characters.
32
+ _SETEXT_H1 = re.compile(r"^ {0,3}=+[ \t]*$")
33
+ # An opening or closing code fence: three or more backticks or tildes.
34
+ _FENCE = re.compile(r"^\s*(`{3,}|~{3,})")
35
+
36
+
37
+ def _level_one_headings(text: str) -> list[tuple[int, str]]:
38
+ """Return ``(line_number, line)`` for every level-1 heading outside a code fence."""
39
+ found: list[tuple[int, str]] = []
40
+ fence: str | None = None
41
+ previous = ""
42
+ for number, line in enumerate(text.splitlines(), start=1):
43
+ match = _FENCE.match(line)
44
+ if fence is None and match:
45
+ fence = match.group(1)
46
+ elif fence is not None:
47
+ # A fence closes on a run of the same character at least as long as the opener.
48
+ if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence):
49
+ fence = None
50
+ elif _ATX_H1.match(line):
51
+ found.append((number, line))
52
+ elif _SETEXT_H1.match(line) and previous.strip() and not previous.lstrip().startswith("|"):
53
+ found.append((number - 1, previous))
54
+ previous = line if fence is None else ""
55
+ return found
56
+
57
+
58
+ def test_pages_are_found() -> None:
59
+ """The glob must see the README and the docs tree, or the check below is vacuous."""
60
+ names = {p.relative_to(REPO_ROOT).as_posix() for p in PAGES}
61
+ assert "README.md" in names
62
+ assert "docs/index.md" in names
63
+ assert len(PAGES) > 30
64
+
65
+
66
+ @pytest.mark.parametrize("page", PAGES, ids=lambda p: p.relative_to(REPO_ROOT).as_posix())
67
+ def test_at_most_one_level_one_heading(page: pathlib.Path) -> None:
68
+ headings = _level_one_headings(page.read_text(encoding="utf-8"))
69
+ extra = headings[1:]
70
+ assert not extra, (
71
+ f"{page.relative_to(REPO_ROOT)} has {len(headings)} level-1 headings; only the title "
72
+ "may be one. A note line starting with '# ' outside a code fence renders as a "
73
+ "giant heading — write it as a '- ' bullet instead (docs/reference/_style.md, Rule 11).\n"
74
+ + "\n".join(f" line {n}: {line}" for n, line in extra)
75
+ )
76
+
77
+
78
+ def test_detector_catches_a_stray_note_after_a_table() -> None:
79
+ """The detector itself must flag the exact shape that shipped, and ignore fenced comments."""
80
+ page = (
81
+ "# Title\n\n"
82
+ "```python\n# a comment inside a fence is fine\n```\n\n"
83
+ "| a | b |\n|---|---|\n| 1 | 2 |\n\n"
84
+ "# 10 rows total, showing 5\n"
85
+ )
86
+ assert _level_one_headings(page) == [(1, "# Title"), (11, "# 10 rows total, showing 5")]
@@ -16,7 +16,7 @@ Quick Start:
16
16
  >>> data = asyncio.run(get_apple_data())
17
17
  """
18
18
 
19
- __version__ = "0.18.0"
19
+ __version__ = "0.18.2"
20
20
  __author__ = "lumduan"
21
21
  __license__ = "MIT"
22
22
 
@@ -31,6 +31,13 @@ from typing import Any
31
31
  from websockets import ClientConnection
32
32
  from websockets.exceptions import ConnectionClosed, WebSocketException
33
33
 
34
+ logger: logging.Logger = logging.getLogger(__name__)
35
+
36
+ # Protocol functions whose parameters are credentials. Their frames are never written to
37
+ # the log verbatim: the bug-report template asks users to paste DEBUG output into a public
38
+ # issue, and a ``set_auth_token`` frame carries the session's real auth token.
39
+ _CREDENTIAL_FUNCS: frozenset[str] = frozenset({"set_auth_token"})
40
+
34
41
 
35
42
  class MessageService:
36
43
  """
@@ -125,15 +132,18 @@ class MessageService:
125
132
  raise RuntimeError("WebSocket connection not established. Call _connect() first.")
126
133
 
127
134
  message: str = self.create_message(func, args)
128
- logging.debug("Sending message: %s", message)
135
+ if func in _CREDENTIAL_FUNCS:
136
+ logger.debug("Sending message: %s (parameters redacted, %d chars)", func, len(message))
137
+ else:
138
+ logger.debug("Sending message: %s", message)
129
139
 
130
140
  try:
131
141
  await self.ws.send(message)
132
142
  except ConnectionClosed as e:
133
- logging.error("WebSocket connection closed while sending message: %s", e)
143
+ logger.error("WebSocket connection closed while sending message: %s", e)
134
144
  raise
135
145
  except WebSocketException as e:
136
- logging.error("Failed to send message: %s", e)
146
+ logger.error("Failed to send message: %s", e)
137
147
  raise
138
148
 
139
149
  def get_send_message_callable(self) -> Callable[[str, list[Any]], Awaitable[None]]:
@@ -103,7 +103,7 @@ async def validate_symbols(exchange_symbol: str | list[str]) -> bool:
103
103
  if exc.response.status_code == 404:
104
104
  raise ValueError(f"Invalid exchange or symbol or index '{item}'") from exc
105
105
 
106
- logging.warning(
106
+ logger.warning(
107
107
  "Attempt %d failed to validate symbol '%s': %s",
108
108
  attempt + 1,
109
109
  item,
@@ -117,7 +117,7 @@ async def validate_symbols(exchange_symbol: str | list[str]) -> bool:
117
117
  f"Invalid symbol '{item}' after {retries} attempts"
118
118
  ) from exc
119
119
  except httpx.RequestError as exc:
120
- logging.warning(
120
+ logger.warning(
121
121
  "Attempt %d failed to validate symbol '%s': %s",
122
122
  attempt + 1,
123
123
  item,