Unit 3 - Practice Quiz

INT222 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is a network socket in the context of web development?

Understanding Network Sockets Easy
A. A type of CSS selector for styling web pages
B. A physical port on a computer, like a USB or Ethernet port
C. A JavaScript library for managing state
D. An endpoint of a two-way communication link between two programs running on a network

2 What is the correct protocol scheme for a secure WebSocket connection?

Creating a basic WebSocket server Easy
A. http://
B. ws://
C. wss://
D. https://

3 In a client-side WebSocket API, which event is triggered when a message is received from the server?

Sending and receiving messages Easy
A. onmessage
B. onopen
C. onclose
D. onerror

4 What is a major advantage of using the Socket.IO library over the native WebSocket API?

A Socket.IO Chat Server Easy
A. It is the only way to create a chat application in Node.js.
B. It does not require a server to function.
C. It is significantly faster than native WebSockets in all situations.
D. It provides automatic fallback to other technologies like long-polling if WebSockets are not supported.

5 In Express.js, what is the primary role of a middleware function?

Introduction to middleware Easy
A. To connect to a database.
B. To execute code during the request-response cycle.
C. To define the front-end user interface.
D. To compile the Node.js application.

6 In an Express middleware function (req, res, next), what happens if next() is not called?

Implementing basic middleware Easy
A. An error is automatically thrown.
B. The request will be left hanging and the client will not receive a response.
C. The server automatically sends a 200 OK response.
D. The next middleware is called automatically.

7 What is the purpose of the cookie-parser middleware?

cookie-parser Easy
A. To create secure, encrypted cookies.
B. To block all cookies from being set.
C. To manage server-side user sessions.
D. To parse the Cookie header and populate req.cookies.

8 Where does the express-session middleware typically store session data by default?

express-session Easy
A. In memory on the server
B. In a local file on the client's machine
C. In the browser's localStorage
D. Inside the cookie on the client's browser

9 How is the app.use() function used in Express.js?

app.use() Easy
A. To define a route that only responds to GET requests.
B. To send a JSON response to the client.
C. To mount a middleware function for all requests or for requests to a specific path.
D. To start the Express server and listen for connections.

10 Which of the following best describes the app.all() routing method in Express?

app.all() Easy
A. It matches all routes in the entire application.
B. It blocks all requests to a specific route.
C. It is an alias for app.use().
D. It matches all HTTP methods (GET, POST, PUT, etc.) for a specific route.

11 What is the difference between authentication and authorization?

Authentication and Security Easy
A. Authentication is for users; authorization is for servers.
B. Authentication is verifying identity; authorization is determining access rights.
C. They are the same concept.
D. Authorization is verifying identity; authentication is determining access rights.

12 What does JWT stand for?

JWT implementation Easy
A. Java Web Task
B. JSON Web Transfer
C. JavaScript Web Token
D. JSON Web Token

13 Which part of a JSON Web Token is used to verify that the token has not been tampered with?

JWT implementation Easy
A. Signature
B. Algorithm
C. Header
D. Payload

14 What does RBAC stand for?

RBAC Easy
A. Route-Based Access Control
B. Rule-Based Access Configuration
C. Role-Based Access Control
D. Request-Based Authentication Code

15 In a Role-Based Access Control (RBAC) model, what is a 'role'?

RBAC Easy
A. A physical server.
B. A security token.
C. A specific, individual user.
D. A collection of permissions, often corresponding to a job function like 'admin' or 'editor'.

16 What is the primary purpose of the Content-Security-Policy (CSP) HTTP header?

Security headers Easy
A. To control caching behavior in browsers.
B. To specify the character encoding of the document.
C. To prevent Cross-Site Scripting (XSS) and other code injection attacks.
D. To enforce the use of HTTPS.

17 Which of the following is a characteristic of the cookie-session middleware?

cookie-session Easy
A. It is the same as the express-session middleware.
B. It requires a server-side database like Redis to store session data.
C. It stores the entire session data within the client-side cookie.
D. It cannot store any session data.

18 In Socket.IO, which method is used to send a message to all clients except for the one that initiated the event?

Sending and receiving messages Easy
A. socket.emit()
B. io.emit()
C. socket.send()
D. socket.broadcast.emit()

