-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsession-service.ts
More file actions
333 lines (301 loc) · 9.71 KB
/
Copy pathsession-service.ts
File metadata and controls
333 lines (301 loc) · 9.71 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
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
/**
* @file session-service.ts
* Handles user session management including creation, validation, and cleanup.
* Implements sliding session expiration and session limiting per user.
*
* Features:
* - Configurable table and column names
* - Sliding session expiration
* - Session cleanup and limits
* - IP and user agent tracking
*
* @license Apache-2.0
*/
import type { Client } from "@libsql/client";
import {
type DbClientFactory,
createDbClient as defaultCreateDbClient,
} from "@private-landing/infrastructure";
import type {
AuthContext,
GetClientIpFn,
SessionConfig,
SessionState,
SessionTable,
SessionTableConfig,
TokenPayload,
} from "@private-landing/types";
import { deleteCookie } from "hono/cookie";
import { nanoid } from "nanoid";
import { defaultSessionConfig } from "../config";
import { getAuthCookieSettings } from "../utils";
import { defaultGetClientIp } from "../utils/get-client-ip";
/**
* Interface defining the session service API.
* Provides methods for session lifecycle management.
*/
export interface SessionService {
/**
* Creates new authenticated session.
* Manages session lifecycle by cleaning expired sessions and enforcing limits.
*
* @param userId - User to create session for
* @param ctx - Auth context with environment and request data
* @param sessionConfig - Optional session behavior configuration
* @returns Newly created session ID
*/
createSession(
userId: number,
ctx: AuthContext,
sessionConfig?: SessionConfig,
): Promise<string>;
/**
* Retrieves and validates current session.
* Implements sliding expiration by extending valid sessions.
*
* @param ctx - Auth context containing session information
* @param sessionConfig - Optional session behavior configuration
* @returns Session data if valid, null otherwise
*/
getSession(
ctx: AuthContext,
sessionConfig?: SessionConfig,
): Promise<SessionState | null>;
/**
* Ends user session and removes associated tokens.
* Expires session immediately and clears auth cookies.
*
* @param ctx - Auth context containing session to end
*/
endSession(ctx: AuthContext): Promise<void>;
/**
* Ends all active sessions for a user.
* Expires all sessions immediately and clears auth cookies.
*
* @param userId - User whose sessions should be ended
* @param ctx - Auth context for cookie clearing
*/
endAllSessionsForUser(userId: number, ctx: AuthContext): Promise<void>;
}
/**
* Configuration options for session service.
*/
export interface SessionServiceConfig extends SessionTableConfig {
/** Optional database client factory for dependency injection */
createDbClient?: DbClientFactory;
/** Optional function to extract client IP from request context */
getClientIp?: GetClientIpFn;
}
/**
* Default table and column names for session management.
* Can be overridden through SessionTableConfig.
*/
const DEFAULT_TABLE_CONFIG: Required<SessionTableConfig> = {
tableName: "session",
idColumn: "id",
userIdColumn: "user_id",
userAgentColumn: "user_agent",
ipAddressColumn: "ip_address",
expiresAtColumn: "expires_at",
createdAtColumn: "created_at",
};
/**
* Maps a database row (snake_case) to SessionState (camelCase).
* Provides type-safe conversion between database and application layers.
*
* @param row - Database row with snake_case column names
* @returns SessionState with camelCase property names
*/
function mapRowToSessionState(row: SessionTable): SessionState {
return {
id: row.id,
userId: row.user_id,
userAgent: row.user_agent,
ipAddress: row.ip_address,
expiresAt: row.expires_at,
createdAt: row.created_at,
};
}
/**
* Creates a configured session management service.
* Provides methods for creating, retrieving, and ending user sessions
* with support for custom table schemas.
*
* @param config - Configuration for session table schema and dependencies
* @returns Session management service with CRUD operations
*/
export function createSessionService(
config: SessionServiceConfig = {},
): SessionService {
const {
createDbClient: injectedCreateDbClient,
getClientIp: injectedGetClientIp,
...tableConfig
} = config;
const resolvedConfig = { ...DEFAULT_TABLE_CONFIG, ...tableConfig };
const createDbClient = injectedCreateDbClient ?? defaultCreateDbClient;
const getClientIp = injectedGetClientIp ?? defaultGetClientIp;
/**
* Removes expired sessions from the database.
* Uses database timestamp comparison for accurate cleanup.
*
* @param dbClient - Database client instance
* @returns Number of sessions removed
*/
async function cleanupExpiredSessions(dbClient: Client): Promise<number> {
const result = await dbClient.execute(
`DELETE FROM ${resolvedConfig.tableName}
WHERE ${resolvedConfig.expiresAtColumn} <= datetime('now')`,
);
return result.rowsAffected;
}
/**
* Enforces maximum concurrent sessions per user.
* Removes oldest sessions when limit is exceeded, keeping most recent ones.
*
* @param userId - User to enforce limits for
* @param dbClient - Database client instance
* @param maxSessions - Maximum allowed concurrent sessions
*/
async function enforceSessionLimit(
userId: number,
dbClient: Client,
maxSessions: number,
): Promise<void> {
await dbClient.execute({
sql: `WITH ranked_sessions AS (
SELECT ${resolvedConfig.idColumn},
ROW_NUMBER() OVER (
PARTITION BY ${resolvedConfig.userIdColumn}
ORDER BY ${resolvedConfig.createdAtColumn} DESC
) as rn
FROM ${resolvedConfig.tableName}
WHERE ${resolvedConfig.userIdColumn} = ?
AND ${resolvedConfig.expiresAtColumn} > datetime('now')
)
DELETE FROM ${resolvedConfig.tableName}
WHERE ${resolvedConfig.idColumn} IN (
SELECT ${resolvedConfig.idColumn} FROM ranked_sessions
WHERE rn > ?
)`,
args: [userId, maxSessions],
});
}
/**
* Extends session lifetime implementing sliding expiration.
* Only extends sessions that haven't already expired.
*
* @param sessionId - Session to extend
* @param dbClient - Database client instance
* @param duration - New duration in seconds
* @returns Whether session was successfully extended
*/
async function extendSession(
sessionId: string,
dbClient: Client,
duration: number,
): Promise<boolean> {
const result = await dbClient.execute({
sql: `UPDATE ${resolvedConfig.tableName}
SET ${resolvedConfig.expiresAtColumn} = datetime('now', '+' || ? || ' seconds')
WHERE ${resolvedConfig.idColumn} = ?
AND ${resolvedConfig.expiresAtColumn} > datetime('now')`,
args: [duration, sessionId],
});
return result.rowsAffected > 0;
}
return {
async createSession(
userId: number,
ctx: AuthContext,
sessionConfig: SessionConfig = defaultSessionConfig,
): Promise<string> {
const dbClient = createDbClient(ctx.env);
// Global expired-session cleanup (can be scoped per user if needed)
await cleanupExpiredSessions(dbClient);
const sessionId = nanoid();
const now = new Date();
const sessionData: SessionState = {
id: sessionId,
userId,
userAgent: ctx.req.header("user-agent") || "unknown",
ipAddress: getClientIp(ctx),
expiresAt: new Date(
now.getTime() + sessionConfig.sessionDuration * 1000,
).toISOString(),
createdAt: now.toISOString(),
};
await dbClient.execute({
sql: `INSERT INTO ${resolvedConfig.tableName} (
${resolvedConfig.idColumn},
${resolvedConfig.userIdColumn},
${resolvedConfig.userAgentColumn},
${resolvedConfig.ipAddressColumn},
${resolvedConfig.expiresAtColumn},
${resolvedConfig.createdAtColumn}
) VALUES (?, ?, ?, ?, ?, ?)`,
args: [
sessionData.id,
sessionData.userId,
sessionData.userAgent,
sessionData.ipAddress,
sessionData.expiresAt,
sessionData.createdAt,
],
});
// Enforce post-insert to avoid off-by-one behavior
await enforceSessionLimit(userId, dbClient, sessionConfig.maxSessions);
return sessionId;
},
async getSession(
ctx: AuthContext,
sessionConfig: SessionConfig = defaultSessionConfig,
): Promise<SessionState | null> {
const payload = ctx.get("jwtPayload") as TokenPayload;
const sessionId = payload?.sid;
if (!sessionId) return null;
const dbClient = createDbClient(ctx.env);
const extended = await extendSession(
sessionId,
dbClient,
sessionConfig.sessionDuration,
);
if (!extended) return null;
const result = await dbClient.execute({
sql: `SELECT * FROM ${resolvedConfig.tableName} WHERE ${resolvedConfig.idColumn} = ?`,
args: [sessionId],
});
if (result.rows.length === 0) return null;
return mapRowToSessionState(result.rows[0] as unknown as SessionTable);
},
async endSession(ctx: AuthContext): Promise<void> {
const payload = ctx.get("jwtPayload") as TokenPayload;
const sessionId = payload.sid;
if (!sessionId) return;
const dbClient = createDbClient(ctx.env);
await dbClient.execute({
sql: `UPDATE ${resolvedConfig.tableName}
SET ${resolvedConfig.expiresAtColumn} = datetime('now')
WHERE ${resolvedConfig.idColumn} = ?`,
args: [sessionId],
});
deleteCookie(ctx, "access_token", getAuthCookieSettings());
deleteCookie(ctx, "refresh_token", getAuthCookieSettings());
},
async endAllSessionsForUser(
userId: number,
ctx: AuthContext,
): Promise<void> {
const dbClient = createDbClient(ctx.env);
await dbClient.execute({
sql: `UPDATE ${resolvedConfig.tableName}
SET ${resolvedConfig.expiresAtColumn} = datetime('now')
WHERE ${resolvedConfig.userIdColumn} = ?
AND ${resolvedConfig.expiresAtColumn} > datetime('now')`,
args: [userId],
});
deleteCookie(ctx, "access_token", getAuthCookieSettings());
deleteCookie(ctx, "refresh_token", getAuthCookieSettings());
},
};
}