-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
197 lines (158 loc) · 5.64 KB
/
server.js
File metadata and controls
197 lines (158 loc) · 5.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import express from 'express';
import cors from 'cors';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import multer from 'multer';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
// Create app
const app = express();
// Middleware
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// Storage
const STORAGE_ROOT = path.resolve('storage/users');
const USER_INDEX_PATH = path.join(STORAGE_ROOT, '_index.json');
const JWT_SECRET = process.env.JWT_SECRET;
function verifyJWT(req, res, next) {
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing token' });
}
try {
const token = auth.slice(7);
const payload = jwt.verify(token, JWT_SECRET);
req.user = payload; // { username }
next();
} catch {
return res.status(401).json({ error: 'Invalid token' });
}
}
if (!JWT_SECRET) {
throw new Error("JWT_SECRET is not set");
}
// Helpers
const canon = u => String(u || '').trim().toLowerCase();
async function loadIndex() {
try { return JSON.parse(await fs.promises.readFile(USER_INDEX_PATH)); }
catch { return {}; }
}
async function saveIndex(i) {
await fs.promises.mkdir(STORAGE_ROOT, { recursive: true });
await fs.promises.writeFile(USER_INDEX_PATH, JSON.stringify(i, null, 2));
}
// AUTH
app.post('/api/auth/register', async (req, res) => {
const { username, password, publicKeyPem } = req.body;
const u = canon(username);
const index = await loadIndex();
if (index[u]) return res.status(400).json({ error: 'User exists' });
if (!publicKeyPem) return res.status(400).json({ error: 'Public key required' });
const hash = await bcrypt.hash(password, 12);
const dir = path.join(STORAGE_ROOT, u);
await fs.promises.mkdir(path.join(dir, 'files'), { recursive: true });
await fs.promises.writeFile(path.join(dir, 'public.pem'), publicKeyPem);
index[u] = { passwordHash: hash };
await saveIndex(index);
res.json({ success: true });
});
app.post('/api/auth/login', async (req, res) => {
const { username, password } = req.body;
const u = canon(username);
const index = await loadIndex();
const user = index[u];
if (!user || !(await bcrypt.compare(password, user.passwordHash)))
return res.status(401).end();
res.json({
token: jwt.sign({ username: u }, JWT_SECRET, { expiresIn: '7d' })
});
});
// PUBKEY
app.get('/api/users/:username/public-key', verifyJWT, async (req, res) => {
const u = canon(req.params.username);
const p = path.join(STORAGE_ROOT, u, 'public.pem');
if (!fs.existsSync(p)) return res.status(404).end();
res.json({ publicKeyPem: await fs.promises.readFile(p, 'utf8') });
});
// FILES
const upload = multer({ storage: multer.memoryStorage() });
app.post('/api/files/upload', verifyJWT, upload.single('file'), async (req, res) => {
try {
const u = canon(req.user.username);
if (!req.file || !req.file.buffer) {
return res.status(400).json({ error: 'Missing file field' });
}
if (!req.body || !req.body.meta) {
return res.status(400).json({ error: 'Missing meta field' });
}
let meta;
try {
meta = JSON.parse(req.body.meta);
} catch {
return res.status(400).json({ error: 'Invalid meta JSON' });
}
const id = crypto.randomUUID();
const dir = path.join(STORAGE_ROOT, u, 'files', id);
await fs.promises.mkdir(dir, { recursive: true });
await fs.promises.writeFile(path.join(dir, 'blob.bin'), req.file.buffer);
// ensure meta has fileId/uploader that matches auth user
meta.fileId = id;
meta.uploader = u;
await fs.promises.writeFile(
path.join(dir, 'meta.json'),
JSON.stringify(meta, null, 2)
);
res.json({ fileId: id });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Upload failed' });
}
});
app.get('/api/files/:id/meta', verifyJWT, async (req, res) => {
const users = await fs.promises.readdir(STORAGE_ROOT);
for (const u of users) {
const p = path.join(STORAGE_ROOT, u, 'files', req.params.id, 'meta.json');
if (fs.existsSync(p)) return res.json(JSON.parse(await fs.promises.readFile(p)));
}
res.status(404).end();
});
app.get('/api/files/:id/blob', verifyJWT, async (req, res) => {
const users = await fs.promises.readdir(STORAGE_ROOT);
for (const u of users) {
const p = path.join(STORAGE_ROOT, u, 'files', req.params.id, 'blob.bin');
if (fs.existsSync(p)) return res.sendFile(p);
}
res.status(404).end();
});
app.get('/api/files/inbox', verifyJWT, async (req, res) => {
const user = canon(req.user.username);
const out = [];
for (const u of await fs.promises.readdir(STORAGE_ROOT)) {
const d = path.join(STORAGE_ROOT, u, 'files');
if (!fs.existsSync(d)) continue;
for (const id of await fs.promises.readdir(d)) {
const m = JSON.parse(await fs.promises.readFile(path.join(d, id, 'meta.json')));
if (m.recipients.includes(user))
out.push({ fileId: id, uploader: m.uploader, filename: m.filename });
}
}
res.json(out);
});
app.get('/api/files/outbox', verifyJWT, async (req, res) => {
const u = canon(req.user.username);
const d = path.join(STORAGE_ROOT, u, 'files');
if (!fs.existsSync(d)) return res.json([]);
const out = [];
for (const id of await fs.promises.readdir(d)) {
const m = JSON.parse(await fs.promises.readFile(path.join(d, id, 'meta.json')));
out.push({ fileId: id, recipients: m.recipients, filename: m.filename });
}
res.json(out);
});
export default app;
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`);
});