Remove unsafe-inline from script-src CSP

Move every inline <script> block and on*= attribute out of the templates
into per-page files under static/js/, then tighten the CSP to
script-src 'self' so injected inline scripts are actually blocked.

- static/js/base.js: QR modal, form[data-confirm] submit confirmation,
  and a shared glimmerCopy clipboard helper (loaded by base.html)
- One script per template: index, bin_view, bin_token, admin,
  admin_edit, admin_bin, admin_bin_edit, admin_uploads
- Template data now flows through data-* attributes (data-slug,
  data-filename, data-max-mb, ...) instead of being interpolated
  into JS; confirm() prompts use data-confirm
- style-src keeps unsafe-inline for the style="" attributes
- Update CLAUDE.md / AGENTS.md with the no-inline-JS rule

Verified in a live browser session: shorten flow, login, QR modal,
paste editor (token radios, name preview), paste cards (preview
dialog, expand/close), public paste view, token prompt redirect, and
uploads page - no console errors or CSP violations.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-06-09 20:14:30 -07:00
1 parent 82fb5122f3
commit a9da249760
22 files changed
+451 -321

No files matched your search

+7 -2
View File
@@ -48,6 +48,9 @@ glimmer/
│ │ └── style.css # Custom Solis-style design system (amber/cream, Outfit font)
│ ├── favicon.ico
│ ├── favicon.png
│ ├── js/ # Per-page scripts (CSP blocks inline JS)
│ │ ├── base.js # QR modal, data-confirm forms, glimmerCopy
│ │ └── *.js # One file per template that needs behaviour
│ └── upload.js # Shared client-side upload helper (window.GlimmerUpload)
└── templates/
├── base.html # Layout wrapper: sidebar (logged in) or public header
@@ -89,8 +92,10 @@ All templates receive a `pageData` struct. Add new fields there when templates n
### Templates are embedded, not on disk
Templates and static files are embedded into the binary via `//go:embed` in `templates.go`. Changes to templates are compiled in; they are **not** reloaded at runtime. Always rebuild after template changes.
### No JS frameworks
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). Most JS is inline in templates; shared upload logic lives in `static/upload.js` and is exposed as `window.GlimmerUpload`. No build step, no npm, no bundler.
### No JS frameworks — and no inline JS
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). No build step, no npm, no bundler.
The CSP is `script-src 'self'`, so **inline `<script>` blocks and `on*=` attributes in templates are blocked by the browser**. All behaviour lives in files under `static/js/` (one per template, plus `base.js` for shared chrome: the QR modal, `glimmerCopy`, and `form[data-confirm]` submit confirmation). To pass template data to JS, put it in `data-*` attributes and read it from the script — never interpolate `{{...}}` into JS. Shared upload logic lives in `static/upload.js` as `window.GlimmerUpload`.
### CSS framework
**No CSS framework.** Glimmer uses a custom design system in `static/css/style.css` inspired by Solis's "Sunlight & Clarity" theme — warm amber (`#d97706`) on cream (`#fafaf9`) with Outfit font, sidebar + main-area layout, soft shadows with amber tint, cubic-bezier spring animations on toasts/modals. All templates are self-contained and offline-capable. **No external CDN dependencies.**
+7 -2
View File
@@ -48,6 +48,9 @@ glimmer/
│ │ └── style.css # Custom Solis-style design system (amber/cream, Outfit font)
│ ├── favicon.ico
│ ├── favicon.png
│ ├── js/ # Per-page scripts (CSP blocks inline JS)
│ │ ├── base.js # QR modal, data-confirm forms, glimmerCopy
│ │ └── *.js # One file per template that needs behaviour
│ └── upload.js # Shared client-side upload helper (window.GlimmerUpload)
└── templates/
├── base.html # Layout wrapper: sidebar (logged in) or public header
@@ -89,8 +92,10 @@ All templates receive a `pageData` struct. Add new fields there when templates n
### Templates are embedded, not on disk
Templates and static files are embedded into the binary via `//go:embed` in `templates.go`. Changes to templates are compiled in; they are **not** reloaded at runtime. Always rebuild after template changes.
### No JS frameworks
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). Most JS is inline in templates; shared upload logic lives in `static/upload.js` and is exposed as `window.GlimmerUpload`. No build step, no npm, no bundler.
### No JS frameworks — and no inline JS
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). No build step, no npm, no bundler.
The CSP is `script-src 'self'`, so **inline `<script>` blocks and `on*=` attributes in templates are blocked by the browser**. All behaviour lives in files under `static/js/` (one per template, plus `base.js` for shared chrome: the QR modal, `glimmerCopy`, and `form[data-confirm]` submit confirmation). To pass template data to JS, put it in `data-*` attributes and read it from the script — never interpolate `{{...}}` into JS. Shared upload logic lives in `static/upload.js` as `window.GlimmerUpload`.
### CSS framework
**No CSS framework.** Glimmer uses a custom design system in `static/css/style.css` inspired by Solis's "Sunlight & Clarity" theme — warm amber (`#d97706`) on cream (`#fafaf9`) with Outfit font, sidebar + main-area layout, soft shadows with amber tint, cubic-bezier spring animations on toasts/modals. The CSS is served from `/static/css/style.css` so the app works fully offline. The Outfit font itself is loaded from Google Fonts (one external request); replace with a vendored woff2 if you need a true air-gapped build. Do not reintroduce CDN `<link>`/`<script>`/image references — everything must be same-origin (enforced by the `Content-Security-Policy` header in `securityHeaders`).
+11 -7
View File
@@ -52,19 +52,23 @@ func securityHeaders(next http.Handler) http.Handler {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
// All assets are served from the same origin (Pico CSS is vendored
// locally), so the app works fully offline and we can lock the origin
// down. img-src allows data: and https: so uploaded/remote images and
// All assets are served from the same origin (CSS and JS are embedded),
// so the app works fully offline and we can lock the origin down.
// img-src allows data: and https: so uploaded/remote images and
// favicons still render, and blob: so the client-side image compressor
// (canvas) can load a selected file before upload. 'unsafe-inline' is required by the inline
// scripts/styles in the templates; object-src/base-uri are pinned to
// blunt injection; frame-ancestors 'self' permits the same-origin paste
// (canvas) can load a selected file before upload. script-src is
// 'self' only — all JS lives in /static/js/ files; do not add inline
// <script> blocks or on*= attributes to templates, they will be
// blocked. style-src keeps 'unsafe-inline' for the style="" attributes
// throughout the templates (style injection is far lower risk than
// script injection). object-src/base-uri are pinned to blunt
// injection; frame-ancestors 'self' permits the same-origin paste
// preview iframe while blocking cross-site clickjacking.
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"img-src 'self' data: https: blob:; "+
"style-src 'self' 'unsafe-inline'; "+
"script-src 'self' 'unsafe-inline'; "+
"script-src 'self'; "+
"object-src 'none'; "+
"base-uri 'none'; "+
"frame-ancestors 'self'")
+19
View File
@@ -0,0 +1,19 @@
// Admin dashboard: hostname compression for tiles and QR modal buttons.
(function() {
'use strict';
// Compress URL displays to hostname for visual cleanliness
document.querySelectorAll('[data-hostname]').forEach(function(el) {
try {
var u = new URL(el.textContent.trim());
el.textContent = u.hostname + (u.pathname !== '/' ? u.pathname : '');
} catch (e) {}
});
document.querySelectorAll('.js-qr').forEach(function(btn) {
btn.addEventListener('click', function() {
var slug = btn.getAttribute('data-slug');
window.openQRModal(slug, slug);
});
});
})();
+99
View File
@@ -0,0 +1,99 @@
// Admin pastes grid: preview dialog, copy-link, QR, and card click handling.
(function() {
'use strict';
function previewURL(name, token) {
var u = '/bin/' + encodeURIComponent(name);
if (token) u += '/' + encodeURIComponent(token);
return u;
}
function openPreview(name, token, title) {
var dlg = document.getElementById('preview-dialog');
var fullURL = previewURL(name, token);
// iframe uses the embed view so it strips the sidebar / header / toolbar —
// only the paste body is rendered inside the dialog.
var embedURL = fullURL + '?embed=1';
document.getElementById('preview-frame').src = embedURL;
// The "Open ↗" link goes to the full URL (with chrome) so a new tab shows the
// normal public page.
document.getElementById('preview-open').href = fullURL;
document.getElementById('preview-title').textContent = title || name;
dlg.classList.remove('expanded');
document.getElementById('preview-expand').innerHTML = '⤢';
document.getElementById('preview-expand').setAttribute('aria-label', 'Expand');
dlg.showModal();
}
function closePreview() {
document.getElementById('preview-dialog').close();
}
function toggleExpand() {
var dlg = document.getElementById('preview-dialog');
var expanded = dlg.classList.toggle('expanded');
var btn = document.getElementById('preview-expand');
btn.innerHTML = expanded ? '⤡' : '⤢';
btn.setAttribute('aria-label', expanded ? 'Shrink' : 'Expand');
}
function showBinQR(name, full) {
var url = location.origin + '/bin/' + encodeURIComponent(name);
var fetchUrl = '/admin/bin/qr/' + encodeURIComponent(name);
if (full) fetchUrl += '?full=1';
var overlay = document.getElementById('qr-modal-overlay');
document.getElementById('qr-modal-image').src = fetchUrl;
document.getElementById('qr-modal-link').textContent = url + (full ? ' (with token)' : '');
var dl = document.getElementById('qr-modal-download');
dl.href = fetchUrl;
dl.download = name + '_QR.svg';
overlay.classList.add('show');
}
// Per-card wiring: action buttons read name/token/title from the card's
// data attributes; clicking the card itself (not an action) opens the
// preview. Clicks on links/buttons/forms are ignored by the card handler,
// so the action buttons need no stopPropagation.
document.querySelectorAll('.js-preview').forEach(function(el) {
var copyBtn = el.querySelector('.js-copy-link');
if (copyBtn) {
copyBtn.addEventListener('click', function() {
var url = location.origin + previewURL(el.dataset.name, el.dataset.token);
window.glimmerCopy(url, copyBtn);
});
}
var qrBtn = el.querySelector('.js-bin-qr');
if (qrBtn) {
qrBtn.addEventListener('click', function() {
showBinQR(el.dataset.name, false);
});
}
el.addEventListener('click', function(e) {
if (e.target.closest('.paste-card-actions')) return;
if (e.target.closest('a, button, form, input')) return;
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
});
el.setAttribute('tabindex', '0');
el.setAttribute('role', 'button');
el.addEventListener('keydown', function(e) {
if ((e.key === 'Enter' || e.key === ' ') && !e.target.closest('.paste-card-actions')) {
e.preventDefault();
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
}
});
});
var expandBtn = document.getElementById('preview-expand');
if (expandBtn) expandBtn.addEventListener('click', toggleExpand);
var closeBtn = document.getElementById('preview-close');
if (closeBtn) closeBtn.addEventListener('click', closePreview);
// Clear iframe when dialog closes
var dlg = document.getElementById('preview-dialog');
if (dlg) {
dlg.addEventListener('close', function() {
document.getElementById('preview-frame').src = 'about:blank';
});
}
})();
@@ -0,0 +1,65 @@
// Paste editor: token radio toggling, name preview, and upload wiring.
(function() {
'use strict';
function toggleCustomToken() {
var wrap = document.getElementById('custom-token-wrap');
if (!wrap) return;
var checked = document.querySelector('input[name="token_action"][value="custom"]:checked') ||
document.querySelector('input[name="enable_token"][value="custom"]:checked');
wrap.style.display = checked ? 'block' : 'none';
}
document.querySelectorAll('input[name="token_action"], input[name="enable_token"]').forEach(function(radio) {
radio.addEventListener('change', toggleCustomToken);
});
toggleCustomToken();
// Slug preview updater
var nameInput = document.getElementById('name');
var preview = document.getElementById('name-preview');
if (nameInput && preview) {
nameInput.addEventListener('input', function() {
preview.textContent = this.value || '...';
});
}
var textarea = document.querySelector('textarea[name="content"]');
var status = document.getElementById('upload-status');
var imgBtn = document.getElementById('upload-img-btn');
function insertAtCursor(text) {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var before = textarea.value.substring(0, start);
var after = textarea.value.substring(end);
textarea.value = before + text + '\n' + after;
textarea.selectionStart = textarea.selectionEnd = start + text.length + 1;
textarea.focus();
}
var uploader = window.GlimmerUpload.init({
imgBtn: imgBtn,
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: status,
maxImageMB: parseInt(imgBtn.getAttribute('data-max-mb'), 10) || 50,
onUploaded: function(data) {
insertAtCursor(data.markdown);
status.textContent = 'Uploaded';
setTimeout(function() { status.textContent = ''; }, 3000);
}
});
textarea.addEventListener('paste', function(e) {
var items = (e.clipboardData || {}).items || [];
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
e.preventDefault();
uploader.doUpload(items[i].getAsFile(), true);
return;
}
}
});
})();
+12
View File
@@ -0,0 +1,12 @@
// Edit-link page: live slug preview.
(function() {
'use strict';
var slugInput = document.getElementById('slug');
var preview = document.getElementById('slug-preview');
if (slugInput && preview) {
slugInput.addEventListener('input', function() {
preview.textContent = this.value || '...';
});
}
})();
@@ -0,0 +1,77 @@
// Uploads admin page: copy-markdown, resize dialog, and upload wiring.
(function() {
'use strict';
var currentResizeFile = '';
document.querySelectorAll('.js-copy-md').forEach(function(btn) {
btn.addEventListener('click', function() {
var filename = btn.getAttribute('data-filename');
var url = '/uploads/' + filename;
var label = btn.getAttribute('data-original') || filename;
var md = btn.getAttribute('data-image') ? '![](' + url + ')' : '[' + label + '](' + url + ')';
window.glimmerCopy(md, btn);
});
});
document.querySelectorAll('.js-resize').forEach(function(btn) {
btn.addEventListener('click', function() {
currentResizeFile = btn.getAttribute('data-filename');
document.getElementById('resize-current').textContent =
'Current: ' + btn.getAttribute('data-width') + '×' + btn.getAttribute('data-height');
document.getElementById('resize-status').textContent = '';
document.getElementById('resize-confirm').disabled = false;
document.getElementById('resize-dialog').showModal();
});
});
document.querySelectorAll('.js-resize-cancel').forEach(function(btn) {
btn.addEventListener('click', function() {
document.getElementById('resize-dialog').close();
});
});
document.getElementById('resize-confirm').addEventListener('click', function() {
var dim = document.getElementById('resize-dim').value;
var status = document.getElementById('resize-status');
var btn = this;
status.textContent = 'Resizing…';
btn.disabled = true;
var fd = new FormData();
fd.append('csrf_token', window.GlimmerUpload.getCsrfToken());
fd.append('max_dim', dim);
fetch('/admin/uploads/resize/' + currentResizeFile, { method: 'POST', body: fd, credentials: 'same-origin' })
.then(function(r) { return r.json(); })
.then(function(data) {
btn.disabled = false;
if (data.error) {
status.textContent = 'Error: ' + data.error;
return;
}
var sizeEl = document.getElementById('size-' + currentResizeFile);
var dimEl = document.getElementById('dim-' + currentResizeFile);
if (sizeEl) sizeEl.textContent = data.size_human;
if (dimEl) dimEl.textContent = data.width + '×' + data.height;
status.textContent = 'Done — ' + data.size_human;
var imgs = document.querySelectorAll('img[src="/uploads/' + currentResizeFile + '"]');
imgs.forEach(function(img) { img.src = '/uploads/' + currentResizeFile + '?t=' + Date.now(); });
})
.catch(function() {
btn.disabled = false;
status.textContent = 'Failed';
});
});
var imgBtn = document.getElementById('upload-img-btn');
window.GlimmerUpload.init({
imgBtn: imgBtn,
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: document.getElementById('upload-status'),
maxImageMB: parseInt(imgBtn.getAttribute('data-max-mb'), 10) || 50,
onUploaded: function() { location.reload(); }
});
})();
+56
View File
@@ -0,0 +1,56 @@
// Shared chrome behaviour for every layout page: QR modal, confirm-on-submit
// forms, and a clipboard helper. The CSP blocks inline scripts, so all page
// behaviour lives in files under /static/js/.
(function() {
'use strict';
// Copy text to the clipboard and flash the button label. Used by the
// per-page scripts.
window.glimmerCopy = function(text, btn) {
var orig = btn.textContent;
navigator.clipboard.writeText(text).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
};
window.openQRModal = function(slug, name) {
var overlay = document.getElementById('qr-modal-overlay');
document.getElementById('qr-modal-image').src = '/admin/qr/' + slug;
document.getElementById('qr-modal-link').textContent = '/admin/qr/' + slug;
var dl = document.getElementById('qr-modal-download');
dl.href = '/admin/qr/' + slug;
dl.download = (name || slug) + '_QR.svg';
overlay.classList.add('show');
};
window.closeQRModal = function() {
document.getElementById('qr-modal-overlay').classList.remove('show');
document.getElementById('qr-modal-image').src = '';
};
var overlay = document.getElementById('qr-modal-overlay');
if (overlay) {
overlay.addEventListener('click', function(e) {
if (e.target === overlay) window.closeQRModal();
});
}
var closeBtn = document.getElementById('qr-modal-close');
if (closeBtn) {
closeBtn.addEventListener('click', function() { window.closeQRModal(); });
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') window.closeQRModal();
});
// Forms with data-confirm ask before submitting (replaces inline
// onsubmit="return confirm(...)"). Delegated so it works for any form.
document.addEventListener('submit', function(e) {
var form = e.target;
if (form && form.getAttribute && form.getAttribute('data-confirm')) {
if (!window.confirm(form.getAttribute('data-confirm'))) {
e.preventDefault();
}
}
});
})();
+15
View File
@@ -0,0 +1,15 @@
// Token prompt for protected pastes: redirect to /bin/{name}/{token}.
(function() {
'use strict';
var form = document.getElementById('token-form');
if (form) {
form.addEventListener('submit', function(e) {
e.preventDefault();
var token = document.getElementById('token-input').value.trim();
if (token) {
window.location.href = window.location.pathname + '/' + encodeURIComponent(token);
}
});
}
})();
+11
View File
@@ -0,0 +1,11 @@
// Public paste viewer: copy-raw-content button.
(function() {
'use strict';
var btn = document.getElementById('copy-paste-btn');
if (btn) {
btn.addEventListener('click', function() {
window.glimmerCopy(document.getElementById('paste-raw').innerText, btn);
});
}
})();
+21
View File
@@ -0,0 +1,21 @@
// Public URL shortener page.
(function() {
'use strict';
var form = document.getElementById('shorten-form');
if (form) {
form.addEventListener('submit', function() {
var input = document.getElementById('url');
if (input.value && input.value.indexOf('://') === -1) {
input.value = 'https://' + input.value;
}
});
}
var copyBtn = document.getElementById('copy-short-url');
if (copyBtn) {
copyBtn.addEventListener('click', function() {
window.glimmerCopy(document.getElementById('short-url').textContent, copyBtn);
});
}
})();
+5 -13
View File
@@ -82,8 +82,8 @@
<td class="col-actions">
<div class="flex gap-1">
<a href="/admin/edit/{{.ID}}" class="btn btn-secondary btn-sm">Edit</a>
<button type="button" class="btn btn-secondary btn-sm" onclick="openQRModal('{{.Slug}}', '{{.Slug}}')">QR</button>
<form method="post" action="/admin/delete/{{.ID}}" style="display:inline" onsubmit="return confirm('Delete /{{.Slug}}?')">
<button type="button" class="btn btn-secondary btn-sm js-qr" data-slug="{{.Slug}}">QR</button>
<form method="post" action="/admin/delete/{{.ID}}" style="display:inline" data-confirm="Delete /{{.Slug}}?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
@@ -134,8 +134,8 @@
<td class="col-actions">
<div class="flex gap-1">
<a href="/admin/edit/{{.ID}}" class="btn btn-secondary btn-sm">Edit</a>
<button type="button" class="btn btn-secondary btn-sm" onclick="openQRModal('{{.Slug}}', '{{.Slug}}')">QR</button>
<form method="post" action="/admin/delete/{{.ID}}" style="display:inline" onsubmit="return confirm('Delete /{{.Slug}}?')">
<button type="button" class="btn btn-secondary btn-sm js-qr" data-slug="{{.Slug}}">QR</button>
<form method="post" action="/admin/delete/{{.ID}}" style="display:inline" data-confirm="Delete /{{.Slug}}?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
@@ -156,13 +156,5 @@
</div>
</section>
<script>
// Compress URL displays to hostname for visual cleanliness
document.querySelectorAll('[data-hostname]').forEach(function(el) {
try {
var u = new URL(el.textContent.trim());
el.textContent = u.hostname + (u.pathname !== '/' ? u.pathname : '');
} catch (e) {}
});
</script>
<script src="/static/js/admin.js"></script>
{{end}}
+7 -86
View File
@@ -46,10 +46,10 @@
</div>
</div>
<div class="paste-card-actions">
<button type="button" class="btn btn-secondary btn-sm" onclick="event.stopPropagation();copyPasteLink('{{.Name}}','{{.Token}}', this)">Copy link</button>
<a href="/admin/bin/edit/{{.ID}}" class="btn btn-secondary btn-sm" onclick="event.stopPropagation()">Edit</a>
<button type="button" class="btn btn-secondary btn-sm" onclick="event.stopPropagation();showBinQR('{{.Name}}', false)">QR</button>
<form method="post" action="/admin/bin/delete/{{.ID}}" style="display:inline" onsubmit="return confirm('Delete paste {{.Name}}?')">
<button type="button" class="btn btn-secondary btn-sm js-copy-link">Copy link</button>
<a href="/admin/bin/edit/{{.ID}}" class="btn btn-secondary btn-sm">Edit</a>
<button type="button" class="btn btn-secondary btn-sm js-bin-qr">QR</button>
<form method="post" action="/admin/bin/delete/{{.ID}}" style="display:inline" data-confirm="Delete paste {{.Name}}?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
@@ -73,91 +73,12 @@
<span class="preview-title" id="preview-title">Preview</span>
<div class="preview-actions">
<a id="preview-open" href="#" target="_blank" rel="noopener" class="btn btn-secondary btn-sm">Open ↗</a>
<button type="button" class="btn btn-secondary btn-sm" id="preview-expand" onclick="toggleExpand()" aria-label="Expand">⤢</button>
<button type="button" class="btn btn-secondary btn-sm" onclick="closePreview()" aria-label="Close">✕</button>
<button type="button" class="btn btn-secondary btn-sm" id="preview-expand" aria-label="Expand">⤢</button>
<button type="button" class="btn btn-secondary btn-sm" id="preview-close" aria-label="Close">✕</button>
</div>
</div>
<iframe id="preview-frame" class="preview-frame" src="about:blank" title="Paste preview"></iframe>
</dialog>
<script>
function previewURL(name, token) {
var u = '/bin/' + encodeURIComponent(name);
if (token) u += '/' + encodeURIComponent(token);
return u;
}
function openPreview(name, token, title) {
var dlg = document.getElementById('preview-dialog');
var fullURL = previewURL(name, token);
// iframe uses the embed view so it strips the sidebar / header / toolbar —
// only the paste body is rendered inside the dialog.
var embedURL = fullURL + '?embed=1';
document.getElementById('preview-frame').src = embedURL;
// The "Open ↗" link goes to the full URL (with chrome) so a new tab shows the
// normal public page.
document.getElementById('preview-open').href = fullURL;
document.getElementById('preview-title').textContent = title || name;
dlg.classList.remove('expanded');
document.getElementById('preview-expand').innerHTML = '⤢';
document.getElementById('preview-expand').setAttribute('aria-label', 'Expand');
dlg.showModal();
}
function closePreview() {
document.getElementById('preview-dialog').close();
}
function toggleExpand() {
var dlg = document.getElementById('preview-dialog');
var expanded = dlg.classList.toggle('expanded');
var btn = document.getElementById('preview-expand');
btn.innerHTML = expanded ? '⤡' : '⤢';
btn.setAttribute('aria-label', expanded ? 'Shrink' : 'Expand');
}
function copyPasteLink(name, token, btn) {
var url = location.origin + previewURL(name, token);
var orig = btn.textContent;
navigator.clipboard.writeText(url).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
}
function showBinQR(name, full) {
var url = location.origin + '/bin/' + encodeURIComponent(name);
var fetchUrl = '/admin/bin/qr/' + encodeURIComponent(name);
if (full) fetchUrl += '?full=1';
var overlay = document.getElementById('qr-modal-overlay');
document.getElementById('qr-modal-image').src = fetchUrl;
document.getElementById('qr-modal-link').textContent = url + (full ? ' (with token)' : '');
var dl = document.getElementById('qr-modal-download');
dl.href = fetchUrl;
dl.download = name + '_QR.svg';
overlay.classList.add('show');
}
// Click on paste card opens preview, except when clicking action buttons
document.querySelectorAll('.js-preview').forEach(function(el) {
el.addEventListener('click', function(e) {
if (e.target.closest('.paste-card-actions')) return;
if (e.target.closest('a, button, form, input')) return;
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
});
el.setAttribute('tabindex', '0');
el.setAttribute('role', 'button');
el.addEventListener('keydown', function(e) {
if ((e.key === 'Enter' || e.key === ' ') && !e.target.closest('.paste-card-actions')) {
e.preventDefault();
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
}
});
});
// Clear iframe when dialog closes
document.getElementById('preview-dialog').addEventListener('close', function() {
document.getElementById('preview-frame').src = 'about:blank';
});
</script>
<script src="/static/js/admin_bin.js"></script>
{{end}}
+12 -71
View File
@@ -63,7 +63,7 @@
<div class="form-group">
<label for="content" class="form-label">Content</label>
<div class="upload-controls" style="margin-bottom: 0.5rem;">
<button type="button" id="upload-img-btn" class="btn btn-secondary btn-sm" title="PNG, JPEG, GIF, WebP — up to 50 MB">
<button type="button" id="upload-img-btn" class="btn btn-secondary btn-sm" data-max-mb="{{$.UploadMaxMB}}" title="PNG, JPEG, GIF, WebP — up to 50 MB">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>
Upload Image
</button>
@@ -90,15 +90,15 @@
<p class="text-muted" style="margin-bottom: 0.75rem;">
Current token: <code>{{.Token}}</code> — URL: <code>/bin/{{.Name}}/{{.Token}}</code>
</p>
<label><input type="radio" name="token_action" value="keep" checked onchange="toggleCustomToken()"> Keep current token</label>
<label><input type="radio" name="token_action" value="regenerate" onchange="toggleCustomToken()"> Regenerate token</label>
<label><input type="radio" name="token_action" value="custom" onchange="toggleCustomToken()"> Set custom token</label>
<label><input type="radio" name="token_action" value="disable" onchange="toggleCustomToken()"> Disable token (public access)</label>
<label><input type="radio" name="token_action" value="keep" checked> Keep current token</label>
<label><input type="radio" name="token_action" value="regenerate"> Regenerate token</label>
<label><input type="radio" name="token_action" value="custom"> Set custom token</label>
<label><input type="radio" name="token_action" value="disable"> Disable token (public access)</label>
{{else}}
<p class="text-muted" style="margin-bottom: 0.75rem;">Token is currently <strong>disabled</strong> — paste is publicly accessible.</p>
<label><input type="radio" name="token_action" value="keep" checked onchange="toggleCustomToken()"> Keep disabled</label>
<label><input type="radio" name="token_action" value="regenerate" onchange="toggleCustomToken()"> Enable with new token</label>
<label><input type="radio" name="token_action" value="custom" onchange="toggleCustomToken()"> Set custom token</label>
<label><input type="radio" name="token_action" value="keep" checked> Keep disabled</label>
<label><input type="radio" name="token_action" value="regenerate"> Enable with new token</label>
<label><input type="radio" name="token_action" value="custom"> Set custom token</label>
{{end}}
<div id="custom-token-wrap" style="display:none; margin: 0.5rem 0 0.5rem 1.5rem;">
<input type="text" name="custom_token" placeholder="Enter custom token" pattern="[a-zA-Z0-9_-]+" maxlength="64">
@@ -109,9 +109,9 @@
</label>
{{end}}
{{else}}
<label><input type="radio" name="enable_token" value="0" checked onchange="toggleCustomToken()"> No token (public access)</label>
<label><input type="radio" name="enable_token" value="1" onchange="toggleCustomToken()"> Generate access token</label>
<label><input type="radio" name="enable_token" value="custom" onchange="toggleCustomToken()"> Custom token</label>
<label><input type="radio" name="enable_token" value="0" checked> No token (public access)</label>
<label><input type="radio" name="enable_token" value="1"> Generate access token</label>
<label><input type="radio" name="enable_token" value="custom"> Custom token</label>
<div id="custom-token-wrap" style="display:none; margin: 0.5rem 0 0.5rem 1.5rem;">
<input type="text" name="custom_token" placeholder="Enter custom token" pattern="[a-zA-Z0-9_-]+" maxlength="64">
</div>
@@ -131,64 +131,5 @@
</div>
<script src="/static/upload.js"></script>
<script>
function toggleCustomToken() {
var wrap = document.getElementById('custom-token-wrap');
if (!wrap) return;
var checked = document.querySelector('input[name="token_action"][value="custom"]:checked') ||
document.querySelector('input[name="enable_token"][value="custom"]:checked');
wrap.style.display = checked ? 'block' : 'none';
}
// Slug preview updater
(function() {
var nameInput = document.getElementById('name');
var preview = document.getElementById('name-preview');
if (nameInput && preview) {
nameInput.addEventListener('input', function() {
preview.textContent = this.value || '...';
});
}
})();
(function() {
var textarea = document.querySelector('textarea[name="content"]');
var status = document.getElementById('upload-status');
function insertAtCursor(text) {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var before = textarea.value.substring(0, start);
var after = textarea.value.substring(end);
textarea.value = before + text + '\n' + after;
textarea.selectionStart = textarea.selectionEnd = start + text.length + 1;
textarea.focus();
}
var uploader = window.GlimmerUpload.init({
imgBtn: document.getElementById('upload-img-btn'),
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: status,
maxImageMB: {{.UploadMaxMB}},
onUploaded: function(data) {
insertAtCursor(data.markdown);
status.textContent = 'Uploaded';
setTimeout(function() { status.textContent = ''; }, 3000);
}
});
textarea.addEventListener('paste', function(e) {
var items = (e.clipboardData || {}).items || [];
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
e.preventDefault();
uploader.doUpload(items[i].getAsFile(), true);
return;
}
}
});
})();
</script>
<script src="/static/js/admin_bin_edit.js"></script>
{{end}}
+1 -5
View File
@@ -40,11 +40,7 @@
</form>
</div>
<script>
document.getElementById('slug').addEventListener('input', function() {
document.getElementById('slug-preview').textContent = this.value || '...';
});
</script>
<script src="/static/js/admin_edit.js"></script>
{{else}}
<div class="alert alert-error">Link not found.</div>
{{end}}
+7 -71
View File
@@ -22,7 +22,7 @@
<p class="card-subtitle">{{len .Uploads}} file{{if ne (len .Uploads) 1}}s{{end}} stored locally.</p>
</div>
<div class="upload-controls">
<button type="button" id="upload-img-btn" class="btn btn-primary btn-sm" title="PNG, JPEG, GIF, WebP — up to 50 MB">
<button type="button" id="upload-img-btn" class="btn btn-primary btn-sm" data-max-mb="{{.UploadMaxMB}}" title="PNG, JPEG, GIF, WebP — up to 50 MB">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>
Upload Image <small style="opacity:.6">(50 MB)</small>
</button>
@@ -71,9 +71,9 @@
<td>{{.ModTime.Format "2006-01-02 15:04"}}</td>
<td class="col-actions">
<div class="flex gap-1">
<button type="button" class="btn btn-secondary btn-sm" onclick="copyMarkdown('{{.Filename}}', {{.IsImage}}, '{{.OriginalName}}', this)">Copy</button>
{{if .CanResize}}<button type="button" class="btn btn-secondary btn-sm" onclick="openResize('{{.Filename}}', {{.Width}}, {{.Height}})">Resize</button>{{end}}
<form method="post" action="/admin/uploads/delete/{{.Filename}}" style="display:inline" onsubmit="return confirm('Delete this file?')">
<button type="button" class="btn btn-secondary btn-sm js-copy-md" data-filename="{{.Filename}}" data-image="{{if .IsImage}}1{{end}}" data-original="{{.OriginalName}}">Copy</button>
{{if .CanResize}}<button type="button" class="btn btn-secondary btn-sm js-resize" data-filename="{{.Filename}}" data-width="{{.Width}}" data-height="{{.Height}}">Resize</button>{{end}}
<form method="post" action="/admin/uploads/delete/{{.Filename}}" style="display:inline" data-confirm="Delete this file?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
@@ -96,7 +96,7 @@
<dialog id="resize-dialog">
<article>
<header>
<button aria-label="Close" onclick="document.getElementById('resize-dialog').close()"></button>
<button class="js-resize-cancel" aria-label="Close"></button>
<h3>Resize Image</h3>
</header>
<p id="resize-current" class="text-muted" style="margin-bottom: 1rem;"></p>
@@ -104,76 +104,12 @@
<input type="number" id="resize-dim" value="1200" min="64" max="8192" step="1">
<small id="resize-status" class="text-muted" style="display:block; margin-top:0.5rem;"></small>
<footer>
<button type="button" class="btn btn-secondary" onclick="document.getElementById('resize-dialog').close()">Cancel</button>
<button type="button" class="btn btn-secondary js-resize-cancel">Cancel</button>
<button type="button" id="resize-confirm" class="btn btn-primary">Resize</button>
</footer>
</article>
</dialog>
<script src="/static/upload.js"></script>
<script>
var currentResizeFile = '';
function copyMarkdown(filename, isImage, originalName, btn) {
var url = '/uploads/' + filename;
var label = originalName || filename;
var md = isImage ? '![](' + url + ')' : '[' + label + '](' + url + ')';
var orig = btn.textContent;
navigator.clipboard.writeText(md).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
}
function openResize(filename, w, h) {
currentResizeFile = filename;
document.getElementById('resize-current').textContent = 'Current: ' + w + '×' + h;
document.getElementById('resize-status').textContent = '';
document.getElementById('resize-confirm').disabled = false;
document.getElementById('resize-dialog').showModal();
}
document.getElementById('resize-confirm').addEventListener('click', function() {
var dim = document.getElementById('resize-dim').value;
var status = document.getElementById('resize-status');
var btn = this;
status.textContent = 'Resizing…';
btn.disabled = true;
var fd = new FormData();
fd.append('csrf_token', window.GlimmerUpload.getCsrfToken());
fd.append('max_dim', dim);
fetch('/admin/uploads/resize/' + currentResizeFile, { method: 'POST', body: fd, credentials: 'same-origin' })
.then(function(r) { return r.json(); })
.then(function(data) {
btn.disabled = false;
if (data.error) {
status.textContent = 'Error: ' + data.error;
return;
}
var sizeEl = document.getElementById('size-' + currentResizeFile);
var dimEl = document.getElementById('dim-' + currentResizeFile);
if (sizeEl) sizeEl.textContent = data.size_human;
if (dimEl) dimEl.textContent = data.width + '×' + data.height;
status.textContent = 'Done — ' + data.size_human;
var imgs = document.querySelectorAll('img[src="/uploads/' + currentResizeFile + '"]');
imgs.forEach(function(img) { img.src = '/uploads/' + currentResizeFile + '?t=' + Date.now(); });
})
.catch(function() {
btn.disabled = false;
status.textContent = 'Failed';
});
});
window.GlimmerUpload.init({
imgBtn: document.getElementById('upload-img-btn'),
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: document.getElementById('upload-status'),
maxImageMB: {{.UploadMaxMB}},
onUploaded: function() { location.reload(); }
});
</script>
<script src="/static/js/admin_uploads.js"></script>
{{end}}
+3 -20
View File
@@ -88,9 +88,9 @@
</div>
<!-- QR Code Preview Modal -->
<div id="qr-modal-overlay" class="qr-modal-overlay" onclick="if(event.target===this)closeQRModal()">
<div id="qr-modal-overlay" class="qr-modal-overlay">
<div id="qr-modal-card" class="qr-modal-card">
<button class="qr-modal-close" onclick="closeQRModal()" aria-label="Close">&times;</button>
<button id="qr-modal-close" class="qr-modal-close" aria-label="Close">&times;</button>
<h3>QR Code</h3>
<img id="qr-modal-image" class="qr-modal-image" src="" alt="QR Code">
<code id="qr-modal-link" class="qr-modal-link"></code>
@@ -98,23 +98,6 @@
</div>
</div>
<script>
function openQRModal(slug, name) {
var overlay = document.getElementById('qr-modal-overlay');
document.getElementById('qr-modal-image').src = '/admin/qr/' + slug;
document.getElementById('qr-modal-link').textContent = '/admin/qr/' + slug;
var dl = document.getElementById('qr-modal-download');
dl.href = '/admin/qr/' + slug;
dl.download = (name || slug) + '_QR.svg';
overlay.classList.add('show');
}
function closeQRModal() {
document.getElementById('qr-modal-overlay').classList.remove('show');
document.getElementById('qr-modal-image').src = '';
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') closeQRModal();
});
</script>
<script src="/static/js/base.js"></script>
</body>
</html>{{end}}
+1 -9
View File
@@ -22,13 +22,5 @@
</div>
<script>
document.getElementById('token-form').addEventListener('submit', function(e) {
e.preventDefault();
var token = document.getElementById('token-input').value.trim();
if (token) {
window.location.href = window.location.pathname + '/' + encodeURIComponent(token);
}
});
</script>
<script src="/static/js/bin_token.js"></script>
{{end}}
+2 -10
View File
@@ -19,7 +19,7 @@
</div>
<div class="paste-toolbar">
<a href="?raw=1" class="btn btn-secondary btn-sm">Raw</a>
<button class="btn btn-primary btn-sm" onclick="copyPaste(this)">Copy</button>
<button id="copy-paste-btn" class="btn btn-primary btn-sm">Copy</button>
</div>
</div>
@@ -33,15 +33,7 @@
</div>
<script>
function copyPaste(btn) {
var orig = btn.textContent;
navigator.clipboard.writeText(document.getElementById('paste-raw').innerText).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
}
</script>
<script src="/static/js/bin_view.js"></script>
{{else}}
<div class="card center-page">
<h2>Paste not found</h2>
+2 -17
View File
@@ -23,7 +23,7 @@
</div>
<div class="result-box">
<code id="short-url">{{.ShortURL}}</code>
<button class="btn btn-secondary btn-sm" onclick="copyToClipboard(document.getElementById('short-url').textContent, this)">Copy</button>
<button id="copy-short-url" class="btn btn-secondary btn-sm">Copy</button>
</div>
{{if .QRSVG}}
<div class="qr-display">{{.QRSVG}}</div>
@@ -52,20 +52,5 @@
</div>
<script>
document.getElementById('shorten-form').addEventListener('submit', function() {
var input = document.getElementById('url');
if (input.value && input.value.indexOf('://') === -1) {
input.value = 'https://' + input.value;
}
});
function copyToClipboard(text, btn) {
var orig = btn.textContent;
navigator.clipboard.writeText(text).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
}
</script>
<script src="/static/js/index.js"></script>
{{end}}
+11 -8
View File
@@ -1,8 +1,7 @@
# Hardening / Robustness Plan
> Progress: items 1–4 done (build/vet/tests green, ARMv5 cross-compile
> verified). Item 5 remains — large template refactor, best done as its own
> piece of work.
> Progress: all five items done. Item 5 verified in a live browser session
> (every page exercised, zero console errors / CSP violations).
Follow-ups from the 2026-06-09 security review (fixes from that review already
landed in `962f5d9`). Status legend: ☐ todo · ◐ in progress · ☑ done
@@ -46,12 +45,16 @@ upload serving) have zero tests. Add `handlers_test.go` covering at least:
- login: wrong password → 401, correct → session cookie + redirect
- oversized-image rejection from item 1
## 5. ☐ Drop `'unsafe-inline'` from `script-src` (CSP)
## 5. ☑ Drop `'unsafe-inline'` from `script-src` (CSP)
All template JS is inline, so the CSP doesn't actually block injected
scripts. Move inline blocks into embedded static files (the `upload.js`
pattern) and tighten `script-src` to `'self'`. Touches every template —
deliberately last, and large enough that it may warrant its own session.
Done: all inline `<script>` blocks and `on*=` attributes moved to per-page
files under `static/js/` (`base.js` carries shared chrome: QR modal,
`glimmerCopy`, `form[data-confirm]`). Template data is passed via `data-*`
attributes instead of `{{...}}` interpolation in JS. `script-src` is now
`'self'`; `style-src` keeps `'unsafe-inline'` for the `style=""` attributes.
Verified live: shorten flow, login, QR modal, paste editor (token radios,
name preview), paste cards (preview dialog, expand/close), public paste view,
token prompt redirect, uploads page — no console errors or CSP violations.
---