UNPKG

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