feat(web): public read-only file browser — GET API public, writes require admin

- /api/v1/* GET (list buckets/objects, download) no longer requires auth
- POST/DELETE/PUT stay behind requireAuth (upload, create/delete bucket, copy, delete object)
- FE drops blocking login screen: visitors browse + download freely
- Admin-only UI (create bucket, upload dropzone, delete, S3 creds) hidden in read-only mode
- Login button in topbar to unlock admin actions
This commit is contained in:
asepharyana
2026-08-01 20:31:40 +07:00
parent 864d41d8fc
commit 91ec588a88
4 changed files with 161 additions and 53 deletions
+58 -26
View File
@@ -136,6 +136,10 @@
}
.auth-card button:disabled { opacity: 0.7; cursor: wait; }
.auth-error { color: var(--danger); font-size: 0.85rem; margin-bottom: 12px; }
.readonly-badge {
font-size: 0.75rem; color: var(--text2); background: var(--bg2);
border: 1px solid var(--border); border-radius: 999px; padding: 2px 10px;
}
</style>
</head>
<body>
@@ -153,9 +157,11 @@
<select id="bucketSelect" onchange="window.switchBucket(this.value)">
<option value="">— Select bucket —</option>
</select>
<button type="button" onclick="window.showCreateBucketModal()">+ New</button>
<button type="button" onclick="window.showCredentialsModal()" title="S3 Credentials">🔑</button>
<button id="newBucketBtn" type="button" onclick="window.showCreateBucketModal()">+ New</button>
<button id="credsBtn" type="button" onclick="window.showCredentialsModal()" title="S3 Credentials">🔑</button>
<button id="loginBtn" type="button" onclick="window.showAuthScreen()" style="display:none">Login</button>
<button id="logoutBtn" type="button" onclick="window.logout()" style="display:none">Logout</button>
<span id="readonlyBadge" class="readonly-badge" style="display:none">👀 read-only</span>
<span class="spacer"></span>
<div class="search">
<input id="searchInput" type="text" placeholder="Filter prefix..." oninput="window.debouncedSearch()">
@@ -179,6 +185,7 @@
</div>
<script>
let currentBucket = null, currentPrefix = '', currentObjects = [], currentPrefixes = [], allBuckets = [], searchTimer = null;
let isAdmin = false;
const setAuthError = (message) => {
const errorEl = document.getElementById('authError');
errorEl.textContent = message;
@@ -186,25 +193,36 @@
};
const showAuthScreen = () => {
document.getElementById('authScreen').style.display = 'flex';
document.getElementById('logoutBtn').style.display = 'none';
setTimeout(() => document.getElementById('authTokenInput')?.focus(), 50);
};
const hideAuthScreen = (showLogout) => {
const hideAuthScreen = () => {
document.getElementById('authScreen').style.display = 'none';
document.getElementById('logoutBtn').style.display = showLogout ? 'inline-block' : 'none';
};
// Applies the admin/read-only UI state based on isAdmin.
const applyAdminUI = () => {
document.getElementById('newBucketBtn').style.display = isAdmin ? 'inline-block' : 'none';
document.getElementById('credsBtn').style.display = isAdmin ? 'inline-block' : 'none';
document.getElementById('loginBtn').style.display = isAdmin ? 'none' : 'inline-block';
document.getElementById('logoutBtn').style.display = isAdmin ? 'inline-block' : 'none';
document.getElementById('readonlyBadge').style.display = isAdmin ? 'none' : 'inline-block';
// Dropzone (upload) is admin-only.
document.getElementById('dropzone').style.display = isAdmin && currentBucket ? 'block' : 'none';
if (currentObjects.length || currentPrefixes.length) renderFileList();
};
// Non-blocking auth check: read-only visitors still get the file browser.
const checkAuth = async () => {
try {
const res = await fetch('/api/v1/auth/me');
if (res.ok) { hideAuthScreen(true); return true; }
if (res.status === 401) { showAuthScreen(); return false; }
if (res.status === 404) { hideAuthScreen(false); return true; }
setAuthError('Unable to verify login status. Please try again.');
showAuthScreen(); return false;
if (res.ok) { isAdmin = true; }
else if (res.status === 401) { isAdmin = false; }
else if (res.status === 404) { isAdmin = true; } // auth disabled — full access
else { isAdmin = false; }
} catch {
setAuthError('Network error while checking login status.');
showAuthScreen(); return false;
isAdmin = false;
}
hideAuthScreen();
applyAdminUI();
return isAdmin;
};
const handleLogin = async () => {
const input = document.getElementById('authTokenInput');
@@ -217,7 +235,7 @@
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token }),
});
if (res.ok) { hideAuthScreen(true); input.value = ''; await loadBuckets(); return; }
if (res.ok) { isAdmin = true; hideAuthScreen(); input.value = ''; applyAdminUI(); await loadBuckets(); return; }
const body = await res.json().catch(() => ({ error: 'Login failed' }));
setAuthError(body.error || 'Login failed');
} catch {
@@ -228,11 +246,8 @@
};
const logout = async () => {
await fetch('/api/v1/auth/logout', { method: 'POST' }).catch(() => {});
currentBucket = null; currentPrefix = ''; currentObjects = []; currentPrefixes = [];
document.getElementById('bucketSelect').innerHTML = '<option value="">— Select bucket —</option>';
document.getElementById('fileList').innerHTML = '<div class="empty"><h2>Logged out</h2><p>Enter the admin token to continue.</p></div>';
document.getElementById('dropzone').style.display = 'none';
showAuthScreen();
isAdmin = false;
applyAdminUI();
};
const api = async (path, opts = {}) => {
const res = await fetch(path, opts);
@@ -249,11 +264,13 @@
};
const switchBucket = async (name) => {
currentBucket = name || null; currentPrefix = '';
if (name) { await loadObjects(); document.getElementById('dropzone').style.display = 'block'; }
if (name) { await loadObjects(); }
else {
document.getElementById('fileList').innerHTML = '<div class="empty"><h2>Select a bucket</h2><p>Choose a bucket from the dropdown above.</p></div>';
document.getElementById('breadcrumb').style.display = 'none'; document.getElementById('dropzone').style.display = 'none';
document.getElementById('breadcrumb').style.display = 'none';
}
// Dropzone (upload) is admin-only.
document.getElementById('dropzone').style.display = isAdmin && currentBucket ? 'block' : 'none';
};
const renderBreadcrumb = () => {
const bc = document.getElementById('breadcrumb');
@@ -278,7 +295,12 @@
};
const renderFileList = () => {
const container = document.getElementById('fileList');
if (currentPrefixes.length === 0 && currentObjects.length === 0) { container.innerHTML = '<div class="empty"><h2>This bucket is empty</h2><p>Drop files here to upload.</p></div>'; return; }
if (currentPrefixes.length === 0 && currentObjects.length === 0) {
container.innerHTML = isAdmin
? '<div class="empty"><h2>This bucket is empty</h2><p>Drop files here to upload.</p></div>'
: '<div class="empty"><h2>This bucket is empty</h2></div>';
return;
}
let html = '';
for (const prefix of currentPrefixes) {
const displayName = prefix.replace(currentPrefix, '');
@@ -286,7 +308,9 @@
}
for (const obj of currentObjects) {
const displayName = obj.key.replace(currentPrefix, '');
html += `<div class="file-row"><span class="icon">📄</span><span class="name">${escapeHtml(displayName)}</span><span class="size">${formatSize(obj.sizeBytes)}</span><span class="date">${formatDate(obj.lastModified)}</span><span class="actions"><button onclick="event.stopPropagation();downloadObject('${obj.key}')" title="Download">⬇</button><button onclick="event.stopPropagation();copyLink('${obj.key}')" title="Copy link">🔗</button><button onclick="event.stopPropagation();deleteObject('${obj.key}')" title="Delete">🗑</button></span></div>`;
// Delete is admin-only; download + copy link are always available.
const deleteBtn = isAdmin ? `<button onclick="event.stopPropagation();deleteObject('${obj.key}')" title="Delete">🗑</button>` : '';
html += `<div class="file-row"><span class="icon">📄</span><span class="name">${escapeHtml(displayName)}</span><span class="size">${formatSize(obj.sizeBytes)}</span><span class="date">${formatDate(obj.lastModified)}</span><span class="actions"><button onclick="event.stopPropagation();downloadObject('${obj.key}')" title="Download">⬇</button><button onclick="event.stopPropagation();copyLink('${obj.key}')" title="Copy link">🔗</button>${deleteBtn}</span></div>`;
}
container.innerHTML = html;
};
@@ -297,11 +321,13 @@
const downloadObject = async (key) => { window.open(`/api/v1/buckets/${encodeURIComponent(currentBucket)}/download/${encodeURIComponent(key)}`,'_blank'); };
const copyLink = (key) => { navigator.clipboard.writeText(`${window.location.origin}/api/v1/buckets/${encodeURIComponent(currentBucket)}/download/${encodeURIComponent(key)}`).catch(()=>{}); };
const deleteObject = async (key) => {
if (!isAdmin) { alert('Read-only mode — login as admin to delete.'); return; }
if(!confirm(`Delete "${key}"?`))return;
try{await api(`/api/v1/buckets/${encodeURIComponent(currentBucket)}/${encodeURIComponent(key)}`,{method:'DELETE'});await loadObjects();}
catch(e){alert(`Delete failed: ${e.message}`);}
};
const uploadFiles = async (files) => {
if (!isAdmin) { alert('Read-only mode — login as admin to upload.'); return; }
if(!currentBucket||files.length===0)return;
const overlay=document.getElementById('progressOverlay'), fill=document.getElementById('progressFill'), pn=document.getElementById('progressFileName'), pp=document.getElementById('progressPercent');
overlay.style.display='flex';
@@ -325,10 +351,16 @@
dropzone.addEventListener('click',()=>{const i=document.createElement('input');i.type='file';i.multiple=true;i.onchange=()=>{if(i.files.length>0)uploadFiles(i.files);};i.click();});
const showModal=(html)=>{document.getElementById('modalContent').innerHTML=html;document.getElementById('modalOverlay').style.display='flex';};
const closeModal=(e)=>{if(e&&e.target!==e.currentTarget)return;document.getElementById('modalOverlay').style.display='none';};
const showCreateBucketModal=()=>{showModal(`<h3>Create Bucket</h3><input id="bucketNameInput" type="text" placeholder="my-bucket-name" pattern="[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]"><p style="font-size:0.8rem;color:var(--text2);margin-bottom:12px">Lowercase, 3-63 chars, no underscores</p><div class="buttons"><button onclick="closeModal()">Cancel</button><button class="primary" onclick="createBucket()">Create</button></div>`);setTimeout(()=>document.getElementById('bucketNameInput')?.focus(),100);};
const createBucket=async()=>{const n=document.getElementById('bucketNameInput').value.trim();if(!n)return;try{await apiJson('/api/v1/buckets',{method:'POST',body:JSON.stringify({name:n})});closeModal();await loadBuckets();document.getElementById('bucketSelect').value=n;await switchBucket(n);}catch(e){alert(`Failed: ${e.message}`);}};
const showCredentialsModal=()=>{showModal(`<h3>S3 Credentials</h3><p style="margin-bottom:12px;font-size:0.85rem;color:var(--text2)">Use these in any S3 client (aws-cli, rclone, s3cmd, etc.)</p><label style="font-size:0.85rem;font-weight:600">Endpoint URL</label><input type="text" value="${window.location.origin}" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Region</label><input type="text" value="us-east-1" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Access Key</label><input id="s3AccessKey" type="text" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Secret Key</label><input id="s3SecretKey" type="password" readonly onclick="this.select()"><div class="buttons"><button type="button" onclick="window.closeModal()">Close</button></div>`);};
const init=async()=>{if(await checkAuth())await loadBuckets();};
const showCreateBucketModal=()=>{
if (!isAdmin) { alert('Read-only mode — login as admin to create buckets.'); return; }
showModal(`<h3>Create Bucket</h3><input id="bucketNameInput" type="text" placeholder="my-bucket-name" pattern="[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]"><p style="font-size:0.8rem;color:var(--text2);margin-bottom:12px">Lowercase, 3-63 chars, no underscores</p><div class="buttons"><button onclick="closeModal()">Cancel</button><button class="primary" onclick="createBucket()">Create</button></div>`);setTimeout(()=>document.getElementById('bucketNameInput')?.focus(),100);};
const createBucket=async()=>{
if (!isAdmin) { alert('Read-only mode — login as admin to create buckets.'); return; }
const n=document.getElementById('bucketNameInput').value.trim();if(!n)return;try{await apiJson('/api/v1/buckets',{method:'POST',body:JSON.stringify({name:n})});closeModal();await loadBuckets();document.getElementById('bucketSelect').value=n;await switchBucket(n);}catch(e){alert(`Failed: ${e.message}`);}};
const showCredentialsModal=()=>{
if (!isAdmin) { alert('Read-only mode — login as admin to view S3 credentials.'); return; }
showModal(`<h3>S3 Credentials</h3><p style="margin-bottom:12px;font-size:0.85rem;color:var(--text2)">Use these in any S3 client (aws-cli, rclone, s3cmd, etc.)</p><label style="font-size:0.85rem;font-weight:600">Endpoint URL</label><input type="text" value="${window.location.origin}" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Region</label><input type="text" value="us-east-1" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Access Key</label><input id="s3AccessKey" type="text" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Secret Key</label><input id="s3SecretKey" type="password" readonly onclick="this.select()"><div class="buttons"><button type="button" onclick="window.closeModal()">Close</button></div>`);};
const init=async()=>{await checkAuth();await loadBuckets();};
document.getElementById('authLoginBtn').addEventListener('click',handleLogin);
document.getElementById('authTokenInput').addEventListener('keydown',e=>{if(e.key==='Enter')handleLogin();});
Object.assign(window, { switchBucket, navigateTo, debouncedSearch, downloadObject, copyLink, deleteObject, closeModal, showCreateBucketModal, createBucket, showCredentialsModal, logout });
+58 -26
View File
@@ -136,6 +136,10 @@
}
.auth-card button:disabled { opacity: 0.7; cursor: wait; }
.auth-error { color: var(--danger); font-size: 0.85rem; margin-bottom: 12px; }
.readonly-badge {
font-size: 0.75rem; color: var(--text2); background: var(--bg2);
border: 1px solid var(--border); border-radius: 999px; padding: 2px 10px;
}
</style>
</head>
<body>
@@ -153,9 +157,11 @@
<select id="bucketSelect" onchange="window.switchBucket(this.value)">
<option value="">— Select bucket —</option>
</select>
<button type="button" onclick="window.showCreateBucketModal()">+ New</button>
<button type="button" onclick="window.showCredentialsModal()" title="S3 Credentials">🔑</button>
<button id="newBucketBtn" type="button" onclick="window.showCreateBucketModal()">+ New</button>
<button id="credsBtn" type="button" onclick="window.showCredentialsModal()" title="S3 Credentials">🔑</button>
<button id="loginBtn" type="button" onclick="window.showAuthScreen()" style="display:none">Login</button>
<button id="logoutBtn" type="button" onclick="window.logout()" style="display:none">Logout</button>
<span id="readonlyBadge" class="readonly-badge" style="display:none">👀 read-only</span>
<span class="spacer"></span>
<div class="search">
<input id="searchInput" type="text" placeholder="Filter prefix..." oninput="window.debouncedSearch()">
@@ -179,6 +185,7 @@
</div>
<script>
let currentBucket = null, currentPrefix = '', currentObjects = [], currentPrefixes = [], allBuckets = [], searchTimer = null;
let isAdmin = false;
const setAuthError = (message) => {
const errorEl = document.getElementById('authError');
errorEl.textContent = message;
@@ -186,25 +193,36 @@
};
const showAuthScreen = () => {
document.getElementById('authScreen').style.display = 'flex';
document.getElementById('logoutBtn').style.display = 'none';
setTimeout(() => document.getElementById('authTokenInput')?.focus(), 50);
};
const hideAuthScreen = (showLogout) => {
const hideAuthScreen = () => {
document.getElementById('authScreen').style.display = 'none';
document.getElementById('logoutBtn').style.display = showLogout ? 'inline-block' : 'none';
};
// Applies the admin/read-only UI state based on isAdmin.
const applyAdminUI = () => {
document.getElementById('newBucketBtn').style.display = isAdmin ? 'inline-block' : 'none';
document.getElementById('credsBtn').style.display = isAdmin ? 'inline-block' : 'none';
document.getElementById('loginBtn').style.display = isAdmin ? 'none' : 'inline-block';
document.getElementById('logoutBtn').style.display = isAdmin ? 'inline-block' : 'none';
document.getElementById('readonlyBadge').style.display = isAdmin ? 'none' : 'inline-block';
// Dropzone (upload) is admin-only.
document.getElementById('dropzone').style.display = isAdmin && currentBucket ? 'block' : 'none';
if (currentObjects.length || currentPrefixes.length) renderFileList();
};
// Non-blocking auth check: read-only visitors still get the file browser.
const checkAuth = async () => {
try {
const res = await fetch('/api/v1/auth/me');
if (res.ok) { hideAuthScreen(true); return true; }
if (res.status === 401) { showAuthScreen(); return false; }
if (res.status === 404) { hideAuthScreen(false); return true; }
setAuthError('Unable to verify login status. Please try again.');
showAuthScreen(); return false;
if (res.ok) { isAdmin = true; }
else if (res.status === 401) { isAdmin = false; }
else if (res.status === 404) { isAdmin = true; } // auth disabled — full access
else { isAdmin = false; }
} catch {
setAuthError('Network error while checking login status.');
showAuthScreen(); return false;
isAdmin = false;
}
hideAuthScreen();
applyAdminUI();
return isAdmin;
};
const handleLogin = async () => {
const input = document.getElementById('authTokenInput');
@@ -217,7 +235,7 @@
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token }),
});
if (res.ok) { hideAuthScreen(true); input.value = ''; await loadBuckets(); return; }
if (res.ok) { isAdmin = true; hideAuthScreen(); input.value = ''; applyAdminUI(); await loadBuckets(); return; }
const body = await res.json().catch(() => ({ error: 'Login failed' }));
setAuthError(body.error || 'Login failed');
} catch {
@@ -228,11 +246,8 @@
};
const logout = async () => {
await fetch('/api/v1/auth/logout', { method: 'POST' }).catch(() => {});
currentBucket = null; currentPrefix = ''; currentObjects = []; currentPrefixes = [];
document.getElementById('bucketSelect').innerHTML = '<option value="">— Select bucket —</option>';
document.getElementById('fileList').innerHTML = '<div class="empty"><h2>Logged out</h2><p>Enter the admin token to continue.</p></div>';
document.getElementById('dropzone').style.display = 'none';
showAuthScreen();
isAdmin = false;
applyAdminUI();
};
const api = async (path, opts = {}) => {
const res = await fetch(path, opts);
@@ -249,11 +264,13 @@
};
const switchBucket = async (name) => {
currentBucket = name || null; currentPrefix = '';
if (name) { await loadObjects(); document.getElementById('dropzone').style.display = 'block'; }
if (name) { await loadObjects(); }
else {
document.getElementById('fileList').innerHTML = '<div class="empty"><h2>Select a bucket</h2><p>Choose a bucket from the dropdown above.</p></div>';
document.getElementById('breadcrumb').style.display = 'none'; document.getElementById('dropzone').style.display = 'none';
document.getElementById('breadcrumb').style.display = 'none';
}
// Dropzone (upload) is admin-only.
document.getElementById('dropzone').style.display = isAdmin && currentBucket ? 'block' : 'none';
};
const renderBreadcrumb = () => {
const bc = document.getElementById('breadcrumb');
@@ -278,7 +295,12 @@
};
const renderFileList = () => {
const container = document.getElementById('fileList');
if (currentPrefixes.length === 0 && currentObjects.length === 0) { container.innerHTML = '<div class="empty"><h2>This bucket is empty</h2><p>Drop files here to upload.</p></div>'; return; }
if (currentPrefixes.length === 0 && currentObjects.length === 0) {
container.innerHTML = isAdmin
? '<div class="empty"><h2>This bucket is empty</h2><p>Drop files here to upload.</p></div>'
: '<div class="empty"><h2>This bucket is empty</h2></div>';
return;
}
let html = '';
for (const prefix of currentPrefixes) {
const displayName = prefix.replace(currentPrefix, '');
@@ -286,7 +308,9 @@
}
for (const obj of currentObjects) {
const displayName = obj.key.replace(currentPrefix, '');
html += `<div class="file-row"><span class="icon">📄</span><span class="name">${escapeHtml(displayName)}</span><span class="size">${formatSize(obj.sizeBytes)}</span><span class="date">${formatDate(obj.lastModified)}</span><span class="actions"><button onclick="event.stopPropagation();downloadObject('${obj.key}')" title="Download">⬇</button><button onclick="event.stopPropagation();copyLink('${obj.key}')" title="Copy link">🔗</button><button onclick="event.stopPropagation();deleteObject('${obj.key}')" title="Delete">🗑</button></span></div>`;
// Delete is admin-only; download + copy link are always available.
const deleteBtn = isAdmin ? `<button onclick="event.stopPropagation();deleteObject('${obj.key}')" title="Delete">🗑</button>` : '';
html += `<div class="file-row"><span class="icon">📄</span><span class="name">${escapeHtml(displayName)}</span><span class="size">${formatSize(obj.sizeBytes)}</span><span class="date">${formatDate(obj.lastModified)}</span><span class="actions"><button onclick="event.stopPropagation();downloadObject('${obj.key}')" title="Download">⬇</button><button onclick="event.stopPropagation();copyLink('${obj.key}')" title="Copy link">🔗</button>${deleteBtn}</span></div>`;
}
container.innerHTML = html;
};
@@ -297,11 +321,13 @@
const downloadObject = async (key) => { window.open(`/api/v1/buckets/${encodeURIComponent(currentBucket)}/download/${encodeURIComponent(key)}`,'_blank'); };
const copyLink = (key) => { navigator.clipboard.writeText(`${window.location.origin}/api/v1/buckets/${encodeURIComponent(currentBucket)}/download/${encodeURIComponent(key)}`).catch(()=>{}); };
const deleteObject = async (key) => {
if (!isAdmin) { alert('Read-only mode — login as admin to delete.'); return; }
if(!confirm(`Delete "${key}"?`))return;
try{await api(`/api/v1/buckets/${encodeURIComponent(currentBucket)}/${encodeURIComponent(key)}`,{method:'DELETE'});await loadObjects();}
catch(e){alert(`Delete failed: ${e.message}`);}
};
const uploadFiles = async (files) => {
if (!isAdmin) { alert('Read-only mode — login as admin to upload.'); return; }
if(!currentBucket||files.length===0)return;
const overlay=document.getElementById('progressOverlay'), fill=document.getElementById('progressFill'), pn=document.getElementById('progressFileName'), pp=document.getElementById('progressPercent');
overlay.style.display='flex';
@@ -325,10 +351,16 @@
dropzone.addEventListener('click',()=>{const i=document.createElement('input');i.type='file';i.multiple=true;i.onchange=()=>{if(i.files.length>0)uploadFiles(i.files);};i.click();});
const showModal=(html)=>{document.getElementById('modalContent').innerHTML=html;document.getElementById('modalOverlay').style.display='flex';};
const closeModal=(e)=>{if(e&&e.target!==e.currentTarget)return;document.getElementById('modalOverlay').style.display='none';};
const showCreateBucketModal=()=>{showModal(`<h3>Create Bucket</h3><input id="bucketNameInput" type="text" placeholder="my-bucket-name" pattern="[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]"><p style="font-size:0.8rem;color:var(--text2);margin-bottom:12px">Lowercase, 3-63 chars, no underscores</p><div class="buttons"><button onclick="closeModal()">Cancel</button><button class="primary" onclick="createBucket()">Create</button></div>`);setTimeout(()=>document.getElementById('bucketNameInput')?.focus(),100);};
const createBucket=async()=>{const n=document.getElementById('bucketNameInput').value.trim();if(!n)return;try{await apiJson('/api/v1/buckets',{method:'POST',body:JSON.stringify({name:n})});closeModal();await loadBuckets();document.getElementById('bucketSelect').value=n;await switchBucket(n);}catch(e){alert(`Failed: ${e.message}`);}};
const showCredentialsModal=()=>{showModal(`<h3>S3 Credentials</h3><p style="margin-bottom:12px;font-size:0.85rem;color:var(--text2)">Use these in any S3 client (aws-cli, rclone, s3cmd, etc.)</p><label style="font-size:0.85rem;font-weight:600">Endpoint URL</label><input type="text" value="${window.location.origin}" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Region</label><input type="text" value="us-east-1" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Access Key</label><input id="s3AccessKey" type="text" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Secret Key</label><input id="s3SecretKey" type="password" readonly onclick="this.select()"><div class="buttons"><button type="button" onclick="window.closeModal()">Close</button></div>`);};
const init=async()=>{if(await checkAuth())await loadBuckets();};
const showCreateBucketModal=()=>{
if (!isAdmin) { alert('Read-only mode — login as admin to create buckets.'); return; }
showModal(`<h3>Create Bucket</h3><input id="bucketNameInput" type="text" placeholder="my-bucket-name" pattern="[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]"><p style="font-size:0.8rem;color:var(--text2);margin-bottom:12px">Lowercase, 3-63 chars, no underscores</p><div class="buttons"><button onclick="closeModal()">Cancel</button><button class="primary" onclick="createBucket()">Create</button></div>`);setTimeout(()=>document.getElementById('bucketNameInput')?.focus(),100);};
const createBucket=async()=>{
if (!isAdmin) { alert('Read-only mode — login as admin to create buckets.'); return; }
const n=document.getElementById('bucketNameInput').value.trim();if(!n)return;try{await apiJson('/api/v1/buckets',{method:'POST',body:JSON.stringify({name:n})});closeModal();await loadBuckets();document.getElementById('bucketSelect').value=n;await switchBucket(n);}catch(e){alert(`Failed: ${e.message}`);}};
const showCredentialsModal=()=>{
if (!isAdmin) { alert('Read-only mode — login as admin to view S3 credentials.'); return; }
showModal(`<h3>S3 Credentials</h3><p style="margin-bottom:12px;font-size:0.85rem;color:var(--text2)">Use these in any S3 client (aws-cli, rclone, s3cmd, etc.)</p><label style="font-size:0.85rem;font-weight:600">Endpoint URL</label><input type="text" value="${window.location.origin}" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Region</label><input type="text" value="us-east-1" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Access Key</label><input id="s3AccessKey" type="text" readonly onclick="this.select()"><label style="font-size:0.85rem;font-weight:600">Secret Key</label><input id="s3SecretKey" type="password" readonly onclick="this.select()"><div class="buttons"><button type="button" onclick="window.closeModal()">Close</button></div>`);};
const init=async()=>{await checkAuth();await loadBuckets();};
document.getElementById('authLoginBtn').addEventListener('click',handleLogin);
document.getElementById('authTokenInput').addEventListener('keydown',e=>{if(e.key==='Enter')handleLogin();});
Object.assign(window, { switchBucket, navigateTo, debouncedSearch, downloadObject, copyLink, deleteObject, closeModal, showCreateBucketModal, createBucket, showCredentialsModal, logout });
+4 -1
View File
@@ -109,8 +109,11 @@ export const routes = {
'/api/v1/auth/me': {
GET: handleMe,
},
// Read endpoints (GET) are public — anyone can list buckets/objects and
// download files. Write endpoints (POST/DELETE/PUT) require admin auth so
// visitors cannot upload, edit, copy, or delete.
'/api/v1/*': {
GET: requireAuth(handleWebApiV1),
GET: handleWebApiV1,
POST: requireAuth(handleWebApiV1),
DELETE: requireAuth(handleWebApiV1),
PUT: requireAuth(handleWebApiV1),
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'bun:test';
const defaultEnv = (key: string, value: string) => {
process.env[key] ||= value;
};
const setEnv = (key: string, value: string) => {
process.env[key] = value;
};
defaultEnv('BOT_TOKENS', '123456:ABC-DEF');
defaultEnv('STORAGE_CHANNEL_ID', '-1001234567890');
defaultEnv('BASE_URL', 'https://example.com');
defaultEnv('DATABASE_URL', 'postgresql://user:***@localhost:5432/test');
defaultEnv('PORT', '3000');
defaultEnv('NODE_ENV', 'test');
setEnv('ADMIN_API_TOKEN', 'route-secret-token');
setEnv('SESSION_COOKIE_NAME', 'route_session');
setEnv('SESSION_COOKIE_MAX_AGE_SECONDS', '3600');
const { routes } = await import('../src/interfaces/http/routes/index');
const { handleWebApiV1 } = await import('../src/interfaces/http/controllers/web-api-controller');
describe('public read-only API routing', () => {
it('serves GET /api/v1/* without auth (read endpoints are public)', () => {
// The GET handler must be the raw web API handler — NOT requireAuth-wrapped.
expect(routes['/api/v1/*'].GET).toBe(handleWebApiV1);
});
it('protects write endpoints with auth (POST/DELETE/PUT)', () => {
// requireAuth wraps the handler into a new function, so these must NOT be
// the raw handler — they are auth-guarded.
expect(routes['/api/v1/*'].POST).not.toBe(handleWebApiV1);
expect(routes['/api/v1/*'].DELETE).not.toBe(handleWebApiV1);
expect(routes['/api/v1/*'].PUT).not.toBe(handleWebApiV1);
});
it('keeps the auth/me endpoint accessible (frontend uses it to detect admin state)', () => {
expect(routes['/api/v1/auth/me']).toBeDefined();
expect(typeof routes['/api/v1/auth/me'].GET).toBe('function');
});
});