File size: 16,030 Bytes
5383ef0
82f6446
ad573c0
82f6446
5383ef0
82f6446
 
 
5383ef0
82f6446
 
 
 
 
 
 
 
5383ef0
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbd337a
 
 
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5383ef0
82f6446
 
 
5383ef0
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbd337a
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad573c0
 
82f6446
 
 
 
 
 
 
 
 
ad573c0
 
 
 
 
 
 
 
 
 
 
 
 
82f6446
ad573c0
 
82f6446
ad573c0
 
5383ef0
82f6446
 
5383ef0
82f6446
 
 
5383ef0
 
 
82f6446
5383ef0
82f6446
 
 
 
 
 
 
 
5383ef0
 
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5383ef0
 
 
82f6446
 
 
ad573c0
5383ef0
 
82f6446
 
 
 
 
 
 
ad573c0
5383ef0
0f84d64
 
 
 
 
82f6446
0f84d64
 
82f6446
 
 
 
 
 
 
 
0f84d64
 
 
 
 
82f6446
0f84d64
 
fec84f7
82f6446
fec84f7
 
 
82f6446
fec84f7
5383ef0
fec84f7
82f6446
 
 
 
 
 
 
 
 
5383ef0
 
fec84f7
82f6446
5383ef0
82f6446
5383ef0
82f6446
 
 
 
 
 
0f84d64
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5383ef0
 
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
5383ef0
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5383ef0
82f6446
 
 
 
 
 
 
 
 
5383ef0
 
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
5383ef0
82f6446
 
 
 
 
 
5383ef0
82f6446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5383ef0
82f6446
 
5383ef0
82f6446
5383ef0
82f6446
 
 
 
 
 
 
 
 
 
5383ef0
 
 
 
 
 
 
82f6446
 
 
 
 
 
 
 
 
5383ef0
 
82f6446
 
 
 
 
 
 
 
 
 
 
5383ef0
82f6446
 
 
5383ef0
82f6446
 
 
 
 
5383ef0
0f84d64
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import crypto from 'crypto';
import fs from 'fs/promises';
import path from 'path';
import { loadEncryptedJson, saveEncryptedJson } from './cryptoUtils.js';

// Local encrypted chat storage.
// Chats are stored per user in /data/chat/users/<userId>/sessions/<sessionId>.json (encrypted),
// with a lightweight encrypted index for fast listing.

let _SUPABASE_URL;
let _SUPABASE_ANON_KEY;
export function initStoreConfig(url, key) {
  _SUPABASE_URL = url;
  _SUPABASE_ANON_KEY = key;
}

const TEMP_TTL_MS = 24 * 60 * 60 * 1000;
const TEMP_INACTIVITY = 12 * 60 * 60 * 1000;
const TEMP_MSG_LIMIT = 10;

const DATA_ROOT = '/data/chat';
const USERS_ROOT = path.join(DATA_ROOT, 'users');
const SHARES_FILE = path.join(DATA_ROOT, 'shares', 'index.json');
const TEMP_STORE_FILE = path.join(DATA_ROOT, 'temp_sessions.json');

const userCache = new Map(); // userId -> UserState
const tempStore = new Map(); // tempId -> TempData
const devSessions = new Map(); // token -> DeviceSession
const userWriteLocks = new Map(); // userId -> Promise

const shareState = {
  loaded: false,
  index: {
    shares: {},
  },
};

function nowIso() {
  return new Date().toISOString();
}

function safeFileId(value, fallback = 'unknown') {
  const normalized = String(value || '').trim();
  if (!normalized) return fallback;
  return normalized.replace(/[^a-zA-Z0-9_.-]+/g, '_').slice(0, 160) || fallback;
}

function ensureSessionShape(raw, fallbackId = null) {
  const created = Number.isFinite(raw?.created) ? raw.created : Date.now();
  return {
    id: raw?.id || fallbackId || crypto.randomUUID(),
    name: String(raw?.name || 'New Chat'),
    created,
    history: Array.isArray(raw?.history) ? raw.history : [],
    model: raw?.model || null,
    updatedAt: typeof raw?.updatedAt === 'string' && raw.updatedAt.trim()
      ? raw.updatedAt
      : nowIso(),
  };
}

function buildSessionMeta(session, existingMeta = null) {
  const created = Number.isFinite(session?.created)
    ? session.created
    : (Number.isFinite(existingMeta?.created) ? existingMeta.created : Date.now());
  return {
    id: session.id,
    name: String(session.name || existingMeta?.name || 'New Chat'),
    created,
    model: session.model || existingMeta?.model || null,
    updatedAt: nowIso(),
  };
}

function ensureUserState(userId) {
  if (!userCache.has(userId)) {
    userCache.set(userId, {
      indexLoaded: false,
      sessionsMeta: new Map(),
      loadedSessions: new Map(),
      online: new Set(),
    });
  }
  return userCache.get(userId);
}

