Initial Commit

This commit is contained in:
2025-09-22 19:44:55 +02:00
commit b668eb3d77
15 changed files with 680 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
__pycache__

284
PyPost.py Normal file
View File

@@ -0,0 +1,284 @@
#!/usr/bin/env python3
import os
import sys
import time
from pathlib import Path
import marko
from marko.ext.gfm import GFM
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Use absolute paths
ROOT = Path(os.path.abspath("."))
MARKDOWN_DIR = ROOT / "markdown"
HTML_DIR = ROOT / "html"
# Create markdown parser with table support
markdown_parser = marko.Markdown(extensions=[GFM])
# Long useless Lorem Ipsum comments
LOREM_IPSUM_COMMENTS = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.",
"Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet.",
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa.",
"gay furry pride >:3 OwO get rekt Charlie Kirk",
"Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.",
"Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias.",
"Nulla facilisi. Cras vehicula aliquet libero, sit amet lacinia nunc commodo eu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae.",
"Proin euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl. Sed euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl.",
"Vivamus euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl. Sed euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl."
]
def render_markdown(md_path: Path):
"""Render a single markdown file to an obfuscated HTML file."""
try:
text = md_path.read_text(encoding="utf-8")
except Exception as e:
print(f"Could not read {md_path}: {e}")
return
html_body = markdown_parser.convert(text)
# Extract title from filename or first H1
title = md_path.stem
for line in text.splitlines():
if line.startswith("# "):
title = line[2:].strip()
break
import base64
import random
from hashes.hashes import hash_list
# Create clean HTML structure
clean_html = f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{title}</title>
<link rel="stylesheet" href="../css/main.css">
<link rel="icon" type="image/x-icon" href="../css/favicon/favicon.ico">
<script src="../js/post/normal.js"></script>
</head>
<body>
<main class="container">
<h1 onclick="window.location.href='/'" style="cursor:pointer">← {title}</h1>
<div class="meta">Written@{time.asctime(time.localtime())}</div>
<hr style="margin:10px 0;" />
{html_body}
<footer style=" position: absolute;bottom: 0;width: 100%;">
<hr style="margin:10px 0;" />
{time.strftime("%Y-%m-%d %H:%M:%S")}<br/>
Hash 1 (<b>UTF-8</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("utf-8")).decode("utf-8")}</i><br />
Hash 2 (<b>ASCII</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("ascii")).decode("ascii")}</i><br />
<i>Decode Hashes to identify pages</i>
</footer>
</main>
</body>
</html>"""
# Obfuscate the HTML for browser output
obfuscated_html = obfuscate_html(clean_html)
# Ensure html directory exists
HTML_DIR.mkdir(exist_ok=True)
# Maintain relative directory structure in html/
relative_path = md_path.relative_to(MARKDOWN_DIR)
out_path = HTML_DIR / relative_path.with_suffix(".html")
# Create parent directories if needed
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(obfuscated_html, encoding="utf-8")
print(f"Rendered: {md_path} -> {out_path}")
def obfuscate_html(html_content):
"""Working obfuscation that maintains functionality"""
import re
import random
# Generate random strings
def generate_random_string(length=8):
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(random.choice(chars) for _ in range(length))
# Protect original content
protected_blocks = []
def protect_scripts(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_SCRIPT_{len(protected_blocks)-1} -->'
def protect_styles(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_STYLE_{len(protected_blocks)-1} -->'
# First pass: protect critical content
temp_html = re.sub(r'<script[^>]*>.*?</script>', protect_scripts, html_content, flags=re.DOTALL)
temp_html = re.sub(r'<style[^>]*>.*?</style>', protect_styles, temp_html, flags=re.DOTALL)
# Protect tables
def protect_tables(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_TABLE_{len(protected_blocks)-1} -->'
temp_html = re.sub(r'<table[^>]*>.*?</table>', protect_tables, temp_html, flags=re.DOTALL)
# Clean up HTML - remove extra whitespace
lines = []
for line in temp_html.split('\n'):
cleaned_line = ' '.join(line.split())
if cleaned_line:
lines.append(cleaned_line)
# Add comments between lines (but not too many)
obfuscated_lines = []
for i, line in enumerate(lines):
# Add comment before some lines
if line and not line.startswith('<!--') and random.random() > 0.7:
lorem_comment = random.choice(LOREM_IPSUM_COMMENTS)
obfuscated_lines.append(f'<!-- {lorem_comment} -->')
obfuscated_lines.append(line)
# Add comment after some lines
if line and not line.startswith('<!--') and random.random() > 0.8:
lorem_comment = random.choice(LOREM_IPSUM_COMMENTS)
obfuscated_lines.append(f'<!-- {lorem_comment} -->')
obfuscated = '\n'.join(obfuscated_lines)
# Inject random comments between SOME elements (not all)
def inject_some_comments(html):
# Only inject between certain safe elements
safe_patterns = [
(r'(</div>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</p>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</span>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h1>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h2>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h3>)', r'\1<!--' + generate_random_string(6) + '-->'),
]
for pattern, replacement in safe_patterns:
if random.random() > 0.5: # 50% chance to apply each pattern
html = re.sub(pattern, replacement, html)
return html
obfuscated = inject_some_comments(obfuscated)
# Add header comments (fewer to avoid breaking the document)
header_comments = [
'auto-obfuscated-' + generate_random_string(10),
'generated-' + generate_random_string(8),
]
header_block = '\n'.join([f'<!-- {comment} -->' for comment in header_comments])
obfuscated = header_block + '\n' + obfuscated
# Add footer comments
footer_comments = [
'end-' + generate_random_string(10),
'completed-' + generate_random_string(8),
]
footer_block = '\n'.join([f'<!-- {comment} -->' for comment in footer_comments])
obfuscated = obfuscated + '\n' + footer_block
# Minimal invisible characters - only in text content, not in tags
invisible_chars = ['\u200B', '\u200C']
def add_minimal_invisible(match):
text = match.group(1)
# NEVER obfuscate script-like content
if any(keyword in text for keyword in ['function', 'const ', 'var ', 'let ', 'document.', 'window.', 'getElement', 'querySelector', 'addEventListener']):
return '>' + text + '<'
# Only add to plain text content
if len(text) > 10: # Only on longer text blocks
result = []
for i, char in enumerate(text):
result.append(char)
# Very rarely add invisible chars
if i % 8 == 0 and i > 0 and random.random() > 0.8:
result.append(random.choice(invisible_chars))
return '>' + ''.join(result) + '<'
return '>' + text + '<'
obfuscated = re.sub(r'>([^<]+)<', add_minimal_invisible, obfuscated)
# Restore protected content exactly as-is
for i, protected_content in enumerate(protected_blocks):
obfuscated = obfuscated.replace(f'<!-- PROTECTED_SCRIPT_{i} -->', protected_content)
obfuscated = obfuscated.replace(f'<!-- PROTECTED_STYLE_{i} -->', protected_content)
obfuscated = obfuscated.replace(f'<!-- PROTECTED_TABLE_{i} -->', protected_content)
# Final cleanup - ensure no double newlines and remove extra spaces
obfuscated = re.sub(r'\n\n+', '\n', obfuscated)
obfuscated = re.sub(r'[ \t]+', ' ', obfuscated) # Remove extra spaces and tabs
return obfuscated
def remove_html(md_path: Path):
relative_path = md_path.relative_to(MARKDOWN_DIR)
out_path = HTML_DIR / relative_path.with_suffix(".html")
if out_path.exists():
out_path.unlink()
print(f"Removed: {out_path}")
def initial_scan(markdown_dir: Path):
print(f"Initial scan for markdown in {markdown_dir}...")
for md in markdown_dir.rglob("*.md"):
render_markdown(md)
class Handler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory and event.src_path.endswith(".md"):
render_markdown(Path(event.src_path))
def on_modified(self, event):
if not event.is_directory and event.src_path.endswith(".md"):
render_markdown(Path(event.src_path))
def on_deleted(self, event):
if not event.is_directory and event.src_path.endswith(".md"):
remove_html(Path(event.src_path))
def on_moved(self, event):
src = Path(event.src_path)
dest = Path(event.dest_path)
if src.suffix.lower() == ".md":
remove_html(src)
if dest.suffix.lower() == ".md":
render_markdown(dest)
if __name__ == "__main__":
if not MARKDOWN_DIR.exists():
print(f"Error: Markdown directory not found: {MARKDOWN_DIR}")
print("Please create a 'markdown' directory in the current working directory.")
sys.exit(1)
initial_scan(MARKDOWN_DIR)
event_handler = Handler()
observer = Observer()
observer.schedule(event_handler, str(MARKDOWN_DIR), recursive=True)
observer.start()
print(f"Watching {MARKDOWN_DIR} for changes. Ctrl+C to stop.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()

51
PyPost.pyproj Normal file
View File

@@ -0,0 +1,51 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>10222d8e-7c54-4460-8d3b-80f10266f307</ProjectGuid>
<ProjectHome>.</ProjectHome>
<StartupFile>PyPost.py</StartupFile>
<SearchPath>
</SearchPath>
<WorkingDirectory>.</WorkingDirectory>
<OutputPath>.</OutputPath>
<Name>PyPost</Name>
<RootNamespace>PyPost</RootNamespace>
<InterpreterId>MSBuild|env|$(MSBuildProjectFullPath)</InterpreterId>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
</PropertyGroup>
<ItemGroup>
<Compile Include="PyPost.py" />
<Compile Include="webserver.py" />
</ItemGroup>
<ItemGroup>
<Interpreter Include="env\">
<Id>env</Id>
<Version>3.13</Version>
<Description>env (Python 3.13)</Description>
<InterpreterPath>Scripts\python.exe</InterpreterPath>
<WindowsInterpreterPath>Scripts\pythonw.exe</WindowsInterpreterPath>
<PathEnvironmentVariable>PYTHONPATH</PathEnvironmentVariable>
<Architecture>X64</Architecture>
</Interpreter>
</ItemGroup>
<ItemGroup>
<Content Include="test.md" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets" />
<!-- Uncomment the CoreCompile target to enable the Build command in
Visual Studio and specify your pre- and post-build commands in
the BeforeBuild and AfterBuild targets below. -->
<!--<Target Name="CoreCompile" />-->
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
</Project>

BIN
css/favicon/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

87
css/main.css Normal file
View File

@@ -0,0 +1,87 @@
/* Reset & basic styles */
body {
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
margin: 1em;
color: #000;
background: #fff;
}
h1, h2, h3, h4, h5, h6 {
font-weight: bold;
margin: 1em 0 0.5em;
}
p, ul, ol, blockquote, pre, table {
margin: 0.5em 0;
}
/* Lists */
ul, ol {
padding-left: 2em;
}
li {
margin: 0.25em 0;
}
/* Links */
a {
color: blue;
text-decoration: underline;
}
a:hover {
color: darkblue;
}
/* Tables */
table {
border-collapse: collapse;
width: 100%;
margin: 1em 0;
}
th, td {
border: 1px solid #000;
padding: 0.5em;
text-align: left;
}
th {
background: #eee;
}
/* Code blocks */
code, pre {
font-family: Consolas, monospace;
background: #f5f5f5;
padding: 2px 4px;
border-radius: 3px;
}
pre {
overflow: auto;
padding: 0.5em;
}
/* Blockquote */
blockquote {
border-left: 4px solid #ccc;
padding-left: 1em;
color: #555;
margin: 1em 0;
}
/* Forms */
input, select, textarea, button {
font: inherit;
padding: 0.4em;
margin: 0.25em 0;
border: 1px solid #999;
border-radius: 3px;
}
button {
background: #eee;
cursor: pointer;
}
button:hover {
background: #ddd;
}

0
hashes/__init__.py Normal file
View File

18
hashes/hashes.py Normal file
View File

@@ -0,0 +1,18 @@
hash_list = [
"femboy flamingo",
"tomboy toucan",
"emo eagle",
"gay giraffe",
"lesbian koala",
"transgender tulcan",
"bisexual bear",
"asexual albatross",
"pansexual panda",
"nonbinary narwhal",
"genderfluid fox",
"intersex iguana",
"demisexual dolphin",
"polysexual penguin",
"aromantic armadillo",
"queer quokka",
]

49
html/base/index.html Normal file
View File

@@ -0,0 +1,49 @@
<!DOCTYPE html>
<html>
<head>
<title>Auto Index</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h1 { color: #333; }
li { transition: font-size 0.5s cubic-bezier(0.075, 0.82, 0.165, 1);}
li:hover { font-size: larger;}
#nojs { display: inline-block;color: red;transition: transform 0.7s cubic-bezier(0.215, 0.610, 0.355, 1); }
#nojs:hover { transform: skewX(-12deg);}
</style>
<link rel="icon" type="image/x-icon" href="../../css/favicon/favicon.ico">
</head>
<body>
<noscript>
<h1 id="nojs">Please enable Javascript!</h1>
<p>
<i><strong> If you might be wondering, what does the Script do?</strong></i><br/>
<ul>
<li>It strips the Links you see below from any .html extension</li>
<li>It is essential for themeswitching to work</li>
<li>it will definetly hak u >:3</li>
</ul>
</p>
</noscript>
<script>
// we just repurpouse the nojs from css
// much easier than adding a new element
document.write('<h1 id="nojs" style="color:black;">Index of PyPost</h1>');
</script>
<p>Available pages:</p>
<!-- CONTENT -->
<script src="../../js/normal.js"></script>
<footer style="
position: absolute;
bottom: 0;
width: 100%;
">
<p>
</p>
</footer>
</body>
</html>

1
js/main.js Normal file

File diff suppressed because one or more lines are too long

38
js/normal.js Normal file
View File

@@ -0,0 +1,38 @@
/**
* Strips ".html" from link text, preserving href.
* Idempotent and works for dynamically added links.
*
* @param {HTMLElement} link - The <a> element to process
*/
function beautifyLinkText(link) {
const originalText = link.dataset.originalText || link.textContent;
// Only strip if the text ends with ".html"
if (originalText.endsWith(".html")) {
link.textContent = originalText.replace(/\.html$/, "");
}
// Store original text to avoid double-processing
link.dataset.originalText = originalText;
}
// Process all existing links
document.querySelectorAll("a").forEach(beautifyLinkText);
// Observe new links added dynamically
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType !== 1) return; // Not an element
if (node.tagName === "A") {
beautifyLinkText(node);
} else {
node.querySelectorAll("a").forEach(beautifyLinkText);
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });

1
js/post/main.js Normal file

File diff suppressed because one or more lines are too long

31
js/post/normal.js Normal file
View File

@@ -0,0 +1,31 @@
// Theme toggling script for PyPost
function toggleTheme() {
const darkStyles = document.getElementById('dark-styles');
const lightStyles = document.getElementById('light-styles');
const currentlyLight = !lightStyles.disabled;
document.body.classList.add('theme-transitioning');
if (currentlyLight) {
// Switch to dark
lightStyles.disabled = true;
darkStyles.disabled = false;
} else {
// Switch to light
lightStyles.disabled = false;
darkStyles.disabled = true;
}
setTimeout(() => {
document.body.classList.remove('theme-transitioning');
}, 400);
}
document.addEventListener('DOMContentLoaded', function() {
const darkStyles = document.getElementById('dark-styles');
const lightStyles = document.getElementById('light-styles');
// Always start in light mode
lightStyles.disabled = false;
darkStyles.disabled = true;
});

9
log/Logger.py Normal file
View File

@@ -0,0 +1,9 @@
class Logger:
def log_error(self, message: str) -> None:
print(f"ERROR: {message}")
def log_info(self, message: str) -> None:
print(f"INFO: {message}")
def log_debug(self, message: str) -> None:
print(f"DEBUG: {message}")
def log_warning(self, message: str) -> None:
print(f"WARNING: {message}")

0
log/__init__.py Normal file
View File

110
webserver.py Normal file
View File

@@ -0,0 +1,110 @@
import os
import sys
import threading
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
import mimetypes
from jsmin import jsmin # pip install jsmin
import PyPost
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
HTML_DIR = os.path.join(PROJECT_ROOT, "html")
BASE_FILE = os.path.join(HTML_DIR, "base", "index.html")
def get_html_files(directory=HTML_DIR):
html_files = []
for entry in os.listdir(directory):
full_path = os.path.join(directory, entry)
if os.path.isfile(full_path) and entry.endswith(".html"):
html_files.append(entry)
return html_files
def build_index_page():
with open(BASE_FILE, "r", encoding="utf-8") as f:
base_html = f.read()
html_files = get_html_files(HTML_DIR)
links = "\n".join(f'<li><a href="/html/{fname}">{fname}</a></li>' for fname in html_files)
content = f"<ul>{links}</ul>"
# Insert footer after content
full_content = content + index_footer()
return base_html.replace("<!-- CONTENT -->", full_content)
import base64
import random
from hashes.hashes import hash_list
def index_footer():
return f"""
<footer style="
position: absolute;
bottom: 0;
width: 100%;
">
<hr style="border: 1px solid #ccc;" />
<p>
Hash 1 (<b>UTF-8</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("utf-8")).decode("utf-8")}</i><br />
Hash 2 (<b>ASCII</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("ascii")).decode("ascii")}</i><br />
<i>Decode Hashes to identify pages</i>
</p>
</footer>
"""
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
req_path = self.path.lstrip("/")
if req_path == "" or req_path == "index.html":
content = build_index_page()
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(content.encode("utf-8"))
return
file_path = os.path.normpath(os.path.join(PROJECT_ROOT, req_path))
if not file_path.startswith(PROJECT_ROOT):
self.send_response(403)
self.end_headers()
self.wfile.write(b"403 - Forbidden")
return
if os.path.isfile(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type is None:
mime_type = "application/octet-stream"
with open(file_path, "rb") as f:
content = f.read()
# Obfuscate JS on the fly
if mime_type == "application/javascript" or file_path.endswith(".js"):
try:
content = jsmin(content.decode("utf-8")).encode("utf-8")
except Exception as e:
print(f"Error minifying JS file {file_path}: {e}")
self.send_response(200)
self.send_header("Content-type", mime_type)
self.end_headers()
self.wfile.write(content)
return
self.send_response(404)
self.end_headers()
self.wfile.write(b"404 - Not Found")
def run_pypost():
"""Run PyPost.py in a separate process."""
script = os.path.join(PROJECT_ROOT, "PyPost.py")
subprocess.run([sys.executable, script])
if __name__ == "__main__":
threading.Thread(target=run_pypost, daemon=True).start()
print("Started PyPost.py in background watcher thread.")
server_address = ("localhost", 8000)
httpd = HTTPServer(server_address, MyHandler)
print("Serving on http://localhost:8000")
httpd.serve_forever()