-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
480 lines (428 loc) · 20.6 KB
/
index.html
File metadata and controls
480 lines (428 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>KitePad</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Exo+2:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@master/qrcode.min.js"></script>
<script type="module">
import { CodeJar } from 'https://cdn.jsdelivr.net/npm/codejar@3.2.2/codejar.js';
window.CodeJar = CodeJar;
</script>
<style>
.katex { font-size: 1.1em; }
.embed-container { margin: 15px 0; max-width: 100%; }
iframe { border-radius: 8px; border: none; }
</style>
</head>
<body>
<div class="container">
<div class="nav-links">
<a href="/view" class="nav-link">View Posts</a>
<a href="https://github.com/irhdab/kitepad/tree/main" class="nav-link" target="_blank">GitHub</a>
</div>
<div class="header-main">
<h1 class="title-text">KitePad</h1>
<span class="tagline">Zero-knowledge pastebin. Configure expiry, view limit and end‑to‑end encryption in one place.</span>
</div>
<hr>
<div id="secret-banner" class="secret-banner hidden">
<span>⚠️ Looks like this might contain credentials. Make sure you trust the recipient.</span>
</div>
<div class="option-group" style="margin-bottom: 20px;">
<label for="title">Title (Optional)</label>
<input type="text" id="title" class="style-input" placeholder="Enter title (e.g. My Notes)" style="width: 100%;">
</div>
<div class="options-container">
<div class="option-group">
<label for="expiration">Paste Expiration:</label>
<select id="expiration" class="style-select">
<option value="never">Never</option>
<option value="10m">10 Minutes</option>
<option value="1h">1 Hour</option>
<option value="1d">1 Day</option>
<option value="1w">1 Week</option>
<option value="burn">Burn After Reading</option>
</select>
</div>
<div class="option-group">
<label for="exposure">Paste Exposure:</label>
<select id="exposure" class="style-select">
<option value="public">Public</option>
<option value="unlisted">Unlisted</option>
</select>
</div>
<div class="option-group">
<label for="view_limit">View Limit (Optional)</label>
<input type="number" id="view_limit" class="style-input" placeholder="e.g. 5" min="1" style="width: 80px;">
</div>
<div class="option-group">
<label for="password">Password (optional)</label>
<input type="password" id="password" class="style-input" placeholder="Enter password">
</div>
</div>
<div class="options-container" style="margin-top: -5px; margin-bottom: 20px;">
<label style="font-size: 13px; color: var(--text-secondary); cursor: pointer; display: flex; align-items: center; gap: 8px;">
<input type="checkbox" id="is_encrypted"> End-to-End Encryption (E2EE) - <span style="font-size: 11px; opacity: 0.7;">Password will be required to decrypt. Content is never sent raw to server.</span>
</label>
</div>
<div class="editor-header">
<div class="tab-container">
<button id="editor-tab" class="tab-btn active" onclick="showEditor()">Editor</button>
<button id="preview-tab" class="tab-btn" onclick="showPreview()">Preview</button>
</div>
<div style="display: flex; gap: 15px; align-items: center;">
<span id="reading-time" class="char-count" style="margin-right: 10px;">Est. Reading: 0 min</span>
<span id="char-count" class="char-count">0</span>
</div>
</div>
<div id="editor-wrapper">
<div class="editor codejar" id="editor" placeholder="Write your markdown here..." contenteditable="true"></div>
</div>
<div id="preview-pane" class="preview-pane content hidden"></div>
<div class="button-container">
<button class="publish-button" onclick="publishContent()">Publish</button>
</div>
<div id="result-container" class="result-container" style="display: none;">
<p>Your paste is ready!</p>
<div class="link-box">
<span id="paste-link"></span>
<button class="copy-btn" onclick="copyResultLink()">Copy</button>
</div>
<div id="qrcode-container" style="margin-top: 20px; display: flex; justify-content: center; background: white; padding: 10px; border-radius: 8px; width: fit-content; margin-left: auto; margin-right: auto;"></div>
<p style="font-size: 11px; margin-top: 10px;">Pro tip: You can access the raw text by adding <code>?raw=1</code> to the URL.</p>
</div>
</div>
<script>
// Fetch CSRF token on load
fetch('/api/get_token.php')
.then(res => res.json())
.then(data => {
window.csrfToken = data.csrf_token;
})
.catch(err => console.error("Failed to fetch CSRF token:", err));
const MAX_PASTE_SIZE = 1024 * 1024; // 1MB
let debounceTimer;
let jar; // CodeJar instance
// Load draft on startup
window.addEventListener('DOMContentLoaded', () => {
// Initialize CodeJar for syntax highlighting
const editorElement = document.getElementById('editor');
const highlight = editor => {
// highlight.js does not line-wrap natively well if we don't handle it,
// but for markdown/code we can let it highlight
editor.innerHTML = hljs.highlightAuto(editor.textContent).value;
};
// If we want raw markdown without weird syntax bugs while typing,
// a simple highlighter wrapper is better. For now we just use a basic text highlight or no highlight
// until we actually want the syntax to colorize.
// Actually, the user asked for Prism.js or CodeJar with Highlight.js.
// Let's use Highlight.js with a markdown language enforced if possible, or auto.
const highlightMarkdown = editor => {
let code = editor.textContent;
editor.innerHTML = hljs.highlight(code, {language: 'markdown'}).value;
};
jar = CodeJar(editorElement, highlightMarkdown, {tab: ' '});
jar.onUpdate(code => {
onEditorInput(code);
});
// Keyboard shortcuts
editorElement.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
publishContent();
}
});
// Handle Edit/Clone Mode
const params = new URLSearchParams(window.location.search);
const editUid = params.get('edit');
const cloneUid = params.get('clone');
const targetUid = editUid || cloneUid;
let draftKey = 'paste_draft';
if (editUid) draftKey += '_edit_' + editUid;
const draft = localStorage.getItem(draftKey);
if (draft) {
jar.updateCode(draft);
updateStats(draft);
console.log("Draft restored from local storage.");
}
if (targetUid) {
fetch(`/api/view_content.php?id=${targetUid}&json=1`)
.then(async res => {
if (res.status === 401) {
const pw = prompt("This post is password protected. Enter password to edit/clone:");
if (pw) {
alert("Please view and unlock the post first, then click Edit/Clone from there.");
window.location.href = `/v/${targetUid}`;
}
throw new Error("Unauthorized");
}
if (!res.ok) throw new Error("Failed to fetch post");
return res.json();
})
.then(data => {
if (!data || !data.content) return;
jar.updateCode(data.content);
updateStats(data.content);
// Restore metadata
document.getElementById('title').value = data.title || "";
if (data.exposure) document.getElementById('exposure').value = data.exposure;
if (data.view_limit) document.getElementById('view_limit').value = data.view_limit;
document.getElementById('is_encrypted').checked = !!data.is_encrypted;
if (data.burn_on_read) {
document.getElementById('expiration').value = 'burn';
}
if (editUid) {
window.isEditMode = true;
window.editUid = editUid;
document.querySelector('.publish-button').textContent = "Update Post";
document.querySelector('.title-text').textContent = "Edit Paste";
}
})
.catch(err => {
if (err.message !== "Unauthorized") {
console.error("Error loading post:", err);
}
});
}
});
function updateStats(content) {
const count = content.length;
const charCountEl = document.getElementById('char-count');
charCountEl.textContent = count.toLocaleString();
if (count > MAX_PASTE_SIZE) {
charCountEl.style.color = "#ff4d4d";
charCountEl.style.fontWeight = "bold";
} else {
charCountEl.style.color = "";
charCountEl.style.fontWeight = "";
}
const words = content.trim().split(/\s+/).length || 0;
const readingTime = Math.ceil(words / 200);
document.getElementById('reading-time').textContent = `Est. Reading: ${readingTime} min`;
}
function scanForSecrets(text) {
const patterns = [
/sk-[a-zA-Z0-9]{48}/, // OpenAI
/AKIA[0-9A-Z]{16}/, // AWS Access Key
/-----BEGIN PRIVATE KEY-----/ // Generic Private Key
];
return patterns.some(pattern => pattern.test(text));
}
function onEditorInput(content) {
updateStats(content);
// Secret Scanner
const banner = document.getElementById('secret-banner');
if (scanForSecrets(content)) {
banner.classList.remove('hidden');
} else {
banner.classList.add('hidden');
}
let draftKey = 'paste_draft';
if (window.isEditMode && window.editUid) draftKey += '_edit_' + window.editUid;
localStorage.setItem(draftKey, content); // Save draft
if (!document.getElementById('preview-pane').classList.contains('hidden')) {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(updatePreview, 300); // 300ms debounce
}
}
function autoEmbed(html) {
// Youtube Links (marked turns them into anchor tags first)
html = html.replace(/<a[^>]*href="https?:\/\/(?:www\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)"[^>]*>.*?<\/a>/g,
'<div class="embed-container"><iframe width="100%" height="450" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></div>');
// Plain Youtube URLs (not inside quotes)
html = html.replace(/(?<!["'])(https?:\/\/(?:www\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]+))/g,
'<div class="embed-container"><iframe width="100%" height="450" src="https://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></div>');
return html;
}
function updatePreview() {
const content = jar.toString();
const previewPane = document.getElementById('preview-pane');
let html = marked.parse(content);
html = autoEmbed(html);
previewPane.innerHTML = DOMPurify.sanitize(html, { ADD_TAGS: ['iframe'], ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });
// Highlight.js
previewPane.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
});
// KaTeX
renderMathInElement(previewPane, {
delimiters: [
{ left: '$$', right: '$$', display: true },
{ left: '$', right: '$', display: false },
{ left: '\\(', right: '\\)', display: false },
{ left: '\\[', right: '\\]', display: true }
],
throwOnError: false
});
}
function showEditor() {
document.getElementById('editor-wrapper').classList.remove('hidden');
document.getElementById('preview-pane').classList.add('hidden');
document.querySelectorAll('.tab-btn')[0].classList.add('active');
document.querySelectorAll('.tab-btn')[1].classList.remove('active');
}
function showPreview() {
document.getElementById('editor-wrapper').classList.add('hidden');
document.getElementById('preview-pane').classList.remove('hidden');
document.querySelectorAll('.tab-btn')[0].classList.remove('active');
document.querySelectorAll('.tab-btn')[1].classList.add('active');
updatePreview();
}
// E2EE Encryption Helpers
async function deriveKey(password, salt) {
const encoder = new TextEncoder();
const baseKey = await crypto.subtle.importKey(
"raw", encoder.encode(password), "PBKDF2", false, ["deriveKey"]
);
return crypto.subtle.deriveKey(
{ name: "PBKDF2", salt, iterations: 100000, hash: "SHA-256" },
baseKey, { name: "AES-GCM", length: 256 }, false, ["encrypt"]
);
}
async function encryptData(text, password) {
const encoder = new TextEncoder();
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
const key = await deriveKey(password, salt);
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv }, key, encoder.encode(text)
);
// Combine Salt + IV + EncryptedData for easy storage
const combined = new Uint8Array(salt.length + iv.length + encrypted.byteLength);
combined.set(salt, 0);
combined.set(iv, salt.length);
combined.set(new Uint8Array(encrypted), salt.length + iv.length);
// Return as base64
return btoa(String.fromCharCode.apply(null, combined));
}
async function publishContent() {
if (!window.csrfToken) {
alert("Security session is still loading. Please wait a second and try again.");
return;
}
let content = jar.toString();
if (content.trim() === "") {
alert("Please write something before publishing.");
return;
}
if (content.length > MAX_PASTE_SIZE) {
alert("The content is too large. The maximum size is 1MB (" + MAX_PASTE_SIZE.toLocaleString() + " characters). Current size: " + content.length.toLocaleString() + " characters.");
return;
}
const expiration = document.getElementById('expiration').value;
const exposure = document.getElementById('exposure').value;
const password = document.getElementById('password').value;
const viewLimit = document.getElementById('view_limit').value;
const isEncrypted = document.getElementById('is_encrypted').checked;
const title = document.getElementById('title').value;
if (isEncrypted && !password) {
alert("Encryption requires a password.");
return;
}
if (isEncrypted) {
try {
content = await encryptData(content, password);
} catch (e) {
console.error(e);
alert("Encryption failed.");
return;
}
}
let editToken = null;
if (window.isEditMode && window.editUid) {
editToken = localStorage.getItem('edit_token_' + window.editUid);
}
const response = await fetch('/save', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: content,
title: title,
expiration: expiration,
exposure: exposure,
password: isEncrypted ? "" : password, // If E2EE, don't store plain password
view_limit: viewLimit,
is_encrypted: isEncrypted,
uid: window.isEditMode ? window.editUid : null,
edit_token: editToken,
csrf_token: window.csrfToken
})
});
const resultContainer = document.getElementById('result-container');
const pasteLinkSpan = document.getElementById('paste-link');
if (response.ok) {
const data = await response.json();
// Save edit token for future updates
if (data.edit_token) {
localStorage.setItem('edit_token_' + data.id, data.edit_token);
}
// Create share URL (without the edit token to prevent accidental leakage)
let shareUrl = window.location.origin + '/v/' + (data.id || window.editUid);
pasteLinkSpan.textContent = shareUrl;
// Generate QR Code
const qrcodeContainer = document.getElementById('qrcode-container');
qrcodeContainer.innerHTML = '';
new QRCode(qrcodeContainer, {
text: shareUrl,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
resultContainer.style.display = 'block';
// Redirect to the new paste after a short delay to let the user see the success message
setTimeout(() => {
window.location.href = shareUrl;
}, 800);
jar.updateCode("");
let draftKey = 'paste_draft';
if (window.isEditMode && window.editUid) draftKey += '_edit_' + window.editUid;
localStorage.removeItem(draftKey); // Clear draft on success
document.getElementById('password').value = "";
document.getElementById('view_limit').value = "";
document.getElementById('is_encrypted').checked = false;
updateStats("");
showEditor();
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
} else {
const text = await response.text();
let errorMessage = "Unknown error";
try {
const errorData = JSON.parse(text);
errorMessage = errorData.message || errorMessage;
} catch (e) {
errorMessage = text.substring(0, 200) || "Empty response from server";
}
alert("Failed to publish content: " + errorMessage);
}
}
function copyResultLink() {
const link = document.getElementById('paste-link').textContent;
navigator.clipboard.writeText(link).then(() => {
alert("Link copied to clipboard!");
});
}
</script>
<footer class="site-footer">
<div class="container">
<hr>
<p>© 2026 KitePad. All rights reserved. <a href="https://github.com/irhdab/kitepad/tree/main" class="nav-link" target="_blank">GitHub</a> | <a href="/contact.html" class="nav-link">Contact</a> | <a href="/privacy.html" class="nav-link">Privacy Policy</a></p>
</div>
</footer>
</body>
</html>