fastify-txstate 3.2.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts ADDED
@@ -0,0 +1,153 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { type FastifyDynamicSwaggerOptions } from '@fastify/swagger';
4
+ import { type FastifySwaggerUiOptions } from '@fastify/swagger-ui';
5
+ import type { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts';
6
+ import { type FastifyInstance, type FastifyRequest, type FastifyReply, type FastifyServerOptions, type FastifyLoggerOptions, type FastifyBaseLogger, type RawServerDefault } from 'fastify';
7
+ import http from 'node:http';
8
+ import type http2 from 'node:http2';
9
+ type ErrorHandler = (error: Error, req: FastifyRequest, res: FastifyReply) => Promise<void>;
10
+ export interface FastifyTxStateAuthInfo {
11
+ /**
12
+ * The primary identifier for the user that is making the request, after processing
13
+ * their session token / JWT.
14
+ */
15
+ username: string;
16
+ /**
17
+ * This should be an identifier for the particular session, so that the same user
18
+ * on different devices/browsers/tabs can be distinguished from one another.
19
+ *
20
+ * It should NOT be usable as a cookie or bearer token, as it will appear in logs. If you
21
+ * use JSON Web Tokens, an easy thing is to combine the username with the `iat` issued
22
+ * date to create something unique but not useful to attackers.
23
+ *
24
+ * For lookup tokens, you can do the same `${username}-${createdAt}` after looking up
25
+ * the session in your database.
26
+ *
27
+ * If all else fails, you can sha256 the session token with a salt.
28
+ */
29
+ sessionId: string;
30
+ /**
31
+ * Some authentication systems allow administrators to impersonate regular users, so that
32
+ * they can see what that user sees and troubleshoot issues. We still want to log the administrator
33
+ * with any actions they take while impersonating someone, for auditing purposes, so you should
34
+ * fill this field when applicable.
35
+ *
36
+ * This will also be available at `req.auth.impersonatedBy`, so it is possible for your API
37
+ * to implement complicated authorization rules based on whether a user is being impersonated.
38
+ * It sort of defeats the purpose of impersonation, but used sparingly it could prevent administrators
39
+ * from making mistakes.
40
+ */
41
+ impersonatedBy?: string;
42
+ /**
43
+ * If your API may be accessed by a different client application, such that the user is actually logged
44
+ * into that application instead of yours, but you accept that application's session tokens, filling
45
+ * this field can help log requests that are authenticated with the other application's token.
46
+ */
47
+ clientId?: string;
48
+ }
49
+ export interface FastifyTxStateOptions extends Partial<FastifyServerOptions> {
50
+ https?: http2.SecureServerOptions;
51
+ validOrigins?: string[];
52
+ validOriginHosts?: string[];
53
+ validOriginSuffixes?: string[];
54
+ skipOriginCheck?: boolean;
55
+ checkOrigin?: (req: FastifyRequest) => boolean;
56
+ /**
57
+ * Run an asynchronous function to check the health of the service.
58
+ *
59
+ * Return a non-empty error message to trigger unhealthy status.
60
+ *
61
+ * Setting a health message with setUnhealthy will override this and prevent it from being executed.
62
+ */
63
+ checkHealth?: () => Promise<string | {
64
+ status?: number;
65
+ message?: string;
66
+ } | undefined>;
67
+ /**
68
+ * Run an async function to get authentication information out of the request
69
+ * object. Should return an object with at least a username and sessionid (see FastifyTxStateAuthInfo
70
+ * for further detail).
71
+ *
72
+ * The return object will be added to the request object as `req.auth` for later
73
+ * use in your route handlers. It will also be added to the logs in production.
74
+ *
75
+ * IMPORTANT: It is not advisable to return excessive amounts of data here, nor anything
76
+ * particularly sensitive, since it will all be included in every log entry.
77
+ *
78
+ * If this function throws, the client will receive a 401 response.
79
+ */
80
+ authenticate?: <T extends FastifyTxStateAuthInfo>(req: FastifyRequest) => Promise<T | undefined>;
81
+ }
82
+ declare module 'fastify' {
83
+ interface FastifyRequest {
84
+ auth?: FastifyTxStateAuthInfo;
85
+ }
86
+ interface FastifyReply {
87
+ extraLogInfo: any;
88
+ }
89
+ }
90
+ export declare const devLogger: {
91
+ level: string;
92
+ info: (msg: any) => void;
93
+ error: {
94
+ (...data: any[]): void;
95
+ (message?: any, ...optionalParams: any[]): void;
96
+ };
97
+ debug: {
98
+ (...data: any[]): void;
99
+ (message?: any, ...optionalParams: any[]): void;
100
+ };
101
+ fatal: {
102
+ (...data: any[]): void;
103
+ (message?: any, ...optionalParams: any[]): void;
104
+ };
105
+ warn: {
106
+ (...data: any[]): void;
107
+ (message?: any, ...optionalParams: any[]): void;
108
+ };
109
+ trace: {
110
+ (...data: any[]): void;
111
+ (message?: any, ...optionalParams: any[]): void;
112
+ };
113
+ silent: (msg: any) => void;
114
+ child(bindings: any, options?: any): any;
115
+ };
116
+ export declare const prodLogger: FastifyLoggerOptions;
117
+ export default class Server {
118
+ protected config: FastifyTxStateOptions & {
119
+ http2?: true;
120
+ };
121
+ protected https: boolean;
122
+ protected errorHandlers: ErrorHandler[];
123
+ protected healthMessage?: string;
124
+ protected healthCallback?: () => Promise<string | {
125
+ status?: number;
126
+ message?: string;
127
+ } | undefined>;
128
+ protected shuttingDown: boolean;
129
+ protected sigHandler: (signal: any) => void;
130
+ protected validOrigins: Record<string, boolean>;
131
+ protected validOriginHosts: Record<string, boolean>;
132
+ protected validOriginSuffixes: Set<string>;
133
+ app: FastifyInstance<RawServerDefault, http.IncomingMessage, http.ServerResponse<http.IncomingMessage>, FastifyBaseLogger, JsonSchemaToTsProvider>;
134
+ constructor(config?: FastifyTxStateOptions & {
135
+ http2?: true;
136
+ });
137
+ start(port?: number): Promise<void>;
138
+ addErrorHandler(handler: ErrorHandler): void;
139
+ setUnhealthy(message: string): void;
140
+ setHealthy(): void;
141
+ setValidOrigins(origins: string[]): void;
142
+ setValidOriginHosts(hosts: string[]): void;
143
+ setValidOriginSuffixes(suffixes: string[]): void;
144
+ swagger(opts?: {
145
+ path?: string;
146
+ openapi?: FastifyDynamicSwaggerOptions['openapi'];
147
+ ui?: FastifySwaggerUiOptions;
148
+ }): Promise<void>;
149
+ close(softSeconds?: number): Promise<void>;
150
+ }
151
+ export * from './analytics';
152
+ export * from './error';
153
+ export * from './unified-auth';
package/lib/index.js CHANGED
@@ -21,6 +21,7 @@ exports.prodLogger = exports.devLogger = void 0;
21
21
  const swagger_1 = __importDefault(require("@fastify/swagger"));
22
22
  const swagger_ui_1 = __importDefault(require("@fastify/swagger-ui"));
23
23
  const ajv_errors_1 = __importDefault(require("ajv-errors"));
24
+ const ajv_formats_1 = __importDefault(require("ajv-formats"));
24
25
  const fastify_1 = require("fastify");
25
26
  const node_fs_1 = __importDefault(require("node:fs"));
26
27
  const node_http_1 = __importDefault(require("node:http"));
@@ -63,7 +64,7 @@ exports.prodLogger = {
63
64
  };
64
65
  class Server {
65
66
  constructor(config = {}) {
66
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
67
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
67
68
  this.config = config;
68
69
  this.https = false;
69
70
  this.errorHandlers = [];
@@ -99,7 +100,7 @@ class Server {
99
100
  else
100
101
  config.trustProxy = process.env.TRUST_PROXY;
101
102
  }
102
- config.ajv = { ...config.ajv, plugins: [...((_c = (_b = (_a = config.ajv) === null || _a === void 0 ? void 0 : _a.plugins) === null || _b === void 0 ? void 0 : _b.filter(p => p !== ajv_errors_1.default)) !== null && _c !== void 0 ? _c : []), ajv_errors_1.default], customOptions: { ...(_d = config.ajv) === null || _d === void 0 ? void 0 : _d.customOptions, allErrors: true, strictSchema: false } };
103
+ config.ajv = { ...config.ajv, plugins: [...((_b = (_a = config.ajv) === null || _a === void 0 ? void 0 : _a.plugins) !== null && _b !== void 0 ? _b : []), ajv_errors_1.default, [ajv_formats_1.default, { mode: 'fast' }]], customOptions: { ...(_c = config.ajv) === null || _c === void 0 ? void 0 : _c.customOptions, allErrors: true, strictSchema: false } };
103
104
  this.healthCallback = config.checkHealth;
104
105
  this.app = (0, fastify_1.fastify)(config);
105
106
  this.app.addHook('onRoute', route => {
@@ -135,9 +136,9 @@ class Server {
135
136
  route.schema = newSchema;
136
137
  });
137
138
  if (!config.skipOriginCheck && !process.env.SKIP_ORIGIN_CHECK) {
138
- this.setValidOrigins([...((_e = config.validOrigins) !== null && _e !== void 0 ? _e : []), ...((_g = (_f = process.env.VALID_ORIGINS) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [])]);
139
- this.setValidOriginHosts([...((_h = config.validOriginHosts) !== null && _h !== void 0 ? _h : []), ...((_k = (_j = process.env.VALID_ORIGIN_HOSTS) === null || _j === void 0 ? void 0 : _j.split(',')) !== null && _k !== void 0 ? _k : [])]);
140
- this.setValidOriginSuffixes([...((_l = config.validOriginSuffixes) !== null && _l !== void 0 ? _l : []), ...((_o = (_m = process.env.VALID_ORIGIN_SUFFIXES) === null || _m === void 0 ? void 0 : _m.split(',')) !== null && _o !== void 0 ? _o : [])]);
139
+ this.setValidOrigins([...((_d = config.validOrigins) !== null && _d !== void 0 ? _d : []), ...((_f = (_e = process.env.VALID_ORIGINS) === null || _e === void 0 ? void 0 : _e.split(',')) !== null && _f !== void 0 ? _f : [])]);
140
+ this.setValidOriginHosts([...((_g = config.validOriginHosts) !== null && _g !== void 0 ? _g : []), ...((_j = (_h = process.env.VALID_ORIGIN_HOSTS) === null || _h === void 0 ? void 0 : _h.split(',')) !== null && _j !== void 0 ? _j : [])]);
141
+ this.setValidOriginSuffixes([...((_k = config.validOriginSuffixes) !== null && _k !== void 0 ? _k : []), ...((_m = (_l = process.env.VALID_ORIGIN_SUFFIXES) === null || _l === void 0 ? void 0 : _l.split(',')) !== null && _m !== void 0 ? _m : [])]);
141
142
  this.app.addHook('preHandler', async (req, res) => {
142
143
  var _a, _b;
143
144
  res.extraLogInfo = {};
package/package.json CHANGED
@@ -1,16 +1,18 @@
1
1
  {
2
2
  "name": "fastify-txstate",
3
- "version": "3.2.0",
3
+ "version": "3.2.1",
4
4
  "description": "A small wrapper for fastify providing a set of common conventions & utility functions we use.",
5
5
  "exports": {
6
- "types": "./lib-esm/index.d.ts",
7
- "require": "./lib/index.js",
8
- "import": "./lib-esm/index.js"
6
+ ".": {
7
+ "types": "./lib/index.d.ts",
8
+ "require": "./lib/index.js",
9
+ "import": "./lib-esm/index.js"
10
+ }
9
11
  },
10
- "types": "./lib-esm/index.d.ts",
12
+ "types": "./lib/index.d.ts",
11
13
  "scripts": {
12
14
  "prepublishOnly": "npm run build",
13
- "build": "rm -rf lib && tsc && mv lib/index.d.ts lib-esm/index.d.ts",
15
+ "build": "rm -rf lib && tsc",
14
16
  "test": "./test.sh",
15
17
  "mocha": "TS_NODE_PROJECT=test/tsconfig.json mocha -r ts-node/register test/**/*.ts",
16
18
  "testserver": "node -r ts-node/register --no-warnings testserver/index.ts"
@@ -22,6 +24,7 @@
22
24
  "@fastify/type-provider-json-schema-to-ts": "^3.0.0",
23
25
  "@txstate-mws/fastify-shared": "^1.0.4",
24
26
  "ajv-errors": "^3.0.0",
27
+ "ajv-formats": "^2.1.1",
25
28
  "fastify": "^4.9.2",
26
29
  "fastify-plugin": "^4.5.1",
27
30
  "http-status-codes": "^2.1.4",