function userDir(userId) {
  return path.join(USERS_ROOT, safeFileId(userId));
}

function userIndexFile(userId) {
  return path.join(userDir(userId), 'index.json');
}

function userSessionFile(userId, sessionId) {
  return path.join(userDir(userId), 'sessions', `${safeFileId(sessionId)}.json`);
}

function userIndexAad(userId) {
  return `chat:user:${userId}:index`;
}

function userSessionAad(userId, sessionId) {
  return `chat:user:${userId}:session:${sessionId}`;
}

function toSerializableSessionMetaMap(map) {
  const sessions = {};
  for (const [id, meta] of map.entries()) {
    sessions[id] = {
      id,
      name: String(meta?.name || 'New Chat'),
      created: Number.isFinite(meta?.created) ? meta.created : Date.now(),
      model: meta?.model || null,
      updatedAt: meta?.updatedAt || nowIso(),
    };
  }
  return sessions;
}

async function ensureUserIndexLoaded(userId) {
  const state = ensureUserState(userId);
  if (state.indexLoaded) return state;

  const stored = await loadEncryptedJson(userIndexFile(userId), userIndexAad(userId));
  state.sessionsMeta.clear();

  const sessions = stored?.sessions || {};
  for (const [id, meta] of Object.entries(sessions)) {
    state.sessionsMeta.set(id, {
      id,
      name: String(meta?.name || 'New Chat'),
      created: Number.isFinite(meta?.created) ? meta.created : Date.now(),
      model: meta?.model || null,
      updatedAt: meta?.updatedAt || nowIso(),
    });
  }

  state.indexLoaded = true;
  return state;
}

async function saveUserIndex(userId) {
  const state = ensureUserState(userId);
  const payload = {
    sessions: toSerializableSessionMetaMap(state.sessionsMeta),
  };
  await saveEncryptedJson(userIndexFile(userId), payload, userIndexAad(userId));
}

async function loadUserSessionFromDisk(userId, sessionId) {
  const raw = await loadEncryptedJson(userSessionFile(userId, sessionId), userSessionAad(userId, sessionId));
  if (!raw) return null;
  return ensureSessionShape(raw, sessionId);
}

async function saveUserSessionToDisk(userId, session) {
  const shaped = ensureSessionShape(session);
  await saveEncryptedJson(userSessionFile(userId, shaped.id), shaped, userSessionAad(userId, shaped.id));
}

async function deleteUserSessionFromDisk(userId, sessionId) {
  await fs.rm(userSessionFile(userId, sessionId), { force: true }).catch(() => {});
}

async function withUserWriteLock(userId, fn) {
  const prior = userWriteLocks.get(userId) || Promise.resolve();
  const next = prior.catch(() => {}).then(fn);
  userWriteLocks.set(userId, next.finally(() => {
    if (userWriteLocks.get(userId) === next) userWriteLocks.delete(userId);
  }));
  return next;
}

function sessionForList(meta, loaded) {
  const source = loaded || meta;
  return {
    id: source.id,
    name: source.name || 'New Chat',
    created: Number.isFinite(source.created) ? source.created : Date.now(),
    history: loaded?.history || [],
    model: source.model || null,
    updatedAt: source.updatedAt || null,
  };
}

async function ensureShareIndexLoaded() {
  if (shareState.loaded) return;
  const stored = await loadEncryptedJson(SHARES_FILE, 'chat:shares:index');
  shareState.index = {
    shares: stored?.shares || {},
  };
  shareState.loaded = true;
}

async function saveShareIndex() {
  await saveEncryptedJson(SHARES_FILE, shareState.index, 'chat:shares:index');
}

async function loadTempStore() {
  const data = await loadEncryptedJson(TEMP_STORE_FILE, 'chat:temp:index');
  if (!data) return;
  for (const [id, d] of Object.entries(data)) {
    tempStore.set(id, {
      sessions: new Map(Object.entries(d.sessions || {})),
      msgCount: d.msgCount || 0,
      created: d.created || Date.now(),
      lastActive: d.lastActive || Date.now(),
    });
  }
}

async function saveTempStore() {
  const data = {};
  for (const [id, d] of tempStore) {
    data[id] = {
      sessions: Object.fromEntries(d.sessions),
      msgCount: d.msgCount,
      created: d.created,
      lastActive: d.lastActive,
    };
  }
  await saveEncryptedJson(TEMP_STORE_FILE, data, 'chat:temp:index');
}

loadTempStore().catch((err) => console.error('Failed to load temp store:', err));

setInterval(async () => {
  const now = Date.now();
  for (const [id, d] of tempStore) {
    if (now - d.created > TEMP_TTL_MS || now - d.lastActive > TEMP_INACTIVITY) {
      tempStore.delete(id);
    }
  }
  await saveTempStore().catch((err) => console.error('Failed to save temp store:', err));
}, 30 * 60 * 1000);

