diff --git a/docs/docs/the-basics/coding-with-practica.md b/docs/docs/the-basics/coding-with-practica.md index 3ee4e804..61e1d6df 100644 --- a/docs/docs/the-basics/coding-with-practica.md +++ b/docs/docs/the-basics/coding-with-practica.md @@ -85,9 +85,10 @@ Now visit our [online POSTMAN collection](https://documenter.getpostman.com/view **Note:** The API routes authorize requests, a valid token must be provided. You may generate one yourself ([see here how](../questions-and-answers.md)), or just use the default _development_ token that we generated for you 👇. Put it inside an 'Authorization' header: -```Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2NjIwMTY5NjIsImV4cCI6MTY5MzU1Mjk2MiwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.65ACAjHy2ZE5i_uS5hyiEkOQfkqOqdj-WtBm-w23qZQ``` +```Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzM4NTIyMTk5NzEsImRhdGEiOnsidXNlciI6ImpvZSIsInJvbGVzIjoiYWRtaW4ifSwiaWF0IjoxNzEyMjUyMjE5fQ.kUS7AnwtGum40biJYt0oyOH_le1KfVD2EOrs-ozclY0``` We have the ground ready 🐥. Let's code now, just remember to run the tests (or POSTMAN) once in a while to ensure nothing breaks + ## The 3 layers of a component A typical component (e.g., Microservice) contains 3 main layers. This is a known and powerful pattern that is called ["3-Tiers"](https://www.techopedia.com/definition/24649/three-tier-architecture). It's an architectural structure that strikes a great balance between simplicity and robustness. Unlike other fancy architectures (e.g. hexagonal architecture, etc), this style is more likely to keep things simple and organized. The three layers represent the physical flow of a request with no abstractions: diff --git a/src/code-templates/libraries/common-fastify-plugins/lib/jwt-verifier/jwt-verifier-plugin.ts b/src/code-templates/libraries/common-fastify-plugins/lib/jwt-verifier/jwt-verifier-plugin.ts index 35c3299e..5af95cd8 100644 --- a/src/code-templates/libraries/common-fastify-plugins/lib/jwt-verifier/jwt-verifier-plugin.ts +++ b/src/code-templates/libraries/common-fastify-plugins/lib/jwt-verifier/jwt-verifier-plugin.ts @@ -46,6 +46,7 @@ const verifyTokenOnRequest = ( let token: string; // A token comes in one of two forms: 'token' or 'Bearer token' const authHeaderParts = authenticationHeader.split(' '); + if (authHeaderParts.length > 2) { // It should have 1 or 2 parts (separated by space), the incoming string has unknown structure return { success: false }; diff --git a/src/code-templates/libraries/error-handling/error-handler.ts b/src/code-templates/libraries/error-handling/error-handler.ts index 6a667c81..62c91005 100644 --- a/src/code-templates/libraries/error-handling/error-handler.ts +++ b/src/code-templates/libraries/error-handling/error-handler.ts @@ -33,6 +33,7 @@ export const errorHandler = { handleError: (errorToHandle: unknown): number => { try { + logger.info('Handling error1'); const appError: AppError = covertUnknownToAppError(errorToHandle); logger.error(appError.message, appError); metricsExporter.fireMetric('error', { errorName: appError.name }); // fire any custom metric when handling error diff --git a/src/code-templates/libraries/error-handling/fastify-error-middleware.ts b/src/code-templates/libraries/error-handling/fastify-error-middleware.ts index c92df727..4e31f683 100644 --- a/src/code-templates/libraries/error-handling/fastify-error-middleware.ts +++ b/src/code-templates/libraries/error-handling/fastify-error-middleware.ts @@ -10,6 +10,5 @@ export function fastifyErrorMiddleware( const standardAppError = covertUnknownToAppError(error); standardAppError.isCatastrophic = false; const responseToRequest = errorHandler.handleError(standardAppError); - reply.status(responseToRequest).send({}); } diff --git a/src/code-templates/libraries/error-handling/package.json b/src/code-templates/libraries/error-handling/package.json index 1e6382fd..1374c9d5 100644 --- a/src/code-templates/libraries/error-handling/package.json +++ b/src/code-templates/libraries/error-handling/package.json @@ -25,10 +25,12 @@ "typescript": "^5.2.2" }, "dependencies": { - "@practica/logger": "^0.0.1-alpha.4", + "@practica/logger": "^0.0.5", "jest": "^28.1.0", "jest-sinon": "^1.0.4", - "sinon": "^14.0.0", + "sinon": "^14.0.0" + }, + "peerDependencies": { "fastify": "4.24.3" } } diff --git a/src/code-templates/libraries/jwt-token-verifier/.npmignore b/src/code-templates/libraries/jwt-token-verifier/.npmignore deleted file mode 100644 index e69de29b..00000000 diff --git a/src/code-templates/libraries/jwt-token-verifier/index.ts b/src/code-templates/libraries/jwt-token-verifier/index.ts deleted file mode 100644 index 1e0b7a7c..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './lib/jwt-verifier-middleware'; diff --git a/src/code-templates/libraries/jwt-token-verifier/jest.config.js b/src/code-templates/libraries/jwt-token-verifier/jest.config.js deleted file mode 100644 index 87b1fb54..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/jest.config.js +++ /dev/null @@ -1,189 +0,0 @@ -/* - * For a detailed explanation regarding each configuration property and type check, visit: - * https://jestjs.io/docs/configuration - */ - -module.exports = { - // All imported modules in your tests should be mocked automatically - // automock: false, - - // Stop running tests after `n` failures - // bail: 0, - - // The directory where Jest should store its cached dependency information - // cacheDirectory: "/private/var/folders/fg/vsxql2fd4rgd8fppxfsgyjb40000gn/T/jest_dx", - - // Automatically clear mock calls, instances and results before every test - // clearMocks: false, - - // Indicates whether the coverage information should be collected while executing the test - collectCoverage: false, - - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: undefined, - - // The directory where Jest should output its coverage files - coverageDirectory: 'coverage', - - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "/node_modules/" - // ], - - // Indicates which provider should be used to instrument code for coverage - coverageProvider: 'v8', - - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], - - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: undefined, - - // A path to a custom dependency extractor - // dependencyExtractor: undefined, - - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, - - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], - - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: "./test/global-setup.js", - - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: "./test/global-teardown.js", - - // A set of global variables that need to be available in all test environments - // globals: {}, - - // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. - // maxWorkers: "50%", - - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], - - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "jsx", - // "ts", - // "tsx", - // "json", - // "node" - // ], - - // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], - - // Activates notifications for test results - notify: true, - - // An enum that specifies notification mode. Requires { notify: true } - notifyMode: 'change', - - // A preset that is used as a base for Jest's configuration - // preset: "ts-jest", - - // Run tests from one or more projects - // projects: undefined, - - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, - - // Automatically reset mock state before every test - // resetMocks: false, - - // Reset the module registry before running each individual test - // resetModules: false, - - // A path to a custom resolver - // resolver: undefined, - - // Automatically restore mock state and implementation before every test - // restoreMocks: false, - - // The root directory that Jest should scan for tests and modules within - // rootDir: undefined, - - // A list of paths to directories that Jest should use to search for files in - // roots: [ - // "" - // ], - - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", - - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], - - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], - - // The number of seconds after which a test is considered as slow and reported as such in the results. - // slowTestThreshold: 5, - - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], - - // The test environment that will be used for testing - testEnvironment: 'node', - - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, - - // Adds a location field to test results - // testLocationInResults: false, - - // The glob patterns Jest uses to detect test files - testMatch: ['**/*.test.ts'], - - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - testPathIgnorePatterns: ['/node_modules/'], - - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], - - // This option allows the use of a custom results processor - // testResultsProcessor: undefined, - - // This option allows use of a custom test runner - // testRunner: "jest-circus/runner", - - // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href - // testURL: "http://localhost", - - // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" - // timers: "real", - - // A map from regular expressions to paths to transformers - transform: { '^.+\\.(t|j)s$': 'ts-jest' }, - - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "/node_modules/", - // "\\.pnp\\.[^\\/]+$" - // ], - - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, - - // Indicates whether each individual test should be reported during the run - // verbose: undefined, - - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], - - // Whether to use watchman for file crawling - // watchman: true, -}; diff --git a/src/code-templates/libraries/jwt-token-verifier/lib/jwt-verifier-middleware.ts b/src/code-templates/libraries/jwt-token-verifier/lib/jwt-verifier-middleware.ts deleted file mode 100644 index df7ff3db..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/lib/jwt-verifier-middleware.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* eslint-disable consistent-return */ -import jwt, { VerifyErrors } from 'jsonwebtoken'; - -export type JWTOptions = { - secret: string; -}; - -export const jwtVerifierMiddleware = (options: JWTOptions) => { - // 🔒 TODO - Once your project is off a POC stage, change your JWT flow to async using JWKS - // Read more here: https://www.npmjs.com/package/jwks-rsa - const middleware = (req, res, next) => { - const authenticationHeader = - req.headers.authorization || req.headers.Authorization; - - if (!authenticationHeader) { - return res.sendStatus(401); - } - - let token: string; - - // A token comes in one of two forms: 'token' or 'Bearer token' - const authHeaderParts = authenticationHeader.split(' '); - if (authHeaderParts.length > 2) { - // It should have 1 or 2 parts (separated by space), the incoming string has unknown structure - return res.sendStatus(401); - } - if (authHeaderParts.length === 2) { - [, token] = authHeaderParts; - } else { - token = authenticationHeader; - } - - jwt.verify( - token, - options.secret, - // TODO: we should remove this any according to the library, jwtContent can not contain data property - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (err: VerifyErrors | null, jwtContent: any) => { - // TODO use logger to report the error here - - if (err) { - return res.sendStatus(401); - } - - req.user = jwtContent.data; - - next(); - } - ); - }; - return middleware; -}; diff --git a/src/code-templates/libraries/jwt-token-verifier/package.json b/src/code-templates/libraries/jwt-token-verifier/package.json deleted file mode 100644 index f8cfea21..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@practica/jwt-token-verifier", - "version": "0.0.2", - "description": "JWT for Practica", - "main": ".dist/index.js", - "scripts": { - "installDependencies": "npm install", - "build": "tsc", - "build:watch": "tsc --watch", - "test": "jest --forceExit", - "test:dev": "jest --silent --runInBand --watch" - }, - "dependencies": { - "jsonwebtoken": "^8.5.1" - }, - "keywords": [ - "jwt", - "authentication", - "practica", - "expressjs" - ], - "author": "Rashad Majali ", - "license": "ISC", - "devDependencies": { - "@types/jest": "^27.5.0", - "@types/jsonwebtoken": "^8.5.8", - "jest": "^28.0.3", - "nock": "^13.2.4", - "node-mocks-http": "^1.11.0", - "node-notifier": "^10.0.1", - "sinon": "^13.0.2", - "ts-jest": "^28.0.1", - "typescript": "4.6.4" - } -} diff --git a/src/code-templates/libraries/jwt-token-verifier/package/jest.config.js b/src/code-templates/libraries/jwt-token-verifier/package/jest.config.js deleted file mode 100644 index 87b1fb54..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/package/jest.config.js +++ /dev/null @@ -1,189 +0,0 @@ -/* - * For a detailed explanation regarding each configuration property and type check, visit: - * https://jestjs.io/docs/configuration - */ - -module.exports = { - // All imported modules in your tests should be mocked automatically - // automock: false, - - // Stop running tests after `n` failures - // bail: 0, - - // The directory where Jest should store its cached dependency information - // cacheDirectory: "/private/var/folders/fg/vsxql2fd4rgd8fppxfsgyjb40000gn/T/jest_dx", - - // Automatically clear mock calls, instances and results before every test - // clearMocks: false, - - // Indicates whether the coverage information should be collected while executing the test - collectCoverage: false, - - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: undefined, - - // The directory where Jest should output its coverage files - coverageDirectory: 'coverage', - - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "/node_modules/" - // ], - - // Indicates which provider should be used to instrument code for coverage - coverageProvider: 'v8', - - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], - - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: undefined, - - // A path to a custom dependency extractor - // dependencyExtractor: undefined, - - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, - - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], - - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: "./test/global-setup.js", - - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: "./test/global-teardown.js", - - // A set of global variables that need to be available in all test environments - // globals: {}, - - // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. - // maxWorkers: "50%", - - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], - - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "jsx", - // "ts", - // "tsx", - // "json", - // "node" - // ], - - // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], - - // Activates notifications for test results - notify: true, - - // An enum that specifies notification mode. Requires { notify: true } - notifyMode: 'change', - - // A preset that is used as a base for Jest's configuration - // preset: "ts-jest", - - // Run tests from one or more projects - // projects: undefined, - - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, - - // Automatically reset mock state before every test - // resetMocks: false, - - // Reset the module registry before running each individual test - // resetModules: false, - - // A path to a custom resolver - // resolver: undefined, - - // Automatically restore mock state and implementation before every test - // restoreMocks: false, - - // The root directory that Jest should scan for tests and modules within - // rootDir: undefined, - - // A list of paths to directories that Jest should use to search for files in - // roots: [ - // "" - // ], - - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", - - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], - - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], - - // The number of seconds after which a test is considered as slow and reported as such in the results. - // slowTestThreshold: 5, - - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], - - // The test environment that will be used for testing - testEnvironment: 'node', - - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, - - // Adds a location field to test results - // testLocationInResults: false, - - // The glob patterns Jest uses to detect test files - testMatch: ['**/*.test.ts'], - - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - testPathIgnorePatterns: ['/node_modules/'], - - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], - - // This option allows the use of a custom results processor - // testResultsProcessor: undefined, - - // This option allows use of a custom test runner - // testRunner: "jest-circus/runner", - - // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href - // testURL: "http://localhost", - - // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" - // timers: "real", - - // A map from regular expressions to paths to transformers - transform: { '^.+\\.(t|j)s$': 'ts-jest' }, - - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "/node_modules/", - // "\\.pnp\\.[^\\/]+$" - // ], - - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, - - // Indicates whether each individual test should be reported during the run - // verbose: undefined, - - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], - - // Whether to use watchman for file crawling - // watchman: true, -}; diff --git a/src/code-templates/libraries/jwt-token-verifier/package/lib/index.ts b/src/code-templates/libraries/jwt-token-verifier/package/lib/index.ts deleted file mode 100644 index d596e80d..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/package/lib/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './jwt-verifier-middleware'; diff --git a/src/code-templates/libraries/jwt-token-verifier/package/lib/jwt-verifier-middleware.ts b/src/code-templates/libraries/jwt-token-verifier/package/lib/jwt-verifier-middleware.ts deleted file mode 100644 index eef09eae..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/package/lib/jwt-verifier-middleware.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* eslint-disable consistent-return */ -import jwt, { VerifyErrors } from 'jsonwebtoken'; - -export type JWTOptions = { - secret: string; -}; - -export const jwtVerifierMiddleware = (options: JWTOptions) => { - // 🔒 TODO - Once your project is off a POC stage, change your JWT flow to async using JWKS - // Read more here: https://www.npmjs.com/package/jwks-rsa - const middleware = (req, res, next) => { - const authenticationHeader = - req.headers.authorization || req.headers.Authorization; - - if (!authenticationHeader) { - return res.sendStatus(401); - } - - let token: string; - - // A token comes in one of two forms: 'token' or 'Bearer token' - const authHeaderParts = authenticationHeader.split(' '); - if (authHeaderParts.length > 2) { - // It should have 1 or 2 parts (separated by space), the incoming string is not supported - return res.sendStatus(401); - } - - if (authHeaderParts.length === 2) { - [, token] = authHeaderParts; - } else { - token = authenticationHeader; - } - - jwt.verify( - token, - options.secret, - // TODO: we should remove this any according to the library, jwtContent can not contain data property - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (err: VerifyErrors | null, jwtContent: any) => { - // @todo: use logger and error handler here - // eslint-disable-next-line no-console - console.log(err); - - if (err) { - return res.sendStatus(401); - } - - req.user = jwtContent.data; - - next(); - } - ); - }; - return middleware; -}; diff --git a/src/code-templates/libraries/jwt-token-verifier/package/test/jwt-helper.ts b/src/code-templates/libraries/jwt-token-verifier/package/test/jwt-helper.ts deleted file mode 100644 index 4069aa0b..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/package/test/jwt-helper.ts +++ /dev/null @@ -1,30 +0,0 @@ -import jwt from 'jsonwebtoken'; - -export function signValidTokenWithDefaultUser() { - return internalSignTokenSynchronously('joe', 'admin', Date.now() + 60 * 60); -} - -export function signValidToken(user, role) { - return internalSignTokenSynchronously(user, role, Date.now() + 60 * 60); -} - -export function signExpiredToken(user, role) { - return internalSignTokenSynchronously(user, role, 0); -} - -function internalSignTokenSynchronously(user, roles, expirationInUnixTime) { - const token = jwt.sign( - { - exp: expirationInUnixTime, - data: { - user, - roles, - }, - }, - exampleSecret - ); - - return token; -} - -export const exampleSecret = 'secret'; diff --git a/src/code-templates/libraries/jwt-token-verifier/package/test/jwt.test.ts b/src/code-templates/libraries/jwt-token-verifier/package/test/jwt.test.ts deleted file mode 100644 index fa3edad8..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/package/test/jwt.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import * as httpMocks from 'node-mocks-http'; -import * as sinon from 'sinon'; -import { jwtVerifierMiddleware } from '../lib/jwt-verifier-middleware'; -import * as jwtHelper from './jwt-helper'; - -beforeEach(() => { - sinon.restore(); -}); - -describe('JWT middleware', () => { - test('When using a valid token with bearer, then should allow request and receive 200 response', async () => { - // Arrange - const validToken = jwtHelper.signValidToken('test-user', ['admin']); - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `Bearer ${validToken}` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(200); - expect(request.user).toEqual({ user: 'test-user', roles: ['admin'] }); - expect(nextFn.called).toBeTruthy(); - }); - - test('When using a valid token without bearer, then should allow request and receive 200 response', async () => { - // Arrange - const validToken = jwtHelper.signValidToken('test-user', ['admin']); - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `${validToken}` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(200); - expect(request.user).toEqual({ user: 'test-user', roles: ['admin'] }); - expect(nextFn.called).toBeTruthy(); - }); - - test('When using an empty token, then should receive unauthorized response', async () => { - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); - - test('When using an invalid multiword header, then receive unauthorized response', async () => { - // Arrange - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `Multiple words bearer one more` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); - - test('When using a fake unsigned token, then should receive unauthorized response', async () => { - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `Bearer Not-really-token-fake` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); - - test('When using an expired token, then should receive unauthorized response', async () => { - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const expiredToken = jwtHelper.signExpiredToken('test-user', ['admin']); - const headers = { Authorization: `Bearer ${expiredToken}` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); -}); diff --git a/src/code-templates/libraries/jwt-token-verifier/test/jwt-helper.ts b/src/code-templates/libraries/jwt-token-verifier/test/jwt-helper.ts deleted file mode 100644 index 4069aa0b..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/test/jwt-helper.ts +++ /dev/null @@ -1,30 +0,0 @@ -import jwt from 'jsonwebtoken'; - -export function signValidTokenWithDefaultUser() { - return internalSignTokenSynchronously('joe', 'admin', Date.now() + 60 * 60); -} - -export function signValidToken(user, role) { - return internalSignTokenSynchronously(user, role, Date.now() + 60 * 60); -} - -export function signExpiredToken(user, role) { - return internalSignTokenSynchronously(user, role, 0); -} - -function internalSignTokenSynchronously(user, roles, expirationInUnixTime) { - const token = jwt.sign( - { - exp: expirationInUnixTime, - data: { - user, - roles, - }, - }, - exampleSecret - ); - - return token; -} - -export const exampleSecret = 'secret'; diff --git a/src/code-templates/libraries/jwt-token-verifier/test/jwt.test.ts b/src/code-templates/libraries/jwt-token-verifier/test/jwt.test.ts deleted file mode 100644 index fa3edad8..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/test/jwt.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import * as httpMocks from 'node-mocks-http'; -import * as sinon from 'sinon'; -import { jwtVerifierMiddleware } from '../lib/jwt-verifier-middleware'; -import * as jwtHelper from './jwt-helper'; - -beforeEach(() => { - sinon.restore(); -}); - -describe('JWT middleware', () => { - test('When using a valid token with bearer, then should allow request and receive 200 response', async () => { - // Arrange - const validToken = jwtHelper.signValidToken('test-user', ['admin']); - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `Bearer ${validToken}` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(200); - expect(request.user).toEqual({ user: 'test-user', roles: ['admin'] }); - expect(nextFn.called).toBeTruthy(); - }); - - test('When using a valid token without bearer, then should allow request and receive 200 response', async () => { - // Arrange - const validToken = jwtHelper.signValidToken('test-user', ['admin']); - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `${validToken}` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(200); - expect(request.user).toEqual({ user: 'test-user', roles: ['admin'] }); - expect(nextFn.called).toBeTruthy(); - }); - - test('When using an empty token, then should receive unauthorized response', async () => { - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); - - test('When using an invalid multiword header, then receive unauthorized response', async () => { - // Arrange - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `Multiple words bearer one more` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); - - test('When using a fake unsigned token, then should receive unauthorized response', async () => { - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const headers = { Authorization: `Bearer Not-really-token-fake` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); - - test('When using an expired token, then should receive unauthorized response', async () => { - const jwtMiddleware = jwtVerifierMiddleware({ - secret: jwtHelper.exampleSecret, - }); - const expiredToken = jwtHelper.signExpiredToken('test-user', ['admin']); - const headers = { Authorization: `Bearer ${expiredToken}` }; - const request = httpMocks.createRequest({ - headers, - }); - const response = httpMocks.createResponse({ req: request }); - const nextFn = sinon.spy(); - - // Act - jwtMiddleware(request, response, nextFn); - - // Assert - expect(response.statusCode).toEqual(401); - expect({ nextCallCount: 0 }).toMatchObject({ - nextCallCount: nextFn.callCount, - }); - }); -}); diff --git a/src/code-templates/libraries/jwt-token-verifier/tsconfig.json b/src/code-templates/libraries/jwt-token-verifier/tsconfig.json deleted file mode 100644 index 275bf7a0..00000000 --- a/src/code-templates/libraries/jwt-token-verifier/tsconfig.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Projects */ - // "incremental": true, /* Enable incremental compilation */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ - // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - - /* Modules */ - "module": "commonjs" /* Specify what module code is generated. */, - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "resolveJsonModule": true, /* Enable importing .json files */ - // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ - "outDir": "./.dist" /* Specify an output folder for all emitted files. */, - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, - - /* Type Checking */ - "strict": true /* Enable all strict type-checking options. */, - "noImplicitAny": false /* Enable error reporting for expressions and declarations with an implied `any` type.. */, - // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ - // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } -} diff --git a/src/code-templates/libraries/logger/index.ts b/src/code-templates/libraries/logger/index.ts index 2d2d3245..0d2d44b5 100644 --- a/src/code-templates/libraries/logger/index.ts +++ b/src/code-templates/libraries/logger/index.ts @@ -7,7 +7,6 @@ export class LoggerWrapper implements Logger { #getInitializeLogger(): Logger { this.configureLogger({}, false); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.#underlyingLogger!; } diff --git a/src/code-templates/libraries/logger/package.json b/src/code-templates/libraries/logger/package.json index 8b6b7108..dc83b69e 100644 --- a/src/code-templates/libraries/logger/package.json +++ b/src/code-templates/libraries/logger/package.json @@ -1,8 +1,8 @@ { "name": "@practica/logger", - "version": "0.0.4", + "version": "0.0.5", "description": "", - "main": "./.dist/index.js", + "main": "./index.ts", "scripts": { "test": "jest --forceExit", "test:dev": "jest --watch --silent --runInBand", diff --git a/src/code-templates/package-lock.json b/src/code-templates/package-lock.json index 8acabc1c..dbbe28ba 100644 --- a/src/code-templates/package-lock.json +++ b/src/code-templates/package-lock.json @@ -137,8 +137,7 @@ "version": "0.0.3", "license": "ISC", "dependencies": { - "@practica/logger": "^0.0.1-alpha.4", - "fastify": "4.24.3", + "@practica/logger": "^0.0.5", "jest": "^28.1.0", "jest-sinon": "^1.0.4", "sinon": "^14.0.0" @@ -147,44 +146,9 @@ "@types/node": "^20.10.0", "ts-jest": "^28.0.3", "typescript": "^5.2.2" - } - }, - "libraries/error-handling/node_modules/@practica/configuration-provider": { - "version": "0.0.1-alpha.3", - "resolved": "https://registry.npmjs.org/@practica/configuration-provider/-/configuration-provider-0.0.1-alpha.3.tgz", - "integrity": "sha512-Jfx89WF9iI/g2Tmjgw7Vpu81Ta4a5mpGArWMDFRaUtMtolzV2RHIoF/0WAmvItPuxIG6JjwFdWp8osrhElKLNA==", - "dependencies": { - "convict": "^6.2.2" - } - }, - "libraries/error-handling/node_modules/@practica/logger": { - "version": "0.0.1-alpha.4", - "resolved": "https://registry.npmjs.org/@practica/logger/-/logger-0.0.1-alpha.4.tgz", - "integrity": "sha512-uLvuX5YA/hkz8eXg60mBwlMp5mWB7sm3mEKmTRTrZUOfmC5O0pOYULSKKNh8pqjXjplgiyFK4CdQ8W7MaqO0uA==", - "dependencies": { - "@practica/configuration-provider": "^0.0.1-alpha.1", - "pino": "^7.11.0" - } - }, - "libraries/error-handling/node_modules/pino": { - "version": "7.11.0", - "resolved": "https://registry.npmjs.org/pino/-/pino-7.11.0.tgz", - "integrity": "sha512-dMACeu63HtRLmCG8VKdy4cShCPKaYDR4youZqoSWLxl5Gu99HUw8bw75thbPv9Nip+H+QYX8o3ZJbTdVZZ2TVg==", - "dependencies": { - "atomic-sleep": "^1.0.0", - "fast-redact": "^3.0.0", - "on-exit-leak-free": "^0.2.0", - "pino-abstract-transport": "v0.5.0", - "pino-std-serializers": "^4.0.0", - "process-warning": "^1.0.0", - "quick-format-unescaped": "^4.0.3", - "real-require": "^0.1.0", - "safe-stable-stringify": "^2.1.0", - "sonic-boom": "^2.2.1", - "thread-stream": "^0.15.1" }, - "bin": { - "pino": "bin.js" + "peerDependencies": { + "fastify": "4.24.3" } }, "libraries/global-context": { @@ -215,60 +179,9 @@ "node": ">=4.2.0" } }, - "libraries/jwt-token-verifier": { - "name": "@practica/jwt-token-verifier", - "version": "0.0.2", - "license": "ISC", - "dependencies": { - "jsonwebtoken": "^8.5.1" - }, - "devDependencies": { - "@types/jest": "^27.5.0", - "@types/jsonwebtoken": "^8.5.8", - "jest": "^28.0.3", - "nock": "^13.2.4", - "node-mocks-http": "^1.11.0", - "node-notifier": "^10.0.1", - "sinon": "^13.0.2", - "ts-jest": "^28.0.1", - "typescript": "4.6.4" - } - }, - "libraries/jwt-token-verifier/node_modules/sinon": { - "version": "13.0.2", - "resolved": "https://registry.npmjs.org/sinon/-/sinon-13.0.2.tgz", - "integrity": "sha512-KvOrztAVqzSJWMDoxM4vM+GPys1df2VBoXm+YciyB/OLMamfS3VXh3oGh5WtrAGSzrgczNWFFY22oKb7Fi5eeA==", - "deprecated": "16.1.1", - "dev": true, - "dependencies": { - "@sinonjs/commons": "^1.8.3", - "@sinonjs/fake-timers": "^9.1.2", - "@sinonjs/samsam": "^6.1.1", - "diff": "^5.0.0", - "nise": "^5.1.1", - "supports-color": "^7.2.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/sinon" - } - }, - "libraries/jwt-token-verifier/node_modules/typescript": { - "version": "4.6.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.6.4.tgz", - "integrity": "sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=4.2.0" - } - }, "libraries/logger": { "name": "@practica/logger", - "version": "0.0.4", + "version": "0.0.5", "license": "ISC", "dependencies": { "@practica/configuration-provider": "^0.0.1-alpha.1", @@ -2670,10 +2583,6 @@ "resolved": "libraries/global-context", "link": true }, - "node_modules/@practica/jwt-token-verifier": { - "resolved": "libraries/jwt-token-verifier", - "link": true - }, "node_modules/@practica/logger": { "resolved": "libraries/logger", "link": true @@ -2895,9 +2804,9 @@ } }, "node_modules/@types/express-serve-static-core": { - "version": "4.17.43", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.43.tgz", - "integrity": "sha512-oaYtiBirUOPQGSWNGPWnzyAFJ0BP3cwvN4oWZQY+zUBwpVIGsKUkpBpSztp74drYcjavs7SKFZ4DX1V2QeN8rg==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.0.tgz", + "integrity": "sha512-bGyep3JqPCRry1wq+O5n7oiBgGWmeIJXPjXXCo8EK0u8duZGSYar7cGqd3ML2JUsLGeB7fmc06KYo9fLGWqPvQ==", "dev": true, "dependencies": { "@types/node": "*", @@ -4299,9 +4208,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001605", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001605.tgz", - "integrity": "sha512-nXwGlFWo34uliI9z3n6Qc0wZaf7zaZWA1CPZ169La5mV3I/gem7bst0vr5XQH5TJXZIMfDeZyOrZnSlVzKxxHQ==", + "version": "1.0.30001606", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001606.tgz", + "integrity": "sha512-LPbwnW4vfpJId225pwjZJOgX1m9sGfbw/RKJvw/t0QhYOOaTXHvkjVGFGPpvwEzufrjvTlsULnVTxdy4/6cqkg==", "funding": [ { "type": "opencollective", @@ -5774,6 +5683,7 @@ "version": "4.1.3", "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", + "dev": true, "dependencies": { "end-of-stream": "^1.4.1", "inherits": "^2.0.3", @@ -5785,6 +5695,7 @@ "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -5798,6 +5709,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, "dependencies": { "safe-buffer": "~5.2.0" } @@ -5855,9 +5767,9 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, "node_modules/electron-to-chromium": { - "version": "1.4.726", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.726.tgz", - "integrity": "sha512-xtjfBXn53RORwkbyKvDfTajtnTp0OJoPOIBzXvkNbb7+YYvCHJflba3L7Txyx/6Fov3ov2bGPr/n5MTixmPhdQ==" + "version": "1.4.728", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.728.tgz", + "integrity": "sha512-Ud1v7hJJYIqehlUJGqR6PF1Ek8l80zWwxA6nGxigBsGJ9f9M2fciHyrIiNMerSHSH3p+0/Ia7jIlnDkt41h5cw==" }, "node_modules/emittery": { "version": "0.8.1", @@ -5888,6 +5800,7 @@ "version": "1.4.4", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dev": true, "dependencies": { "once": "^1.4.0" } @@ -6919,11 +6832,6 @@ "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-4.5.1.tgz", "integrity": "sha512-stRHYGeuqpEZTL1Ef0Ovr2ltazUT9g844X5z/zEBFLG8RYlpDiOCIG+ATvYEp+/zmc7sN29mcIMp8gvYplYPIQ==" }, - "node_modules/fastify/node_modules/process-warning": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-2.3.2.tgz", - "integrity": "sha512-n9wh8tvBe5sFmsqlg+XQhaQLumwpqoAUruLwjCopgTmUBjJ/fjtBsJzKleCaIGBOMXYEhp1YfKl4d7rJ5ZKJGA==" - }, "node_modules/fastq": { "version": "1.17.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", @@ -11514,9 +11422,12 @@ "dev": true }, "node_modules/on-exit-leak-free": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-0.2.0.tgz", - "integrity": "sha512-dqaz3u44QbRXQooZLTUKU41ZrzYrcvLISVgbrzbyCMxpmSLJvZ3ZamIJIZ29P6OhZIkNIQKosdeM6t1LYbA9hg==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "engines": { + "node": ">=14.0.0" + } }, "node_modules/on-finished": { "version": "2.4.1", @@ -11916,14 +11827,37 @@ } }, "node_modules/pino-abstract-transport": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-0.5.0.tgz", - "integrity": "sha512-+KAgmVeqXYbTtU2FScx1XS3kNyfZ5TrXY07V96QnUSFqo2gAqlvmaxH67Lj7SWazqsMabf+58ctdTcBgnOLUOQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-1.1.0.tgz", + "integrity": "sha512-lsleG3/2a/JIWUtf9Q5gUNErBqwIu1tUKTT3dUzaf5DySw9ra1wcqKjJjLX1VTY64Wk1eEOYsVGSaGfCK85ekA==", "dependencies": { - "duplexify": "^4.1.2", + "readable-stream": "^4.0.0", "split2": "^4.0.0" } }, + "node_modules/pino-abstract-transport/node_modules/readable-stream": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/pino-abstract-transport/node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/pino-pretty": { "version": "7.6.1", "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-7.6.1.tgz", @@ -11948,6 +11882,22 @@ "pino-pretty": "bin.js" } }, + "node_modules/pino-pretty/node_modules/on-exit-leak-free": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-0.2.0.tgz", + "integrity": "sha512-dqaz3u44QbRXQooZLTUKU41ZrzYrcvLISVgbrzbyCMxpmSLJvZ3ZamIJIZ29P6OhZIkNIQKosdeM6t1LYbA9hg==", + "dev": true + }, + "node_modules/pino-pretty/node_modules/pino-abstract-transport": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-0.5.0.tgz", + "integrity": "sha512-+KAgmVeqXYbTtU2FScx1XS3kNyfZ5TrXY07V96QnUSFqo2gAqlvmaxH67Lj7SWazqsMabf+58ctdTcBgnOLUOQ==", + "dev": true, + "dependencies": { + "duplexify": "^4.1.2", + "split2": "^4.0.0" + } + }, "node_modules/pino-pretty/node_modules/readable-stream": { "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", @@ -11962,6 +11912,15 @@ "node": ">= 6" } }, + "node_modules/pino-pretty/node_modules/sonic-boom": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-2.8.0.tgz", + "integrity": "sha512-kuonw1YOYYNOve5iHdSahXPOK49GqwA+LZhI6Wz/l0rP57iKyXXIHaRagOBHAPmGwJC6od2Z9zgvZ5loSgMlVg==", + "dev": true, + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, "node_modules/pino-pretty/node_modules/string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -11972,28 +11931,6 @@ } }, "node_modules/pino-std-serializers": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-4.0.0.tgz", - "integrity": "sha512-cK0pekc1Kjy5w9V2/n+8MkZwusa6EyyxfeQCB799CQRhRt/CqYKiWs5adeu8Shve2ZNffvfC/7J64A2PJo1W/Q==" - }, - "node_modules/pino/node_modules/on-exit-leak-free": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", - "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/pino/node_modules/pino-abstract-transport": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-1.1.0.tgz", - "integrity": "sha512-lsleG3/2a/JIWUtf9Q5gUNErBqwIu1tUKTT3dUzaf5DySw9ra1wcqKjJjLX1VTY64Wk1eEOYsVGSaGfCK85ekA==", - "dependencies": { - "readable-stream": "^4.0.0", - "split2": "^4.0.0" - } - }, - "node_modules/pino/node_modules/pino-std-serializers": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-6.2.2.tgz", "integrity": "sha512-cHjPPsE+vhj/tnhCy/wiMh3M3z3h/j15zHQX+S9GkTBgqJuTuJzYJ4gUyACLhDaJ7kk9ba9iRDmbH2tJU03OiA==" @@ -12003,53 +11940,6 @@ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz", "integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==" }, - "node_modules/pino/node_modules/readable-stream": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", - "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", - "dependencies": { - "abort-controller": "^3.0.0", - "buffer": "^6.0.3", - "events": "^3.3.0", - "process": "^0.11.10", - "string_decoder": "^1.3.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, - "node_modules/pino/node_modules/real-require": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", - "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", - "engines": { - "node": ">= 12.13.0" - } - }, - "node_modules/pino/node_modules/sonic-boom": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.8.0.tgz", - "integrity": "sha512-ybz6OYOUjoQQCQ/i4LU8kaToD8ACtYP+Cj5qd2AO36bwbdewxWJ3ArmJ2cr6AvxlL2o0PqnCcPGUgkILbfkaCA==", - "dependencies": { - "atomic-sleep": "^1.0.0" - } - }, - "node_modules/pino/node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/pino/node_modules/thread-stream": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-2.4.1.tgz", - "integrity": "sha512-d/Ex2iWd1whipbT681JmTINKw0ZwOUBZm7+Gjs64DHuX34mmw8vJL2bFAaNacaW72zYiTJxSHi5abUuOi5nsfg==", - "dependencies": { - "real-require": "^0.2.0" - } - }, "node_modules/pirates": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", @@ -12210,9 +12100,9 @@ } }, "node_modules/process-warning": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-1.0.0.tgz", - "integrity": "sha512-du4wfLyj4yCZq1VupnVSZmRsPJsNuxoDQFdCFHLaYiEbFBD7QE0a+I4D7hOxrVnh78QE/YipFAj9lXHiXocV+Q==" + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-2.3.2.tgz", + "integrity": "sha512-n9wh8tvBe5sFmsqlg+XQhaQLumwpqoAUruLwjCopgTmUBjJ/fjtBsJzKleCaIGBOMXYEhp1YfKl4d7rJ5ZKJGA==" }, "node_modules/prompts": { "version": "2.4.2", @@ -12400,9 +12290,9 @@ } }, "node_modules/real-require": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.1.0.tgz", - "integrity": "sha512-r/H9MzAWtrv8aSVjPCMFpDMl5q66GqtmmRkRjpHTsp4zBAa+snZyiQNlMONiUmEJcsnaw0wCauJ2GWODr/aFkg==", + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", "engines": { "node": ">= 12.13.0" } @@ -13034,9 +12924,9 @@ } }, "node_modules/sonic-boom": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-2.8.0.tgz", - "integrity": "sha512-kuonw1YOYYNOve5iHdSahXPOK49GqwA+LZhI6Wz/l0rP57iKyXXIHaRagOBHAPmGwJC6od2Z9zgvZ5loSgMlVg==", + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.8.1.tgz", + "integrity": "sha512-y4Z8LCDBuum+PBP3lSV7RHrXscqksve/bi0as7mhwVnBW+/wUqKT/2Kb7um8yqcFy0duYbbPxzt89Zy2nOCaxg==", "dependencies": { "atomic-sleep": "^1.0.0" } @@ -13102,7 +12992,8 @@ "node_modules/stream-shift": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", - "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==" + "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==", + "dev": true }, "node_modules/string_decoder": { "version": "0.10.31", @@ -13388,11 +13279,11 @@ "dev": true }, "node_modules/thread-stream": { - "version": "0.15.2", - "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-0.15.2.tgz", - "integrity": "sha512-UkEhKIg2pD+fjkHQKyJO3yoIvAP3N6RlNFt2dUhcS1FGvCD1cQa1M/PGknCLFIyZdtJOWQjejp7bdNqmN7zwdA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-2.4.1.tgz", + "integrity": "sha512-d/Ex2iWd1whipbT681JmTINKw0ZwOUBZm7+Gjs64DHuX34mmw8vJL2bFAaNacaW72zYiTJxSHi5abUuOi5nsfg==", "dependencies": { - "real-require": "^0.1.0" + "real-require": "^0.2.0" } }, "node_modules/throat": { @@ -14049,7 +13940,8 @@ "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true }, "node_modules/utils-merge": { "version": "1.0.1", @@ -14413,7 +14305,7 @@ "@practica/common-fastify-plugins": "^0.0.1", "@practica/configuration-provider": "^0.0.2", "@practica/error-handling": "^0.0.3", - "@practica/logger": "^0.0.4", + "@practica/logger": "^0.0.5", "@practica/validation": "^0.0.3", "@prisma/client": "^4.6.1", "@sinclair/typebox": "^0.31.28", diff --git a/src/code-templates/services/order-service/entry-points-fastify/api/server.ts b/src/code-templates/services/order-service/entry-points-fastify/api/server.ts index f2662c7f..1aed6419 100644 --- a/src/code-templates/services/order-service/entry-points-fastify/api/server.ts +++ b/src/code-templates/services/order-service/entry-points-fastify/api/server.ts @@ -22,7 +22,6 @@ export async function startWebServer(): Promise { const app = Fastify({ logger: true, }); - app.setErrorHandler(fastifyErrorMiddleware); await generateOpenAPI(app); registerCommonPlugins(app); diff --git a/src/code-templates/services/order-service/package.json b/src/code-templates/services/order-service/package.json index edf2c393..4506ac2a 100644 --- a/src/code-templates/services/order-service/package.json +++ b/src/code-templates/services/order-service/package.json @@ -30,7 +30,7 @@ "@practica/common-fastify-plugins": "^0.0.1", "@practica/configuration-provider": "^0.0.2", "@practica/error-handling": "^0.0.3", - "@practica/logger": "^0.0.4", + "@practica/logger": "^0.0.5", "@practica/validation": "^0.0.3", "@prisma/client": "^4.6.1", "@sinclair/typebox": "^0.31.28", diff --git a/src/code-templates/services/order-service/test/test-helpers.ts b/src/code-templates/services/order-service/test/test-helpers.ts index 6ba979cb..dd9966b3 100644 --- a/src/code-templates/services/order-service/test/test-helpers.ts +++ b/src/code-templates/services/order-service/test/test-helpers.ts @@ -14,7 +14,11 @@ export const getAxiosInstance = (address) => { }; export function signValidTokenWithDefaultUser() { - return internalSignTokenSynchronously('joe', 'admin', Date.now() + 60 * 60); + return internalSignTokenSynchronously( + 'joe', + 'admin', + Date.now() + 60 * 60 * 60 * 100000 + ); } export function signValidToken(user, role) { @@ -40,4 +44,4 @@ function internalSignTokenSynchronously(user, roles, expirationInUnixTime) { return token; } -export const exampleSecret = 'secret'; +export const exampleSecret = 'just-a-default-secret';