@adaptive-js/extension-auth 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -3
  3. package/dist/api-adapter.d.ts +2 -0
  4. package/dist/api-adapter.js +8 -0
  5. package/dist/api-adapter.js.map +1 -0
  6. package/dist/client.d.ts +41 -0
  7. package/dist/client.js +128 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/cookies.d.ts +10 -0
  10. package/dist/cookies.js +107 -0
  11. package/dist/cookies.js.map +1 -0
  12. package/dist/errors.d.ts +6 -0
  13. package/dist/errors.js +11 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/external-adapter.d.ts +93 -0
  16. package/dist/external-adapter.js +235 -0
  17. package/dist/external-adapter.js.map +1 -0
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +8 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/intended-url.d.ts +18 -0
  22. package/dist/intended-url.js +55 -0
  23. package/dist/intended-url.js.map +1 -0
  24. package/dist/memory-adapter.d.ts +16 -0
  25. package/dist/memory-adapter.js +112 -0
  26. package/dist/memory-adapter.js.map +1 -0
  27. package/dist/rate-limit.d.ts +28 -0
  28. package/dist/rate-limit.js +104 -0
  29. package/dist/rate-limit.js.map +1 -0
  30. package/dist/server.d.ts +54 -0
  31. package/dist/server.js +745 -0
  32. package/dist/server.js.map +1 -0
  33. package/dist/types.d.ts +225 -0
  34. package/dist/types.js +2 -0
  35. package/dist/types.js.map +1 -0
  36. package/docs/01-getting-started.md +347 -0
  37. package/docs/02-server-actions.md +176 -0
  38. package/docs/03-protecting-pages.md +144 -0
  39. package/docs/04-session-lifecycle.md +169 -0
  40. package/docs/05-adapters.md +242 -0
  41. package/docs/06-client.md +126 -0
  42. package/docs/07-security-checklist.md +93 -0
  43. package/docs/08-integration.md +134 -0
  44. package/docs/09-troubleshooting.md +96 -0
  45. package/docs/README.md +17 -0
  46. package/package.json +72 -4