19 On a Socket.IO server, what does the io object typically represent?

A Socket.IO Chat Server Easy
A. A specific chat room.
B. A single client's connection.
C. The main server instance that manages all connected clients.
D. An input/output stream for a file.

20 What is the function of the X-Content-Type-Options: nosniff header?

Security headers Easy
A. To enable a special sniffing mode for debugging.
B. To prevent the browser from MIME-sniffing a response away from the declared Content-Type.
C. To specify which content types are allowed.
D. To disable all content sniffing on the server.

21 Analyze the following Node.js code snippet using the ws library. What is the primary role of the 'connection' event listener?

javascript
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
// ... logic here
});

Creating a basic WebSocket server Medium
A. It is triggered every time any message is received from any client.
B. It is triggered once for each client that successfully establishes a WebSocket connection, providing a unique ws object for that client.
C. It is triggered when the server itself successfully starts and binds to the specified port.
D. It is responsible for closing all existing connections when the server shuts down.

22 In a chat application using the ws library, you need to broadcast a message to all connected clients except the one who sent it. Given a WebSocket.Server instance wss and the sender's WebSocket instance ws, which code snippet correctly implements this logic?

Sending and receiving messages Medium
A. javascript
for (const client of wss.clients) {
client.send(message);
}
B. javascript
wss.clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
C. wss.broadcast(message, { except: ws });
D. ws.broadcast(message);

23 What is the primary purpose of using socket.join('room-name') followed by io.to('room-name').emit(...) in a Socket.IO application?

A Socket.IO Chat Server Medium
A. To send a private message from one specific socket to another.
B. To create a persistent channel that stores messages even after clients disconnect.
C. To send a message only to clients who have been explicitly grouped into 'room-name'.
D. To broadcast a message to every single client connected to the server, regardless of their room.

24 Consider the following Express middleware. What will be the Content-Type header in the response if a request is made to /api/data?

javascript
const express = require('express');
const app = express();

app.use((req, res, next) => {
res.setHeader('Content-Type', 'text/plain');
next();
});

app.use((req, res, next) => {
res.setHeader('Content-Type', 'application/json');
next();
});

app.get('/api/data', (req, res) => {
res.send({ message: 'Hello' });
});

Implementing basic middleware Medium
A. application/json
B. text/html; charset=utf-8
C. It will throw an error because the header is set twice.
D. text/plain

25 You are using the cookie-parser middleware with a secret key to handle signed cookies. How would you correctly access the value of a signed cookie named user_id on the server?

javascript
const cookieParser = require('cookie-parser');
app.use(cookieParser('my-secret-key'));

// In a route handler...
// res.cookie('user_id', '12345', { signed: true });

cookie-parser Medium
A. req.cookies.user_id
B. req.cookies['user_id.signed']
C. Manually decrypting the value from req.cookies.user_id.
D. req.signedCookies.user_id

26 When using the express-session middleware with its default MemoryStore, what is a significant drawback in a production environment?

express-session Medium
A. It stores all session data in a client-side cookie, which is insecure and limited by size.
B. It causes a memory leak and is not designed for a multi-process or multi-server setup, as each process will have its own memory store.
C. It does not support the rolling: true session option.
D. It is significantly slower than disk-based session stores.

27 Given the code app.use('/admin', adminRoutes);, which of the following incoming request paths will be handled by the adminRoutes router?

app.use() Medium
A. /admin, /admin/users, and /admin/users/1
B. Only the exact path /admin
C. Any path that contains the substring /admin, such as /api/admin/data
D. Only /admin/ and not /admin

28 When a server receives a JSON Web Token (JWT) from a client, what is the most critical step it must perform to ensure the token's authenticity and integrity?

JWT implementation Medium
A. Check the exp (expiration) claim to ensure the token has not expired.
B. Decode the header and verify the alg (algorithm) used is HS256.
C. Verify the token's signature using the secret key (or public key) that was used to sign it.
D. Decode the payload and check if the user ID exists in the database.

29 You are implementing Role-Based Access Control (RBAC) in an Express app. You have a JWT payload that includes a roles array (e.g., ['editor', 'viewer']). Which middleware function correctly checks if a user has the 'admin' role before proceeding?

