websocket-claim-audit 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 websocket-claim-audit contributors
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,2 @@
1
+ include LICENSE README.md
2
+ recursive-include tests *.py *.md .env
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: websocket-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented framed socket capabilities
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # websocket-claim-audit
12
+
13
+ Offline, standard-library-only audit of documented framed socket capabilities against Python AST evidence. Version 0.1.0, Python 3.9 or later.
14
+
15
+ Install and run:
16
+
17
+ ```sh
18
+ python3 -m pip install .
19
+ websocket-claim-audit /path/to/project --json
20
+ python3 -m websocket_claim_audit /path/to/project --verbose
21
+ python3 -m unittest discover -s tests -v
22
+ python3 -m build
23
+ ```
24
+
25
+ The scanner reads root README.md and Markdown files with a docs path component. It excludes fenced blocks, counts inline code, joins paragraph lines, lowercases text, expands contractions, and converts hyphens to spaces. Negative spans are removed before positive matching. Exact word-boundary templates alone count; the complete template lists are in the package's POSITIVE and NEGATIVE constants.
26
+
27
+ Production evidence comes from alias-resolved library calls, annotated parameters that accept a channel, or paired object creation and activation calls in the same module. Source is parsed, never executed. Tests, fixtures, documentation, examples, and symlinked files are excluded from production evidence. Evidence confined to tests produces a MEDIUM finding. Environment files are never read.
28
+
29
+ Options: `--json` emits a JSON object with verdict, findings, claim flags, evidence paths and routes, and parse errors. `--verbose` lists evidence in human output. Repeat `--ignore GLOB` to exclude root-relative paths. `--fail-on HIGH` is the default; `--fail-on MEDIUM` also fails on MEDIUM findings. `--version` prints the version. Exit 0 means PASS, 2 means findings meet the threshold, and 1 means a usage or root access error.
30
+
31
+ Rule identifiers:
32
+
33
+ ```text
34
+ documented-websocket-claim-false
35
+ documented-no-websocket-claim-false
36
+ ```
37
+
38
+ ## Limitations
39
+
40
+ Only the exact phrase templates in the constants count as claims. Bare websocket, web socket, socket, live, real time, and real-time words do not count. HTTP polling, TCP sockets, HTTP hooks, and chunked output do not establish a framed socket channel. Imports, names, comments, docstrings, decorators alone, and string literals are insufficient evidence. Static patterns cannot prove runtime behavior. Paired calls need only share a module; they need not share a receiver. Invalid source is reported in parse_errors and supplies no evidence. A positive promise without source fails; a negative promise without source passes. Each family yields at most one finding. This repository deliberately describes the audit using paraphrases so its own prose contains no audited claim.
@@ -0,0 +1,30 @@
1
+ # websocket-claim-audit
2
+
3
+ Offline, standard-library-only audit of documented framed socket capabilities against Python AST evidence. Version 0.1.0, Python 3.9 or later.
4
+
5
+ Install and run:
6
+
7
+ ```sh
8
+ python3 -m pip install .
9
+ websocket-claim-audit /path/to/project --json
10
+ python3 -m websocket_claim_audit /path/to/project --verbose
11
+ python3 -m unittest discover -s tests -v
12
+ python3 -m build
13
+ ```
14
+
15
+ The scanner reads root README.md and Markdown files with a docs path component. It excludes fenced blocks, counts inline code, joins paragraph lines, lowercases text, expands contractions, and converts hyphens to spaces. Negative spans are removed before positive matching. Exact word-boundary templates alone count; the complete template lists are in the package's POSITIVE and NEGATIVE constants.
16
+
17
+ Production evidence comes from alias-resolved library calls, annotated parameters that accept a channel, or paired object creation and activation calls in the same module. Source is parsed, never executed. Tests, fixtures, documentation, examples, and symlinked files are excluded from production evidence. Evidence confined to tests produces a MEDIUM finding. Environment files are never read.
18
+
19
+ Options: `--json` emits a JSON object with verdict, findings, claim flags, evidence paths and routes, and parse errors. `--verbose` lists evidence in human output. Repeat `--ignore GLOB` to exclude root-relative paths. `--fail-on HIGH` is the default; `--fail-on MEDIUM` also fails on MEDIUM findings. `--version` prints the version. Exit 0 means PASS, 2 means findings meet the threshold, and 1 means a usage or root access error.
20
+
21
+ Rule identifiers:
22
+
23
+ ```text
24
+ documented-websocket-claim-false
25
+ documented-no-websocket-claim-false
26
+ ```
27
+
28
+ ## Limitations
29
+
30
+ Only the exact phrase templates in the constants count as claims. Bare websocket, web socket, socket, live, real time, and real-time words do not count. HTTP polling, TCP sockets, HTTP hooks, and chunked output do not establish a framed socket channel. Imports, names, comments, docstrings, decorators alone, and string literals are insufficient evidence. Static patterns cannot prove runtime behavior. Paired calls need only share a module; they need not share a receiver. Invalid source is reported in parse_errors and supplies no evidence. A positive promise without source fails; a negative promise without source passes. Each family yields at most one finding. This repository deliberately describes the audit using paraphrases so its own prose contains no audited claim.
@@ -0,0 +1,18 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "websocket-claim-audit"
7
+ version = "0.1.0"
8
+ description = "Offline static audit of documented framed socket capabilities"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ dependencies = []
13
+
14
+ [project.scripts]
15
+ websocket-claim-audit = "websocket_claim_audit:main"
16
+
17
+ [tool.setuptools.packages.find]
18
+ include = ["websocket_claim_audit*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ MARKER_ONLY_NOT_A_SECRET
@@ -0,0 +1 @@
1
+ websocket server
@@ -0,0 +1,3 @@
1
+ def websocket_handler():
2
+ print("hi")
3
+ return []
@@ -0,0 +1 @@
1
+ websocket server
@@ -0,0 +1,2 @@
1
+ import websockets
2
+ websockets.serve(handler, "localhost", 8765)
@@ -0,0 +1,197 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ import tempfile
7
+ import unittest
8
+ from unittest.mock import patch
9
+
10
+ from websocket_claim_audit import audit, claims, evidence, main
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+ A = 'import websockets\nwebsockets.serve(handler, "localhost", 8765)'
14
+
15
+
16
+ class AuditTests(unittest.TestCase):
17
+ def setUp(self):
18
+ self.temp = tempfile.TemporaryDirectory()
19
+ self.addCleanup(self.temp.cleanup)
20
+ self.root = Path(self.temp.name)
21
+
22
+ def put(self, name, text):
23
+ path = self.root / name
24
+ path.parent.mkdir(parents=True, exist_ok=True)
25
+ path.write_text(text, encoding='utf-8')
26
+ return path
27
+
28
+ def run_cli(self, *args):
29
+ output = io.StringIO()
30
+ with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output):
31
+ try:
32
+ code = main(list(args))
33
+ except SystemExit as exc:
34
+ code = exc.code
35
+ return code, output.getvalue()
36
+
37
+ def case(self, claim, source=None, severity=None, rule='documented-websocket-claim-false'):
38
+ self.put('README.md', claim)
39
+ if source is not None:
40
+ self.put('app.py', source)
41
+ code, output = self.run_cli(str(self.root), '--json')
42
+ result = json.loads(output)
43
+ if severity:
44
+ self.assertEqual([(f['rule'], f['severity']) for f in result['findings']], [(rule, severity)])
45
+ else:
46
+ self.assertEqual(result['findings'], [])
47
+ self.assertEqual(code, 2 if severity == 'HIGH' else 0)
48
+ self.assertEqual(result['verdict'], 'FAIL' if code == 2 else 'PASS')
49
+ return result
50
+
51
+ def test_01_serve(self):
52
+ self.case('websocket server', A)
53
+
54
+ def test_02_connect(self):
55
+ self.case('supports websockets', 'import websockets\nwebsockets.connect("ws://localhost:8765")')
56
+
57
+ def test_03_framework(self):
58
+ self.case('websocket endpoint', 'async def endpoint(ws: WebSocket):\n await ws.accept()')
59
+
60
+ def test_04_app(self):
61
+ self.case('uses websockets', 'from websocket import WebSocketApp\na = WebSocketApp(url)\na.run_forever()')
62
+
63
+ def test_05_aiohttp(self):
64
+ self.case('websocket support', 'from aiohttp.web import WebSocketResponse\na = WebSocketResponse()\na.prepare(request)')
65
+
66
+ def test_06_socketio(self):
67
+ self.case('over websockets', 'import socketio\na = socketio.AsyncServer()\na.emit("event")')
68
+
69
+ def test_07_handler(self):
70
+ self.case('websocket server', 'def websocket_handler():\n print("hi")\n return []', 'HIGH')
71
+
72
+ def test_08_import(self):
73
+ for module in ['websockets', 'websocket', 'websocket_client', 'socketio', 'aiohttp']:
74
+ with self.subTest(module=module):
75
+ self.case('supports websocket', 'import ' + module, 'HIGH')
76
+
77
+ def test_09_tcp(self):
78
+ self.case('websocket connection', 'import socket\ns = socket.socket()\ns.send(b"hi")\ns.recv(10)', 'HIGH')
79
+
80
+ def test_10_polling(self):
81
+ self.case('websocket client', 'import requests, time\nwhile True:\n requests.get(url)\n time.sleep(1)', 'HIGH')
82
+
83
+ def test_11_no_accept(self):
84
+ self.case('websocket endpoint', '@app.websocket("/ws")\ndef endpoint(ws: WebSocket):\n return 1', 'HIGH')
85
+
86
+ def test_12_no_prepare(self):
87
+ self.case('websocket support', 'from aiohttp import WebSocketResponse\na = WebSocketResponse()', 'HIGH')
88
+
89
+ def test_13_negative(self):
90
+ self.case('no websocket support', A, 'HIGH', 'documented-no-websocket-claim-false')
91
+
92
+ def test_14_no_claim(self):
93
+ self.case('A small utility.', A)
94
+
95
+ def test_15_bare_noun(self):
96
+ self.case('the websocket chapter explains the protocol', 'import websockets')
97
+
98
+ def test_16_polling_claim(self):
99
+ self.case('polls every second for updates', 'while True:\n requests.get(url)')
100
+
101
+ def test_17_no_source(self):
102
+ self.case('supports websockets', severity='HIGH')
103
+ self.case('no websocket support')
104
+
105
+ def test_18_test_only(self):
106
+ self.put('tests/test_link.py', A)
107
+ result = self.case('supports websockets', severity='MEDIUM')
108
+ self.assertEqual(result['evidence'], [])
109
+ self.assertEqual(self.run_cli(str(self.root), '--fail-on', 'MEDIUM')[0], 2)
110
+
111
+ def test_19_fences_inline(self):
112
+ self.case('```text\nwebsocket support\n```')
113
+ self.case('~~~\nwebsocket server\n~~~')
114
+ self.case('`websocket support`', severity='HIGH')
115
+
116
+ def test_20_negation(self):
117
+ self.assertEqual(claims('does not support websockets'), (False, True))
118
+ self.case('does not support websockets', A, 'HIGH', 'documented-no-websocket-claim-false')
119
+
120
+ def test_21_generic_connect(self):
121
+ for source in ['import sqlite3 as db\ndb.connect("db")', 'client.connect(url)', 'connect(url)']:
122
+ self.case('supports websockets', source, 'HIGH')
123
+
124
+ def test_22_cli(self):
125
+ self.assertEqual(self.run_cli('--version'), (0, '0.1.0\n'))
126
+ self.put('app.py', A)
127
+ self.put('docs/guide.md', 'no websocket support')
128
+ self.assertEqual(self.run_cli(str(self.root), '--json')[0], 2)
129
+ code, output = self.run_cli(str(self.root), '--verbose', '--ignore', 'docs/*')
130
+ self.assertEqual(code, 0)
131
+ self.assertIn('Evidence app.py: route A', output)
132
+ self.assertEqual(self.run_cli(str(self.root / 'missing'))[0], 1)
133
+ self.assertEqual(self.run_cli('--bad')[0], 1)
134
+
135
+ def test_23_self(self):
136
+ result = audit(ROOT)
137
+ self.assertEqual(result['verdict'], 'PASS')
138
+ self.assertEqual(result['findings'], [])
139
+ self.assertEqual(result['claims'], {'positive': False, 'negative': False})
140
+
141
+ def test_24_env_guard(self):
142
+ self.put('fixtures/.env', 'MARKER_ONLY_NOT_A_SECRET')
143
+ original = Path.open
144
+ def guarded(path, *args, **kwargs):
145
+ self.assertNotEqual(path.name, '.env')
146
+ return original(path, *args, **kwargs)
147
+ with patch.object(Path, 'open', guarded):
148
+ self.case('A utility', A)
149
+
150
+ def test_25_packaging(self):
151
+ bare = re.compile(r'\b' + 'py' + r'thon\b(?!3)')
152
+ for path in list((ROOT / 'websocket_claim_audit').glob('*.py')) + list((ROOT / 'tests').rglob('*.py')) + [ROOT / 'README.md']:
153
+ self.assertIsNone(bare.search(path.read_text()), str(path))
154
+ config = (ROOT / 'pyproject.toml').read_text()
155
+ self.assertIn('setuptools>=77', config)
156
+ self.assertIn('license = "MIT"', config)
157
+ self.assertIn('recursive-include tests', (ROOT / 'MANIFEST.in').read_text())
158
+
159
+ def test_26_aliases(self):
160
+ for source in ['import websockets as ws\nws.connect(url)', 'from websockets import sync as ws\nws.connect(url)', 'import websocket as ws\nws.create_connection(url)', 'from websocket import WebSocketApp as App\na=App(url)\na.run_forever()', 'from websocket_server import WebsocketServer as S\ns=S()\ns.serve_forever()', 'import SimpleWebSocketServer as sw\ns=sw.SimpleWebSocketServer()\ns.run_forever()']:
161
+ self.assertIsNotNone(evidence(source))
162
+
163
+ def test_27_incomplete_and_fake(self):
164
+ for source in ['WebSocketApp(url)\na.run_forever()', 'from websocket import WebSocketApp\na=WebSocketApp(url)', 'import socketio\ns=socketio.Server()', 'import socketio\ns.emit("x")', '"websockets.connect(url)"', 'class WebSocketResponse: pass\na=WebSocketResponse()\na.prepare(r)', '@app.websocket("/")\ndef handler():\n return 1']:
165
+ self.assertIsNone(evidence(source))
166
+
167
+ def test_28_scope_and_pairing(self):
168
+ self.put('README.md', 'websocket support')
169
+ for name in ['fixtures/a.py', 'examples/a.py', 'docs/a.py']:
170
+ self.put(name, A)
171
+ self.put('a.py', 'from websocket import WebSocketApp\na=WebSocketApp(url)')
172
+ self.put('b.py', 'a.run_forever()')
173
+ self.assertEqual(audit(self.root)['findings'][0]['severity'], 'HIGH')
174
+ self.put('test_link.py', A)
175
+ self.assertEqual(audit(self.root)['findings'][0]['severity'], 'MEDIUM')
176
+ self.put('link.py', '').unlink()
177
+ (self.root / 'link.py').symlink_to(self.root / 'test_link.py')
178
+ self.assertEqual(audit(self.root)['evidence'], [])
179
+
180
+ def test_29_normalization(self):
181
+ self.assertEqual(claims("doesn't use websockets"), (False, True))
182
+ self.assertEqual(claims('WebSocket-\nsupport'), (True, False))
183
+ self.assertEqual(claims('websocket\n\nsupport'), (False, False))
184
+ self.assertEqual(claims('xwebsocket supportx'), (False, False))
185
+ self.assertEqual(claims('tcp socket; webhook; streams results; real-time'), (False, False))
186
+
187
+ def test_30_both_families(self):
188
+ result = self.case('websocket support. No websockets.', severity='HIGH')
189
+ self.assertEqual(result['claims'], {'positive': True, 'negative': True})
190
+ self.put('docs/negative.md', 'no websockets')
191
+ self.put('app.py', A)
192
+ result = audit(self.root)
193
+ self.assertEqual([f['rule'] for f in result['findings']], ['documented-no-websocket-claim-false'])
194
+
195
+
196
+ if __name__ == '__main__':
197
+ unittest.main()
@@ -0,0 +1,190 @@
1
+ """Offline documentation and AST audit."""
2
+ import argparse
3
+ import ast
4
+ import fnmatch
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+
9
+ __version__ = '0.1.0'
10
+ WS_MODULES = {'websockets', 'websocket', 'websocket_client'}
11
+ POSITIVE = [
12
+ 'websocket support', 'web socket support', 'websocket connections',
13
+ 'web socket connections', 'websocket connection', 'web socket connection',
14
+ 'websocket server', 'web socket server', 'websocket client', 'web socket client',
15
+ 'websocket api', 'websocket endpoint', 'websocket endpoints',
16
+ 'supports websockets', 'supports web sockets', 'supports websocket',
17
+ 'support for websockets', 'support for web sockets', 'support for websocket',
18
+ 'uses websockets', 'uses web sockets', 'uses websocket',
19
+ 'using websockets', 'using web sockets', 'using websocket',
20
+ 'over websockets', 'over web sockets', 'over websocket',
21
+ 'via websockets', 'via web sockets', 'via websocket',
22
+ 'websocket based', 'websocket powered',
23
+ ]
24
+ NEGATIVE = [
25
+ 'no websocket support', 'no web socket support',
26
+ 'does not support websockets', 'does not support web sockets',
27
+ 'does not support websocket', 'does not use websockets',
28
+ 'does not use web sockets', 'does not use websocket',
29
+ 'websocket not supported', 'web socket not supported',
30
+ 'without websockets', 'without web sockets', 'without websocket',
31
+ 'no websockets', 'no web sockets', 'no websocket',
32
+ ]
33
+
34
+
35
+ def pattern(phrases):
36
+ return re.compile(r'\b(?:' + '|'.join(re.escape(p) for p in sorted(phrases, key=len, reverse=True)) + r')\b')
37
+
38
+
39
+ def claims(text):
40
+ lines = []
41
+ fence = None
42
+ for line in text.splitlines():
43
+ match = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
44
+ if fence:
45
+ if re.match(r'^\s{0,3}' + re.escape(fence[0]) + '{' + str(fence[1]) + r',}\s*$', line):
46
+ fence = None
47
+ lines.append('')
48
+ elif match:
49
+ fence = (match[1][0], len(match[1]))
50
+ lines.append('')
51
+ else:
52
+ lines.append(line)
53
+ positive = negative = False
54
+ for paragraph in re.split(r'\n\s*\n', '\n'.join(lines)):
55
+ normalized = re.sub(r'\s+', ' ', paragraph.lower().replace("n't", ' not').replace('-', ' '))
56
+ negative |= bool(pattern(NEGATIVE).search(normalized))
57
+ normalized = pattern(NEGATIVE).sub(' ', normalized)
58
+ positive |= bool(pattern(POSITIVE).search(normalized))
59
+ return positive, negative
60
+
61
+
62
+ def evidence(text):
63
+ tree = ast.parse(text)
64
+ imports = {}
65
+ for node in ast.walk(tree):
66
+ if isinstance(node, ast.Import):
67
+ for alias in node.names:
68
+ imports[alias.asname or alias.name.split('.')[0]] = alias.name
69
+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
70
+ for alias in node.names:
71
+ imports[alias.asname or alias.name] = node.module + '.' + alias.name
72
+
73
+ def resolved(node):
74
+ if isinstance(node, ast.Name):
75
+ return imports.get(node.id, '')
76
+ if isinstance(node, ast.Attribute):
77
+ base = resolved(node.value)
78
+ return base + '.' + node.attr if base else ''
79
+ return ''
80
+
81
+ calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call)]
82
+ methods = {n.func.attr for n in calls if isinstance(n.func, ast.Attribute)}
83
+ for call in calls:
84
+ func = call.func
85
+ if (isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name)
86
+ and func.attr in {'serve', 'connect', 'create_connection'}
87
+ and imports.get(func.value.id, '').split('.')[0] in WS_MODULES):
88
+ return 'A'
89
+ for node in ast.walk(tree):
90
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
91
+ args = node.args.posonlyargs + node.args.args + node.args.kwonlyargs
92
+ args += [a for a in (node.args.vararg, node.args.kwarg) if a]
93
+ for arg in args:
94
+ annotation = arg.annotation
95
+ name = annotation.id if isinstance(annotation, ast.Name) else annotation.attr if isinstance(annotation, ast.Attribute) else ''
96
+ if name == 'WebSocket':
97
+ for child in ast.walk(node):
98
+ if (isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute)
99
+ and child.func.attr == 'accept' and isinstance(child.func.value, ast.Name)
100
+ and child.func.value.id == arg.arg):
101
+ return 'B'
102
+ for call in calls:
103
+ name = resolved(call.func)
104
+ module, _, cls = name.rpartition('.')
105
+ root = module.split('.')[0]
106
+ if cls == 'WebSocketApp' and root in WS_MODULES and 'run_forever' in methods:
107
+ return 'C'
108
+ if cls == 'WebSocketResponse' and root == 'aiohttp' and 'prepare' in methods:
109
+ return 'C'
110
+ if cls in {'Server', 'AsyncServer'} and root == 'socketio' and methods & {'emit', 'send', 'on'}:
111
+ return 'C'
112
+ if ((cls == 'WebsocketServer' and root == 'websocket_server') or
113
+ (cls == 'SimpleWebSocketServer' and root == 'SimpleWebSocketServer')) and methods & {'serve_forever', 'run_forever'}:
114
+ return 'C'
115
+ return None
116
+
117
+
118
+ def audit(root, ignore=(), fail_on='HIGH'):
119
+ root = Path(root)
120
+ if not root.is_dir() or not root.stat().st_mode & 0o444:
121
+ raise ValueError('root must be a readable directory')
122
+ positive = negative = False
123
+ production = []
124
+ testing = []
125
+ errors = []
126
+ for path in sorted(root.rglob('*')):
127
+ if path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent != root.parent):
128
+ continue
129
+ relative = path.relative_to(root)
130
+ name = relative.as_posix()
131
+ if any(fnmatch.fnmatchcase(name, glob) for glob in ignore):
132
+ continue
133
+ if not path.is_file():
134
+ continue
135
+ if (name == 'README.md' or ('docs' in relative.parts[:-1] and path.suffix.lower() == '.md')):
136
+ p, n = claims(path.read_text(encoding='utf-8'))
137
+ positive |= p
138
+ negative |= n
139
+ if path.suffix != '.py':
140
+ continue
141
+ is_test = 'tests' in relative.parts[:-1] or path.name.startswith('test_') or path.name.endswith('_test.py')
142
+ if {'fixtures', 'docs', 'examples'} & set(relative.parts[:-1]):
143
+ continue
144
+ try:
145
+ route = evidence(path.read_text(encoding='utf-8'))
146
+ except (SyntaxError, UnicodeError) as exc:
147
+ errors.append(name + ': ' + str(exc))
148
+ continue
149
+ if route:
150
+ (testing if is_test else production).append({'path': name, 'route': route})
151
+ findings = []
152
+ if positive and not production:
153
+ findings.append({'rule': 'documented-websocket-claim-false', 'severity': 'MEDIUM' if testing else 'HIGH', 'message': 'Documented live socket link lacks production evidence.'})
154
+ if negative and production:
155
+ findings.append({'rule': 'documented-no-websocket-claim-false', 'severity': 'HIGH', 'message': 'Documented absence conflicts with production evidence.'})
156
+ failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
157
+ return {'verdict': 'FAIL' if failed else 'PASS', 'findings': findings,
158
+ 'claims': {'positive': positive, 'negative': negative},
159
+ 'evidence': production, 'test_evidence': testing, 'parse_errors': errors}
160
+
161
+
162
+ def main(argv=None):
163
+ class Parser(argparse.ArgumentParser):
164
+ def error(self, message):
165
+ self.print_usage()
166
+ self.exit(1, message + '\n')
167
+ parser = Parser(description=__doc__)
168
+ parser.add_argument('root')
169
+ parser.add_argument('--json', action='store_true')
170
+ parser.add_argument('--verbose', action='store_true')
171
+ parser.add_argument('--ignore', action='append', default=[])
172
+ parser.add_argument('--fail-on', choices=['HIGH', 'MEDIUM'], default='HIGH')
173
+ parser.add_argument('--version', action='version', version=__version__)
174
+ args = parser.parse_args(argv)
175
+ try:
176
+ result = audit(args.root, args.ignore, args.fail_on)
177
+ except (OSError, ValueError) as exc:
178
+ parser.exit(1, str(exc) + '\n')
179
+ if args.json:
180
+ print(json.dumps(result))
181
+ else:
182
+ print(result['verdict'])
183
+ for finding in result['findings']:
184
+ print('{severity} {rule}: {message}'.format(**finding))
185
+ if args.verbose:
186
+ for item in result['evidence'] + result['test_evidence']:
187
+ print('Evidence {path}: route {route}'.format(**item))
188
+ for error in result['parse_errors']:
189
+ print('Parse error: ' + error)
190
+ return 2 if result['verdict'] == 'FAIL' else 0
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: websocket-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented framed socket capabilities
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # websocket-claim-audit
12
+
13
+ Offline, standard-library-only audit of documented framed socket capabilities against Python AST evidence. Version 0.1.0, Python 3.9 or later.
14
+
15
+ Install and run:
16
+
17
+ ```sh
18
+ python3 -m pip install .
19
+ websocket-claim-audit /path/to/project --json
20
+ python3 -m websocket_claim_audit /path/to/project --verbose
21
+ python3 -m unittest discover -s tests -v
22
+ python3 -m build
23
+ ```
24
+
25
+ The scanner reads root README.md and Markdown files with a docs path component. It excludes fenced blocks, counts inline code, joins paragraph lines, lowercases text, expands contractions, and converts hyphens to spaces. Negative spans are removed before positive matching. Exact word-boundary templates alone count; the complete template lists are in the package's POSITIVE and NEGATIVE constants.
26
+
27
+ Production evidence comes from alias-resolved library calls, annotated parameters that accept a channel, or paired object creation and activation calls in the same module. Source is parsed, never executed. Tests, fixtures, documentation, examples, and symlinked files are excluded from production evidence. Evidence confined to tests produces a MEDIUM finding. Environment files are never read.
28
+
29
+ Options: `--json` emits a JSON object with verdict, findings, claim flags, evidence paths and routes, and parse errors. `--verbose` lists evidence in human output. Repeat `--ignore GLOB` to exclude root-relative paths. `--fail-on HIGH` is the default; `--fail-on MEDIUM` also fails on MEDIUM findings. `--version` prints the version. Exit 0 means PASS, 2 means findings meet the threshold, and 1 means a usage or root access error.
30
+
31
+ Rule identifiers:
32
+
33
+ ```text
34
+ documented-websocket-claim-false
35
+ documented-no-websocket-claim-false
36
+ ```
37
+
38
+ ## Limitations
39
+
40
+ Only the exact phrase templates in the constants count as claims. Bare websocket, web socket, socket, live, real time, and real-time words do not count. HTTP polling, TCP sockets, HTTP hooks, and chunked output do not establish a framed socket channel. Imports, names, comments, docstrings, decorators alone, and string literals are insufficient evidence. Static patterns cannot prove runtime behavior. Paired calls need only share a module; they need not share a receiver. Invalid source is reported in parse_errors and supplies no evidence. A positive promise without source fails; a negative promise without source passes. Each family yields at most one finding. This repository deliberately describes the audit using paraphrases so its own prose contains no audited claim.
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ tests/test_audit.py
6
+ tests/fixtures/.env
7
+ tests/fixtures/bad/README.md
8
+ tests/fixtures/bad/app.py
9
+ tests/fixtures/good/README.md
10
+ tests/fixtures/good/app.py
11
+ websocket_claim_audit/__init__.py
12
+ websocket_claim_audit/__main__.py
13
+ websocket_claim_audit.egg-info/PKG-INFO
14
+ websocket_claim_audit.egg-info/SOURCES.txt
15
+ websocket_claim_audit.egg-info/dependency_links.txt
16
+ websocket_claim_audit.egg-info/entry_points.txt
17
+ websocket_claim_audit.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ websocket-claim-audit = websocket_claim_audit:main
@@ -0,0 +1 @@
1
+ websocket_claim_audit