BlueGit

timfa filemanager

block mobile

timfa Tim Falken · pushed by timfa

Authored 2026-05-04 · 6 months ago

Hash
4a4ba9a781163d3284255aacf10e95f006e57e74
Parent
d6714975
5 files changed +120 −48
.github/technical-reference.md +1 −1
@@ -64,7 +64,7 @@
64 64 - createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
65 65 - loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
66 66 - isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
67 - makeFileItem(item) - Builds a .file-item element; wires desktop click-select + dblclick open, and mobile tap-open with long-press sidebar actions.
67 - makeFileItem(item) - Builds a .file-item element; wires desktop click-select + dblclick open, mobile tap-open with long-press sidebar actions, and blocks default mobile contextmenu on long-press.
68 68 - attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
69 69
70 70 ## public/drag-move.js
@@ -64,7 +64,7 @@
64- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
64- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
65- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
65- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
66- isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
66- isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
67- makeFileItem(item) - Builds a .file-item element; wires desktop click-select + dblclick open, and mobile tap-open with long-press sidebar actions.
67- makeFileItem(item) - Builds a .file-item element; wires desktop click-select + dblclick open, mobile tap-open with long-press sidebar actions, and blocks default mobile contextmenu on long-press.
68- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
68- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
69
69
70## public/drag-move.js
70## public/drag-move.js
installsystemdservice.sh +1 −1
@@ -32,7 +32,7 @@ After=network.target
32 32 Type=simple
33 33 User=${RUN_AS}
34 34 WorkingDirectory=${SCRIPT_DIR}
35 ExecStart=${SCRIPT_DIR}/start.sh
35 ExecStart=/bin/sh ${SCRIPT_DIR}/start.sh
36 36 Restart=always
37 37 RestartSec=5
38 38 # Allow binding to privileged ports (< 1024) without running as root.
@@ -32,7 +32,7 @@ After=network.target
32Type=simple
32Type=simple
33User=${RUN_AS}
33User=${RUN_AS}
34WorkingDirectory=${SCRIPT_DIR}
34WorkingDirectory=${SCRIPT_DIR}
35ExecStart=${SCRIPT_DIR}/start.sh
35ExecStart=/bin/sh ${SCRIPT_DIR}/start.sh
36Restart=always
36Restart=always
37RestartSec=5
37RestartSec=5
38# Allow binding to privileged ports (< 1024) without running as root.
38# Allow binding to privileged ports (< 1024) without running as root.
public/app.js +7 −0
@@ -924,6 +924,13 @@ function makeFileItem (item)
924 924 makeDraggable(el, item);
925 925 attachMobileLongPress(el, item);
926 926
927 el.addEventListener('contextmenu', (e) =>
928 {
929 if (!isMobileViewport()) return;
930 e.preventDefault();
931 e.stopPropagation();
932 });
933
927 934 // Single-click: open sidebar
928 935 el.addEventListener('click', (e) =>
929 936 {
@@ -924,6 +924,13 @@ function makeFileItem (item)
924 makeDraggable(el, item);
924 makeDraggable(el, item);
925 attachMobileLongPress(el, item);
925 attachMobileLongPress(el, item);
926
926
927 el.addEventListener('contextmenu', (e) =>
928 {
929 if (!isMobileViewport()) return;
930 e.preventDefault();
931 e.stopPropagation();
932 });
933
927 // Single-click: open sidebar
934 // Single-click: open sidebar
928 el.addEventListener('click', (e) =>
935 el.addEventListener('click', (e) =>
929 {
936 {
tests/admin.routes.test.js +78 −45
@@ -4,17 +4,20 @@
4 4 * Unit tests for server/routes/admin.js — user CRUD and config management.
5 5 */
6 6
7 const express = require('express');
8 const http = require('http');
7 const express = require('express');
8 const http = require('http');
9 9 const { once } = require('events');
10 const crypto = require('crypto');
10 const crypto = require('crypto');
11 11
12 12 // ── in-memory DB mock ───────────────────────────────────────────────────────
13 jest.mock('../server/db', () => {
13 jest.mock('../server/db', () =>
14 {
14 15 const { Database } = require('node-sqlite3-wasm');
15 16 let db;
16 function getDb() {
17 if (!db) {
17 function getDb ()
18 {
19 if (!db)
20 {
18 21 db = new Database(':memory:');
19 22 db.exec(`
20 23 CREATE TABLE IF NOT EXISTS users (
@@ -39,34 +42,36 @@ jest.mock('../server/db', () => {
39 42 // ── config mock ─────────────────────────────────────────────────────────────
40 43 const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
41 44 jest.mock('../server/config', () => ({
42 loadConfig: () => ({ ...mockConfig }),
43 saveConfig: (c) => Object.assign(mockConfig, c),
45 loadConfig: () => ({ ...mockConfig }),
46 saveConfig: (c) => Object.assign(mockConfig, c),
44 47 getEffectivePaths: (p) => p,
45 getAllowedRoot: () => null,
48 getAllowedRoot: () => null,
46 49 }));
47 50
48 51 // ── auth mock — bypass JWT verification ─────────────────────────────────────
49 52 let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
50 53 jest.mock('../server/auth', () => ({
51 54 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
52 requireAdmin: (req, res, next) => {
55 requireAdmin: (req, res, next) =>
56 {
53 57 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
54 58 next();
55 59 },
56 60 createToken: () => 'mock-token',
57 61 getClientIp: () => '127.0.0.1',
58 getRegion: () => 'US:CA',
62 getRegion: () => 'US:CA',
59 63 }));
60 64
61 65 const adminRoutes = require('../server/routes/admin');
62 const { getDb } = require('../server/db');
63 const bcrypt = require('bcrypt');
66 const { getDb } = require('../server/db');
67 const bcrypt = require('bcrypt');
64 68
65 69 jest.setTimeout(30000);
66 70
67 71 // ── seed a default admin before anything runs ────────────────────────────────
68 beforeAll(() => {
69 const db = getDb();
72 beforeAll(() =>
73 {
74 const db = getDb();
70 75 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
71 76 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
72 77 .run(['admin', hash, '{}']);
@@ -77,15 +82,17 @@ let server;
77 82 let baseUrl;
78 83 let shutdownForRestartMock;
79 84
80 beforeAll(async () => {
85 beforeAll(async () =>
86 {
81 87 const app = express();
82 88 shutdownForRestartMock = jest.fn();
83 89 app.set('shutdownForRestart', shutdownForRestartMock);
84 90 app.use(express.json());
85 91 app.use('/api/admin', adminRoutes);
86 app.use((err, req, res, next) => {
87 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
88 });
92 app.use((err, req, res, next) =>
93 {
94 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
95 });
89 96 server = http.createServer(app);
90 97 server.listen(0);
91 98 await once(server, 'listening');
@@ -95,16 +102,19 @@ beforeAll(async () => {
95 102 afterAll(() => server.close());
96 103
97 104 // ── helpers ──────────────────────────────────────────────────────────────────
98 function req(method, path, body) {
105 function req (method, path, body)
106 {
99 107 const payload = body ? JSON.stringify(body) : undefined;
100 return new Promise((resolve, reject) => {
108 return new Promise((resolve, reject) =>
109 {
101 110 const r = http.request(baseUrl + path, {
102 111 method,
103 112 headers: {
104 113 'Content-Type': 'application/json',
105 114 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
106 115 },
107 }, res => {
116 }, res =>
117 {
108 118 let data = '';
109 119 res.on('data', d => data += d);
110 120 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
@@ -117,8 +127,10 @@ function req(method, path, body) {
117 127
118 128 // ── tests ─────────────────────────────────────────────────────────────────────
119 129
120 describe('GET /api/admin/users', () => {
121 test('returns the list of users', async () => {
130 describe('GET /api/admin/users', () =>
131 {
132 test('returns the list of users', async () =>
133 {
122 134 const { status, body } = await req('GET', '/api/admin/users');
123 135 expect(status).toBe(200);
124 136 expect(Array.isArray(body.users)).toBe(true);
@@ -126,8 +138,10 @@ describe('GET /api/admin/users', () => {
126 138 });
127 139 });
128 140
129 describe('POST /api/admin/users', () => {
130 test('creates a new user', async () => {
141 describe('POST /api/admin/users', () =>
142 {
143 test('creates a new user', async () =>
144 {
131 145 const { status, body } = await req('POST', '/api/admin/users', {
132 146 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
133 147 });
@@ -135,14 +149,16 @@ describe('POST /api/admin/users', () => {
135 149 expect(body.ok).toBe(true);
136 150 });
137 151
138 test('rejects duplicate username', async () => {
152 test('rejects duplicate username', async () =>
153 {
139 154 const { status } = await req('POST', '/api/admin/users', {
140 155 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
141 156 });
142 157 expect(status).toBe(409);
143 158 });
144 159
145 test('rejects short password', async () => {
160 test('rejects short password', async () =>
161 {
146 162 const { status } = await req('POST', '/api/admin/users', {
147 163 username: 'carol', password: 'short', isAdmin: false, permissions: {},
148 164 });
@@ -150,15 +166,18 @@ describe('POST /api/admin/users', () => {
150 166 });
151 167 });
152 168
153 describe('PATCH /api/admin/users/:id', () => {
169 describe('PATCH /api/admin/users/:id', () =>
170 {
154 171 let bobId;
155 172
156 beforeAll(async () => {
173 beforeAll(async () =>
174 {
157 175 const { body } = await req('GET', '/api/admin/users');
158 176 bobId = body.users.find(u => u.username === 'bob').id;
159 177 });
160 178
161 test('updates permissions', async () => {
179 test('updates permissions', async () =>
180 {
162 181 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
163 182 permissions: { data: { read: true, write: false } },
164 183 });
@@ -166,34 +185,40 @@ describe('PATCH /api/admin/users/:id', () => {
166 185 expect(body.ok).toBe(true);
167 186 });
168 187
169 test('returns 404 for unknown user', async () => {
188 test('returns 404 for unknown user', async () =>
189 {
170 190 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
171 191 expect(status).toBe(404);
172 192 });
173 193 });
174 194
175 describe('DELETE /api/admin/users/:id', () => {
195 describe('DELETE /api/admin/users/:id', () =>
196 {
176 197 let bobId;
177 198
178 beforeAll(async () => {
199 beforeAll(async () =>
200 {
179 201 const { body } = await req('GET', '/api/admin/users');
180 202 bobId = body.users.find(u => u.username === 'bob').id;
181 203 });
182 204
183 test('cannot delete own account', async () => {
205 test('cannot delete own account', async () =>
206 {
184 207 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
185 208 const adminId = mockUser.id;
186 209 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
187 210 expect(status).toBe(400);
188 211 });
189 212
190 test('deletes another user', async () => {
213 test('deletes another user', async () =>
214 {
191 215 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
192 216 expect(status).toBe(200);
193 217 expect(body.ok).toBe(true);
194 218 });
195 219
196 test('cannot delete the last admin', async () => {
220 test('cannot delete the last admin', async () =>
221 {
197 222 // Only 'admin' left; try to delete them (switch mockUser to be different)
198 223 const { body: users } = await req('GET', '/api/admin/users');
199 224 const adminUser = users.users.find(u => u.username === 'admin');
@@ -203,8 +228,10 @@ describe('DELETE /api/admin/users/:id', () => {
203 228 });
204 229 });
205 230
206 describe('GET /api/admin/config', () => {
207 test('returns port and paths', async () => {
231 describe('GET /api/admin/config', () =>
232 {
233 test('returns port and paths', async () =>
234 {
208 235 const { status, body } = await req('GET', '/api/admin/config');
209 236 expect(status).toBe(200);
210 237 expect(body.port).toBe(3000);
@@ -212,8 +239,10 @@ describe('GET /api/admin/config', () => {
212 239 });
213 240 });
214 241
215 describe('PUT /api/admin/config', () => {
216 test('saves new paths', async () => {
242 describe('PUT /api/admin/config', () =>
243 {
244 test('saves new paths', async () =>
245 {
217 246 const { status, body } = await req('PUT', '/api/admin/config', {
218 247 paths: ['/mnt/newpath'],
219 248 });
@@ -221,19 +250,23 @@ describe('PUT /api/admin/config', () => {
221 250 expect(body.ok).toBe(true);
222 251 });
223 252
224 test('rejects non-array paths', async () => {
253 test('rejects non-array paths', async () =>
254 {
225 255 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
226 256 expect(status).toBe(400);
227 257 });
228 258
229 test('rejects invalid port', async () => {
259 test('rejects invalid port', async () =>
260 {
230 261 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
231 262 expect(status).toBe(400);
232 263 });
233 264 });
234 265
235 describe('POST /api/admin/shutdown', () => {
236 test('responds ok and invokes shutdown callback', async () => {
266 describe('POST /api/admin/shutdown', () =>
267 {
268 test('responds ok and invokes shutdown callback', async () =>
269 {
237 270 shutdownForRestartMock.mockClear();
238 271 const { status, body } = await req('POST', '/api/admin/shutdown');
239 272 expect(status).toBe(200);
@@ -4,17 +4,20 @@
4 * Unit tests for server/routes/admin.js — user CRUD and config management.
4 * Unit tests for server/routes/admin.js — user CRUD and config management.
5 */
5 */
6
6
7const express = require('express');
7const express = require('express');
8const http = require('http');
8const http = require('http');
9const { once } = require('events');
9const { once } = require('events');
10const crypto = require('crypto');
10const crypto = require('crypto');
11
11
12// ── in-memory DB mock ───────────────────────────────────────────────────────
12// ── in-memory DB mock ───────────────────────────────────────────────────────
13jest.mock('../server/db', () => {
13jest.mock('../server/db', () =>
14{
14 const { Database } = require('node-sqlite3-wasm');
15 const { Database } = require('node-sqlite3-wasm');
15 let db;
16 let db;
16 function getDb() {
17 function getDb ()
17 if (!db) {
18 {
19 if (!db)
20 {
18 db = new Database(':memory:');
21 db = new Database(':memory:');
19 db.exec(`
22 db.exec(`
20 CREATE TABLE IF NOT EXISTS users (
23 CREATE TABLE IF NOT EXISTS users (
@@ -39,34 +42,36 @@ jest.mock('../server/db', () => {
39// ── config mock ─────────────────────────────────────────────────────────────
42// ── config mock ─────────────────────────────────────────────────────────────
40const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
43const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
41jest.mock('../server/config', () => ({
44jest.mock('../server/config', () => ({
42 loadConfig: () => ({ ...mockConfig }),
45 loadConfig: () => ({ ...mockConfig }),
43 saveConfig: (c) => Object.assign(mockConfig, c),
46 saveConfig: (c) => Object.assign(mockConfig, c),
44 getEffectivePaths: (p) => p,
47 getEffectivePaths: (p) => p,
45 getAllowedRoot: () => null,
48 getAllowedRoot: () => null,
46}));
49}));
47
50
48// ── auth mock — bypass JWT verification ─────────────────────────────────────
51// ── auth mock — bypass JWT verification ─────────────────────────────────────
49let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
52let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
50jest.mock('../server/auth', () => ({
53jest.mock('../server/auth', () => ({
51 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
54 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
52 requireAdmin: (req, res, next) => {
55 requireAdmin: (req, res, next) =>
56 {
53 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
57 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
54 next();
58 next();
55 },
59 },
56 createToken: () => 'mock-token',
60 createToken: () => 'mock-token',
57 getClientIp: () => '127.0.0.1',
61 getClientIp: () => '127.0.0.1',
58 getRegion: () => 'US:CA',
62 getRegion: () => 'US:CA',
59}));
63}));
60
64
61const adminRoutes = require('../server/routes/admin');
65const adminRoutes = require('../server/routes/admin');
62const { getDb } = require('../server/db');
66const { getDb } = require('../server/db');
63const bcrypt = require('bcrypt');
67const bcrypt = require('bcrypt');
64
68
65jest.setTimeout(30000);
69jest.setTimeout(30000);
66
70
67// ── seed a default admin before anything runs ────────────────────────────────
71// ── seed a default admin before anything runs ────────────────────────────────
68beforeAll(() => {
72beforeAll(() =>
69 const db = getDb();
73{
74 const db = getDb();
70 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
75 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
71 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
76 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
72 .run(['admin', hash, '{}']);
77 .run(['admin', hash, '{}']);
@@ -77,15 +82,17 @@ let server;
77let baseUrl;
82let baseUrl;
78let shutdownForRestartMock;
83let shutdownForRestartMock;
79
84
80beforeAll(async () => {
85beforeAll(async () =>
86{
81 const app = express();
87 const app = express();
82 shutdownForRestartMock = jest.fn();
88 shutdownForRestartMock = jest.fn();
83 app.set('shutdownForRestart', shutdownForRestartMock);
89 app.set('shutdownForRestart', shutdownForRestartMock);
84 app.use(express.json());
90 app.use(express.json());
85 app.use('/api/admin', adminRoutes);
91 app.use('/api/admin', adminRoutes);
86 app.use((err, req, res, next) => {
92 app.use((err, req, res, next) =>
87 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
93 {
88 });
94 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
95 });
89 server = http.createServer(app);
96 server = http.createServer(app);
90 server.listen(0);
97 server.listen(0);
91 await once(server, 'listening');
98 await once(server, 'listening');
@@ -95,16 +102,19 @@ beforeAll(async () => {
95afterAll(() => server.close());
102afterAll(() => server.close());
96
103
97// ── helpers ──────────────────────────────────────────────────────────────────
104// ── helpers ──────────────────────────────────────────────────────────────────
98function req(method, path, body) {
105function req (method, path, body)
106{
99 const payload = body ? JSON.stringify(body) : undefined;
107 const payload = body ? JSON.stringify(body) : undefined;
100 return new Promise((resolve, reject) => {
108 return new Promise((resolve, reject) =>
109 {
101 const r = http.request(baseUrl + path, {
110 const r = http.request(baseUrl + path, {
102 method,
111 method,
103 headers: {
112 headers: {
104 'Content-Type': 'application/json',
113 'Content-Type': 'application/json',
105 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
114 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
106 },
115 },
107 }, res => {
116 }, res =>
117 {
108 let data = '';
118 let data = '';
109 res.on('data', d => data += d);
119 res.on('data', d => data += d);
110 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
120 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
@@ -117,8 +127,10 @@ function req(method, path, body) {
117
127
118// ── tests ─────────────────────────────────────────────────────────────────────
128// ── tests ─────────────────────────────────────────────────────────────────────
119
129
120describe('GET /api/admin/users', () => {
130describe('GET /api/admin/users', () =>
121 test('returns the list of users', async () => {
131{
132 test('returns the list of users', async () =>
133 {
122 const { status, body } = await req('GET', '/api/admin/users');
134 const { status, body } = await req('GET', '/api/admin/users');
123 expect(status).toBe(200);
135 expect(status).toBe(200);
124 expect(Array.isArray(body.users)).toBe(true);
136 expect(Array.isArray(body.users)).toBe(true);
@@ -126,8 +138,10 @@ describe('GET /api/admin/users', () => {
126 });
138 });
127});
139});
128
140
129describe('POST /api/admin/users', () => {
141describe('POST /api/admin/users', () =>
130 test('creates a new user', async () => {
142{
143 test('creates a new user', async () =>
144 {
131 const { status, body } = await req('POST', '/api/admin/users', {
145 const { status, body } = await req('POST', '/api/admin/users', {
132 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
146 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
133 });
147 });
@@ -135,14 +149,16 @@ describe('POST /api/admin/users', () => {
135 expect(body.ok).toBe(true);
149 expect(body.ok).toBe(true);
136 });
150 });
137
151
138 test('rejects duplicate username', async () => {
152 test('rejects duplicate username', async () =>
153 {
139 const { status } = await req('POST', '/api/admin/users', {
154 const { status } = await req('POST', '/api/admin/users', {
140 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
155 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
141 });
156 });
142 expect(status).toBe(409);
157 expect(status).toBe(409);
143 });
158 });
144
159
145 test('rejects short password', async () => {
160 test('rejects short password', async () =>
161 {
146 const { status } = await req('POST', '/api/admin/users', {
162 const { status } = await req('POST', '/api/admin/users', {
147 username: 'carol', password: 'short', isAdmin: false, permissions: {},
163 username: 'carol', password: 'short', isAdmin: false, permissions: {},
148 });
164 });
@@ -150,15 +166,18 @@ describe('POST /api/admin/users', () => {
150 });
166 });
151});
167});
152
168
153describe('PATCH /api/admin/users/:id', () => {
169describe('PATCH /api/admin/users/:id', () =>
170{
154 let bobId;
171 let bobId;
155
172
156 beforeAll(async () => {
173 beforeAll(async () =>
174 {
157 const { body } = await req('GET', '/api/admin/users');
175 const { body } = await req('GET', '/api/admin/users');
158 bobId = body.users.find(u => u.username === 'bob').id;
176 bobId = body.users.find(u => u.username === 'bob').id;
159 });
177 });
160
178
161 test('updates permissions', async () => {
179 test('updates permissions', async () =>
180 {
162 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
181 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
163 permissions: { data: { read: true, write: false } },
182 permissions: { data: { read: true, write: false } },
164 });
183 });
@@ -166,34 +185,40 @@ describe('PATCH /api/admin/users/:id', () => {
166 expect(body.ok).toBe(true);
185 expect(body.ok).toBe(true);
167 });
186 });
168
187
169 test('returns 404 for unknown user', async () => {
188 test('returns 404 for unknown user', async () =>
189 {
170 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
190 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
171 expect(status).toBe(404);
191 expect(status).toBe(404);
172 });
192 });
173});
193});
174
194
175describe('DELETE /api/admin/users/:id', () => {
195describe('DELETE /api/admin/users/:id', () =>
196{
176 let bobId;
197 let bobId;
177
198
178 beforeAll(async () => {
199 beforeAll(async () =>
200 {
179 const { body } = await req('GET', '/api/admin/users');
201 const { body } = await req('GET', '/api/admin/users');
180 bobId = body.users.find(u => u.username === 'bob').id;
202 bobId = body.users.find(u => u.username === 'bob').id;
181 });
203 });
182
204
183 test('cannot delete own account', async () => {
205 test('cannot delete own account', async () =>
206 {
184 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
207 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
185 const adminId = mockUser.id;
208 const adminId = mockUser.id;
186 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
209 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
187 expect(status).toBe(400);
210 expect(status).toBe(400);
188 });
211 });
189
212
190 test('deletes another user', async () => {
213 test('deletes another user', async () =>
214 {
191 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
215 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
192 expect(status).toBe(200);
216 expect(status).toBe(200);
193 expect(body.ok).toBe(true);
217 expect(body.ok).toBe(true);
194 });
218 });
195
219
196 test('cannot delete the last admin', async () => {
220 test('cannot delete the last admin', async () =>
221 {
197 // Only 'admin' left; try to delete them (switch mockUser to be different)
222 // Only 'admin' left; try to delete them (switch mockUser to be different)
198 const { body: users } = await req('GET', '/api/admin/users');
223 const { body: users } = await req('GET', '/api/admin/users');
199 const adminUser = users.users.find(u => u.username === 'admin');
224 const adminUser = users.users.find(u => u.username === 'admin');
@@ -203,8 +228,10 @@ describe('DELETE /api/admin/users/:id', () => {
203 });
228 });
204});
229});
205
230
206describe('GET /api/admin/config', () => {
231describe('GET /api/admin/config', () =>
207 test('returns port and paths', async () => {
232{
233 test('returns port and paths', async () =>
234 {
208 const { status, body } = await req('GET', '/api/admin/config');
235 const { status, body } = await req('GET', '/api/admin/config');
209 expect(status).toBe(200);
236 expect(status).toBe(200);
210 expect(body.port).toBe(3000);
237 expect(body.port).toBe(3000);
@@ -212,8 +239,10 @@ describe('GET /api/admin/config', () => {
212 });
239 });
213});
240});
214
241
215describe('PUT /api/admin/config', () => {
242describe('PUT /api/admin/config', () =>
216 test('saves new paths', async () => {
243{
244 test('saves new paths', async () =>
245 {
217 const { status, body } = await req('PUT', '/api/admin/config', {
246 const { status, body } = await req('PUT', '/api/admin/config', {
218 paths: ['/mnt/newpath'],
247 paths: ['/mnt/newpath'],
219 });
248 });
@@ -221,19 +250,23 @@ describe('PUT /api/admin/config', () => {
221 expect(body.ok).toBe(true);
250 expect(body.ok).toBe(true);
222 });
251 });
223
252
224 test('rejects non-array paths', async () => {
253 test('rejects non-array paths', async () =>
254 {
225 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
255 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
226 expect(status).toBe(400);
256 expect(status).toBe(400);
227 });
257 });
228
258
229 test('rejects invalid port', async () => {
259 test('rejects invalid port', async () =>
260 {
230 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
261 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
231 expect(status).toBe(400);
262 expect(status).toBe(400);
232 });
263 });
233});
264});
234
265
235describe('POST /api/admin/shutdown', () => {
266describe('POST /api/admin/shutdown', () =>
236 test('responds ok and invokes shutdown callback', async () => {
267{
268 test('responds ok and invokes shutdown callback', async () =>
269 {
237 shutdownForRestartMock.mockClear();
270 shutdownForRestartMock.mockClear();
238 const { status, body } = await req('POST', '/api/admin/shutdown');
271 const { status, body } = await req('POST', '/api/admin/shutdown');
239 expect(status).toBe(200);
272 expect(status).toBe(200);
tests/page.load.test.js +33 −1
@@ -27,7 +27,17 @@ describe('page load smoke test', () =>
27 27 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
28 28 app.get('/api/auth/me', (req, res) => res.json({ username: 'tester', isAdmin: false, permissions: {} }));
29 29 app.get('/api/files/roots', (req, res) => res.json({ roots: [{ label: 'Root', path: '/data' }] }));
30 app.get('/api/files/list', (req, res) => res.json({ items: [] }));
30 app.get('/api/files/list', (req, res) => res.json({
31 items: [
32 {
33 name: 'readme.txt',
34 path: '/data/readme.txt',
35 isDir: false,
36 size: 12,
37 mtime: Date.now(),
38 },
39 ],
40 }));
31 41 app.get('/api/files/space', (req, res) => res.json({ usedBytes: 0, freeBytes: 1024 * 1024 }));
32 42 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
33 43 app.get('*', (req, res) => res.sendFile(path.join(publicDir, 'index.html')));
@@ -106,4 +116,26 @@ describe('page load smoke test', () =>
106 116
107 117 dom.window.close();
108 118 });
119
120 test('suppresses default context menu on mobile file long-press', async () =>
121 {
122 const { dom, runtimeErrors } = await bootClient({ mobile: true });
123
124 expect(runtimeErrors).toEqual([]);
125
126 const tile = dom.window.document.querySelector('.file-item');
127 expect(tile).toBeTruthy();
128
129 const evt = new dom.window.MouseEvent('contextmenu', {
130 bubbles: true,
131 cancelable: true,
132 view: dom.window,
133 });
134
135 const dispatchResult = tile.dispatchEvent(evt);
136 expect(dispatchResult).toBe(false);
137 expect(evt.defaultPrevented).toBe(true);
138
139 dom.window.close();
140 });
109 141 });
@@ -27,7 +27,17 @@ describe('page load smoke test', () =>
27 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
27 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
28 app.get('/api/auth/me', (req, res) => res.json({ username: 'tester', isAdmin: false, permissions: {} }));
28 app.get('/api/auth/me', (req, res) => res.json({ username: 'tester', isAdmin: false, permissions: {} }));
29 app.get('/api/files/roots', (req, res) => res.json({ roots: [{ label: 'Root', path: '/data' }] }));
29 app.get('/api/files/roots', (req, res) => res.json({ roots: [{ label: 'Root', path: '/data' }] }));
30 app.get('/api/files/list', (req, res) => res.json({ items: [] }));
30 app.get('/api/files/list', (req, res) => res.json({
31 items: [
32 {
33 name: 'readme.txt',
34 path: '/data/readme.txt',
35 isDir: false,
36 size: 12,
37 mtime: Date.now(),
38 },
39 ],
40 }));
31 app.get('/api/files/space', (req, res) => res.json({ usedBytes: 0, freeBytes: 1024 * 1024 }));
41 app.get('/api/files/space', (req, res) => res.json({ usedBytes: 0, freeBytes: 1024 * 1024 }));
32 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
42 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
33 app.get('*', (req, res) => res.sendFile(path.join(publicDir, 'index.html')));
43 app.get('*', (req, res) => res.sendFile(path.join(publicDir, 'index.html')));
@@ -106,4 +116,26 @@ describe('page load smoke test', () =>
106
116
107 dom.window.close();
117 dom.window.close();
108 });
118 });
119
120 test('suppresses default context menu on mobile file long-press', async () =>
121 {
122 const { dom, runtimeErrors } = await bootClient({ mobile: true });
123
124 expect(runtimeErrors).toEqual([]);
125
126 const tile = dom.window.document.querySelector('.file-item');
127 expect(tile).toBeTruthy();
128
129 const evt = new dom.window.MouseEvent('contextmenu', {
130 bubbles: true,
131 cancelable: true,
132 view: dom.window,
133 });
134
135 const dispatchResult = tile.dispatchEvent(evt);
136 expect(dispatchResult).toBe(false);
137 expect(evt.defaultPrevented).toBe(true);
138
139 dom.window.close();
140 });
109});
141});