nestlens 0.9.7 → 0.10.0

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.
Files changed (107) hide show
  1. package/dist/api/dashboard-server.d.ts +62 -0
  2. package/dist/api/dashboard-server.js +244 -0
  3. package/dist/api/index.d.ts +1 -0
  4. package/dist/api/index.js +1 -0
  5. package/dist/core/collector.service.d.ts +8 -0
  6. package/dist/core/collector.service.js +8 -0
  7. package/dist/core/data-masker.service.d.ts +21 -6
  8. package/dist/core/data-masker.service.js +75 -12
  9. package/dist/core/masking-terms.d.ts +30 -0
  10. package/dist/core/masking-terms.js +21 -0
  11. package/dist/core/sampling.d.ts +41 -0
  12. package/dist/core/sampling.js +54 -0
  13. package/dist/core/sanitized-payload.d.ts +9 -0
  14. package/dist/core/sanitized-payload.js +42 -0
  15. package/dist/core/storage/memory.storage.d.ts +26 -0
  16. package/dist/core/storage/memory.storage.js +37 -8
  17. package/dist/dashboard/public/assets/{BatchDetailView-BVwqprXl.js → BatchDetailView-OHEP4EJE.js} +1 -1
  18. package/dist/dashboard/public/assets/{BatchesPage-D6Y-VbZW.js → BatchesPage-4A8E53WI.js} +1 -1
  19. package/dist/dashboard/public/assets/{CacheDetailView-DAKwW79l.js → CacheDetailView-Dg0Uog4A.js} +1 -1
  20. package/dist/dashboard/public/assets/{CachePage-D3ZAuKbE.js → CachePage-CSk-oJmA.js} +1 -1
  21. package/dist/dashboard/public/assets/{CommandDetailView-DUlOruy-.js → CommandDetailView-C8XSw30M.js} +1 -1
  22. package/dist/dashboard/public/assets/{CommandsPage-8Ly-1pVn.js → CommandsPage-HTadvAan.js} +1 -1
  23. package/dist/dashboard/public/assets/{CopyButton-CCiHK8SA.js → CopyButton-BAPIvnms.js} +1 -1
  24. package/dist/dashboard/public/assets/{DashboardPage-HQJ5EqZi.js → DashboardPage-Dg9R9N6e.js} +1 -1
  25. package/dist/dashboard/public/assets/{DataTable-IY4rgbLi.js → DataTable-I_pOB_dU.js} +1 -1
  26. package/dist/dashboard/public/assets/{DetailRow-BrSIGemm.js → DetailRow-BJpWENam.js} +1 -1
  27. package/dist/dashboard/public/assets/{DumpDetailView-Df-ygu8R.js → DumpDetailView-liV4M1Tm.js} +1 -1
  28. package/dist/dashboard/public/assets/{DumpsPage-DX7kzOSi.js → DumpsPage-DvJs2qEc.js} +1 -1
  29. package/dist/dashboard/public/assets/{EntryDetailPage-CvuUpMuM.js → EntryDetailPage-4TXR22IQ.js} +3 -3
  30. package/dist/dashboard/public/assets/{EntrySearchInput-Cep2-s2v.js → EntrySearchInput-BtDhCEYy.js} +1 -1
  31. package/dist/dashboard/public/assets/{EventDetailView-DTTwJXmG.js → EventDetailView-CPWggB-6.js} +1 -1
  32. package/dist/dashboard/public/assets/{EventsPage-DDPJ2rMk.js → EventsPage-Cc6sNFrT.js} +1 -1
  33. package/dist/dashboard/public/assets/{ExceptionDetailView-IU2r55Ep.js → ExceptionDetailView-CB_7IQK2.js} +1 -1
  34. package/dist/dashboard/public/assets/{ExceptionsPage-DBYRnysW.js → ExceptionsPage-BjohVGjI.js} +1 -1
  35. package/dist/dashboard/public/assets/{GateDetailView-Dk4Dflc1.js → GateDetailView-G556MQ4j.js} +1 -1
  36. package/dist/dashboard/public/assets/{GatesPage-CbZbVBab.js → GatesPage-C0OJdWiH.js} +1 -1
  37. package/dist/dashboard/public/assets/{GraphQLDetailView-CkaJ573i.js → GraphQLDetailView-BoUScdHu.js} +1 -1
  38. package/dist/dashboard/public/assets/{GraphQLPage-CT1lBIqP.js → GraphQLPage-MRkzqOku.js} +1 -1
  39. package/dist/dashboard/public/assets/{HttpClientDetailView-uzkJ0a2W.js → HttpClientDetailView-v4KjJ3M3.js} +1 -1
  40. package/dist/dashboard/public/assets/{HttpClientPage-UVqfS3lX.js → HttpClientPage-oBgNLYoM.js} +1 -1
  41. package/dist/dashboard/public/assets/{JobDetailView-Bw_G0h-k.js → JobDetailView-Oh4QxHuV.js} +1 -1
  42. package/dist/dashboard/public/assets/{JobsPage-BehPu36v.js → JobsPage-CZuI-ty_.js} +1 -1
  43. package/dist/dashboard/public/assets/{LogDetailView-C4zHaxtW.js → LogDetailView-DWeM3NRs.js} +1 -1
  44. package/dist/dashboard/public/assets/{LogsPage-rc3m7U7I.js → LogsPage-BQpZY0u2.js} +1 -1
  45. package/dist/dashboard/public/assets/{MailDetailView-C0agIRwB.js → MailDetailView-By51HMbn.js} +1 -1
  46. package/dist/dashboard/public/assets/{MailPage-DKkMqiyO.js → MailPage-Cft1XE-8.js} +1 -1
  47. package/dist/dashboard/public/assets/{ModelDetailView-ezmk3atr.js → ModelDetailView-DZS_vBVa.js} +1 -1
  48. package/dist/dashboard/public/assets/{ModelsPage-BHnRG1du.js → ModelsPage-CZydqfSq.js} +1 -1
  49. package/dist/dashboard/public/assets/{NotificationDetailView-BRxW--Ek.js → NotificationDetailView-BftIOSac.js} +1 -1
  50. package/dist/dashboard/public/assets/{NotificationsPage-BrTG1nga.js → NotificationsPage-C3nm7MhW.js} +1 -1
  51. package/dist/dashboard/public/assets/{PageHeader-CA02rA6z.js → PageHeader-DXlayfuf.js} +1 -1
  52. package/dist/dashboard/public/assets/{QueriesPage-kGgFPHUq.js → QueriesPage-Ci9_loTF.js} +1 -1
  53. package/dist/dashboard/public/assets/{QueryDetailView-BuP7IA2L.js → QueryDetailView-8TJGdLgB.js} +1 -1
  54. package/dist/dashboard/public/assets/{RedisDetailView-CnhWC0Lh.js → RedisDetailView-B0e_VEEA.js} +1 -1
  55. package/dist/dashboard/public/assets/{RedisPage-BSyT0Q7O.js → RedisPage-C7oQHi2e.js} +1 -1
  56. package/dist/dashboard/public/assets/{RequestDetailView-Nb4Miizp.js → RequestDetailView-CeUQruUe.js} +1 -1
  57. package/dist/dashboard/public/assets/{RequestsPage-ExHuUYNY.js → RequestsPage-B47UuIis.js} +1 -1
  58. package/dist/dashboard/public/assets/{ScheduleDetailView-sPecJ0Wy.js → ScheduleDetailView-CqXLiQIh.js} +1 -1
  59. package/dist/dashboard/public/assets/{SchedulePage-BqISID5x.js → SchedulePage-DOgC2i20.js} +1 -1
  60. package/dist/dashboard/public/assets/{UserCard-Ds2eFQ5u.js → UserCard-CQuSJVMQ.js} +1 -1
  61. package/dist/dashboard/public/assets/{ViewDetailView-B-euVoGK.js → ViewDetailView-jP5GzjsR.js} +1 -1
  62. package/dist/dashboard/public/assets/{ViewsPage-Czow9YAd.js → ViewsPage-CnW3nbmf.js} +1 -1
  63. package/dist/dashboard/public/assets/{calendar-DjIv6CVc.js → calendar-_FdO9hEG.js} +1 -1
  64. package/dist/dashboard/public/assets/{circle-alert-YrNLnEY3.js → circle-alert-ixD_mUrj.js} +1 -1
  65. package/dist/dashboard/public/assets/{circle-check-big-DArmNZLQ.js → circle-check-big-BhBOqv5N.js} +1 -1
  66. package/dist/dashboard/public/assets/{circle-x-BAiU-N3B.js → circle-x-D8zZLF65.js} +1 -1
  67. package/dist/dashboard/public/assets/{eye-DMeWKkCr.js → eye-BaOzqvYb.js} +1 -1
  68. package/dist/dashboard/public/assets/{index-CCIS1AbN.js → index-B1zEwzCO.js} +2 -2
  69. package/dist/dashboard/public/assets/{search-CtGPQIEG.js → search-B8t3Uc43.js} +1 -1
  70. package/dist/dashboard/public/assets/{send-BjuXpyOz.js → send-0u7_FljH.js} +1 -1
  71. package/dist/dashboard/public/assets/{timer-C0_HYkkd.js → timer-CNv17rPG.js} +1 -1
  72. package/dist/dashboard/public/assets/{types-DTQLegxJ.js → types-qB4a6tUe.js} +1 -1
  73. package/dist/dashboard/public/assets/{users-CUxyUz2K.js → users-Bhj4UkIk.js} +1 -1
  74. package/dist/dashboard/public/assets/{zap-DzO0l81l.js → zap-BE6UnUHh.js} +1 -1
  75. package/dist/dashboard/public/index.html +1 -1
  76. package/dist/index.d.ts +2 -1
  77. package/dist/index.js +0 -1
  78. package/dist/nestlens.config.d.ts +159 -11
  79. package/dist/nestlens.config.js +5 -0
  80. package/dist/nestlens.module.js +25 -10
  81. package/dist/types/entry.types.d.ts +5 -1
  82. package/dist/watchers/batch.watcher.js +2 -2
  83. package/dist/watchers/cache.watcher.js +2 -2
  84. package/dist/watchers/command.watcher.js +2 -2
  85. package/dist/watchers/dump.watcher.js +2 -2
  86. package/dist/watchers/event.watcher.js +2 -2
  87. package/dist/watchers/exception.watcher.js +2 -2
  88. package/dist/watchers/gate.watcher.js +2 -2
  89. package/dist/watchers/graphql/graphql.watcher.js +5 -1
  90. package/dist/watchers/graphql/types.d.ts +1 -1
  91. package/dist/watchers/graphql/types.js +41 -3
  92. package/dist/watchers/graphql/utils/variable-sanitizer.d.ts +5 -0
  93. package/dist/watchers/graphql/utils/variable-sanitizer.js +339 -30
  94. package/dist/watchers/http-client.watcher.js +2 -2
  95. package/dist/watchers/job.watcher.js +2 -2
  96. package/dist/watchers/log.watcher.js +2 -4
  97. package/dist/watchers/mail.watcher.js +2 -2
  98. package/dist/watchers/model.watcher.js +2 -2
  99. package/dist/watchers/notification.watcher.js +2 -2
  100. package/dist/watchers/query/query.watcher.js +2 -4
  101. package/dist/watchers/redis.watcher.js +2 -2
  102. package/dist/watchers/request.watcher.js +12 -5
  103. package/dist/watchers/schedule.watcher.js +2 -2
  104. package/dist/watchers/view.watcher.js +2 -2
  105. package/dist/watchers/watcher-config.d.ts +27 -0
  106. package/dist/watchers/watcher-config.js +31 -0
  107. package/package.json +3 -1
