21 kBTypeScriptView Raw
1import express = require("express");
2import { CipherKey } from "crypto";
3import { EventEmitter } from "events";
4
5declare global {
6 namespace Express {
7 type SessionStore = session.Store & { generate: (req: Request) => void };
8
9 // Inject additional properties on express.Request
10 interface Request {
11 /**
12 * This request's `Session` object.
13 * Even though this property isn't marked as optional, it won't exist until you use the `express-session` middleware
14 * [Declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to add your own properties.
15 *
16 * @see SessionData
17 */
18 session: session.Session & Partial<session.SessionData>;
19
20 /**
21 * This request's session ID.
22 * Even though this property isn't marked as optional, it won't exist until you use the `express-session` middleware
23 */
24 sessionID: string;
25
26 /**
27 * The Store in use.
28 * Even though this property isn't marked as optional, it won't exist until you use the `express-session` middleware
29 * The function `generate` is added by express-session
30 */
31 sessionStore: SessionStore;
32 }
33 }
34}
35
36export = session;
37
38declare function session(options?: session.SessionOptions): express.RequestHandler;
39
40declare namespace session {
41 interface SessionOptions {
42 /**
43 * This is the secret used to sign the session ID cookie.
44 * The secret can be any type of value that is supported by Node.js `crypto.createHmac` (like a string or a Buffer).
45 * This can be either a single secret, or an array of multiple secrets.
46 * If an array of secrets is provided, only the first element will be used to sign the session ID cookie, while all the elements will be considered when verifying the signature in requests.
47 * The secret itself should be not easily parsed by a human and would best be a random set of characters.
48 *
49 * A best practice may include:
50 * * The use of environment variables to store the secret, ensuring the secret itself does not exist in your repository.
51 * * Periodic updates of the secret, while ensuring the previous secret is in the array.
52 *
53 * Using a secret that cannot be guessed will reduce the ability to hijack a session to only guessing the session ID (as determined by the `genid` option).
54 *
55 * Changing the secret value will invalidate all existing sessions.
56 * In order to rotate the secret without invalidating sessions, provide an array of secrets, with the new secret as first element of the array, and including previous secrets as the later elements.
57 *
58 * Note HMAC-256 is used to sign the session ID. For this reason, the secret should contain at least 32 bytes of entropy.
59 */
60 secret: CipherKey | CipherKey[];
61
62 /**
63 * Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID.
64 * The function is given the request as the first argument if you want to use some value attached to it when generating the ID.
65 *
66 * The default value is a function which uses the uid-safe library to generate IDs.
67 * Be careful to generate unique IDs so your sessions do not conflict.
68 */
69 genid?(req: express.Request): string;
70
71 /**
72 * The name of the session ID cookie to set in the response (and read from in the request).
73 * The default value is 'connect.sid'.
74 *
75 * Note if you have multiple apps running on the same hostname (this is just the name, i.e. `localhost` or `127.0.0.1`; different schemes and ports do not name a different hostname),
76 * then you need to separate the session cookies from each other.
77 * The simplest method is to simply set different names per app.
78 */
79 name?: string | undefined;
80
81 /**
82 * The session store instance, defaults to a new `MemoryStore` instance.
83 * @see MemoryStore
84 */
85 store?: Store | undefined;
86
87 /**
88 * Settings object for the session ID cookie.
89 * @see CookieOptions
90 */
91 cookie?: CookieOptions | undefined;
92
93 /**
94 * Force the session identifier cookie to be set on every response. The expiration is reset to the original `maxAge`, resetting the expiration countdown.
95 * The default value is `false`.
96 *
97 * With this enabled, the session identifier cookie will expire in `maxAge` *since the last response was sent* instead of in `maxAge` *since the session was last modified by the server*.
98 * This is typically used in conjuction with short, non-session-length `maxAge` values to provide a quick timeout of the session data
99 * with reduced potential of it occurring during on going server interactions.
100 *
101 * Note that when this option is set to `true` but the `saveUninitialized` option is set to `false`, the cookie will not be set on a response with an uninitialized session.
102 * This option only modifies the behavior when an existing session was loaded for the request.
103 *
104 * @see saveUninitialized
105 */
106 rolling?: boolean | undefined;
107
108 /**
109 * Forces the session to be saved back to the session store, even if the session was never modified during the request.
110 * Depending on your store this may be necessary, but it can also create race conditions where a client makes two parallel requests to your server
111 * and changes made to the session in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using).
112 *
113 * The default value is `true`, but using the default has been deprecated, as the default will change in the future.
114 * Please research into this setting and choose what is appropriate to your use-case. Typically, you'll want `false`.
115 *
116 * How do I know if this is necessary for my store? The best way to know is to check with your store if it implements the `touch` method.
117 * If it does, then you can safely set `resave: false`.
118 * If it does not implement the `touch` method and your store sets an expiration date on stored sessions, then you likely need `resave: true`.
119 */
120 resave?: boolean | undefined;
121
122 /**
123 * Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" header).
124 * The default value is undefined.
125 *
126 * - `true`: The `X-Forwarded-Proto` header will be used.
127 * - `false`: All headers are ignored and the connection is considered secure only if there is a direct TLS/SSL connection.
128 * - `undefined`: Uses the "trust proxy" setting from express
129 */
130 proxy?: boolean | undefined;
131
132 /**
133 * Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
134 * Choosing `false` is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie.
135 * Choosing `false` will also help with race conditions where a client makes multiple parallel requests without a session.
136 *
137 * The default value is `true`, but using the default has been deprecated, as the default will change in the future.
138 * Please research into this setting and choose what is appropriate to your use-case.
139 *
140 * **If you are using `express-session` in conjunction with PassportJS:**
141 * Passport will add an empty Passport object to the session for use after a user is authenticated, which will be treated as a modification to the session, causing it to be saved.
142 * This has been fixed in PassportJS 0.3.0.
143 */
144 saveUninitialized?: boolean | undefined;
145
146 /**
147 * Control the result of unsetting req.session (through delete, setting to null, etc.).
148 * - `destroy`: The session will be destroyed (deleted) when the response ends.
149 * - `keep`: The session in the store will be kept, but modifications made during the request are ignored and not saved.
150 * @default 'keep'
151 */
152 unset?: "destroy" | "keep" | undefined;
153 }
154
155 class Session {
156 private constructor(request: Express.Request, data: SessionData);
157
158 /**
159 * Each session has a unique ID associated with it.
160 * This property is an alias of `req.sessionID` and cannot be modified.
161 * It has been added to make the session ID accessible from the session object.
162 */
163 id: string;
164
165 /**
166 * Each session has a unique cookie object accompany it.
167 * This allows you to alter the session cookie per visitor.
168 * For example we can set `req.session.cookie.expires` to `false` to enable the cookie to remain for only the duration of the user-agent.
169 */
170 cookie: Cookie;
171
172 /** To regenerate the session simply invoke the method. Once complete, a new SID and `Session` instance will be initialized at `req.session` and the `callback` will be invoked. */
173 regenerate(callback: (err: any) => void): this;
174
175 /** Destroys the session and will unset the `req.session` property. Once complete, the `callback` will be invoked. */
176 destroy(callback: (err: any) => void): this;
177
178 /** Reloads the session data from the store and re-populates the `req.session` object. Once complete, the `callback` will be invoked. */
179 reload(callback: (err: any) => void): this;
180
181 /**
182 * Resets the cookie's `maxAge` to `originalMaxAge`
183 * @see Cookie
184 */
185 resetMaxAge(): this;
186
187 /**
188 * Save the session back to the store, replacing the contents on the store with the contents in memory
189 * (though a store may do something else - consult the store's documentation for exact behavior).
190 *
191 * This method is automatically called at the end of the HTTP response if the session data has been altered
192 * (though this behavior can be altered with various options in the middleware constructor).
193 * Because of this, typically this method does not need to be called.
194 * There are some cases where it is useful to call this method, for example: redirects, long-lived requests or in WebSockets.
195 */
196 save(callback?: (err: any) => void): this;
197
198 /** Updates the `maxAge` property. Typically this is not necessary to call, as the session middleware does this for you. */
199 touch(): this;
200 }
201
202 /**
203 * This interface allows you to declare additional properties on your session object using [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).
204 *
205 * @example
206 * declare module 'express-session' {
207 * interface SessionData {
208 * views: number;
209 * }
210 * }
211 */
212 interface SessionData {
213 cookie: Cookie;
214 }
215
216 interface CookieOptions {
217 /**
218 * Specifies the number (in milliseconds) to use when calculating the `Expires Set-Cookie` attribute.
219 * This is done by taking the current server time and adding `maxAge` milliseconds to the value to calculate an `Expires` datetime. By default, no maximum age is set.
220 *
221 * If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used.
222 * `maxAge` should be preferred over `expires`.
223 *
224 * @see expires
225 */
226 maxAge?: number | undefined;
227
228 /**
229 * Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/)
230 * attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not.
231 * By default, the `Partitioned` attribute is not set.
232 *
233 * **Note** This is an attribute that has not yet been fully standardized, and may
234 * change in the future. This also means many clients may ignore this attribute until
235 * they understand it.
236 */
237 partitioned?: boolean | undefined;
238
239 /**
240 * Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).
241 *
242 * - `'low'` will set the `Priority` attribute to `Low`.
243 * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
244 * - `'high'` will set the `Priority` attribute to `High`.
245 *
246 * More information about the different priority levels can be found in
247 * [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).
248 *
249 * **Note** This is an attribute that has not yet been fully standardized, and may change in the future.
250 * This also means many clients may ignore this attribute until they understand it.
251 */
252 priority?: "low" | "medium" | "high" | undefined;
253
254 signed?: boolean | undefined;
255
256 /**
257 * Specifies the `Date` object to be the value for the `Expires Set-Cookie` attribute.
258 * By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.
259 *
260 * If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used.
261 *
262 * @deprecated The `expires` option should not be set directly; instead only use the `maxAge` option
263 * @see maxAge
264 */
265 expires?: Date | null | undefined;
266
267 /**
268 * Specifies the boolean value for the `HttpOnly Set-Cookie` attribute. When truthy, the `HttpOnly` attribute is set, otherwise it is not.
269 * By default, the `HttpOnly` attribute is set.
270 *
271 * Be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`.
272 */
273 httpOnly?: boolean | undefined;
274
275 /**
276 * Specifies the value for the `Path Set-Cookie` attribute.
277 * By default, this is set to '/', which is the root path of the domain.
278 */
279 path?: string | undefined;
280
281 /**
282 * Specifies the value for the `Domain Set-Cookie` attribute.
283 * By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
284 */
285 domain?: string | undefined;
286
287 /**
288 * Specifies the boolean value for the `Secure Set-Cookie` attribute. When truthy, the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
289 * Be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.
290 *
291 * Please note that `secure: true` is a **recommended option**.
292 * However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies.
293 * If `secure` is set, and you access your site over HTTP, **the cookie will not be set**.
294 *
295 * The cookie.secure option can also be set to the special value `auto` to have this setting automatically match the determined security of the connection.
296 * Be careful when using this setting if the site is available both as HTTP and HTTPS, as once the cookie is set on HTTPS, it will no longer be visible over HTTP.
297 * This is useful when the Express "trust proxy" setting is properly setup to simplify development vs production configuration.
298 *
299 * If you have your node.js behind a proxy and are using `secure: true`, you need to set "trust proxy" in express. Please see the [README](https://github.com/expressjs/session) for details.
300 *
301 * Please see the [README](https://github.com/expressjs/session) for an example of using secure cookies in production, but allowing for testing in development based on NODE_ENV.
302 */
303 secure?: boolean | "auto" | undefined;
304
305 encode?: ((val: string) => string) | undefined;
306
307 /**
308 * Specifies the boolean or string to be the value for the `SameSite Set-Cookie` attribute.
309 * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
310 * - `false` will not set the `SameSite` attribute.
311 * - `lax` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
312 * - `none` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
313 * - `strict` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
314 *
315 * More information about the different enforcement levels can be found in the specification.
316 *
317 * **Note:** This is an attribute that has not yet been fully standardized, and may change in the future.
318 * This also means many clients may ignore this attribute until they understand it.
319 */
320 sameSite?: boolean | "lax" | "strict" | "none" | undefined;
321 }
322
323 class Cookie implements CookieOptions {
324 /** Returns the original `maxAge` (time-to-live), in milliseconds, of the session cookie. */
325 originalMaxAge: number | null;
326
327 maxAge?: number | undefined;
328 signed?: boolean | undefined;
329 expires?: Date | null | undefined;
330 httpOnly?: boolean | undefined;
331 path?: string | undefined;
332 domain?: string | undefined;
333 secure?: boolean | "auto" | undefined;
334 sameSite?: boolean | "lax" | "strict" | "none" | undefined;
335 }
336
337 abstract class Store extends EventEmitter {
338 regenerate(req: express.Request, callback: (err?: any) => any): void;
339
340 load(sid: string, callback: (err: any, session?: SessionData) => any): void;
341
342 createSession(req: express.Request, session: SessionData): Session & SessionData;
343
344 /**
345 * Gets the session from the store given a session ID and passes it to `callback`.
346 *
347 * The `session` argument should be a `Session` object if found, otherwise `null` or `undefined` if the session was not found and there was no error.
348 * A special case is made when `error.code === 'ENOENT'` to act like `callback(null, null)`.
349 */
350 abstract get(sid: string, callback: (err: any, session?: SessionData | null) => void): void;
351
352 /** Upsert a session in the store given a session ID and `SessionData` */
353 abstract set(sid: string, session: SessionData, callback?: (err?: any) => void): void;
354
355 /** Destroys the session with the given session ID. */
356 abstract destroy(sid: string, callback?: (err?: any) => void): void;
357
358 /** Returns all sessions in the store */
359 // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/38783, https://github.com/expressjs/session/pull/700#issuecomment-540855551
360 all?(callback: (err: any, obj?: SessionData[] | { [sid: string]: SessionData } | null) => void): void;
361
362 /** Returns the amount of sessions in the store. */
363 length?(callback: (err: any, length?: number) => void): void;
364
365 /** Delete all sessions from the store. */
366 clear?(callback?: (err?: any) => void): void;
367
368 /** "Touches" a given session, resetting the idle timer. */
369 touch?(sid: string, session: SessionData, callback?: () => void): void;
370 }
371
372 /**
373 * **Warning:** the default server-side session storage, `MemoryStore`, is purposely not designed for a production environment.
374 * It will leak memory under most conditions, does not scale past a single process, and is only meant for debugging and developing.
375 */
376 class MemoryStore extends Store {
377 get(sid: string, callback: (err: any, session?: SessionData | null) => void): void;
378
379 set(sid: string, session: SessionData, callback?: (err?: any) => void): void;
380
381 destroy(sid: string, callback?: (err?: any) => void): void;
382
383 all(callback: (err: any, obj?: { [sid: string]: SessionData } | null) => void): void;
384
385 length(callback: (err: any, length?: number) => void): void;
386
387 clear(callback?: (err?: any) => void): void;
388
389 touch(sid: string, session: SessionData, callback?: () => void): void;
390 }
391}
392
\No newline at end of file