RBAC Medium
A. javascript
function requireAdmin(req, res, next) {
if (req.user.role === 'admin') {
return next;
}
res.status(401).send('Unauthorized');
}
B. javascript
function requireAdmin(req, res, next) {
if (req.user && req.user.roles && req.user.roles.includes('admin')) {
next();
} else {
res.status(403).send('Forbidden: Admins only');
}
}
C. javascript
function requireAdmin(req, res, next) {
if (req.user.roles == ['admin']) {
next();
} else {
res.status(403).send('Forbidden');
}
}
D. javascript
function requireAdmin(req, res, next) {
if (req.user.roles.indexOf('admin')) {
next();
} else {
res.status(403).send('Forbidden');
}
}

30 What is the primary security benefit of setting the Strict-Transport-Security (HSTS) header in a web application's response?

Security headers Medium
A. It prevents the website from being loaded in an <iframe>, <frame>, <embed> or <object>, mitigating clickjacking attacks.
B. It prevents the browser from rendering a page if it detects a reflected or stored Cross-Site Scripting (XSS) attack.
C. It controls which resources (scripts, images, etc.) the browser is allowed to load for a given page.
D. It instructs the browser to only communicate with the server over HTTPS, preventing protocol downgrade attacks and cookie hijacking over insecure connections.

31 In the context of web communication, what is the key difference between a standard HTTP request/response cycle and a WebSocket connection?

Understanding Network Sockets Medium
A. A WebSocket connection is persistent and full-duplex, allowing for two-way communication at any time, while HTTP is a stateless, unidirectional request/response protocol.
B. HTTP connections are always encrypted with TLS, while WebSocket connections are not.
C. A WebSocket connection can only transmit text data, while HTTP can handle various content types like images and JSON.
D. WebSockets use UDP for faster, less reliable communication, whereas HTTP is built on top of TCP.

32 In the Express.js framework, what is the canonical role of the next function when passed as the third argument to a middleware function (req, res, next)?

Introduction to middleware Medium
A. To pass control to the next middleware function in the stack. If it's not called, the request-response cycle is left hanging for that request.
B. To immediately send a "200 OK" response to the client and end the request.
C. To append data to the response body that will be sent after the main route handler finishes.
D. To skip all subsequent middleware and go directly to the global error-handling middleware when called with an argument (e.g., next(error)).

33 How does the cookie-session middleware differ from express-session in its primary storage mechanism?

cookie-session Medium
A. cookie-session requires a database like Redis or MongoDB to function, while express-session works out-of-the-box.
B. cookie-session stores session data in the server's memory, while express-session stores it in a file on the server's disk.
C. Both are identical in function, but cookie-session is an older, deprecated package.
D. cookie-session stores the entire session data object directly in the client-side cookie, while express-session stores only a session ID in the cookie and keeps the session data on the server.

34 You want to implement a piece of middleware that runs for a specific route, /api/resource, regardless of the HTTP method (GET, POST, PUT, DELETE, etc.). Which Express method is most appropriate for this task?

app.all() Medium
A. app.all('/api/resource', myMiddleware)
B. app.get('/api/resource', myMiddleware); app.post('/api/resource', myMiddleware); // etc...
C. app.use('/api/resource', myMiddleware)
D. app.route('/api/resource').any(myMiddleware)

35 A JWT is composed of three parts separated by dots: header.payload.signature. Which statement accurately describes the payload section?

JWT implementation Medium
A. It is an encrypted blob of data that can only be read by the server using its secret key.
B. It is a hash of the header and the secret key, ensuring the token's integrity.
C. It contains the algorithm used for signing and the token type, and it is not encoded.
D. It is a Base64Url-encoded JSON object containing claims (user data and metadata) that is readable by anyone, but cannot be tampered with without invalidating the signature.

36 To mitigate Cross-Site Scripting (XSS) attacks, which HTTP response header is most effective at instructing the browser to enable its built-in XSS filter and, in some cases, block rendering of the page if an attack is detected?

Security headers Medium
A. X-XSS-Protection: 1; mode=block
B. Content-Security-Policy: "default-src 'self'"
C. X-Frame-Options: DENY
D. X-Content-Type-Options: nosniff

