@devmoods/express-extras 0.52.0 → 0.52.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.
@@ -95,17 +95,18 @@ export function extractAccessTokenFromRequest(req) {
95
95
  * If the provided token is `null` the cookie will be cleared.
96
96
  */
97
97
  export function setAccessTokenCookie(res, token) {
98
+ const sameSite = (config.value.AUTH_COOKIE_SAME_SITE || 'strict');
98
99
  if (token == null) {
99
100
  res.cookie(ACCESS_TOKEN_COOKIE_NAME, v4(), {
100
101
  expires: new Date(1970, 0, 1),
101
- sameSite: 'strict',
102
+ sameSite,
102
103
  secure: process.env.NODE_ENV === 'production',
103
104
  });
104
105
  }
105
106
  else {
106
107
  res.cookie(ACCESS_TOKEN_COOKIE_NAME, token, {
107
108
  httpOnly: true,
108
- sameSite: 'strict',
109
+ sameSite,
109
110
  secure: process.env.NODE_ENV === 'production',
110
111
  });
111
112
  }
package/dist/auth.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type RequestHandler, Router } from 'express';
1
+ import { type RequestHandler, type Response, type Request, Router } from 'express';
2
2
  import { TokenStorage, type AnyUser, type AuthMiddlewareOptions, type AuthOptions, type DecodedTemporaryToken } from './auth/types.js';
3
3
  import { type RedisClient } from './redis.js';
4
4
  export * from './auth/types.js';
@@ -14,6 +14,7 @@ export interface CreateAuth<UserModel extends AnyUser> {
14
14
  createTemporaryToken(user: UserModel): Promise<string>;
15
15
  verifyTemporaryToken(token: string, user: UserModel): Promise<void>;
16
16
  decodeTemporaryToken(token: string): DecodedTemporaryToken;
17
+ logout: (req: Request, res: Response) => Promise<void>;
17
18
  }
18
19
  export declare class RedisTokenStorage extends TokenStorage {
19
20
  private readonly redis;
package/dist/auth.js CHANGED
@@ -52,9 +52,12 @@ export function createAuth({ getUserById, filterUser, tokenStorage, providers, l
52
52
  }
53
53
  return accessToken;
54
54
  };
55
- const logout = async (res, sessionId) => {
56
- await tokenStorage.invalidate(sessionId);
57
- setAccessTokenCookie(res, null);
55
+ const logout = async (req, res) => {
56
+ const token = extractAccessTokenFromRequest(req);
57
+ if (token) {
58
+ await tokenStorage.invalidate(sha256(token));
59
+ setAccessTokenCookie(res, null);
60
+ }
58
61
  };
59
62
  // Make timing attacks harder
60
63
  const jitter = (duration = 0) => new Promise((resolve) => void setTimeout(resolve, Math.max((0.5 - duration) * 1000, 200)));
@@ -80,10 +83,7 @@ export function createAuth({ getUserById, filterUser, tokenStorage, providers, l
80
83
  return filterUser(user);
81
84
  }));
82
85
  router.get('/logout', route(async (req, res) => {
83
- const token = extractAccessTokenFromRequest(req);
84
- if (token) {
85
- await logout(res, sha256(token));
86
- }
86
+ await logout(req, res);
87
87
  res.redirect(loginUrl);
88
88
  }));
89
89
  /**
@@ -139,12 +139,12 @@ export function createAuth({ getUserById, filterUser, tokenStorage, providers, l
139
139
  logger.warn('request with invalid access token');
140
140
  return next();
141
141
  }
142
- await logout(res, sessionId);
142
+ await logout(req, res);
143
143
  throw new InvalidToken('session token expired');
144
144
  }
145
145
  const decoded = decodeAccessToken(token);
146
146
  if (decoded.v !== sessionTokenVersion) {
147
- await logout(res, token);
147
+ await logout(req, res);
148
148
  throw new InvalidToken('Invalid token version');
149
149
  }
150
150
  let user;
@@ -152,7 +152,7 @@ export function createAuth({ getUserById, filterUser, tokenStorage, providers, l
152
152
  user = await getUserById(decoded.uid);
153
153
  }
154
154
  catch {
155
- await logout(res, token);
155
+ await logout(req, res);
156
156
  throw new InvalidToken('User not found');
157
157
  }
158
158
  const tokenLifetimeMs = decoded.exp * 1000 - decoded.iat * 1000;
@@ -241,5 +241,6 @@ export function createAuth({ getUserById, filterUser, tokenStorage, providers, l
241
241
  createTemporaryToken,
242
242
  verifyTemporaryToken,
243
243
  decodeTemporaryToken,
244
+ logout,
244
245
  };
245
246
  }
package/dist/cache.d.ts CHANGED
@@ -19,5 +19,8 @@ export declare function createCache(adapter: CacheAdapter): {
19
19
  get: (key: string) => Promise<any>;
20
20
  clear: (key?: string) => Promise<void>;
21
21
  wrap: <T>(key: string, options: CacheOptions | number | null, fn: () => Promise<T>) => Promise<T>;
22
- decorate: <T, Arguments extends any[]>(options: CacheOptions | number | null, fn: (...args: Arguments) => T | Promise<T>) => (...args: Arguments) => Promise<T>;
22
+ decorate: <T, Arguments extends any[]>(options: CacheOptions | number | null, fn: (...args: Arguments) => T | Promise<T>) => {
23
+ (...args: Arguments): Promise<T>;
24
+ clear(...args: Arguments): Promise<void>;
25
+ };
23
26
  };
package/dist/cache.js CHANGED
@@ -69,11 +69,14 @@ export function createCache(adapter) {
69
69
  return result;
70
70
  }
71
71
  function cachedFn(options, fn) {
72
- return async (...args) => {
72
+ const getCacheKey = (...args) => {
73
73
  const baseKey = typeof options === 'object' && options != null
74
74
  ? options.key
75
75
  : undefined;
76
- const cacheKey = `${baseKey ?? Buffer.from(fn.toString()).toString('hex')}-${JSON.stringify(args)}`;
76
+ return `${baseKey ?? Buffer.from(fn.toString()).toString('hex')}-${hashKey(args)}`;
77
+ };
78
+ const wrapped = async (...args) => {
79
+ const cacheKey = getCacheKey(...args);
77
80
  const cachedValue = await adapter.get(cacheKey);
78
81
  if (cachedValue != null) {
79
82
  return cachedValue;
@@ -85,6 +88,8 @@ export function createCache(adapter) {
85
88
  await adapter.set(cacheKey, result, expiresMs);
86
89
  return result;
87
90
  };
91
+ wrapped.clear = (...args) => adapter.clear(getCacheKey(...args));
92
+ return wrapped;
88
93
  }
89
94
  return {
90
95
  set: adapter.set.bind(adapter),
@@ -94,3 +99,22 @@ export function createCache(adapter) {
94
99
  decorate: cachedFn,
95
100
  };
96
101
  }
102
+ function hashKey(obj) {
103
+ return JSON.stringify(obj, (key, value) => {
104
+ if (value === null || value === undefined) {
105
+ return String(value);
106
+ }
107
+ if (typeof value === 'object') {
108
+ if (Array.isArray(value)) {
109
+ return value;
110
+ }
111
+ return Object.keys(value)
112
+ .sort()
113
+ .reduce((result, item) => {
114
+ result[item] = value[item];
115
+ return result;
116
+ }, {});
117
+ }
118
+ return value;
119
+ });
120
+ }
package/dist/config.d.ts CHANGED
@@ -6,6 +6,7 @@ export declare const config: {
6
6
  AUTH_TOKEN_EXPIRES_IN: number;
7
7
  AUTH_TEMP_TOKEN_EXPIRES_IN: number;
8
8
  AUTH_SECRET: string;
9
+ AUTH_COOKIE_SAME_SITE: string;
9
10
  REDIS_URL: string;
10
11
  REDIS_KEY_PREFIX: string;
11
12
  POSTGRES_URL: string;
@@ -37,6 +38,7 @@ export declare function extendConfig<T extends Record<string, unknown>>(appConfi
37
38
  AUTH_TOKEN_EXPIRES_IN: number;
38
39
  AUTH_TEMP_TOKEN_EXPIRES_IN: number;
39
40
  AUTH_SECRET: string;
41
+ AUTH_COOKIE_SAME_SITE: string;
40
42
  REDIS_URL: string;
41
43
  REDIS_KEY_PREFIX: string;
42
44
  POSTGRES_URL: string;
package/dist/config.js CHANGED
@@ -9,6 +9,7 @@ const baseConfig = {
9
9
  AUTH_TOKEN_EXPIRES_IN: readEnv.number('AUTH_TOKEN_EXPIRES', 3600 * 24 * 30), // 30 days
10
10
  AUTH_TEMP_TOKEN_EXPIRES_IN: readEnv.number('AUTH_TEMP_TOKEN_EXPIRES', 3600),
11
11
  AUTH_SECRET: readEnv('AUTH_JWT_SECRET', ''),
12
+ AUTH_COOKIE_SAME_SITE: readEnv('AUTH_COOKIE_SAME_SITE', 'strict'),
12
13
  REDIS_URL: readEnv('REDIS_URL', ''),
13
14
  REDIS_KEY_PREFIX: readEnv('REDIS_KEY_PREFIX', ''),
14
15
  POSTGRES_URL: readEnv('POSTGRES_URL', ''),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devmoods/express-extras",
3
- "version": "0.52.0",
3
+ "version": "0.52.2",
4
4
  "description": "Kubernetes-ready utilities for rapid Node.js application development",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",