@@ -0,0 +1,62 @@
1
+ import { DynamicModule, OnModuleDestroy, OnApplicationBootstrap, Provider } from '@nestjs/common';
2
+ import { HttpAdapterHost, ModuleRef } from '@nestjs/core';
3
+ import type { AddressInfo } from 'net';
4
+ import { DashboardServerConfig, NestLensConfig } from '../nestlens.config';
5
+ /** The resolved `server` block, provided only when one was configured. */
6
+ export declare const NESTLENS_SERVER_CONFIG: unique symbol;
7
+ /**
8
+ * The dashboard, its API and its event stream — and nothing else.
9
+ *
10
+ * The application's own controllers, middleware and global interceptors are not
11
+ * here, which is the point: this listener answers for NestLens and has no route
12
+ * that reaches anything else.
13
+ */
14
+ export declare class NestLensDashboardModule {
15
+ static forRoot(shared: Provider[]): DynamicModule;
16
+ }
17
+ /**
18
+ * Runs the dashboard on a socket NestLens owns.
19
+ *
20
+ * Provided only when `server` is configured; without it nothing here is
21
+ * constructed and the dashboard controllers are registered on the application
22
+ * exactly as they always were.
23
+ */
24
+ export declare class NestLensDashboardServer implements OnApplicationBootstrap, OnModuleDestroy {
25
+ private readonly server;
26
+ private readonly config;
27
+ private readonly moduleRef;
28
+ private readonly adapterHost?;
29
+ private readonly logger;
30
+ private application?;
31
+ private bound?;
32
+ constructor(server: DashboardServerConfig, config: NestLensConfig, moduleRef: ModuleRef, adapterHost?: HttpAdapterHost | undefined);
33
+ /**
34
+ * Where the listener actually ended up, once it is listening.
35
+ *
36
+ * Read from the socket rather than from the configuration, so `port: 0`
37
+ * reports the port the operating system chose and the address is the one the
38
+ * kernel bound — the answer, not the request.
39
+ */
40
+ address(): AddressInfo | undefined;
41
+ /**
42
+ * Bound after the application has finished starting, so a dashboard is never
43
+ * reachable before the thing it reports on is ready.
44
+ */
45
+ onApplicationBootstrap(): Promise<void>;
46
+ onModuleDestroy(): Promise<void>;
47
+ private hostAdapterType;
48
+ /**
49
+ * The running services, lent to the dashboard application.
50
+ *
51
+ * `strict: false` because they live in the global core module, not in the one
52
+ * this service was declared in.
53
+ *
54
+ * `NESTLENS_CONFIG` is passed as it is: a plain configuration object with no
55
+ * lifecycle to protect. `ApplicationConfig` and `HttpAdapterHost` are
56
+ * deliberately *not* lent — the dashboard application supplies its own, which
57
+ * is what makes the mount point come out right. A global prefix set with
58
+ * `app.setGlobalPrefix()` moves the application's routes and has nothing to
59
+ * do with this listener, where `path` is the whole story.
60
+ */
61
+ private sharedProviders;
62
+ }
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var NestLensDashboardModule_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.NestLensDashboardServer = exports.NestLensDashboardModule = exports.NESTLENS_SERVER_CONFIG = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const core_1 = require("@nestjs/core");
19
+ const nestlens_config_1 = require("../nestlens.config");
20
+ const storage_interface_1 = require("../core/storage/storage.interface");
21
+ const collector_service_1 = require("../core/collector.service");
22
+ const pruning_service_1 = require("../core/pruning.service");
23
+ const tag_service_1 = require("../core/tag.service");
24
+ const api_controller_1 = require("./api.controller");
25
+ const dashboard_controller_1 = require("./dashboard.controller");
26
+ const stream_controller_1 = require("./stream.controller");
27
+ const tag_controller_1 = require("./tag.controller");
28
+ const api_guard_1 = require("./api.guard");
29
+ const spa_wildcard_1 = require("./spa-wildcard");
30
+ const route_path_1 = require("./route-path");
31
+ /** The resolved `server` block, provided only when one was configured. */
32
+ exports.NESTLENS_SERVER_CONFIG = Symbol('NESTLENS_SERVER_CONFIG');
33
+ /**
34
+ * Hooks Nest calls on every instance it holds, including value providers.
35
+ *
36
+ * The dashboard application below is handed the *running* collector, storage
37
+ * and pruning service rather than copies — one process, one set of entries, one
38
+ * SQLite handle. Nest does not know they are on loan: it would call
39
+ * `onModuleInit` on them a second time, starting a second pruning timer, and
40
+ * `onModuleDestroy` when the dashboard listener closes, flushing and completing
41
+ * the collector of an application that is still running.
42
+ *
43
+ * So the borrowed instances are handed over without these. Ownership stays with
44
+ * the module that created them.
45
+ */
46
+ const LIFECYCLE_HOOKS = new Set([
47
+ 'onModuleInit',
48
+ 'onModuleDestroy',
49
+ 'onApplicationBootstrap',
50
+ 'onApplicationShutdown',
51
+ 'beforeApplicationShutdown',
52
+ ]);
53
+ /**
54
+ * The same object, minus its lifecycle hooks.
55
+ *
56
+ * Methods are bound to the original so `this` is never the proxy — the services
57
+ * behind these read their own fields, and a proxied receiver is exactly the
58
+ * kind of difference that shows up much later as something subtle.
59
+ */
60
+ function borrow(instance) {
61
+ return new Proxy(instance, {
62
+ get(target, property) {
63
+ if (typeof property === 'string' && LIFECYCLE_HOOKS.has(property)) {
64
+ return undefined;
65
+ }
66
+ const value = Reflect.get(target, property);
67
+ return typeof value === 'function'
68
+ ? value.bind(target)
69
+ : value;
70
+ },
71
+ has(target, property) {
72
+ if (typeof property === 'string' && LIFECYCLE_HOOKS.has(property)) {
73
+ return false;
74
+ }
75
+ return Reflect.has(target, property);
76
+ },
77
+ });
78
+ }
79
+ /**
80
+ * The dashboard, its API and its event stream — and nothing else.
81
+ *
82
+ * The application's own controllers, middleware and global interceptors are not
83
+ * here, which is the point: this listener answers for NestLens and has no route
84
+ * that reaches anything else.
85
+ */
86
+ let NestLensDashboardModule = NestLensDashboardModule_1 = class NestLensDashboardModule {
87
+ static forRoot(shared) {
88
+ return {
89
+ module: NestLensDashboardModule_1,
90
+ // Same order as the mounted arrangement: the dashboard's SPA catch-all is
91
+ // last so it cannot swallow the API routes.
92
+ controllers: [
93
+ api_controller_1.NestLensApiController,
94
+ tag_controller_1.TagController,
95
+ stream_controller_1.NestLensStreamController,
96
+ dashboard_controller_1.DashboardController,
97
+ ],
98
+ providers: [api_guard_1.NestLensGuard, spa_wildcard_1.SpaRouteRegistrar, ...shared],
99
+ };
100
+ }
101
+ };
102
+ exports.NestLensDashboardModule = NestLensDashboardModule;
103
+ exports.NestLensDashboardModule = NestLensDashboardModule = NestLensDashboardModule_1 = __decorate([
104
+ (0, common_1.Module)({})
105
+ ], NestLensDashboardModule);
106
+ const PLATFORMS = [
107
+ { type: 'express', packageName: '@nestjs/platform-express', exportName: 'ExpressAdapter' },
108
+ { type: 'fastify', packageName: '@nestjs/platform-fastify', exportName: 'FastifyAdapter' },
109
+ ];
110
+ /**
111
+ * An adapter of the same kind the application is already running on.
112
+ *
113
+ * Neither platform package is a dependency of NestLens, so both are required
114
+ * lazily and the application's own choice is tried first: matching it means the
115
+ * dashboard's request handling on this listener is the handling it gets on the
116
+ * mounted path, rather than a second code path that only this mode exercises.
117
+ */
118
+ function createAdapter(preferredType) {
119
+ const ordered = [
120
+ ...PLATFORMS.filter((platform) => platform.type === preferredType),
121
+ ...PLATFORMS.filter((platform) => platform.type !== preferredType),
122
+ ];
123
+ for (const platform of ordered) {
124
+ try {
125
+ const loaded = require(platform.packageName);
126
+ const Adapter = loaded[platform.exportName];
127
+ if (Adapter) {
128
+ return new Adapter();
129
+ }
130
+ }
131
+ catch {
132
+ continue;
133
+ }
134
+ }
135
+ throw new Error('NestLens needs an HTTP platform to serve its dashboard on a listener of its own, and ' +
136
+ 'neither @nestjs/platform-express nor @nestjs/platform-fastify could be loaded. ' +
137
+ 'Install the one the application uses, or remove `server` from the NestLens configuration ' +
138
+ 'to mount the dashboard on the application instead.');
139
+ }
140
+ /**
141
+ * Runs the dashboard on a socket NestLens owns.
142
+ *
143
+ * Provided only when `server` is configured; without it nothing here is
144
+ * constructed and the dashboard controllers are registered on the application
145
+ * exactly as they always were.
146
+ */
147
+ let NestLensDashboardServer = class NestLensDashboardServer {
148
+ constructor(server, config, moduleRef, adapterHost) {
149
+ this.server = server;
150
+ this.config = config;
151
+ this.moduleRef = moduleRef;
152
+ this.adapterHost = adapterHost;
153
+ this.logger = new common_1.Logger('NestLens');
154
+ }
155
+ /**
156
+ * Where the listener actually ended up, once it is listening.
157
+ *
158
+ * Read from the socket rather than from the configuration, so `port: 0`
159
+ * reports the port the operating system chose and the address is the one the
160
+ * kernel bound — the answer, not the request.
161
+ */
162
+ address() {
163
+ return this.bound;
164
+ }
165
+ /**
166
+ * Bound after the application has finished starting, so a dashboard is never
167
+ * reachable before the thing it reports on is ready.
168
+ */
169
+ async onApplicationBootstrap() {
170
+ const application = await core_1.NestFactory.create(NestLensDashboardModule.forRoot(this.sharedProviders()), createAdapter(this.hostAdapterType()),
171
+ // Its own bootstrap log — route mappings for controllers the application
172
+ // already described — would read as a second application starting up.
173
+ { logger: false });
174
+ try {
175
+ await application.listen(this.server.port, this.server.host);
176
+ }
177
+ catch (error) {
178
+ await application.close().catch(() => undefined);
179
+ // Thrown, not logged and swallowed. Carrying on would leave the dashboard
180
+ // unreachable at the address that was asked for while the application
181
+ // starts normally — and the failure mode this option exists to prevent is
182
+ // exactly a dashboard that is somewhere other than where it was thought
183
+ // to be.
184
+ throw new Error(`NestLens could not bind its dashboard listener to ${this.server.host}:${this.server.port} — ` +
185
+ `${error instanceof Error ? error.message : String(error)}. The dashboard is not mounted on ` +
186
+ 'the application either, so it would not be reachable at all; fix the address or remove ' +
187
+ '`server` from the NestLens configuration.');
188
+ }
189
+ this.application = application;
190
+ this.bound = application.getHttpServer().address();
191
+ const host = this.bound.family === 'IPv6' ? `[${this.bound.address}]` : this.bound.address;
192
+ this.logger.log(`Dashboard on its own listener: http://${host}:${this.bound.port}${(0, route_path_1.toBaseHref)(this.config.path)} ` +
193
+ '— not mounted on the application');
194
+ }
195
+ async onModuleDestroy() {
196
+ await this.application?.close();
197
+ this.application = undefined;
198
+ this.bound = undefined;
199
+ }
200
+ hostAdapterType() {
201
+ const adapter = this.adapterHost?.httpAdapter;
202
+ return typeof adapter?.getType === 'function' ? adapter.getType() : undefined;
203
+ }
204
+ /**
205
+ * The running services, lent to the dashboard application.
206
+ *
207
+ * `strict: false` because they live in the global core module, not in the one
208
+ * this service was declared in.
209
+ *
210
+ * `NESTLENS_CONFIG` is passed as it is: a plain configuration object with no
211
+ * lifecycle to protect. `ApplicationConfig` and `HttpAdapterHost` are
212
+ * deliberately *not* lent — the dashboard application supplies its own, which
213
+ * is what makes the mount point come out right. A global prefix set with
214
+ * `app.setGlobalPrefix()` moves the application's routes and has nothing to
215
+ * do with this listener, where `path` is the whole story.
216
+ */
217
+ sharedProviders() {
218
+ return [
219
+ { provide: nestlens_config_1.NESTLENS_CONFIG, useValue: this.config },
220
+ { provide: storage_interface_1.STORAGE, useValue: borrow(this.moduleRef.get(storage_interface_1.STORAGE, { strict: false })) },
221
+ {
222
+ provide: collector_service_1.CollectorService,
223
+ useValue: borrow(this.moduleRef.get(collector_service_1.CollectorService, { strict: false })),
224
+ },
225
+ {
226
+ provide: pruning_service_1.PruningService,
227
+ useValue: borrow(this.moduleRef.get(pruning_service_1.PruningService, { strict: false })),
228
+ },
229
+ {
230
+ provide: tag_service_1.TagService,
231
+ useValue: borrow(this.moduleRef.get(tag_service_1.TagService, { strict: false })),
232
+ },
233
+ ];
234
+ }
235
+ };
236
+ exports.NestLensDashboardServer = NestLensDashboardServer;
237
+ exports.NestLensDashboardServer = NestLensDashboardServer = __decorate([
238
+ (0, common_1.Injectable)(),
239
+ __param(0, (0, common_1.Inject)(exports.NESTLENS_SERVER_CONFIG)),
240
+ __param(1, (0, common_1.Inject)(nestlens_config_1.NESTLENS_CONFIG)),
241
+ __param(3, (0, common_1.Optional)()),
242
+ __metadata("design:paramtypes", [Object, Object, core_1.ModuleRef,
243
+ core_1.HttpAdapterHost])
244
+ ], NestLensDashboardServer);
@@ -4,3 +4,4 @@ export * from './dashboard.controller';
4
4
  export * from './stream.controller';