package/dist/server.js ADDED
@@ -0,0 +1,745 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { DEFAULT_AUTH_COOKIE_NAME, createBlankSessionCookie, createSessionCookie, getCookie, validateCookieOptions } from "./cookies.js";
3
+ import { AuthError } from "./errors.js";
4
+ import { buildLoginReturnUrl } from "./intended-url.js";
5
+ import { evaluateRateLimit, extractClientIp } from "./rate-limit.js";
6
+ const DEFAULT_SESSION_DURATION = 60 * 60 * 24 * 30;
7
+ const DEFAULT_ABSOLUTE_SESSION_DURATION = 60 * 60 * 24 * 90;
8
+ const DEFAULT_RENEW_BEFORE = 60 * 60 * 24 * 7;
9
+ const DEFAULT_CSRF_HEADER_NAME = "x-adaptive-csrf-token";
10
+ function defaultGenerateSessionId() {
11
+ return randomBytes(32).toString("base64url");
12
+ }
13
+ function defaultGenerateCsrfToken() {
14
+ return randomBytes(32).toString("base64url");
15
+ }
16
+ function toPublicSession(stored, user) {
17
+ const { csrfToken: _, binding: __, ...session } = stored;
18
+ return {
19
+ ...session,
20
+ user
21
+ };
22
+ }
23
+ function readHeader(request, name) {
24
+ if (typeof request === "string")
25
+ return null;
26
+ const headers = request instanceof Headers
27
+ ? request
28
+ : "headers" in request && request.headers
29
+ ? request.headers
30
+ : request;
31
+ if (headers instanceof Headers) {
32
+ return headers.get(name);
33
+ }
34
+ const record = headers;
35
+ const value = record[name] ?? record[name.toLowerCase()] ?? record[name.toUpperCase()];
36
+ return Array.isArray(value) ? value[0] ?? null : value ?? null;
37
+ }
38
+ function isSameSecret(expected, received) {
39
+ const expectedBuffer = Buffer.from(expected);
40
+ const receivedBuffer = Buffer.from(received);
41
+ return expectedBuffer.length === receivedBuffer.length && timingSafeEqual(expectedBuffer, receivedBuffer);
42
+ }
43
+ function normalizeOrigin(value) {
44
+ try {
45
+ return new URL(value).origin;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ function validateAllowedOrigins(origins) {
52
+ if (!Array.isArray(origins) || origins.length === 0) {
53
+ throw new AuthError("CSRF_CONFIGURATION_INVALID", "CSRF allowedOrigins must include at least one valid origin.", 500);
54
+ }
55
+ const normalized = new Set();
56
+ for (const origin of origins) {
57
+ const value = normalizeOrigin(origin);
58
+ if (!value) {
59
+ throw new AuthError("CSRF_CONFIGURATION_INVALID", `Invalid CSRF allowed origin: "${origin}".`, 500);
60
+ }
61
+ normalized.add(value);
62
+ }
63
+ if (normalized.size === 0) {
64
+ throw new AuthError("CSRF_CONFIGURATION_INVALID", "CSRF allowedOrigins must include at least one valid origin.", 500);
65
+ }
66
+ return normalized;
67
+ }
68
+ function normalizeAuthRequest(input) {
69
+ if (!input) {
70
+ return { headers: {} };
71
+ }
72
+ if (input instanceof Headers) {
73
+ return { headers: input };
74
+ }
75
+ if (typeof input === "object") {
76
+ if (input.event) {
77
+ return normalizeAuthRequest(input.event);
78
+ }
79
+ if (input.node?.req) {
80
+ return {
81
+ headers: input.node.req.headers ?? {},
82
+ url: input.node.req.url
83
+ };
84
+ }
85
+ if (input.req?.headers) {
86
+ return {
87
+ headers: input.req.headers,
88
+ url: input.req.url
89
+ };
90
+ }
91
+ if (input.request) {
92
+ return normalizeAuthRequest(input.request);
93
+ }
94
+ if (input.headers) {
95
+ return {
96
+ headers: input.headers,
97
+ url: input.url
98
+ };
99
+ }
100
+ }
101
+ return { headers: {} };
102
+ }
103
+ function extractCsrfFromFormData(formData) {
104
+ if (!formData || typeof formData.get !== "function")
105
+ return null;
106
+ return (formData.get("csrfToken") ??
107
+ formData.get("_csrf") ??
108
+ formData.get("x-adaptive-csrf-token") ??
109
+ null);
110
+ }
111
+ function extractCsrfFromArgs(args) {
112
+ for (const arg of args) {
113
+ if (arg && typeof arg === "object") {
114
+ if (typeof arg.get === "function") {
115
+ const fromForm = extractCsrfFromFormData(arg);
116
+ if (fromForm)
117
+ return fromForm;
118
+ }
119
+ if ("csrfToken" in arg && typeof arg.csrfToken === "string") {
120
+ return arg.csrfToken;
121
+ }
122
+ if ("_csrf" in arg && typeof arg._csrf === "string") {
123
+ return arg._csrf;
124
+ }
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+ function tryApplyFreshCookie(context, freshCookie) {
130
+ if (!context || !freshCookie)
131
+ return;
132
+ if (typeof context.appendSetCookie === "function") {
133
+ context.appendSetCookie(freshCookie.header);
134
+ }
135
+ if (context.event?.node?.res?.setHeader) {
136
+ const existing = context.event.node.res.getHeader("Set-Cookie");
137
+ if (!existing) {
138
+ context.event.node.res.setHeader("Set-Cookie", freshCookie.header);
139
+ }
140
+ else if (Array.isArray(existing)) {
141
+ context.event.node.res.setHeader("Set-Cookie", [...existing, freshCookie.header]);
142
+ }
143
+ else {
144
+ context.event.node.res.setHeader("Set-Cookie", [existing, freshCookie.header]);
145
+ }
146
+ }
147
+ else if (context.event?.res?.headers?.append) {
148
+ context.event.res.headers.append("set-cookie", freshCookie.header);
149
+ }
150
+ }
151
+ export function createAuth(options) {
152
+ if (!options.csrf || !options.csrf.allowedOrigins) {
153
+ throw new AuthError("CSRF_CONFIGURATION_INVALID", "CSRF configuration is required: csrf.allowedOrigins must be provided in createAuth().", 500);
154
+ }
155
+ const allowedOrigins = validateAllowedOrigins(options.csrf.allowedOrigins);
156
+ const sessionDuration = options.sessionDuration ?? DEFAULT_SESSION_DURATION;
157
+ const absoluteSessionDuration = options.absoluteSessionDuration ?? DEFAULT_ABSOLUTE_SESSION_DURATION;
158
+ const renewBefore = options.renewBefore ?? DEFAULT_RENEW_BEFORE;
159
+ const generateSessionId = options.generateSessionId ?? defaultGenerateSessionId;
160
+ const cookieOptions = {
161
+ ...options.cookie,
162
+ maxAge: options.cookie?.maxAge ?? sessionDuration
163
+ };
164
+ const csrfHeaderName = options.csrf.headerName ?? DEFAULT_CSRF_HEADER_NAME;
165
+ if (sessionDuration <= 0 || absoluteSessionDuration <= 0 || renewBefore < 0) {
166
+ throw new AuthError("AUTH_CONFIGURATION_INVALID", "[AdaptiveJS auth] Session durations must be positive and renewBefore cannot be negative.", 500);
167
+ }
168
+ const isProduction = process.env.NODE_ENV === "production";
169
+ validateCookieOptions(cookieOptions.name, cookieOptions, isProduction || Boolean(options.secureDefaults));
170
+ if (isProduction && !options.onAuditEvent) {
171
+ console.warn("[AdaptiveJS auth] Warning: onAuditEvent should be configured in production for security auditing.");
172
+ }
173
+ // Renewal concurrency management
174
+ const renewalInFlight = new Map();
175
+ const renewalGraceCache = new Map();
176
+ async function audit(type, details) {
177
+ if (!options.onAuditEvent) {
178
+ return;
179
+ }
180
+ try {
181
+ await options.onAuditEvent({ type, at: new Date(), ...details });
182
+ }
183
+ catch {
184
+ // Audit is best-effort. Failures must not break session lifecycle operations.
185
+ }
186
+ }
187
+ async function createSession(user, sessionOptions = {}, request) {
188
+ // Rate limit check
189
+ if (options.rateLimit?.createSession) {
190
+ const ip = extractClientIp(request);
191
+ const evalResult = await evaluateRateLimit(options.rateLimit.createSession, {
192
+ ip,
193
+ userId: user.id,
194
+ user,
195
+ request
196
+ });
197
+ if (!evalResult.allowed) {
198
+ await audit("session.rejected", {
199
+ userId: user.id,
200
+ reason: "rate-limit-exceeded"
201
+ });
202
+ throw new AuthError("RATE_LIMIT_EXCEEDED", `Too many session creation attempts. Please try again after ${evalResult.retryAfterSeconds} seconds.`, 429);
203
+ }
204
+ }
205
+ await options.beforeCreateSession?.({ user, request });
206
+ // Session binding extraction
207
+ let binding;
208
+ if (options.sessionBinding) {
209
+ binding = {};
210
+ if (options.sessionBinding.userAgent) {
211
+ binding.userAgent = readHeader(request ?? { headers: {} }, "user-agent") ?? undefined;
212
+ }
213
+ if (options.sessionBinding.ip) {
214
+ binding.ip = extractClientIp(request) ?? undefined;
215
+ }
216
+ if (options.sessionBinding.fingerprint) {
217
+ binding.fingerprint = readHeader(request ?? { headers: {} }, "x-client-fingerprint") ?? undefined;
218
+ }
219
+ }
220
+ const now = new Date();
221
+ const absoluteExpiresAt = sessionOptions.absoluteExpiresAt ?? new Date(now.getTime() + absoluteSessionDuration * 1000);
222
+ const requestedExpiry = sessionOptions.expiresAt ?? new Date(now.getTime() + sessionDuration * 1000);
223
+ const stored = {
224
+ id: generateSessionId(),
225
+ userId: user.id,
226
+ data: (sessionOptions.data ?? {}),
227
+ createdAt: now,
228
+ expiresAt: new Date(Math.min(requestedExpiry.getTime(), absoluteExpiresAt.getTime())),
229
+ absoluteExpiresAt,
230
+ csrfToken: defaultGenerateCsrfToken(),
231
+ binding: sessionOptions.binding ?? binding
232
+ };
233
+ if (typeof options.adapter.setUser === "function") {
234
+ await options.adapter.setUser(user);
235
+ }
236
+ await options.adapter.createSession(stored);
237
+ await audit("session.created", { sessionId: stored.id, userId: stored.userId });
238
+ return {
239
+ session: toPublicSession(stored, user),
240
+ cookie: createSessionCookie(stored.id, {
241
+ ...cookieOptions,
242
+ maxAge: Math.max(0, Math.floor((stored.expiresAt.getTime() - now.getTime()) / 1000))
243
+ })
244
+ };
245
+ }
246
+ async function readSession(request) {
247
+ const cookieName = cookieOptions.name ?? DEFAULT_AUTH_COOKIE_NAME;
248
+ const sessionId = getCookie(request, cookieName);
249
+ if (!sessionId) {
250
+ return { session: null };
251
+ }
252
+ // 1. Check grace cache for recently rotated sessions
253
+ const grace = renewalGraceCache.get(sessionId);
254
+ if (grace) {
255
+ if (Date.now() < grace.expiresAtMs) {
256
+ return {
257
+ session: toPublicSession(grace.stored, grace.user),
258
+ freshCookie: grace.freshCookie
259
+ };
260
+ }
261
+ renewalGraceCache.delete(sessionId);
262
+ }
263
+ // 2. Join in-flight renewal if this session is currently being processed
264
+ const inFlight = renewalInFlight.get(sessionId);
265
+ if (inFlight) {
266
+ return await inFlight;
267
+ }
268
+ const inFlightPromise = (async () => {
269
+ const stored = await options.adapter.getSession(sessionId);
270
+ if (!stored) {
271
+ // Check grace cache once more in case it was rotated concurrently
272
+ const raceGrace = renewalGraceCache.get(sessionId);
273
+ if (raceGrace && Date.now() < raceGrace.expiresAtMs) {
274
+ return {
275
+ session: toPublicSession(raceGrace.stored, raceGrace.user),
276
+ freshCookie: raceGrace.freshCookie
277
+ };
278
+ }
279
+ await audit("session.rejected", { reason: "session-not-found" });
280
+ return {
281
+ session: null,
282
+ freshCookie: createBlankSessionCookie(cookieOptions)
283
+ };
284
+ }
285
+ const now = Date.now();
286
+ if (stored.expiresAt.getTime() <= now || stored.absoluteExpiresAt.getTime() <= now) {
287
+ await options.adapter.deleteSession(stored.id);
288
+ await audit("session.expired", { sessionId: stored.id, userId: stored.userId });
289
+ return {
290
+ session: null,
291
+ freshCookie: createBlankSessionCookie(cookieOptions)
292
+ };
293
+ }
294
+ const user = await options.adapter.getUser(stored.userId);
295
+ if (!user) {
296
+ await options.adapter.deleteSession(stored.id);
297
+ await audit("session.rejected", { sessionId: stored.id, userId: stored.userId, reason: "user-not-found" });
298
+ throw new AuthError("SESSION_USER_NOT_FOUND", `The user "${stored.userId}" associated with this session no longer exists.`, 401);
299
+ }
300
+ // Session binding validation
301
+ if (options.sessionBinding && stored.binding) {
302
+ let mismatchReason = null;
303
+ if (options.sessionBinding.userAgent && stored.binding.userAgent) {
304
+ const currentUa = readHeader(request, "user-agent");
305
+ if (currentUa && currentUa !== stored.binding.userAgent) {
306
+ mismatchReason = "session-binding-user-agent-mismatch";
307
+ }
308
+ }
309
+ if (!mismatchReason && options.sessionBinding.ip && stored.binding.ip) {
310
+ const currentIp = extractClientIp(request);
311
+ if (currentIp && currentIp !== stored.binding.ip) {
312
+ mismatchReason = "session-binding-ip-mismatch";
313
+ }
314
+ }
315
+ if (!mismatchReason && options.sessionBinding.fingerprint && stored.binding.fingerprint) {
316
+ const currentFp = readHeader(request, "x-client-fingerprint");
317
+ if (currentFp && currentFp !== stored.binding.fingerprint) {
318
+ mismatchReason = "session-binding-fingerprint-mismatch";
319
+ }
320
+ }
321
+ if (mismatchReason) {
322
+ await options.adapter.deleteSession(stored.id);
323
+ await audit("session.rejected", {
324
+ sessionId: stored.id,
325
+ userId: stored.userId,
326
+ reason: mismatchReason
327
+ });
328
+ return {
329
+ session: null,
330
+ freshCookie: createBlankSessionCookie(cookieOptions)
331
+ };
332
+ }
333
+ }
334
+ const remainingSeconds = Math.floor((stored.expiresAt.getTime() - now) / 1000);
335
+ if (remainingSeconds <= renewBefore) {
336
+ const renewed = {
337
+ ...stored,
338
+ id: generateSessionId(),
339
+ expiresAt: new Date(Math.min(now + sessionDuration * 1000, stored.absoluteExpiresAt.getTime()))
340
+ };
341
+ await options.adapter.createSession(renewed);
342
+ await options.adapter.deleteSession(stored.id);
343
+ await audit("session.renewed", { sessionId: renewed.id, userId: renewed.userId });
344
+ const freshCookie = createSessionCookie(renewed.id, {
345
+ ...cookieOptions,
346
+ maxAge: Math.max(0, Math.floor((renewed.expiresAt.getTime() - now) / 1000))
347
+ });
348
+ // 15 seconds grace period for parallel in-flight requests
349
+ renewalGraceCache.set(stored.id, {
350
+ stored: renewed,
351
+ freshCookie,
352
+ user,
353
+ expiresAtMs: Date.now() + 15_000
354
+ });
355
+ return {
356
+ session: toPublicSession(renewed, user),
357
+ freshCookie
358
+ };
359
+ }
360
+ return {
361
+ session: toPublicSession(stored, user),
362
+ freshCookie: undefined
363
+ };
364
+ })();
365
+ renewalInFlight.set(sessionId, inFlightPromise);
366
+ try {
367
+ return await inFlightPromise;
368
+ }
369
+ finally {
370
+ renewalInFlight.delete(sessionId);
371
+ }
372
+ }
373
+ async function requireSession(request) {
374
+ const result = await readSession(request);
375
+ if (!result.session) {
376
+ throw new AuthError("AUTHENTICATION_REQUIRED", "An authenticated session is required.", 401);
377
+ }
378
+ return {
379
+ session: result.session,
380
+ freshCookie: result.freshCookie
381
+ };
382
+ }
383
+ async function invalidateSession(sessionId) {
384
+ const stored = await options.adapter.getSession(sessionId);
385
+ await options.adapter.deleteSession(sessionId);
386
+ renewalGraceCache.delete(sessionId);
387
+ await audit("session.invalidated", { sessionId, userId: stored?.userId });
388
+ return createBlankSessionCookie(cookieOptions);
389
+ }
390
+ async function invalidateRequestSession(request) {
391
+ const cookieName = cookieOptions.name ?? DEFAULT_AUTH_COOKIE_NAME;
392
+ const sessionId = getCookie(request, cookieName);
393
+ if (sessionId) {
394
+ const stored = await options.adapter.getSession(sessionId);
395
+ await options.adapter.deleteSession(sessionId);
396
+ renewalGraceCache.delete(sessionId);
397
+ await audit("session.invalidated", { sessionId, userId: stored?.userId });
398
+ }
399
+ return createBlankSessionCookie(cookieOptions);
400
+ }
401
+ async function invalidateUserSessions(userId) {
402
+ if (!options.adapter.deleteUserSessions) {
403
+ throw new Error("[AdaptiveJS auth] The configured adapter does not implement deleteUserSessions().");
404
+ }
405
+ await options.adapter.deleteUserSessions(userId);
406
+ await audit("session.invalidated", { userId, reason: "user-sessions-invalidated" });
407
+ }
408
+ async function invalidateUserSessionsExcept(userId, currentSessionId) {
409
+ if (!options.adapter.deleteUserSessionsExcept) {
410
+ throw new Error("[AdaptiveJS auth] The configured adapter does not implement deleteUserSessionsExcept().");
411
+ }
412
+ await options.adapter.deleteUserSessionsExcept(userId, currentSessionId);
413
+ await audit("session.invalidated", {
414
+ userId,
415
+ sessionId: currentSessionId,
416
+ reason: "other-user-sessions-invalidated"
417
+ });
418
+ }
419
+ async function listUserSessions(userId) {
420
+ if (options.adapter.listUserSessions) {
421
+ return options.adapter.listUserSessions(userId);
422
+ }
423
+ throw new Error("[AdaptiveJS auth] The configured adapter does not implement listUserSessions().");
424
+ }
425
+ async function getCsrfToken(session) {
426
+ const stored = await options.adapter.getSession(session.id);
427
+ if (!stored || stored.expiresAt.getTime() <= Date.now() || stored.absoluteExpiresAt.getTime() <= Date.now()) {
428
+ throw new AuthError("AUTHENTICATION_REQUIRED", "An authenticated session is required.", 401);
429
+ }
430
+ return stored.csrfToken;
431
+ }
432
+ async function requireCsrf(request, session, submittedToken) {
433
+ if (!session) {
434
+ throw new AuthError("AUTHENTICATION_REQUIRED", "An authenticated session is required.", 401);
435
+ }
436
+ const origin = readHeader(request, "origin");
437
+ if (!origin || !allowedOrigins.has(normalizeOrigin(origin) ?? "")) {
438
+ await audit("csrf.rejected", {
439
+ sessionId: session.id,
440
+ userId: session.userId,
441
+ reason: origin ? "origin" : "origin-missing"
442
+ });
443
+ throw new AuthError("CSRF_ORIGIN_INVALID", origin
444
+ ? "The request origin is not allowed."
445
+ : "The request must include a valid Origin header.", 403);
446
+ }
447
+ const stored = await options.adapter.getSession(session.id);
448
+ const token = submittedToken ?? readHeader(request, csrfHeaderName);
449
+ if (!stored || !token || !isSameSecret(stored.csrfToken, token)) {
450
+ await audit("csrf.rejected", { sessionId: session.id, userId: session.userId, reason: "token" });
451
+ throw new AuthError("CSRF_TOKEN_INVALID", "The CSRF token is invalid.", 403);
452
+ }
453
+ }
454
+ // Risk Event Methods
455
+ async function passwordChanged(userId) {
456
+ await invalidateUserSessions(userId);
457
+ await audit("session.invalidated", { userId, reason: "password-changed" });
458
+ try {
459
+ await options.onPasswordChanged?.(userId);
460
+ }
461
+ catch {
462
+ // Best-effort
463
+ }
464
+ }
465
+ async function roleElevated(userId) {
466
+ await invalidateUserSessions(userId);
467
+ await audit("session.invalidated", { userId, reason: "role-elevated" });
468
+ try {
469
+ await options.onRoleChanged?.(userId);
470
+ }
471
+ catch {
472
+ // Best-effort
473
+ }
474
+ }
475
+ async function forceReauth(userId, reason = "force-reauth") {
476
+ await invalidateUserSessions(userId);
477
+ await audit("session.invalidated", { userId, reason });
478
+ try {
479
+ await options.onSuspiciousActivity?.(userId, reason);
480
+ }
481
+ catch {
482
+ // Best-effort
483
+ }
484
+ }
485
+ async function mfaEnabled(userId) {
486
+ await invalidateUserSessions(userId);
487
+ await audit("session.invalidated", { userId, reason: "mfa-enabled" });
488
+ try {
489
+ await options.onMfaEnabled?.(userId);
490
+ }
491
+ catch {
492
+ // Best-effort
493
+ }
494
+ }
495
+ // Session Data Updates
496
+ async function updateSessionData(sessionId, dataOrUpdater) {
497
+ const stored = await options.adapter.getSession(sessionId);
498
+ if (!stored) {
499
+ throw new AuthError("AUTHENTICATION_REQUIRED", "Session not found.", 401);
500
+ }
501
+ const nextData = typeof dataOrUpdater === "function"
502
+ ? dataOrUpdater(stored.data)
503
+ : dataOrUpdater;
504
+ const updated = {
505
+ ...stored,
506
+ data: { ...stored.data, ...nextData }
507
+ };
508
+ await options.adapter.updateSession(updated);
509
+ }
510
+ // Request wrappers & high-level helpers
511
+ async function withSession(request, handler) {
512
+ const { session, freshCookie } = await requireSession(request);
513
+ const result = await handler({ session, freshCookie });
514
+ if (freshCookie) {
515
+ if (typeof request === "object" &&
516
+ request !== null &&
517
+ "appendSetCookie" in request &&
518
+ typeof request.appendSetCookie === "function") {
519
+ request.appendSetCookie(freshCookie.header);
520
+ }
521
+ if (typeof Response !== "undefined" && result instanceof Response) {
522
+ result.headers.append("Set-Cookie", freshCookie.header);
523
+ }
524
+ }
525
+ return result;
526
+ }
527
+ async function login(userOrInput, request, sessionOptions) {
528
+ if (userOrInput && typeof userOrInput === "object" && "id" in userOrInput && !("password" in userOrInput) && typeof userOrInput.id === "string") {
529
+ const res = await createSession(userOrInput, sessionOptions, request);
530
+ return { ...res, user: userOrInput };
531
+ }
532
+ const adapterLoginFn = options.adapter.login ?? options.adapter.request;
533
+ if (typeof adapterLoginFn === "function") {
534
+ const result = await adapterLoginFn.call(options.adapter, userOrInput);
535
+ const user = result.user ?? result;
536
+ const token = result.token;
537
+ const mergedOptions = token
538
+ ? { ...sessionOptions, data: { ...(sessionOptions?.data ?? {}), authToken: token } }
539
+ : sessionOptions;
540
+ const res = await createSession(user, mergedOptions, request);
541
+ return {
542
+ ...res,
543
+ user,
544
+ token
545
+ };
546
+ }
547
+ throw new AuthError("AUTHENTICATION_REQUIRED", "[AdaptiveJS auth] The configured adapter does not support credentials login. Pass an AuthUser directly or use an adapter with .login() / .request() support.", 400);
548
+ }
549
+ async function logout(request) {
550
+ if (typeof options.adapter.logout === "function") {
551
+ try {
552
+ await options.adapter.logout();
553
+ }
554
+ catch {
555
+ // best-effort
556
+ }
557
+ }
558
+ const cookie = request
559
+ ? await invalidateRequestSession(request)
560
+ : createBlankSessionCookie(cookieOptions);
561
+ return { cookie };
562
+ }
563
+ async function logoutEverywhere(userId) {
564
+ await invalidateUserSessions(userId);
565
+ }
566
+ // Protect page helpers
567
+ function handleUnauthenticated(context, protection) {
568
+ if (typeof protection.onUnauthenticated === "function") {
569
+ return protection.onUnauthenticated(context);
570
+ }
571
+ if (protection.onUnauthenticated === "redirect") {
572
+ const currentUrl = context.request?.url;
573
+ const returnTo = protection.returnTo ? currentUrl : undefined;
574
+ const location = buildLoginReturnUrl(protection.redirectTo ?? "/login", returnTo);
575
+ return { __type: "redirect", location, status: 302 };
576
+ }
577
+ if (protection.onUnauthenticated === "401") {
578
+ return { __type: "error", status: 401 };
579
+ }
580
+ return { __type: "not-found" };
581
+ }
582
+ function handleForbidden(context, protection) {
583
+ if (typeof protection.onForbidden === "function") {
584
+ return protection.onForbidden(context);
585
+ }
586
+ if (protection.onForbidden === "403") {
587
+ return { __type: "error", status: 403 };
588
+ }
589
+ return { __type: "not-found" };
590
+ }
591
+ function protectPage(page, protection = {}) {
592
+ return async (context) => {
593
+ let result;
594
+ try {
595
+ result = await readSession(context?.request ?? { headers: {} });
596
+ }
597
+ catch (error) {
598
+ if (error instanceof AuthError) {
599
+ return handleUnauthenticated(context, protection);
600
+ }
601
+ throw error;
602
+ }
603
+ if (!result.session) {
604
+ return handleUnauthenticated(context, protection);
605
+ }
606
+ if (result.freshCookie) {
607
+ context?.appendSetCookie?.(result.freshCookie.header);
608
+ }
609
+ if (protection.roles?.some((role) => !hasRole(result.session, role))) {
610
+ await audit("session.rejected", {
611
+ sessionId: result.session.id,
612
+ userId: result.session.userId,
613
+ reason: "route-role"
614
+ });
615
+ return handleForbidden(context, protection);
616
+ }
617
+ return page({ ...context, session: result.session });
618
+ };
619
+ }
620
+ // Server Action helper
621
+ function action(optionsOrHandler, maybeHandler) {
622
+ const actionOptions = typeof optionsOrHandler === "function" ? {} : optionsOrHandler;
623
+ const handler = typeof optionsOrHandler === "function" ? optionsOrHandler : maybeHandler;
624
+ return async (...args) => {
625
+ const lastArg = args[args.length - 1];
626
+ const isContextArg = lastArg &&
627
+ typeof lastArg === "object" &&
628
+ ("event" in lastArg || "request" in lastArg || "node" in lastArg);
629
+ const context = isContextArg ? lastArg : {};
630
+ const actionArgs = isContextArg ? args.slice(0, -1) : args;
631
+ const request = normalizeAuthRequest(context?.request ?? context?.event ?? (isContextArg ? undefined : lastArg) ?? actionArgs[0]);
632
+ let formData;
633
+ for (const arg of actionArgs) {
634
+ if (arg && typeof arg === "object" && typeof arg.entries === "function") {
635
+ formData = arg;
636
+ break;
637
+ }
638
+ }
639
+ let submittedToken = null;
640
+ if (formData) {
641
+ submittedToken = extractCsrfFromFormData(formData);
642
+ }
643
+ if (!submittedToken) {
644
+ submittedToken = extractCsrfFromArgs(actionArgs);
645
+ }
646
+ // 1. Require session
647
+ const { session, freshCookie } = await requireSession(request);
648
+ // 2. Require role if specified
649
+ if (actionOptions.roles) {
650
+ for (const role of actionOptions.roles) {
651
+ requireRole(session, role);
652
+ }
653
+ }
654
+ // 3. Require CSRF
655
+ await requireCsrf(request, session, submittedToken);
656
+ // 4. Attach freshCookie if present
657
+ if (freshCookie) {
658
+ tryApplyFreshCookie(context, freshCookie);
659
+ }
660
+ // 5. Execute user handler
661
+ return handler({
662
+ session,
663
+ freshCookie,
664
+ formData,
665
+ request,
666
+ args: actionArgs,
667
+ event: context?.event,
668
+ adapter: options.adapter
669
+ });
670
+ };
671
+ }
672
+ function protectAction(actionFn, protection = {}) {
673
+ return async (...args) => {
674
+ const lastArg = args[args.length - 1];
675
+ const request = normalizeAuthRequest(lastArg);
676
+ const { session } = await requireSession(request);
677
+ let formData;
678
+ for (const arg of args) {
679
+ if (arg && typeof arg === "object" && typeof arg.entries === "function") {
680
+ formData = arg;
681
+ break;
682
+ }
683
+ }
684
+ const submittedToken = formData
685
+ ? extractCsrfFromFormData(formData) ?? extractCsrfFromArgs(args.slice(0, -1))
686
+ : extractCsrfFromArgs(args.slice(0, -1));
687
+ if (protection.roles) {
688
+ for (const role of protection.roles) {
689
+ requireRole(session, role);
690
+ }
691
+ }
692
+ await requireCsrf(request, session, submittedToken);
693
+ return actionFn(...args);
694
+ };
695
+ }
696
+ function protectRoute(handler, protection = {}) {
697
+ return protectPage(handler, protection);
698
+ }
699
+ function hasRole(session, role) {
700
+ return session?.user.roles?.includes(role) ?? false;
701
+ }
702
+ function requireRole(session, role) {
703
+ if (!session) {
704
+ throw new AuthError("AUTHENTICATION_REQUIRED", "An authenticated session is required.", 401);
705
+ }
706
+ if (!hasRole(session, role)) {
707
+ throw new AuthError("AUTHORIZATION_FAILED", `The authenticated user does not have the required "${role}" role.`, 403);
708
+ }
709
+ return session;
710
+ }
711
+ return {
712
+ createSession,
713
+ readSession,
714
+ requireSession,
715
+ invalidateSession,
716
+ invalidateRequestSession,
717
+ invalidateUserSessions,
718
+ invalidateUserSessionsExcept,
719
+ listUserSessions,
720
+ getCsrfToken,
721
+ requireCsrf,
722
+ passwordChanged,
723
+ roleElevated,
724
+ forceReauth,
725
+ mfaEnabled,
726
+ updateSessionData,
727
+ withSession,
728
+ login,
729
+ logout,
730
+ logoutEverywhere,
731
+ protectPage,
732
+ protectAction,
733
+ protectRoute,
734
+ action,
735
+ hasRole,
736
+ requireRole,
737
+ adapter: options.adapter,
738
+ cookie: {
739
+ create: (sessionId) => createSessionCookie(sessionId, cookieOptions),
740
+ blank: () => createBlankSessionCookie(cookieOptions)
741
+ }
742
+ };
743
+ }
744
+ export { buildLoginReturnUrl, readReturnToFromSearchParams, sanitizeReturnTo } from "./intended-url.js";
745
+ //# sourceMappingURL=server.js.map