export const sessionStore = {
  // TEMP
  initTemp(t) {
    if (!tempStore.has(t)) {
      tempStore.set(t, {
        sessions: new Map(),
        msgCount: 0,
        created: Date.now(),
        lastActive: Date.now(),
      });
    }
    return tempStore.get(t);
  },
  tempCanSend(t) {
    const d = tempStore.get(t);
    return d ? d.msgCount < TEMP_MSG_LIMIT : false;
  },
  tempBump(t) {
    const d = tempStore.get(t);
    if (d) {
      d.msgCount++;
      d.lastActive = Date.now();
    }
  },
  getTempSessions(t) {
    return [...(tempStore.get(t)?.sessions.values() || [])];
  },
  getTempSession(t, id) {
    return tempStore.get(t)?.sessions.get(id) || null;
  },
  createTempSession(t) {
    const d = this.initTemp(t);
    const s = { id: crypto.randomUUID(), name: 'New Chat', created: Date.now(), history: [] };
    d.sessions.set(s.id, s);
    d.lastActive = Date.now();
    saveTempStore().catch((err) => console.error('Failed to save temp store:', err));
    return s;
  },
  updateTempSession(t, id, patch) {
    const d = tempStore.get(t);
    if (!d) return null;
    const s = d.sessions.get(id);
    if (!s) return null;
    Object.assign(s, patch);
    d.lastActive = Date.now();
    saveTempStore().catch((err) => console.error('Failed to save temp store:', err));
    return s;
  },
  restoreTempSession(t, session) {
    const d = this.initTemp(t);
    const restored = JSON.parse(JSON.stringify(session));
    d.sessions.set(restored.id, restored);
    d.lastActive = Date.now();
    saveTempStore().catch((err) => console.error('Failed to save temp store:', err));
    return restored;
  },
  deleteTempSession(t, id) {
    tempStore.get(t)?.sessions.delete(id);
    saveTempStore().catch((err) => console.error('Failed to save temp store:', err));
  },
  deleteTempAll(t) {
    tempStore.get(t)?.sessions.clear();
    saveTempStore().catch((err) => console.error('Failed to save temp store:', err));
  },
  deleteTempSessionEverywhere(id) {
    let changed = false;
    for (const temp of tempStore.values()) {
      if (temp.sessions.delete(id)) changed = true;
    }
    if (changed) saveTempStore().catch((err) => console.error('Failed to save temp store:', err));
    return changed;
  },

  async transferTempToUser(tempId, userId, _accessToken) {
    const d = tempStore.get(tempId);
    if (!d || !d.sessions.size) return;

    await ensureUserIndexLoaded(userId);

    for (const s of d.sessions.values()) {
      if (!s.history || s.history.length === 0) continue;
      if (ensureUserState(userId).sessionsMeta.has(s.id)) continue;
      const copy = ensureSessionShape(JSON.parse(JSON.stringify(s)));
      await withUserWriteLock(userId, async () => {
        const state = ensureUserState(userId);
        state.loadedSessions.set(copy.id, copy);
        state.sessionsMeta.set(copy.id, buildSessionMeta(copy));
        await saveUserSessionToDisk(userId, copy);
        await saveUserIndex(userId);
      });
    }
  },

  // USERS
  _ensureUser(uid) {
    return ensureUserState(uid);
  },

  async loadUserSessions(userId, _accessToken) {
    const state = await ensureUserIndexLoaded(userId);
    return [...state.sessionsMeta.values()]
      .sort((a, b) => new Date(b.updatedAt || 0).getTime() - new Date(a.updatedAt || 0).getTime())
      .map((meta) => sessionForList(meta, state.loadedSessions.get(meta.id)));
  },

  getUserSessions(uid) {
    const state = userCache.get(uid);
    if (!state) return [];
    return [...state.sessionsMeta.values()].map((meta) => sessionForList(meta, state.loadedSessions.get(meta.id)));
  },

  getUserSession(uid, id) {
    return userCache.get(uid)?.loadedSessions.get(id) || null;
  },

  async getUserSessionResolved(uid, id) {
    const state = await ensureUserIndexLoaded(uid);
    if (state.loadedSessions.has(id)) return state.loadedSessions.get(id);
    const meta = state.sessionsMeta.get(id);
    if (!meta) return null;

    const loaded = await loadUserSessionFromDisk(uid, id);
    if (!loaded) return null;

    const merged = ensureSessionShape({
      ...loaded,
      id,
      name: loaded.name || meta.name,
      created: Number.isFinite(loaded.created) ? loaded.created : meta.created,
      model: loaded.model || meta.model,
    }, id);

    state.loadedSessions.set(id, merged);
    return merged;
  },

  async createUserSession(userId, _accessToken) {
    const s = ensureSessionShape({
      id: crypto.randomUUID(),
      name: 'New Chat',
      created: Date.now(),
      history: [],
      model: null,
    });

    await ensureUserIndexLoaded(userId);
    await withUserWriteLock(userId, async () => {
      const state = ensureUserState(userId);
      state.loadedSessions.set(s.id, s);
      state.sessionsMeta.set(s.id, buildSessionMeta(s));
      await saveUserSessionToDisk(userId, s);
      await saveUserIndex(userId);
    });
    return s;
  },

  async restoreUserSession(userId, _accessToken, session) {
    const restored = ensureSessionShape(JSON.parse(JSON.stringify(session)));
    await ensureUserIndexLoaded(userId);

    await withUserWriteLock(userId, async () => {
      const state = ensureUserState(userId);
      state.loadedSessions.set(restored.id, restored);
      state.sessionsMeta.set(restored.id, buildSessionMeta(restored, state.sessionsMeta.get(restored.id)));
      await saveUserSessionToDisk(userId, restored);
      await saveUserIndex(userId);
    });
    return restored;
  },

  async updateUserSession(userId, _accessToken, sessionId, patch) {
    await ensureUserIndexLoaded(userId);
    const current = await this.getUserSessionResolved(userId, sessionId);
    if (!current) return null;

    Object.assign(current, patch || {});
    const updated = ensureSessionShape(current, sessionId);

    await withUserWriteLock(userId, async () => {
      const state = ensureUserState(userId);
      state.loadedSessions.set(sessionId, updated);
      state.sessionsMeta.set(sessionId, buildSessionMeta(updated, state.sessionsMeta.get(sessionId)));
      await saveUserSessionToDisk(userId, updated);
      await saveUserIndex(userId);
    });

    return updated;
  },

  async deleteUserSession(userId, _accessToken, id) {
    await ensureUserIndexLoaded(userId);
    await withUserWriteLock(userId, async () => {
      const state = ensureUserState(userId);
      state.loadedSessions.delete(id);
      state.sessionsMeta.delete(id);
      await deleteUserSessionFromDisk(userId, id);
      await saveUserIndex(userId);
    });
  },

  async deleteAllUserSessions(userId, _accessToken) {
    await ensureUserIndexLoaded(userId);
    const state = ensureUserState(userId);
    const ids = [...state.sessionsMeta.keys()];

    await withUserWriteLock(userId, async () => {
      for (const id of ids) {
        await deleteUserSessionFromDisk(userId, id);
      }
      state.loadedSessions.clear();
      state.sessionsMeta.clear();
      await saveUserIndex(userId);
    });

    return true;
  },

  markOnline(uid, ws) {
    ensureUserState(uid).online.add(ws);
  },

  markOffline(uid, ws) {
    userCache.get(uid)?.online.delete(ws);
  },

  // SHARE
  async createShareToken(userId, _accessToken, sessionId) {
    const s = await this.getUserSessionResolved(userId, sessionId);
    if (!s) return null;

    const token = crypto.randomBytes(24).toString('base64url');
    await ensureShareIndexLoaded();
    shareState.index.shares[token] = {
      token,
      owner_id: userId,
      session_snapshot: JSON.parse(JSON.stringify(s)),
      created_at: nowIso(),
    };
    await saveShareIndex();
    return token;
  },

  async resolveShareToken(token) {
    await ensureShareIndexLoaded();
    return shareState.index.shares[String(token || '')] || null;
  },

  async importSharedSession(userId, accessToken, token) {
    const shared = await this.resolveShareToken(token);
    if (!shared) return null;
    const snap = ensureSessionShape(shared.session_snapshot);
    const newSession = {
      ...snap,
      id: crypto.randomUUID(),
      name: `${snap.name} (shared)`,
      created: Date.now(),
    };
    await this.restoreUserSession(userId, accessToken, newSession);
    return newSession;
  },
};

export const deviceSessionStore = {
  create(userId, ip, userAgent) {
    const token = crypto.randomBytes(32).toString('hex');
    devSessions.set(token, {
      token,
      userId,
      ip,
      userAgent,
      createdAt: nowIso(),
      lastSeen: nowIso(),
      active: true,
    });
    return token;
  },
  getForUser(uid) {
    return [...devSessions.values()].filter((s) => s.userId === uid && s.active);
  },
  revoke(token) {
    const s = devSessions.get(token);
    if (s) {
      s.active = false;
      return s;
    }
    return null;
  },
  revokeAllExcept(uid, except) {
    for (const [t, s] of devSessions) {
      if (s.userId === uid && t !== except) s.active = false;
    }
  },
  validate(token) {
    const s = devSessions.get(token);
    if (!s || !s.active) return null;
    s.lastSeen = nowIso();
    return s;
  },
};