5
5
  export * from './tag.controller';
6
6
  export * from './spa-wildcard';
7
+ export * from './dashboard-server';
package/dist/api/index.js CHANGED
@@ -20,3 +20,4 @@ __exportStar(require("./dashboard.controller"), exports);
20
20
  __exportStar(require("./stream.controller"), exports);
21
21
  __exportStar(require("./tag.controller"), exports);
22
22
  __exportStar(require("./spa-wildcard"), exports);
23
+ __exportStar(require("./dashboard-server"), exports);
@@ -45,6 +45,14 @@ export declare class CollectorService implements OnModuleDestroy {
45
45
  get entryStream$(): Observable<Entry>;
46
46
  private emit;
47
47
  constructor(storage: StorageInterface, config: NestLensConfig, dataMasker?: DataMaskerService | undefined, tagService?: TagService | undefined, familyHashService?: FamilyHashService | undefined);
48
+ /**
49
+ * Drops entries the configured rate does not keep.
50
+ *
51
+ * Applied before the filter, the mask and the buffer, because an entry that
52
+ * is not being kept should not be paid for. `undefined` unless `sampling` is
53
+ * configured with a rate below 1, so the default path costs nothing.
54
+ */
55
+ private readonly sampler?;
48
56
  /**
49
57
  * Apply filter to an entry
50
58
  */
@@ -17,6 +17,7 @@ exports.CollectorService = void 0;
17
17
  const common_1 = require("@nestjs/common");
18
18
  const rxjs_1 = require("rxjs");
19
19
  const data_masker_service_1 = require("./data-masker.service");
20
+ const sampling_1 = require("./sampling");
20
21
  const request_context_1 = require("./request-context");
21
22
  const storage_interface_1 = require("./storage/storage.interface");
22
23
  const tag_service_1 = require("./tag.service");
@@ -68,6 +69,7 @@ let CollectorService = CollectorService_1 = class CollectorService {
68
69
  // alerting service. Entries are emitted after they have been saved (so they
69
70
  // carry an id), never blocking collection if a subscriber misbehaves.
70
71
  this.entrySubject = new rxjs_1.Subject();
72
+ this.sampler = (0, sampling_1.createSampler)(this.config.sampling);
71
73
  this.startFlushTimer();
72
74
  }
73
75
  /**
@@ -135,6 +137,9 @@ let CollectorService = CollectorService_1 = class CollectorService {
135
137
  // ends up on the detail page of the request that ran it.
136
138
  requestId: requestId ?? (0, request_context_1.currentRequestId)(),
137
139
  };
140
+ if (this.sampler && !this.sampler.shouldRecord(entry)) {
141
+ return;
142
+ }
138
143
  // The filter callback runs in the application's own process against its own
139
144
  // data, so it sees the entry as recorded; what gets buffered — and from
140
145
  // there stored, streamed and posted to webhooks — is masked.
@@ -165,6 +170,9 @@ let CollectorService = CollectorService_1 = class CollectorService {
165
170
  payload,
166
171
  requestId: requestId ?? (0, request_context_1.currentRequestId)(),
167
172
  };
173
+ if (this.sampler && !this.sampler.shouldRecord(entry)) {
174
+ return null;
175
+ }
168
176
  // Apply filter
169
177
  const shouldCollect = await this.applyFilter(entry);
170
178
  if (!shouldCollect) {
@@ -1,13 +1,14 @@
1
+ import { MaskingTerms } from './masking-terms';
1
2
  /**
2
3
  * Configuration for data masking behavior.
3
4
  */
4
5
  export interface DataMaskerConfig {
5
- /** Headers to mask (case-insensitive) */
6
- sensitiveHeaders?: string[];
7
- /** Body/query parameter names to mask (case-insensitive) */
8
- sensitiveParams?: string[];
9
- /** User object fields to mask (case-insensitive) */
10
- sensitiveUserFields?: string[];
6
+ /** Headers to mask, added to the built-in list. See {@link MaskingTerms}. */
7
+ sensitiveHeaders?: MaskingTerms;
8
+ /** Body/query parameter names to mask, added to the built-in list. */
9
+ sensitiveParams?: MaskingTerms;
10
+ /** User object fields to mask, added to the built-in list. */
11
+ sensitiveUserFields?: MaskingTerms;
11
12
  /** Replacement string for masked values */
12
13
  maskReplacement?: string;
13
14
  /** Whether to sanitize stack traces in production */
@@ -21,11 +22,25 @@ export interface DataMaskerConfig {
21
22
  */
22
23
  stackTraceSanitization?: StackTraceSanitization;
23
24
  }
25
+ /**
26
+ * Every term this masker will redact a body or query parameter for.
27
+ *
28
+ * Exported because the GraphQL watcher sanitises its own payloads and marks
29
+ * them so the collector does not walk them a second time. That mark is only
30
+ * safe while the watcher redacts at least as much as the collector would, so
31
+ * the watcher resolves its list from this one rather than keeping a shorter
32
+ * list of its own — which is what let `cvv`, `passwd` and anything added
33
+ * through `security.dataMasking.sensitiveParams` reach storage in the clear.
34
+ */
35
+ export declare function resolveSensitiveParams(configured?: MaskingTerms): string[];
24
36
  export type StackTraceSanitization = 'none' | 'partial' | 'full';
25
37
  export declare class DataMaskerService {
26
38
  private readonly sensitiveHeaders;
27
39
  private readonly sensitiveParams;
28
40
  private readonly sensitiveUserFields;
41
+ private readonly matchesHeader;
42
+ private readonly matchesParam;
43
+ private readonly matchesUserField;
29
44
  private readonly maskReplacement;
30
45
  private readonly sanitizeStackTraces;
31
46
  private readonly stackTraceSanitization;
@@ -10,7 +10,10 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.DataMaskerService = void 0;
13
+ exports.resolveSensitiveParams = resolveSensitiveParams;
13
14
  const common_1 = require("@nestjs/common");
15
+ const sanitized_payload_1 = require("./sanitized-payload");
16
+ const masking_terms_1 = require("./masking-terms");
14
17
  /**
15
18
  * Default sensitive headers that should always be masked.
16
19
  */
@@ -49,6 +52,19 @@ const DEFAULT_SENSITIVE_PARAMS = [
49
52
  'private_key',
50
53
  'privatekey',
51
54
  ];
55
+ /**
56
+ * Every term this masker will redact a body or query parameter for.
57
+ *
58
+ * Exported because the GraphQL watcher sanitises its own payloads and marks
59
+ * them so the collector does not walk them a second time. That mark is only
60
+ * safe while the watcher redacts at least as much as the collector would, so
61
+ * the watcher resolves its list from this one rather than keeping a shorter
62
+ * list of its own — which is what let `cvv`, `passwd` and anything added
63
+ * through `security.dataMasking.sensitiveParams` reach storage in the clear.
64
+ */
65
+ function resolveSensitiveParams(configured) {
66
+ return (0, masking_terms_1.resolveMaskingTerms)(DEFAULT_SENSITIVE_PARAMS, configured);
67
+ }
52
68
  /**
53
69
  * Default sensitive user fields that should always be masked.
54
70
  */
@@ -89,9 +105,45 @@ const normalizeFieldName = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, ''
89
105
  * right direction for something recording production traffic. A field that
90
106
  * should be readable can be kept by narrowing the configured list.
91
107
  */
92
- const matchesSensitiveTerm = (fieldName, terms) => {
93
- const normalized = normalizeFieldName(fieldName);
94
- return terms.some((term) => term.length > 0 && normalized.includes(term));
108
+ /**
109
+ * How many distinct field names one matcher will remember.
110
+ *
111
+ * A payload's key names come from a schema, a header set and a query string —
112
+ * a few dozen names repeated across every entry — so the memo answers nearly
113
+ * every lookup after the first entry. A body assembled by whoever is calling
114
+ * has no such bound, which is why there is a cap; past it the answers stay
115
+ * correct and are recomputed.
116
+ */
117
+ const MEMO_LIMIT = 1024;
118
+ /**
119
+ * One term list, with its answers remembered.
120
+ *
121
+ * Deciding a single field name normalises it — a `toLowerCase` and a regex
122
+ * replace, both allocating — and then scans every configured term for a
123
+ * substring. That is twenty-odd comparisons per key, on every key of every
124
+ * entry, for an answer that never changes for a given name. The GraphQL
125
+ * sanitiser memoised this in 0.10.0 and measured the difference; the collector
126
+ * masker, which runs on *every* entry rather than on GraphQL ones, kept
127
+ * recomputing it and was the largest single cost in the masker under load.
128
+ *
129
+ * The term list belongs to the masker and never changes after construction, so
130
+ * the memo lives as long as the masker and needs nothing to invalidate it.
131
+ */
132
+ const createTermMatcher = (terms) => {
133
+ const meaningful = terms.filter((term) => term.length > 0);
134
+ const memo = new Map();
135
+ return (fieldName) => {
136
+ const remembered = memo.get(fieldName);
137
+ if (remembered !== undefined) {
138
+ return remembered;
139
+ }
140
+ const normalized = normalizeFieldName(fieldName);
141
+ const result = meaningful.some((term) => normalized.includes(term));
142
+ if (memo.size < MEMO_LIMIT) {
143
+ memo.set(fieldName, result);
144
+ }
145
+ return result;
146
+ };
95
147
  };
96
148
  /**
97
149
  * Replaces `(/absolute/path/to/file.js:1:2)` with `(...)`.
@@ -120,12 +172,15 @@ function replaceParenthesisedPaths(line) {
120
172
  }
121
173
  let DataMaskerService = class DataMaskerService {
122
174
  constructor(config) {
123
- const headers = [...DEFAULT_SENSITIVE_HEADERS, ...(config?.sensitiveHeaders ?? [])];
124
- const params = [...DEFAULT_SENSITIVE_PARAMS, ...(config?.sensitiveParams ?? [])];
125
- const userFields = [...DEFAULT_SENSITIVE_USER_FIELDS, ...(config?.sensitiveUserFields ?? [])];
175
+ const headers = (0, masking_terms_1.resolveMaskingTerms)(DEFAULT_SENSITIVE_HEADERS, config?.sensitiveHeaders);
176
+ const params = resolveSensitiveParams(config?.sensitiveParams);
177
+ const userFields = (0, masking_terms_1.resolveMaskingTerms)(DEFAULT_SENSITIVE_USER_FIELDS, config?.sensitiveUserFields);
126
178
  this.sensitiveHeaders = headers.map(normalizeFieldName);
127
179
  this.sensitiveParams = params.map(normalizeFieldName);
128
180
  this.sensitiveUserFields = userFields.map(normalizeFieldName);
181
+ this.matchesHeader = createTermMatcher(this.sensitiveHeaders);
182
+ this.matchesParam = createTermMatcher(this.sensitiveParams);
183
+ this.matchesUserField = createTermMatcher(this.sensitiveUserFields);
129
184
  this.maskReplacement = config?.maskReplacement ?? DEFAULT_MASK;
130
185
  this.sanitizeStackTraces = config?.sanitizeStackTraces ?? true;
131
186
  this.stackTraceSanitization =
@@ -141,7 +196,7 @@ let DataMaskerService = class DataMaskerService {
141
196
  }
142
197
  const masked = {};
143
198
  for (const [key, value] of Object.entries(headers)) {
144
- if (matchesSensitiveTerm(key, this.sensitiveHeaders)) {
199
+ if (this.matchesHeader(key)) {
145
200
  masked[key] = this.maskReplacement;
146
201
  }
147
202
  else {
@@ -157,6 +212,9 @@ let DataMaskerService = class DataMaskerService {
157
212
  if (body === null || body === undefined) {
158
213
  return body;
159
214
  }
215
+ if ((0, sanitized_payload_1.isSanitized)(body)) {
216
+ return body;
217
+ }
160
218
  if (typeof body === 'string') {
161
219
  // Try to parse JSON and mask it
162
220
  try {
@@ -181,9 +239,16 @@ let DataMaskerService = class DataMaskerService {
181
239
  maskObject(obj) {
182
240
  const masked = {};
183
241
  for (const [key, value] of Object.entries(obj)) {
184
- if (matchesSensitiveTerm(key, this.sensitiveParams)) {
242
+ if (this.matchesParam(key)) {
185
243
  masked[key] = this.maskReplacement;
186
244
  }
245
+ else if ((0, sanitized_payload_1.isSanitized)(value)) {
246
+ // A watcher that already produced a clean copy of this subtree — the
247
+ // GraphQL response and its variables — is taken at its word rather
248
+ // than deep-cloned a second time. Only what `markSanitized` touched
249
+ // qualifies, so the rest of the payload is masked as it always was.
250
+ masked[key] = value;
251
+ }
187
252
  else if (value !== null && typeof value === 'object') {
188
253
  if (Array.isArray(value)) {
189
254
  masked[key] = value.map((item) => typeof item === 'object' && item !== null
@@ -210,7 +275,7 @@ let DataMaskerService = class DataMaskerService {
210
275
  const masked = {};
211
276
  const userObj = user;
212
277
  for (const [key, value] of Object.entries(userObj)) {
213
- if (matchesSensitiveTerm(key, this.sensitiveUserFields)) {
278
+ if (this.matchesUserField(key)) {
214
279
  masked[key] = this.maskReplacement;
215
280
  }
216
281
  else if (value !== null && typeof value === 'object') {
@@ -249,9 +314,7 @@ let DataMaskerService = class DataMaskerService {
249
314
  * Check if a key is sensitive.
250
315
  */
251
316
  isSensitiveKey(key) {
252
- return (matchesSensitiveTerm(key, this.sensitiveHeaders) ||
253
- matchesSensitiveTerm(key, this.sensitiveParams) ||
254
- matchesSensitiveTerm(key, this.sensitiveUserFields));
317
+ return this.matchesHeader(key) || this.matchesParam(key) || this.matchesUserField(key);
255
318
  }
256
319
  /**
257
320
  * Get the mask replacement string.
@@ -0,0 +1,30 @@
1
+ /**
2
+ * How a configured list of sensitive names relates to the built-in one.
3
+ *
4
+ * An array *adds*: the built-in list stays and these join it. That is what
5
+ * every masking option here has always effectively done — the collector masks
6
+ * every payload on its way to storage with its own defaults, so a shorter list
7
+ * configured on a watcher never actually narrowed anything.
8
+ *
9
+ * `{ replace: [...] }` is the way to say the other thing, and it has to be said
10
+ * out loud. It drops the built-in list entirely and masks exactly what is
11
+ * named, which is the right answer when the defaults redact a field this
12
+ * application needs to read — and the wrong answer by accident, which is why
13
+ * it is not what a bare array means.
14
+ *
15
+ * sensitiveParams: ['iban'] // the defaults, plus iban
16
+ * sensitiveParams: { replace: ['iban'] } // iban, and nothing else
17
+ */
18
+ export type MaskingTerms = string[] | {
19
+ replace: string[];
20
+ };
21
+ /** Whether this list was written to stand in for the built-in one. */
22
+ export declare function replacesDefaults(terms: MaskingTerms | undefined): boolean;
23
+ /**
24
+ * The terms a masking list resolves to, defaults included unless replaced.
25
+ *
26
+ * Deduplicated, and one array per resolution: the GraphQL sanitiser caches its
27
+ * compiled matcher on the array's identity, so handing out a fresh array per
28
+ * call would quietly turn a cache hit into a rebuild.
29
+ */
30
+ export declare function resolveMaskingTerms(defaults: readonly string[], configured?: MaskingTerms): string[];
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.replacesDefaults = replacesDefaults;
4
+ exports.resolveMaskingTerms = resolveMaskingTerms;
5
+ /** Whether this list was written to stand in for the built-in one. */
6
+ function replacesDefaults(terms) {
7
+ return terms !== undefined && !Array.isArray(terms);
8
+ }
9
+ /**
10
+ * The terms a masking list resolves to, defaults included unless replaced.
11
+ *
12
+ * Deduplicated, and one array per resolution: the GraphQL sanitiser caches its
13
+ * compiled matcher on the array's identity, so handing out a fresh array per
14
+ * call would quietly turn a cache hit into a rebuild.
15
+ */
16
+ function resolveMaskingTerms(defaults, configured) {
17
+ if (replacesDefaults(configured)) {
18
+ return [...new Set(configured.replace)];
19
+ }
20
+ return [...new Set([...defaults, ...(configured ?? [])])];
21
+ }
@@ -0,0 +1,41 @@
1
+ import { Entry } from '../types';
2
+ import { SamplingConfig } from '../nestlens.config';
3
+ /**
4
+ * Decides which entries are kept when not everything can be.
5
+ *
6
+ * Off unless configured: NestLens records everything by default, and that is
7
+ * the point of it. This exists for the application that has grown past what it
8
+ * wants to pay for that, and would rather see one request in ten completely
9
+ * than all of them not at all.
10
+ *
11
+ * ## Whole requests, not scattered entries
12
+ *
13
+ * The decision is made from the request id, not per entry. A request, its
14
+ * queries, its cache reads, its logs and its outgoing HTTP calls share one id,
15
+ * so they are kept together or dropped together. Sampling entry by entry would
16
+ * fill the dashboard with queries whose request was never recorded and requests
17
+ * whose queries were not — every detail page half empty, which is worse than a
18
+ * smaller number of complete ones.
19
+ *
20
+ * ## Deterministic, so it needs no memory
21
+ *
22
+ * The id is hashed and compared against the rate. The same id always gets the
23
+ * same answer, from any watcher, in any order, with nothing held between calls
24
+ * — no set of sampled requests to grow, expire or synchronise, and no
25
+ * difference between the entry that arrives first and the one that arrives
26
+ * after the response has been sent.
27
+ *
28
+ * Entries with no request id — a scheduled task, a console command, a job
29
+ * picked off a queue — are sampled on their own hash, since there is no request
30
+ * for them to belong to.
31
+ */
32
+ export interface Sampler {
33
+ shouldRecord(entry: Entry): boolean;
34
+ }
35
+ /**
36
+ * A sampler for the configured rate, or `undefined` when everything is kept.
37
+ *
38
+ * Returning `undefined` rather than a sampler that always says yes keeps the
39
+ * default path free of a call per entry.
40
+ */
41
+ export declare function createSampler(config?: SamplingConfig): Sampler | undefined;