37 In a Socket.IO server, you notice that when a user closes their browser tab, the 'disconnect' event doesn't fire immediately. What is the most likely reason for this behavior?

A Socket.IO Chat Server Medium
A. The 'disconnect' event only fires if the client explicitly calls socket.disconnect() in their code.
B. The server is waiting for a transport-level timeout because the client did not send a clean disconnect packet. The event will fire after a short delay.
C. The server must periodically ping each client with a custom event, and only if a client fails to respond will the connection be considered closed.
D. There is a bug in the server code, as the 'disconnect' event should always be instantaneous.

38 You are building an API that will be consumed by a Single-Page Application (SPA) on a different domain. Which middleware is essential to enable this cross-origin communication in a secure way?

Authentication and Security Medium
A. helmet
B. body-parser
C. csurf
D. cors

39 When configuring the express-session middleware, what is the purpose of the secret option?

express-session Medium
A. It defines the name of the cookie that will be sent to the client.
B. It is a password required by clients to connect to the session store.
C. It is a string or array of strings used to sign the session ID cookie, making it harder to forge.
D. It is an encryption key used to encrypt the session data stored on the server.

40 What happens during the "handshake" phase when a client initiates a WebSocket connection to a server?

Understanding Network Sockets Medium
A. The server sends an HTTP 200 OK response with the WebSocket connection details in the response body.
B. The client sends its public key, and the server responds with a session token, completing a full TLS handshake separate from HTTP.
C. The client sends a standard HTTP GET request with an Upgrade: websocket header, and if the server agrees, it responds with a special 101 Switching Protocols status code to establish the socket.
D. The client and server exchange a series of UDP packets to negotiate a port and session key for the real-time connection.

41 You are designing a stateless authentication system using JWTs. A requirement is to allow immediate invalidation of a specific user's token (e.g., upon password change or logout). Given that JWTs are self-contained and cannot be modified after issuance, which of the following is the most robust and scalable strategy to implement this functionality without sacrificing the primary benefits of a stateless architecture?

JWT implementation Hard
A. Maintain a server-side blacklist of invalidated token IDs (jti claim) in a fast-access database like Redis, checking against it for every request.
B. Embed a session ID within the JWT payload and store the session state on the server. To invalidate, simply delete the server-side session.
C. Shorten the JWT expiration time to a few minutes and rely on a refresh token mechanism. Invalidation then only requires blacklisting the refresh token.
D. Store a 'token version' number in the user's database record. Include this version in the JWT payload. On each request, compare the token's version with the user's current version. Increment the user's version to invalidate all their old tokens.

42 In an Express application using express-session with a persistent store like Redis, you observe a race condition where two concurrent API calls from the same client attempt to modify the session (req.session.cart.items++). The final state of the cart is incorrect. Which combination of express-session options and practices is designed to prevent this specific type of race condition?

express-session Hard
A. The library does not handle this natively. You must implement a manual locking mechanism using a library like redlock on the req.sessionID before reading and writing to the session.
B. Setting resave: true and saveUninitialized: true to force the session to be saved on every request.
C. This is a fundamental limitation of HTTP. The client should batch updates into a single request.
D. Setting resave: false and ensuring the session store supports atomic updates. The application logic should not read, modify, and then write the session object in separate steps if the store doesn't support locking.

43 You are scaling a Socket.IO chat application across multiple Node.js processes using the socket.io-redis adapter. A user connected to Process A needs to receive a private message sent from a user on Process B. How does the adapter ensure the message is delivered only to the intended recipient's socket and not broadcast to all sockets on Process A?

A Socket.IO Chat Server Hard
A. When Process B calls io.to(socketId).emit(), the adapter broadcasts the message along with the target socketId to all processes. Each process then iterates through its local clients to find a match for the socketId and delivers the message.
B. The adapter does not handle private messaging; it's only for broadcasting to rooms. Private messages must be handled via a separate message queue system.
C. The adapter creates a unique Redis channel for every connected client. Process B publishes the message to the recipient's unique channel, and only Process A subscribes to it if the client is connected there.
D. This is handled by the sticky-session mechanism of the load balancer, which ensures both users are always routed to the same process, making the adapter unnecessary for private messages.

