Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
254 lines (229 loc) · 9.16 KB
/
Copy pathserver.js
File metadata and controls
254 lines (229 loc) · 9.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'secure-cloud-docs-secret-key-2026';
// ---------------------------------------------------------------------------
// Middleware
// ---------------------------------------------------------------------------
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(express.static(path.join(__dirname, 'public')));
// ---------------------------------------------------------------------------
// Persistent JSON file storage
// ---------------------------------------------------------------------------
const DATA_DIR = path.join(__dirname, 'data');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
const DOCUMENTS_FILE = path.join(DATA_DIR, 'documents.json');
const SHARES_FILE = path.join(DATA_DIR, 'shares.json');
// Ensure data directory exists
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
function loadJSON(filePath) {
try {
if (fs.existsSync(filePath)) {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}
} catch (err) {
console.error(`Error loading ${filePath}:`, err.message);
}
return {};
}
function saveJSON(filePath, data) {
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
}
// Load persisted data
const users = loadJSON(USERS_FILE); // username → { id, username, passwordHash, publicKeyJwk }
const documents = loadJSON(DOCUMENTS_FILE); // docId → { id, ownerId, ownerName, fileName, encryptedData, iv, fileHash, ownerRawAesKey, createdAt }
const shares = loadJSON(SHARES_FILE); // docId → [ { recipientId, encryptedAesKey } ]
function saveUsers() { saveJSON(USERS_FILE, users); }
function saveDocs() { saveJSON(DOCUMENTS_FILE, documents); }
function saveShares() { saveJSON(SHARES_FILE, shares); }
// ---------------------------------------------------------------------------
// Auth middleware
// ---------------------------------------------------------------------------
function authenticate(req, res, next) {
const header = req.headers.authorization;
if (!header || !header.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Authentication required' });
}
try {
const decoded = jwt.verify(header.split(' ')[1], JWT_SECRET);
req.user = decoded;
next();
} catch {
return res.status(401).json({ error: 'Invalid or expired token' });
}
}
// ---------------------------------------------------------------------------
// AUTH routes
// ---------------------------------------------------------------------------
app.post('/api/register', async (req, res) => {
try {
const { username, password, publicKeyJwk } = req.body;
if (!username || !password || !publicKeyJwk) {
return res.status(400).json({ error: 'username, password, and publicKeyJwk are required' });
}
if (users[username]) {
return res.status(409).json({ error: 'Username already exists' });
}
const id = uuidv4();
const passwordHash = await bcrypt.hash(password, 10);
users[username] = { id, username, passwordHash, publicKeyJwk };
saveUsers();
const token = jwt.sign({ id, username }, JWT_SECRET, { expiresIn: '24h' });
res.status(201).json({ token, user: { id, username } });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/login', async (req, res) => {
try {
const { username, password } = req.body;
const user = users[username];
if (!user || !(await bcrypt.compare(password, user.passwordHash))) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
res.json({ token, user: { id: user.id, username: user.username } });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ---------------------------------------------------------------------------
// USER routes
// ---------------------------------------------------------------------------
app.get('/api/users', authenticate, (req, res) => {
const list = [];
for (const key of Object.keys(users)) {
const u = users[key];
if (u.id !== req.user.id) {
list.push({ id: u.id, username: u.username, publicKeyJwk: u.publicKeyJwk });
}
}
res.json(list);
});
// Update public key (called on login to sync key pair)
app.put('/api/users/publickey', authenticate, (req, res) => {
const { publicKeyJwk } = req.body;
if (!publicKeyJwk) return res.status(400).json({ error: 'publicKeyJwk is required' });
for (const key of Object.keys(users)) {
if (users[key].id === req.user.id) {
users[key].publicKeyJwk = publicKeyJwk;
saveUsers();
return res.json({ message: 'Public key updated' });
}
}
res.status(404).json({ error: 'User not found' });
});
// ---------------------------------------------------------------------------
// DOCUMENT routes
// ---------------------------------------------------------------------------
// Upload an encrypted document
app.post('/api/documents/upload', authenticate, (req, res) => {
try {
const { fileName, encryptedData, iv, fileHash, ownerRawAesKey } = req.body;
if (!fileName || !encryptedData || !iv || !fileHash || !ownerRawAesKey) {
return res.status(400).json({ error: 'Missing required fields' });
}
const id = uuidv4();
documents[id] = {
id,
ownerId: req.user.id,
ownerName: req.user.username,
fileName,
encryptedData,
iv,
fileHash,
ownerRawAesKey,
createdAt: new Date().toISOString(),
};
saveDocs();
res.status(201).json({ id, fileName, createdAt: documents[id].createdAt });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// List documents the current user owns or has been shared with
app.get('/api/documents', authenticate, (req, res) => {
const result = [];
for (const docId of Object.keys(documents)) {
const doc = documents[docId];
if (doc.ownerId === req.user.id) {
result.push({
id: doc.id, fileName: doc.fileName, ownerName: doc.ownerName,
createdAt: doc.createdAt, isOwner: true,
});
continue;
}
const docShares = shares[doc.id] || [];
const share = docShares.find(s => s.recipientId === req.user.id);
if (share) {
result.push({
id: doc.id, fileName: doc.fileName, ownerName: doc.ownerName,
createdAt: doc.createdAt, isOwner: false,
sharedEncryptedAesKey: share.encryptedAesKey,
});
}
}
res.json(result);
});
// Download an encrypted document
app.get('/api/documents/:id/download', authenticate, (req, res) => {
const doc = documents[req.params.id];
if (!doc) return res.status(404).json({ error: 'Document not found' });
const isOwner = doc.ownerId === req.user.id;
if (!isOwner) {
const docShares = shares[doc.id] || [];
const share = docShares.find(s => s.recipientId === req.user.id);
if (!share) return res.status(403).json({ error: 'Access denied' });
return res.json({
id: doc.id, fileName: doc.fileName, ownerName: doc.ownerName,
encryptedData: doc.encryptedData, iv: doc.iv, fileHash: doc.fileHash,
encryptedAesKey: share.encryptedAesKey, isOwner: false,
createdAt: doc.createdAt,
});
}
res.json({
id: doc.id, fileName: doc.fileName, ownerName: doc.ownerName,
encryptedData: doc.encryptedData, iv: doc.iv, fileHash: doc.fileHash,
ownerRawAesKey: doc.ownerRawAesKey, isOwner: true,
createdAt: doc.createdAt,
});
});
// Share a document with another user
app.post('/api/documents/share', authenticate, (req, res) => {
try {
const { documentId, recipientId, encryptedAesKey } = req.body;
if (!documentId || !recipientId || !encryptedAesKey) {
return res.status(400).json({ error: 'Missing required fields' });
}
const doc = documents[documentId];
if (!doc) return res.status(404).json({ error: 'Document not found' });
if (doc.ownerId !== req.user.id) return res.status(403).json({ error: 'Only the owner can share' });
if (!shares[documentId]) shares[documentId] = [];
const docShares = shares[documentId];
const existing = docShares.findIndex(s => s.recipientId === recipientId);
if (existing !== -1) docShares[existing].encryptedAesKey = encryptedAesKey;
else docShares.push({ recipientId, encryptedAesKey });
saveShares();
res.json({ message: 'Document shared successfully' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ---------------------------------------------------------------------------
// Fallback — serve SPA
// ---------------------------------------------------------------------------
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
console.log(`🔒 Secure Cloud Docs server running at http://localhost:${PORT}`);
console.log(` Data stored in: ${DATA_DIR}`);
});