UNPKG

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