-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
299 lines (271 loc) · 9.58 KB
/
database.js
File metadata and controls
299 lines (271 loc) · 9.58 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
const sqlite = require("sqlite");
const sqlite3 = require("sqlite3");
const bcrypt = require("bcryptjs");
const crypto = require("crypto");
const { generateKeyPairSync } = require("crypto");
// Reusable function to derive key
async function deriveKey(password, salt) {
return new Promise((resolve, reject) => {
crypto.pbkdf2(password, salt, 100000, 32, "sha512", (err, derivedKey) => {
if (err) return reject(err);
resolve(derivedKey);
});
});
}
function encrypt(text, key, iv) {
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let encrypted = cipher.update(text, "utf8", "hex");
encrypted += cipher.final("hex");
return {
encryptedData: encrypted,
iv: iv.toString("hex"),
};
}
function decrypt(encrypted, ivHex, key) {
const iv = Buffer.from(ivHex, "hex");
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
let decrypted = decipher.update(encrypted, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
async function initializeDB() {
try {
const db = await sqlite.open({
filename: "./TokyoChat.sqlite",
driver: sqlite3.Database,
});
console.log("Connected to the SQLite database");
await db.run(
`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)`,
);
console.log("Users table checked");
await db.run(
`CREATE TABLE IF NOT EXISTS contacts (
user_id INTEGER PRIMARY KEY,
encrypted_contacts TEXT NOT NULL,
iv TEXT NOT NULL,
salt TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
);
console.log("Encrypted contacts table checked");
await db.run(
`CREATE TABLE IF NOT EXISTS user_keys (
user_id INTEGER PRIMARY KEY,
public_key TEXT NOT NULL,
encrypted_private_key TEXT NOT NULL,
private_iv TEXT NOT NULL,
private_salt TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
);
console.log("User keys table checked");
await db.run(
`CREATE TABLE IF NOT EXISTS rooms (
room_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL
)`,
);
console.log("Rooms table checked");
await db.run(`
CREATE TABLE IF NOT EXISTS private_chats (
id INTEGER PRIMARY KEY AUTOINCREMENT
)`);
console.log("private_chats table checked");
// join table that connects users from the users table to the private_chats table.
// Each row in this table represents one user participating in one chat.
await db.run(`
CREATE TABLE IF NOT EXISTS chat_participants (
chat_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (chat_id, user_id),
FOREIGN KEY (chat_id) REFERENCES private_chats(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`);
console.log("chat_participants table checked");
await db.run(`
CREATE TABLE IF NOT EXISTS private_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
sender_id INTEGER NOT NULL,
encrypted_message TEXT NOT NULL,
iv TEXT NOT NULL,
salt TEXT NOT NULL,
deleted_by TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (chat_id) REFERENCES private_chats(id) ON DELETE CASCADE,
FOREIGN KEY (sender_id) REFERENCES users(id) ON DELETE CASCADE
)`);
console.log("private_messages table checked");
const defaultRooms = ["General", "Random"];
for (const roomName of defaultRooms) {
const room = await db.get(`SELECT room_id FROM rooms WHERE name = ?`, [
roomName,
]);
if (!room) {
await db.run("INSERT INTO rooms (name) VALUES (?)", [roomName]);
console.log(`Default room '${roomName}' inserted.`);
}
}
const row = await db.get("SELECT COUNT(*) as count FROM users");
if (row.count === 0) {
const defaultUsername1 = "testuser";
const defaultPassword = "password";
const defaultUsername2 = "testuser2";
console.log(`No users found. Creating default users...`);
const hash = await bcrypt.hash(defaultPassword, 10);
const result1 = await db.run(
`INSERT INTO users (username, password) VALUES (?, ?)`,
[defaultUsername1, hash],
);
const userId1 = result1.lastID;
const result2 = await db.run(
`INSERT INTO users (username, password) VALUES (?, ?)`,
[defaultUsername2, hash],
);
const userId2 = result2.lastID;
console.log(
`Default users '${defaultUsername1}' (ID: ${userId1}) and '${defaultUsername2}' (ID: ${userId2}) created.`,
);
// key pairs for default users
const { publicKey: pub1, privateKey: priv1 } = generateKeyPairSync("ec", {
namedCurve: "prime256v1",
publicKeyEncoding: { type: "spki", format: "der" },
privateKeyEncoding: { type: "pkcs8", format: "der" },
});
const { publicKey: pub2, privateKey: priv2 } = generateKeyPairSync("ec", {
namedCurve: "prime256v1",
publicKeyEncoding: { type: "spki", format: "der" },
privateKeyEncoding: { type: "pkcs8", format: "der" },
});
// user 1 keys
const salt1 = crypto.randomBytes(16);
const key1 = await deriveKey(defaultPassword, salt1);
const privSalt1 = crypto.randomBytes(16);
const privIv1 = crypto.randomBytes(16);
const privKeyDer1 = await deriveKey(defaultPassword, privSalt1);
const encPriv1 = encrypt(priv1, privKeyDer1, privIv1);
await db.run(
`INSERT INTO user_keys (user_id, public_key, encrypted_private_key, private_iv, private_salt) VALUES (?, ?, ?, ?, ?)`,
[
userId1,
pub1.toString("hex"),
encPriv1.encryptedData,
encPriv1.iv,
privSalt1.toString("hex"),
],
);
// user 2 keys
const salt2 = crypto.randomBytes(16);
const key2 = await deriveKey(defaultPassword, salt2);
const privSalt2 = crypto.randomBytes(16);
const privIv2 = crypto.randomBytes(16);
const privKeyDer2 = await deriveKey(defaultPassword, privSalt2);
const encPriv2 = encrypt(priv2, privKeyDer2, privIv2);
await db.run(
`INSERT INTO user_keys (user_id, public_key, encrypted_private_key, private_iv, private_salt) VALUES (?, ?, ?, ?, ?)`,
[
userId2,
pub2.toString("hex"),
encPriv2.encryptedData,
encPriv2.iv,
privSalt2.toString("hex"),
],
);
// initial contacts without pubkeys
const contacts1 = [
{
contactUserID: userId2,
alias: "user2",
contactUsername: defaultUsername2,
},
];
const contacts2 = [
{
contactUserID: userId1,
alias: "user1",
contactUsername: defaultUsername1,
},
];
const iv1 = crypto.randomBytes(16);
const encrypted_contacts1 = encrypt(JSON.stringify(contacts1), key1, iv1);
await db.run(
`INSERT INTO contacts (user_id, encrypted_contacts, iv, salt) VALUES (?, ?, ?, ?)`,
[
userId1,
encrypted_contacts1.encryptedData,
encrypted_contacts1.iv,
salt1.toString("hex"),
],
);
const iv2 = crypto.randomBytes(16);
const encrypted_contacts2 = encrypt(JSON.stringify(contacts2), key2, iv2);
await db.run(
`INSERT INTO contacts (user_id, encrypted_contacts, iv, salt) VALUES (?, ?, ?, ?)`,
[
userId2,
encrypted_contacts2.encryptedData,
encrypted_contacts2.iv,
salt2.toString("hex"),
],
);
// update contacts to include public keys
const contacts1Updated = [
{
contactUserID: userId2,
alias: "user2",
contactUsername: defaultUsername2,
publicKey: pub2.toString("hex"),
},
];
const newIv1 = crypto.randomBytes(16);
const encContacts1Updated = encrypt(
JSON.stringify(contacts1Updated),
key1,
newIv1,
);
await db.run(
`UPDATE contacts
SET encrypted_contacts = ?, iv = ?
WHERE user_id = ?`,
[encContacts1Updated.encryptedData, encContacts1Updated.iv, userId1],
);
const contacts2Updated = [
{
contactUserID: userId1,
alias: "user1",
contactUsername: defaultUsername1,
publicKey: pub1.toString("hex"),
},
];
const newIv2 = crypto.randomBytes(16);
const encContacts2Updated = encrypt(
JSON.stringify(contacts2Updated),
key2,
newIv2,
);
await db.run(
`UPDATE contacts SET encrypted_contacts = ?, iv = ? WHERE user_id = ?`,
[encContacts2Updated.encryptedData, encContacts2Updated.iv, userId2],
);
console.log(
"Default contacts established for 'testuser' and 'testuser2'.",
);
}
return db;
} catch (err) {
console.error("Database initialization failed: ", err.message);
process.exit(1);
}
}
module.exports = {
dbPromise: initializeDB(),
encrypt,
decrypt,
deriveKey,
generateKeyPairSync,
};