44 Consider the following Express middleware chain. What will be the final HTTP response body sent to the client after a request to /?

javascript
const app = express();

app.use((req, res, next) => {
req.data = ['A'];
next();
req.data.push('D');
});

app.use((req, res, next) => {
req.data.push('B');
setTimeout(() => {
req.data.push('C');
next();
}, 10);
});

app.get('/', (req, res) => {
res.send(req.data);
});

Creating middlewares
A. The request will hang and time out.
B. ['A', 'B', 'D']
C. ['A', 'B', 'C', 'D']
D. ['A', 'B']

45 You are tasked with setting a Content Security Policy (CSP) for a web application. The goal is to allow scripts from the same origin and from https://apis.google.com, allow inline styles on specific elements via a nonce, and disallow all other sources including unsafe-inline and unsafe-eval for scripts. Which of the following CSP headers is correctly formulated to achieve this specific policy?

Security headers Hard
A. Content-Security-Policy: default-src 'none'; script-src 'self' https://apis.google.com; style-src 'nonce-R4nd0m...'; connect-src 'self'; img-src 'self'
B. Content-Security-Policy: script-src 'self' https://apis.google.com; style-src 'self' 'unsafe-inline'; default-src 'self'
C. Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.google.com; style-src 'self' 'nonce-R4nd0m...'
D. Content-Security-Policy: script-src 'self' https://apis.google.com; style-src 'nonce-R4nd0m...'; object-src 'none'

46 An architect is deciding between cookie-session and express-session (with a Redis store) for a new high-traffic, horizontally-scaled application. The session data is small (user ID, role, theme preference). The primary design goals are minimizing server-side storage, reducing database/store lookups per request, and maintaining a stateless-as-possible architecture for the web servers. Which middleware should be chosen and why?

cookie-session vs. express-session Hard
A. express-session because it supports session regeneration (req.session.regenerate()) which is crucial for preventing session fixation attacks.
B. express-session because storing sessions in Redis is more secure than storing them in a client-side cookie.
C. cookie-session because it stores all session data in the cookie itself, eliminating the need for any server-side session store lookups, which aligns perfectly with the design goals.
D. cookie-session because it encrypts the cookie data, whereas express-session only stores a session ID in the cookie, making cookie-session inherently more secure.

47 You are implementing a Role-Based Access Control (RBAC) middleware in Express. The system has hierarchical roles: 'superadmin' can do everything an 'admin' can, and 'admin' can do everything a 'moderator' can. Given a user's role, the middleware must efficiently check if they have the required permission for a route. Which data structure and logic combination for representing and checking roles would be the most scalable and maintainable?

RBAC Hard
A. A flat map of roles to an array of permissions: const roles = { moderator: ['delete_comment'], admin: ['delete_comment', 'delete_post'] ... }. The check involves iterating through the array for the user's role.
B. A map of roles where each role inherits from a parent: const roles = { moderator: { permissions: new Set(['p1']) }, admin: { parent: 'moderator', permissions: new Set(['p2']) } }. The check requires traversing up the parent chain, collecting permissions.
C. A series of if/else if statements in the middleware: if (user.role === 'moderator' && required === 'moderator') {...} else if (user.role === 'admin' && (required === 'admin' || required === 'moderator')) {...}.
D. Store a numeric level for each role (moderator: 10, admin: 20, superadmin: 30). The middleware check is a simple numeric comparison: if (user.role.level >= required.level) { next(); }.

48 In the context of a Node.js WebSocket server, how does TCP's Nagle's algorithm potentially impact the real-time performance of a chat application sending many small, frequent messages, and what is the common method to mitigate this?

Understanding Network Sockets Hard
A. Nagle's algorithm improves performance by bundling small messages into a single TCP segment, reducing network overhead. No mitigation is needed.
B. Nagle's algorithm causes packet loss for small messages under network congestion. This is mitigated by implementing an application-level acknowledgment (ACK) system.
C. Nagle's algorithm encrypts each small packet individually, increasing CPU load. This is mitigated by using TLS session resumption.
D. Nagle's algorithm can introduce latency by delaying the transmission of small packets, waiting to see if more data will be sent. This can be mitigated by setting the TCP_NODELAY socket option to true.

