-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js-backup-working-basic
More file actions
264 lines (236 loc) · 7.98 KB
/
Copy pathserver.js-backup-working-basic
File metadata and controls
264 lines (236 loc) · 7.98 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
255
256
257
258
259
260
261
262
263
264
const express = require("express");
const session = require("express-session");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const crypto = require("crypto");
require("dotenv").config();
const app = express();
app.use(express.urlencoded({ extended: true }));
// --- session ---
app.use(session({
secret: process.env.SESSION_SECRET || "dev_secret_change_me",
resave: false,
saveUninitialized: false
}));
// --- mongo ---
const mongoUri = process.env.MONGODB_URI;
if (!mongoUri) {
console.error("❌ MONGODB_URI is missing. Please set it in your .env file");
process.exit(1);
}
mongoose.connect(mongoUri, { dbName: process.env.MONGODB_DB || "pwmanager" })
.then(() => console.log("✅ MongoDB connected:", mongoUri))
.catch(err => {
console.error("❌ MongoDB connection error:", err.message);
process.exit(1);
});
// --- models ---
const User = mongoose.model("User", new mongoose.Schema({
email: { type: String, unique: true },
hash: String,
}));
const Entry = mongoose.model("Entry", new mongoose.Schema({
userId: mongoose.Types.ObjectId,
site: String,
link: String,
uname: String,
cipher: String, // base64(iv|tag|ciphertext)
}));
// --- crypto helpers ---
const KEY = crypto.createHash("sha256").update(process.env.VAULT_KEY || "dev_vault_key_change_me").digest();
function enc(text) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", KEY, iv);
const enc = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, enc]).toString("base64");
}
function dec(b64) {
const buf = Buffer.from(b64, "base64");
const iv = buf.subarray(0, 12), tag = buf.subarray(12, 28), data = buf.subarray(28);
const decipher = crypto.createDecipheriv("aes-256-gcm", KEY, iv);
decipher.setAuthTag(tag);
const dec = Buffer.concat([decipher.update(data), decipher.final()]);
return dec.toString("utf8");
}
// --- auth middleware ---
function authed(req, res, next) {
if (!req.session.uid) return res.redirect("/");
next();
}
// --- views ---
function page(body) {
return `<!doctype html><html><head><meta charset="utf-8"><title>Password Manager</title></head>
<body>
<h2 align="center">Password Manager</h2>
${body}
<p align="center"><small>Demo app. Don’t use in production without hardening.</small></p>
<script>
async function copyPw(id){
const r = await fetch('/pw/'+id);
if(!r.ok){ alert('Failed'); return;}
const t = await r.text();
await navigator.clipboard.writeText(t);
alert('Password copied.');
}
function togglePw(id){
const f = document.getElementById(id);
f.type = (f.type === 'password') ? 'text' : 'password';
}
</script>
</body></html>`;
}
const home = (msg = "") => page(`
${msg ? `<p align="center">${msg}</p>` : ""}
<!-- Login Form -->
<div id="loginForm">
<h3 align="center">Login</h3>
<form method="post" action="/login">
<table align="center" cellpadding="5">
<tr>
<td>Username:</td>
<td><input name="email" required></td>
</tr>
<tr>
<td>Password:</td>
<td>
<input id="loginPass" name="pass" type="password" required>
<button type="button" onclick="togglePw('loginPass')">Show</button>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button>Login</button>
<a href="javascript:void(0)" onclick="showRegister()">Register</a>
</td>
</tr>
</table>
</form>
</div>
<!-- Register Form (hidden by default) -->
<div id="registerForm" style="display:none;">
<h3 align="center">Register</h3>
<form method="post" action="/register">
<table align="center" cellpadding="5">
<tr>
<td>Username:</td>
<td><input name="email" required></td>
</tr>
<tr>
<td>Password:</td>
<td>
<input id="regPass" name="pass" type="password" required>
<button type="button" onclick="togglePw('regPass')">Show</button>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button>Register</button>
<a href="javascript:void(0)" onclick="showLogin()">Back to Login</a>
</td>
</tr>
</table>
</form>
</div>
<script>
function showRegister(){
document.getElementById("loginForm").style.display = "none";
document.getElementById("registerForm").style.display = "block";
}
function showLogin(){
document.getElementById("registerForm").style.display = "none";
document.getElementById("loginForm").style.display = "block";
}
</script>
`);
function dash(user, entries) {
const rows = entries.map(e => `<tr>
<td>${e.site || ""}</td>
<td><a href="${e.link || "#"}" target="_blank">${e.link || ""}</a></td>
<td>${e.uname || ""}</td>
<td>
<button type="button" onclick="copyPw('${e._id}')">Copy</button>
<a href="/del/${e._id}" onclick="return confirm('Delete?')">Delete</a>
</td>
</tr>`).join("");
return page(`
<p align="center">Logged in as <b>${user.email}</b> | <a href="/logout">Logout</a></p>
<h3 align="center">Add Entry</h3>
<form method="post" action="/add">
<table align="center" cellpadding="5">
<tr>
<td>Website:</td>
<td><input name="site" placeholder="Website name" required></td>
</tr>
<tr>
<td>Link:</td>
<td><input name="link" placeholder="https://..."></td>
</tr>
<tr>
<td>Username:</td>
<td><input name="uname" placeholder="Username" required></td>
</tr>
<tr>
<td>Password:</td>
<td>
<input id="addPw" name="pw" type="password" placeholder="Password" required>
<button type="button" onclick="togglePw('addPw')">Show</button>
</td>
</tr>
<tr>
<td colspan="2" align="center"><button>Add</button></td>
</tr>
</table>
</form>
<h3 align="center">Your Entries</h3>
<table border="1" cellpadding="6" cellspacing="0" align="center">
<tr><th>Website</th><th>Link</th><th>Username</th><th>Actions</th></tr>
${rows || `<tr><td colspan="4">No entries yet</td></tr>`}
</table>
`);
}
// --- routes ---
app.get("/", (req, res) => { if (req.session.uid) return res.redirect("/vault"); res.send(home()); });
app.post("/register", async (req, res) => {
try {
const { email, pass } = req.body;
if (!email || !pass) return res.send(home("Missing fields"));
const hash = await bcrypt.hash(pass, 12);
await User.create({ email, hash });
res.send(home("Registered! Please login."));
} catch (e) {
res.send(home("Registration failed (maybe user exists)."));
}
});
app.post("/login", async (req, res) => {
const { email, pass } = req.body;
const u = await User.findOne({ email });
if (!u || !(await bcrypt.compare(pass, u.hash))) return res.send(home("Invalid credentials"));
req.session.uid = u._id.toString();
res.redirect("/vault");
});
app.get("/logout", (req, res) => { req.session.destroy(() => res.redirect("/")); });
app.get("/vault", authed, async (req, res) => {
const u = await User.findById(req.session.uid);
const entries = await Entry.find({ userId: u._id }).sort({ _id: -1 }).lean();
res.send(dash(u, entries));
});
app.post("/add", authed, async (req, res) => {
const { site, link, uname, pw } = req.body;
if (!site || !uname || !pw) return res.redirect("/vault");
await Entry.create({ userId: req.session.uid, site, link, uname, cipher: enc(pw) });
res.redirect("/vault");
});
app.get("/del/:id", authed, async (req, res) => {
await Entry.deleteOne({ _id: req.params.id, userId: req.session.uid });
res.redirect("/vault");
});
app.get("/pw/:id", authed, async (req, res) => {
const e = await Entry.findOne({ _id: req.params.id, userId: req.session.uid }).lean();
if (!e) return res.status(404).send("Not found");
try {
res.type("text").send(dec(e.cipher));
} catch (err) { res.status(500).send("Decrypt error"); }
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`🚀 Server running: http://localhost:${PORT}`));