Skip to content

Commit 7f1a6e5

Browse files
chore(api): add request/response shadow dev tool (freeCodeCamp#56628)
1 parent 5385af0 commit 7f1a6e5

File tree

5 files changed

+150
-0
lines changed

5 files changed

+150
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,3 +210,6 @@ curriculum/build
210210
### Playwright ###
211211

212212
/playwright
213+
214+
### Shadow Testing Log Files Folder ###
215+
api/logs/

api/src/app.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import bouncer from './plugins/bouncer';
2727
import errorHandling from './plugins/error-handling';
2828
import csrf from './plugins/csrf';
2929
import notFound from './plugins/not-found';
30+
import shadowCapture from './plugins/shadow-capture';
31+
3032
import * as publicRoutes from './routes/public';
3133
import * as protectedRoutes from './routes/protected';
3234

@@ -35,6 +37,7 @@ import {
3537
EMAIL_PROVIDER,
3638
FCC_ENABLE_DEV_LOGIN_MODE,
3739
FCC_ENABLE_SWAGGER_UI,
40+
FCC_ENABLE_SHADOW_CAPTURE,
3841
FREECODECAMP_NODE_ENV
3942
} from './utils/env';
4043
import { isObjectID } from './utils/validation';
@@ -127,6 +130,10 @@ export const build = async (
127130
fastify.log.info(`Swagger UI available at ${API_LOCATION}/documentation`);
128131
}
129132

133+
if (FCC_ENABLE_SHADOW_CAPTURE) {
134+
void fastify.register(shadowCapture);
135+
}
136+
130137
void fastify.register(auth);
131138
void fastify.register(notFound);
132139
void fastify.register(prismaPlugin);

api/src/plugins/shadow-capture.ts

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import { randomUUID } from 'crypto';
2+
import { appendFileSync, mkdirSync } from 'fs';
3+
import { join } from 'path';
4+
import type { FastifyPluginCallback } from 'fastify';
5+
6+
import fp from 'fastify-plugin';
7+
import { FastifyReply } from 'fastify/types/reply';
8+
import { FastifyRequest } from 'fastify/types/request';
9+
10+
const LOGS_DIRECTORY = 'logs';
11+
const REQUEST_CAPTURE_FILE = 'request-capture.jsonl';
12+
const RESPONSE_CAPTURE_FILE = 'response-capture.jsonl';
13+
14+
let REQUEST_BUFFER: unknown[] = [];
15+
let RESPONSE_BUFFER: unknown[] = [];
16+
17+
/**
18+
* Plugin for capturing requests and responses to allow shadow testing.
19+
*
20+
* @param fastify The Fastify instance.
21+
* @param _options Options passed to the plugin via `fastify.register(plugin, options)`.
22+
* @param done Callback to signal that the logic has completed.
23+
*/
24+
const shadowCapture: FastifyPluginCallback = (fastify, _options, done) => {
25+
mkdirSync(LOGS_DIRECTORY, { recursive: true });
26+
fastify.addHook('onRequest', (req, rep, done) => {
27+
// Attach timestamp at beginning of lifecycle
28+
// @ts-expect-error Exists
29+
req.__timestamp = Date.now();
30+
31+
// Give request and response same id to match.
32+
const id = randomUUID();
33+
// @ts-expect-error Exists
34+
req.__id = id;
35+
// @ts-expect-error Exists
36+
rep.__id = id;
37+
done();
38+
});
39+
40+
// Body is only included after `Parsing` lifecycle
41+
fastify.addHook('preValidation', (req, rep, done) => {
42+
captureRequest(req);
43+
done();
44+
});
45+
46+
fastify.addHook('onSend', async (_req, rep, payload) => {
47+
// @ts-expect-error Exists
48+
rep.__payload = payload;
49+
return payload;
50+
});
51+
52+
fastify.addHook('onResponse', (_req, rep, done) => {
53+
captureReply(rep);
54+
done();
55+
});
56+
57+
done();
58+
};
59+
60+
/* eslint-disable @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-return */
61+
function captureRequest(req: FastifyRequest) {
62+
const savedRequest = {
63+
// @ts-expect-error Exists
64+
id: req.__id,
65+
// @ts-expect-error Exists
66+
timestamp: req.__timestamp,
67+
url: req.url,
68+
headers: omit(req.headers, 'cookie'),
69+
cookies: include(req.cookies, '_csrf', 'csrf_token', 'jwt_access_token'),
70+
user: req.user,
71+
body: req.body
72+
};
73+
74+
if (REQUEST_BUFFER.length > 10) {
75+
appendFileSync(
76+
join(LOGS_DIRECTORY, REQUEST_CAPTURE_FILE),
77+
REQUEST_BUFFER.map(rb => JSON.stringify(rb)).join('\n') + '\n'
78+
);
79+
REQUEST_BUFFER = [savedRequest];
80+
} else {
81+
REQUEST_BUFFER.push(savedRequest);
82+
}
83+
}
84+
85+
function captureReply(rep: FastifyReply) {
86+
const savedReply = {
87+
// @ts-expect-error Exists
88+
id: rep.__id,
89+
headers: rep.getHeaders(),
90+
timestamp: Date.now(),
91+
// @ts-expect-error Exists
92+
payload: rep.__payload,
93+
statusCode: rep.statusCode
94+
};
95+
96+
if (RESPONSE_BUFFER.length > 10) {
97+
appendFileSync(
98+
join(LOGS_DIRECTORY, RESPONSE_CAPTURE_FILE),
99+
RESPONSE_BUFFER.map(rb => JSON.stringify(rb)).join('\n') + '\n'
100+
);
101+
RESPONSE_BUFFER = [savedReply];
102+
} else {
103+
RESPONSE_BUFFER.push(savedReply);
104+
}
105+
}
106+
107+
/**
108+
* Returns a subset of the given object with the values or properties given removed.
109+
* @param obj - An array or an object literal.
110+
* @param vals - Items or properties to exclude from `obj`.
111+
* @returns Subset of `obj`.
112+
*/
113+
function omit(obj: Record<string, unknown> | unknown[], ...vals: unknown[]) {
114+
if (Array.isArray(obj)) {
115+
return obj.filter(o => !vals.includes(o));
116+
} else {
117+
return Object.keys(obj)
118+
.filter(k => {
119+
return !vals.includes(k);
120+
})
121+
.reduce((acc, curr) => ({ ...acc, [curr]: obj[curr] }), {});
122+
}
123+
}
124+
125+
function include(obj: Record<string, unknown> | unknown[], ...vals: unknown[]) {
126+
if (Array.isArray(obj)) {
127+
return obj.filter(o => vals.includes(o));
128+
} else {
129+
return Object.keys(obj)
130+
.filter(k => {
131+
return vals.includes(k);
132+
})
133+
.reduce((acc, curr) => ({ ...acc, [curr]: obj[curr] }), {});
134+
}
135+
}
136+
137+
export default fp(shadowCapture);

api/src/utils/env.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ export const FCC_ENABLE_SWAGGER_UI =
125125
process.env.FCC_ENABLE_SWAGGER_UI === 'true';
126126
export const FCC_ENABLE_DEV_LOGIN_MODE =
127127
process.env.FCC_ENABLE_DEV_LOGIN_MODE === 'true';
128+
export const FCC_ENABLE_SHADOW_CAPTURE =
129+
process.env.FCC_ENABLE_SHADOW_CAPTURE === 'true';
128130
export const SENTRY_DSN =
129131
process.env.SENTRY_DSN === 'dsn_from_sentry_dashboard'
130132
? ''

sample.env

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ NODE_ENV=development
6868
PORT=3000
6969
FCC_ENABLE_SWAGGER_UI=true
7070
FCC_ENABLE_DEV_LOGIN_MODE=true
71+
FCC_ENABLE_SHADOW_CAPTURE=false
7172

7273
# Email
7374
# use ses in production

0 commit comments

Comments
 (0)