49 Consider the following Express setup. Which middleware functions will execute for a GET request to /api/v1/users?

javascript
app.use('/api', middlewareA); // A
app.use('/api/v1', middlewareB); // B
app.get('/api/v1/users', handler); // C
app.use('/api/v2', middlewareD); // D

app.use() Hard
A. Only A and C
B. Only B and C
C. A, B, and C
D. A, B, C, and D

50 A junior developer implements JWT authentication using the jsonwebtoken library with the HS256 algorithm. They store the secret key in their source code. A senior developer insists on switching to RS256. What is the primary security advantage of using RS256 (asymmetric) over HS256 (symmetric) in a distributed system where a dedicated authentication service generates tokens and multiple resource services validate them?

JWT implementation Hard
A. Both B and C are significant advantages of RS256 in this architecture.
B. RS256 is a more computationally complex algorithm, making it harder to brute-force the token signature.
C. The RS256 public key can be safely exposed in a URL (e.g., a JWKS endpoint), whereas the HS256 secret must always be kept hidden.
D. The authentication service can sign tokens with its private key, while the resource services only need the public key to validate signatures. This prevents the resource services from being able to create valid tokens.

51 During the WebSocket handshake, the client sends a Sec-WebSocket-Key header. The server must respond with a Sec-WebSocket-Accept header. How is the value of the server's Sec-WebSocket-Accept header generated according to the WebSocket protocol (RFC 6455)?

Creating a basic WebSocket server Hard
A. It is the Sec-WebSocket-Key value encrypted with the server's private SSL/TLS key.
B. It is a SHA-1 hash of the Sec-WebSocket-Key value.
C. It is the Base64 encoding of the SHA-1 hash of the concatenation of the Sec-WebSocket-Key and a specific protocol GUID ('258EAFA5-E914-47DA-95CA-C5AB0DC85B11').
D. It is a completely random, cryptographically secure string generated by the server for each connection.

52 A Node.js WebSocket server is sending a large 10MB file to a client. To avoid buffering the entire file in memory, the server reads the file as a stream and sends it in chunks. However, the client is on a slow connection and its receive buffer fills up, causing the server's send buffer to also fill. In the ws library for Node.js, what is the correct way for the server to handle this backpressure and avoid crashing from excessive memory usage?

Sending and receiving messages Hard
A. The server should listen for the bufferfull event on the socket, and upon receiving it, destroy and reconnect the socket.
B. The socket.send() method returns false when the buffer is full. The server should pause the file stream and wait for the drain event on the socket before resuming.
C. The WebSocket protocol has no mechanism for backpressure; the server must implement its own throttling logic using setTimeout to pace the sending of chunks.
D. The socket.send() method will automatically handle backpressure by blocking the event loop until the client buffer has space.

53 In an Express application using cookie-parser, a developer wants to set a signed cookie to prevent client-side tampering. They write the following code:

javascript
const cookieParser = require('cookie-parser');
const secret = 'my-super-secret-key';
app.use(cookieParser(secret));

app.get('/set', (req, res) => {
res.cookie('user', 'admin', { signed: true });
res.send('Cookie set');
});

app.get('/get', (req, res) => {
// What should be logged here?
console.log(req.cookies.user, req.signedCookies.user);
res.send(req.signedCookies);
});


When a client makes a request to /get after visiting /set, what will be logged to the server's console?

cookie-parser Hard
A. s:admin.<signature>, admin
B. undefined, admin
C. admin, admin
D. admin, undefined

54 An asynchronous middleware in an Express app is designed to fetch user data from a database. Which of the following implementations correctly handles both success and potential database errors?

javascript
// A
app.use(async (req, res, next) => {
try {
req.user = await db.fetchUser(req.userId);
next();
} catch (err) {
next(err);
}
});

// B
app.use((req, res, next) => {
db.fetchUser(req.userId)
.then(user => { req.user = user; next(); })
.catch(err => next(err));
});

// C
app.use(async (req, res, next) => {
req.user = await db.fetchUser(req.userId);
next();
});

