UNPKG

19.4 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 // Inject additional properties on express.Request
19 interface Request {
20 /**
21 * This request's `Session` object.
22 * Even though this property isn't marked as optional, it won't exist until you use the `express-session` middleware
23 * [Declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to add your own properties.
24 *
25 * @see SessionData
26 */
27 session: session.Session & Partial<session.SessionData>;
28
29 /**
30 * This request's session ID.
31 * Even though this property isn't marked as optional, it won't exist until you use the `express-session` middleware
32 */
33 sessionID: string;
34 }
35 }
36}
37
38export = session;
39
40declare function session(options?: session.SessionOptions): express.RequestHandler;
41
42declare namespace session {
43 interface SessionOptions {
44 /**
45 * 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.
46 * If an array of secrets is provided, **only the first element will be used to sign** the session ID cookie,
47 * while **all the elements will be considered when verifying the signature** in requests.
48 * The secret itself should be not easily parsed by a human and would best be a random set of characters
49 *
50 * Best practices may include:
51 * - The use of environment variables to store the secret, ensuring the secret itself does not exist in your repository.
52 * - Periodic updates of the secret, while ensuring the previous secret is in the array.
53 *
54 * 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).
55 *
56 * Changing the secret value will invalidate all existing sessions.
57 * In order to rotate the secret without invalidating sessions, provide an array of secrets,
58 * with the new secret as first element of the array, and including previous secrets as the later elements.
59 */
60 secret: string | string[];
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 */
213 interface SessionData {
214 cookie: Cookie;
215 }
216
217 interface CookieOptions {
218 /**
219 * Specifies the number (in milliseconds) to use when calculating the `Expires Set-Cookie` attribute.
220 * 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.
221 *
222 * If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used.
223 * `maxAge` should be preferred over `expires`.
224 *
225 * @see expires
226 */
227 maxAge?: number | undefined;
228
229 signed?: boolean | undefined;
230
231 /**
232 * Specifies the `Date` object to be the value for the `Expires Set-Cookie` attribute.
233 * 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.
234 *
235 * If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used.
236 *
237 * @deprecated The `expires` option should not be set directly; instead only use the `maxAge` option
238 * @see maxAge
239 */
240 expires?: Date | undefined;
241
242 /**
243 * Specifies the boolean value for the `HttpOnly Set-Cookie` attribute. When truthy, the `HttpOnly` attribute is set, otherwise it is not.
244 * By default, the `HttpOnly` attribute is set.
245 *
246 * Be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`.
247 */
248 httpOnly?: boolean | undefined;
249
250 /**
251 * Specifies the value for the `Path Set-Cookie` attribute.
252 * By default, this is set to '/', which is the root path of the domain.
253 */
254 path?: string | undefined;
255
256 /**
257 * Specifies the value for the `Domain Set-Cookie` attribute.
258 * By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
259 */
260 domain?: string | undefined;
261
262 /**
263 * 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.
264 * 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.
265 *
266 * Please note that `secure: true` is a **recommended option**.
267 * However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies.
268 * If `secure` is set, and you access your site over HTTP, **the cookie will not be set**.
269 *
270 * 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.
271 * 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.
272 * This is useful when the Express "trust proxy" setting is properly setup to simplify development vs production configuration.
273 *
274 * 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.
275 *
276 * 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.
277 */
278 secure?: boolean | 'auto' | undefined;
279
280 encode?: ((val: string) => string) | undefined;
281
282 /**
283 * Specifies the boolean or string to be the value for the `SameSite Set-Cookie` attribute.
284 * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
285 * - `false` will not set the `SameSite` attribute.
286 * - `lax` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
287 * - `none` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
288 * - `strict` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
289 *
290 * More information about the different enforcement levels can be found in the specification.
291 *
292 * **Note:** This is an attribute that has not yet been fully standardized, and may change in the future.
293 * This also means many clients may ignore this attribute until they understand it.
294 */
295 sameSite?: boolean | 'lax' | 'strict' | 'none' | undefined;
296 }
297
298 class Cookie implements CookieOptions {
299 /** Returns the original `maxAge` (time-to-live), in milliseconds, of the session cookie. */
300 originalMaxAge: number;
301
302 maxAge?: number | undefined;
303 signed?: boolean | undefined;
304 expires?: Date | undefined;
305 httpOnly?: boolean | undefined;
306 path?: string | undefined;
307 domain?: string | undefined;
308 secure?: boolean | 'auto' | undefined;
309 sameSite?: boolean | 'lax' | 'strict' | 'none' | undefined;
310 }
311
312 abstract class Store extends EventEmitter {
313 regenerate(req: express.Request, callback: (err?: any) => any): void;
314 load(sid: string, callback: (err: any, session?: SessionData) => any): void;
315 createSession(req: express.Request, session: SessionData): void;
316
317 /**
318 * Gets the session from the store given a session ID and passes it to `callback`.
319 *
320 * 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.
321 * A special case is made when `error.code === 'ENOENT'` to act like `callback(null, null)`.
322 */
323 abstract get(sid: string, callback: (err: any, session?: SessionData | null) => void): void;
324
325 /** Upsert a session in the store given a session ID and `SessionData` */
326 abstract set(sid: string, session: SessionData, callback?: (err?: any) => void): void;
327
328 /** Destroys the dession with the given session ID. */
329 abstract destroy(sid: string, callback?: (err?: any) => void): void;
330
331 /** Returns all sessions in the store */
332 // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/38783, https://github.com/expressjs/session/pull/700#issuecomment-540855551
333 all?(callback: (err: any, obj?: SessionData[] | { [sid: string]: SessionData; } | null) => void): void;
334
335 /** Returns the amount of sessions in the store. */
336 length?(callback: (err: any, length: number) => void): void;
337
338 /** Delete all sessions from the store. */
339 clear?(callback?: (err?: any) => void): void;
340
341 /** "Touches" a given session, resetting the idle timer. */
342 touch?(sid: string, session: SessionData, callback?: () => void): void;
343 }
344
345 /**
346 * **Warning:** the default server-side session storage, `MemoryStore`, is purposely not designed for a production environment.
347 * It will leak memory under most conditions, does not scale past a single process, and is only meant for debugging and developing.
348 */
349 class MemoryStore extends Store {
350 get(sid: string, callback: (err: any, session?: SessionData | null) => void): void;
351 set(sid: string, session: SessionData, callback?: (err?: any) => void): void;
352 destroy(sid: string, callback?: (err?: any) => void): void;
353
354 all(callback: (err: any, obj?: { [sid: string]: SessionData; } | null) => void): void;
355 length(callback: (err: any, length: number) => void): void;
356 clear(callback?: (err?: any) => void): void;
357 touch(sid: string, session: SessionData, callback?: () => void): void;
358 }
359}
360
\No newline at end of file