|
| 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); |
0 commit comments