// D
app.use((req, res, next) => {
try {
db.fetchUser(req.userId, (err, user) => {
if (err) throw err;
req.user = user;
next();
});
} catch (err) {
next(err);
}
});

Implementing basic middleware Hard
A. Only A and B are correct.
B. Only D is correct.
C. All four (A, B, C, D) are correct.
D. Only A, B, and C are correct.

55 What is the primary use case for volatile events in Socket.IO, and what is the trade-off involved?

A Socket.IO Chat Server Hard
A. They are events that will be dropped if the underlying transport is not ready to send data (e.g., during a reconnection). The trade-off is performance (no buffering) for a lack of delivery guarantee.
B. They are events that are automatically retried by the client if a network disconnection occurs during transmission, but they increase latency.
C. They are high-priority messages that bypass the normal event queue to be sent immediately, but they consume more server CPU.
D. They are encrypted events that provide end-to-end security but require a pre-shared key between the client and server.

56 To mitigate Cross-Site Request Forgery (CSRF) in a traditional session-based Express application, the 'Double Submit Cookie' pattern is often used. How does this pattern work, and why is it effective against CSRF attacks?

Authentication and Security Hard
A. The server sets two identical cookies with the same session ID. A CSRF attack cannot succeed because the attacker does not know they need to forge two cookies.
B. The server sets an httpOnly session cookie and a separate, readable JavaScript cookie with a CSRF token. The client-side script reads the token from the cookie and includes it in a request header. The server then validates that the header token matches the one associated with the session.
C. On login, the server generates a random CSRF token and stores it in the user's session. For every state-changing request, the client must send this token as a parameter. The server matches the parameter with the session value.
D. The server generates a random token and sends it in both a cookie and an embedded hidden field in the HTML form. On submission, the server verifies that the token from the cookie and the token from the form body are identical.

57 When implementing Role-Based Access Control (RBAC) as an Express middleware, a common mistake can lead to security vulnerabilities. Consider the following faulty middleware meant to protect a route for 'admins' only. What is the critical security flaw?

javascript
function isAdmin(req, res, next) {
if (req.user.role === 'admin') {
next();
}
res.status(403).send('Forbidden');
}

RBAC Hard
A. It does not check if req.user or req.user.role exist, which could lead to a TypeError and crash the server.
B. The middleware does not handle asynchronous errors that might occur when checking the user's role.
C. The res.status(403).send() call happens even if the user is an admin because there is no return or else block after next().
D. It uses === for comparison which could fail for different data types, it should use ==.

58 What is the primary purpose of the Strict-Transport-Security (HSTS) header, and what is the significant, long-term implication of using its preload directive?

Security headers Hard
A. HSTS prevents cross-site scripting (XSS) attacks by disabling inline scripts. The preload directive caches this setting in the browser permanently.
B. HSTS prevents clickjacking by disallowing the site to be framed. The preload directive ensures this setting cannot be overridden by other headers.
C. HSTS enforces a strong Content Security Policy (CSP). The preload directive tells CDNs to cache and serve the policy, improving performance.
D. HSTS instructs the browser to only communicate with the server over HTTPS, preventing protocol downgrade attacks. The preload directive submits the domain to a global list hardcoded into browsers, forcing HTTPS for all future visitors even on their very first visit.

59 In what scenario would using app.all('/api/*', authMiddleware) be functionally and semantically superior to using app.use('/api', authMiddleware) for applying an authentication middleware?

app.all() Hard
A. app.use is more efficient as it is designed specifically for middleware.
B. There is no functional difference; they are aliases for each other.
C. app.all should be used when the middleware needs to modify the res object, whereas app.use is for req object modifications.
D. app.all applies the middleware only to routes that have been explicitly defined under /api/*, while app.use would apply it to any request whose path starts with /api, including potentially non-existent routes that would later result in a 404.

60 What happens in an Express application if a middleware function neither sends a response (e.g., res.send()) nor calls the next() function?

Introduction to middleware Hard
A. An error is thrown immediately, and the application's error handling middleware is invoked.
B. The request-response cycle is left in a hanging state, and the client will eventually time out.
C. The middleware function is popped from the stack, and the next middleware in the chain is automatically executed.
D. Express automatically calls next() after a timeout period to prevent stalls.