File size: 10,692 Bytes
9daebd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { randomBytes, createHash, scrypt, timingSafeEqual } = require("node:crypto");
const { promisify } = require("node:util");

const deriveKey = promisify(scrypt);
const COOKIE = "locmouth_session";
const SESSION_MS = 7 * 24 * 60 * 60 * 1000;
const SCRYPT_OPTIONS = { N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
const digest = (value) => createHash("sha256").update(value).digest("hex");

async function hashPassword(password, salt = randomBytes(16).toString("hex")) {
  const key = await deriveKey(password, salt, 64, SCRYPT_OPTIONS);
  return `${salt}:${key.toString("hex")}`;
}

async function verifyPassword(password, stored) {
  const [salt, expected] = stored.split(":");
  const actual = await hashPassword(password, salt);
  return timingSafeEqual(Buffer.from(actual.split(":")[1], "hex"), Buffer.from(expected, "hex"));
}

function initializeProfiles(db) {
  db.transaction(() => {
    db.exec(`
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL COLLATE NOCASE UNIQUE,
        password_hash TEXT NOT NULL,
        settings TEXT NOT NULL DEFAULT '{}',
        created_at TEXT NOT NULL DEFAULT (datetime('now'))
      );
      CREATE TABLE IF NOT EXISTS sessions (
        token_hash TEXT PRIMARY KEY,
        user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        expires_at INTEGER NOT NULL
      );
      CREATE INDEX IF NOT EXISTS idx_sessions_expiry ON sessions(expires_at);
    `);
    if (!db.prepare("PRAGMA table_info(fiches)").all().some((c) => c.name === "user_id")) {
      db.exec("ALTER TABLE fiches ADD COLUMN user_id INTEGER REFERENCES users(id)");
    }
    // Replace the legacy global URL uniqueness with uniqueness within each profile.
    if (!db.prepare("PRAGMA table_info(immo_sites)").all().some((c) => c.name === "user_id")) {
      db.exec(`
        ALTER TABLE immo_sites RENAME TO immo_sites_legacy;
        CREATE TABLE immo_sites (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          user_id INTEGER REFERENCES users(id),
          nom TEXT NOT NULL, url TEXT NOT NULL,
          favicon_url TEXT GENERATED ALWAYS AS (
            'https://www.google.com/s2/favicons?domain=' || url || '&sz=32'
          ) VIRTUAL,
          categorie TEXT, sort_order INTEGER DEFAULT 0, actif INTEGER DEFAULT 1,
          notes TEXT, created_at TEXT DEFAULT (datetime('now','localtime')),
          UNIQUE(user_id, url)
        );
        INSERT INTO immo_sites (id, nom, url, categorie, sort_order, actif, notes, created_at)
          SELECT id, nom, url, categorie, sort_order, actif, notes, created_at FROM immo_sites_legacy;
        DROP TABLE immo_sites_legacy;
      `);
    }
    db.exec(`
      CREATE INDEX IF NOT EXISTS idx_fiches_user ON fiches(user_id);
      CREATE INDEX IF NOT EXISTS idx_immo_sites_user ON immo_sites(user_id);
    `);
  })();
}

function installAuth(app, db) {
  initializeProfiles(db);
  const attempts = new Map();
  // A fixed fake hash makes unknown usernames take the same hashing path.
  const dummyHash = `${"0".repeat(32)}:${"0".repeat(128)}`;
  const secureCookie = process.env.COOKIE_SECURE === "true" ||
    (process.env.COOKIE_SECURE !== "false" && process.env.NODE_ENV === "production");
  const cookieOptions = { httpOnly: true, sameSite: "lax", secure: secureCookie, path: "/" };

  function readSession(req) {
    const token = (req.headers.cookie || "").split(";")
      .map((part) => part.trim()).find((part) => part.startsWith(`${COOKIE}=`))?.slice(COOKIE.length + 1);
    if (!token || !/^[a-f0-9]{64}$/.test(token)) return null;
    return db.prepare(`SELECT users.id, users.username, users.settings, sessions.token_hash
      FROM sessions JOIN users ON users.id = sessions.user_id
      WHERE token_hash = ? AND expires_at > ?`).get(digest(token), Date.now());
  }

  function startSession(req, res, userId) {
    const previous = readSession(req);
    if (previous) db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(previous.token_hash);
    db.prepare("DELETE FROM sessions WHERE expires_at <= ?").run(Date.now());
    const token = randomBytes(32).toString("hex");
    db.prepare("INSERT INTO sessions VALUES (?, ?, ?)").run(digest(token), userId, Date.now() + SESSION_MS);
    res.cookie(COOKIE, token, { ...cookieOptions, maxAge: SESSION_MS });
  }

  function publicUser(user) {
    return { id: user.id, username: user.username };
  }

  function validCredentials(username, password) {
    return typeof username === "string" && /^[a-zA-Z0-9_.-]{3,40}$/.test(username) &&
      typeof password === "string" && password.length >= 10 && password.length <= 256;
  }

  function throttle(req, res, next) {
    const now = Date.now();
    for (const [key, entry] of attempts) if (entry.until <= now) attempts.delete(key);
    const key = req.socket.remoteAddress;
    const entry = attempts.get(key) || { count: 0, until: now + 15 * 60 * 1000 };
    entry.count += 1;
    attempts.set(key, entry);
    if (entry.count > 30) {
      res.set("Retry-After", String(Math.ceil((entry.until - now) / 1000)));
      return res.status(429).json({ error: "Trop de tentatives. Réessayez dans quelques minutes." });
    }
    next();
  }

  app.use("/api", (req, res, next) => {
    res.set("Cache-Control", "no-store");
    // Custom header + absence of CORS permissions prevents cross-origin form/fetch mutations.
    if (!["GET", "HEAD", "OPTIONS"].includes(req.method) && req.get("X-LocMouth-Request") !== "1") {
      return res.status(403).json({ error: "Requête non autorisée" });
    }
    next();
  });

  app.get("/api/auth/session", (req, res) => {
    const user = readSession(req);
    res.json({ user: user ? publicUser(user) : null,
      setupRequired: !db.prepare("SELECT 1 FROM users LIMIT 1").get(),
      hasLegacyData: !!db.prepare("SELECT 1 FROM fiches WHERE user_id IS NULL UNION ALL SELECT 1 FROM immo_sites WHERE user_id IS NULL LIMIT 1").get() });
  });

  app.post("/api/auth/register", throttle, async (req, res) => {
    const username = typeof req.body?.username === "string" ? req.body.username.trim() : "";
    const { password } = req.body || {};
    if (!validCredentials(username, password)) {
      return res.status(400).json({ error: "Identifiant : 3 à 40 lettres, chiffres, points, tirets ou underscores. Mot de passe : 10 à 256 caractères." });
    }
    const passwordHash = await hashPassword(password);
    let id;
    try {
      id = db.transaction(() => {
        const firstProfile = !db.prepare("SELECT 1 FROM users LIMIT 1").get();
        const result = db.prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)").run(username, passwordHash);
        if (firstProfile) {
          db.prepare("UPDATE fiches SET user_id = ? WHERE user_id IS NULL").run(result.lastInsertRowid);
          db.prepare("UPDATE immo_sites SET user_id = ? WHERE user_id IS NULL").run(result.lastInsertRowid);
        }
        return result.lastInsertRowid;
      }).immediate();
    } catch (error) {
      if (error.code === "SQLITE_CONSTRAINT_UNIQUE") return res.status(409).json({ error: "Cet identifiant est déjà utilisé." });
      throw error;
    }
    startSession(req, res, id);
    res.status(201).json({ user: { id, username } });
  });

  app.post("/api/auth/login", throttle, async (req, res) => {
    const { username, password } = req.body || {};
    if (typeof username !== "string" || typeof password !== "string" || password.length > 256) {
      return res.status(400).json({ error: "Identifiant ou mot de passe invalide." });
    }
    const user = db.prepare("SELECT * FROM users WHERE username = ?").get(username.trim());
    const matches = await verifyPassword(password, user?.password_hash || dummyHash);
    if (!user || !matches) return res.status(401).json({ error: "Identifiant ou mot de passe incorrect." });
    startSession(req, res, user.id);
    res.json({ user: publicUser(user) });
  });

  function requireAuth(req, res, next) {
    const user = readSession(req);
    if (!user) return res.status(401).json({ error: "Veuillez vous connecter." });
    // An old tab must not write its data into a newly selected account.
    const expectedProfile = req.get("X-LocMouth-Profile");
    if (expectedProfile && expectedProfile !== String(user.id)) {
      res.set("X-LocMouth-Profile-Changed", "1");
      return res.status(409).json({ error: "Le profil connecté a changé. Rechargez la page." });
    }
    req.user = user;
    next();
  }
  app.use("/api", requireAuth);

  app.post("/api/auth/logout", (req, res) => {
    db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(req.user.token_hash);
    res.clearCookie(COOKIE, cookieOptions);
    res.json({ message: "Déconnexion effectuée" });
  });

  app.get("/api/profile/settings", (req, res) => res.json(JSON.parse(req.user.settings)));
  app.put("/api/profile/settings", (req, res) => {
    const settings = req.body;
    if (!settings || Array.isArray(settings) || typeof settings !== "object" || JSON.stringify(settings).length > 32768) {
      return res.status(400).json({ error: "Paramètres invalides ou trop volumineux." });
    }
    db.prepare("UPDATE users SET settings = ? WHERE id = ?").run(JSON.stringify(settings), req.user.id);
    res.json(settings);
  });

  app.put("/api/profile", throttle, async (req, res) => {
    const { currentPassword, password } = req.body || {};
    const username = typeof req.body?.username === "string" ? req.body.username.trim() : "";
    if (!validCredentials(username, password || currentPassword)) {
      return res.status(400).json({ error: "Identifiant invalide ou mot de passe trop court (10 caractères minimum)." });
    }
    const user = db.prepare("SELECT * FROM users WHERE id = ?").get(req.user.id);
    if (typeof currentPassword !== "string" || currentPassword.length > 256 || !await verifyPassword(currentPassword, user.password_hash)) {
      return res.status(403).json({ error: "Mot de passe actuel incorrect." });
    }
    const passwordHash = password ? await hashPassword(password) : user.password_hash;
    try {
      db.transaction(() => {
        db.prepare("UPDATE users SET username = ?, password_hash = ? WHERE id = ?").run(username, passwordHash, user.id);
        db.prepare("DELETE FROM sessions WHERE user_id = ?").run(user.id);
      })();
    } catch (error) {
      if (error.code === "SQLITE_CONSTRAINT_UNIQUE") return res.status(409).json({ error: "Cet identifiant est déjà utilisé." });
      throw error;
    }
    startSession(req, res, user.id);
    res.json({ user: { id: user.id, username } });
  });
  return { requireAuth };
}

module.exports = { installAuth };