@gasket/plugin-elastic-apm 0.0.0-canary-20250922152503

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/EXAMPLES.md ADDED
@@ -0,0 +1,133 @@
1
+ # Examples
2
+
3
+ This document provides working examples for all exported functions and lifecycle hooks from `@gasket/plugin-elastic-apm`.
4
+
5
+ ## Plugin Configuration
6
+
7
+ ### Basic Configuration
8
+
9
+ ```js
10
+ // gasket.js
11
+ import { makeGasket } from '@gasket/core';
12
+ import pluginElasticApm from '@gasket/plugin-elastic-apm';
13
+
14
+ export default makeGasket({
15
+ plugins: [
16
+ pluginElasticApm
17
+ ],
18
+ elasticAPM: {
19
+ sensitiveCookies: ['sessionId', 'authToken']
20
+ }
21
+ });
22
+ ```
23
+
24
+ ### Environment Variable Configuration
25
+
26
+ ```js
27
+ // setup.js
28
+ import 'dotenv/config';
29
+ import apm from 'elastic-apm-node';
30
+
31
+ apm.start({
32
+ serviceName: 'my-service',
33
+ secretToken: process.env.ELASTIC_APM_SECRET_TOKEN,
34
+ serverUrl: process.env.ELASTIC_APM_SERVER_URL
35
+ });
36
+ ```
37
+
38
+ ## Actions
39
+
40
+ ### getApmTransaction
41
+
42
+ Access and decorate the current APM transaction:
43
+
44
+ ```js
45
+ // In a middleware or lifecycle
46
+ export default {
47
+ name: 'my-plugin',
48
+ hooks: {
49
+ middleware(gasket, app) {
50
+ app.use(async (req, res, next) => {
51
+ const transaction = await gasket.actions.getApmTransaction(req);
52
+
53
+ if (transaction) {
54
+ transaction.setLabel('userId', req.user?.id);
55
+ transaction.setLabel('requestId', req.headers['x-request-id']);
56
+ }
57
+
58
+ next();
59
+ });
60
+ }
61
+ }
62
+ };
63
+ ```
64
+
65
+ ```js
66
+ // In Next.js API route
67
+ // pages/api/users.js
68
+ import gasket from '../../gasket.js';
69
+
70
+ export default async function handler(req, res) {
71
+ const transaction = await gasket.actions.getApmTransaction(req);
72
+
73
+ if (transaction) {
74
+ transaction.setLabel('endpoint', '/api/users');
75
+ }
76
+
77
+ // Your API logic here
78
+ res.json({ users: [] });
79
+ }
80
+ ```
81
+
82
+ ## Lifecycle Hooks
83
+
84
+ ### apmTransaction
85
+
86
+ Customize APM transaction with additional context:
87
+
88
+ ```js
89
+ // In a plugin
90
+ export default {
91
+ name: 'apm-customization-plugin',
92
+ hooks: {
93
+ apmTransaction(gasket, transaction, { req }) {
94
+ // Add custom labels
95
+ transaction.setLabel('userAgent', req.headers['user-agent']);
96
+ transaction.setLabel('locale', req.headers['accept-language']);
97
+
98
+ // Set custom name based on route
99
+ if (req.route?.path) {
100
+ transaction.name = `${req.method} ${req.route.path}`;
101
+ }
102
+
103
+ // Add user context
104
+ if (req.user) {
105
+ transaction.setUser({
106
+ id: req.user.id,
107
+ email: req.user.email
108
+ });
109
+ }
110
+ }
111
+ }
112
+ };
113
+ ```
114
+
115
+ ```js
116
+ // Conditional APM decoration
117
+ export default {
118
+ name: 'conditional-apm-plugin',
119
+ hooks: {
120
+ apmTransaction(gasket, transaction, { req }) {
121
+ // Only add expensive labels for non-health check requests
122
+ if (!req.path.startsWith('/health')) {
123
+ transaction.setLabel('expensive-operation', true);
124
+
125
+ // Add custom data based on request
126
+ if (req.path.startsWith('/api/')) {
127
+ transaction.setLabel('api-version', req.headers['api-version'] || 'v1');
128
+ }
129
+ }
130
+ }
131
+ }
132
+ };
133
+ ```
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 GoDaddy Operating Company, LLC.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,230 @@
1
+ # @gasket/plugin-elastic-apm
2
+
3
+ Adds Elastic APM instrumentation to your application
4
+
5
+ ## Installation
6
+
7
+ ```
8
+ npm i @gasket/plugin-elastic-apm
9
+ ```
10
+
11
+ Update your `gasket` file plugin configuration:
12
+
13
+ ```diff
14
+ // gasket.js
15
+
16
+ + import pluginElasticApm from '@gasket/plugin-elastic-apm';
17
+
18
+ export default makeGasket({
19
+ plugins: [
20
+ + pluginElasticApm
21
+ ]
22
+ });
23
+ ```
24
+
25
+ Add `NODE_OPTIONS=--import=./setup.js` to the `package.json` start script:
26
+
27
+ ```diff
28
+ "scripts": {
29
+ "build": "next build",
30
+ - "start": "next start",
31
+ + "start": "NODE_OPTIONS=--import=./setup.js next start",
32
+ "local": "next dev"
33
+ }
34
+ ```
35
+
36
+ Add a `setup.js` script to the root of your app
37
+
38
+ ```
39
+ // setup.js
40
+ import apm from 'elastic-apm-node';
41
+
42
+ // Elastic APM setup
43
+ apm.start({
44
+ serviceName: 'my-service-name',
45
+ captureHeaders: false,
46
+ secretToken: process.env.ELASTIC_APM_SECRET_TOKEN,
47
+ serverUrl: process.env.ELASTIC_APM_SERVER_URL
48
+ // additional configuration options
49
+ });
50
+ ```
51
+
52
+ ## Configuration
53
+
54
+ The [start recommendations] for the APM agent are to require it as early as
55
+ possible in your app. For Gasket apps, using `NODE_OPTIONS=--import=./setup.js`
56
+ will accomplish this. To configure the APM agent, set the environment variables
57
+ described in the [configuration options documentation].
58
+
59
+ In particular, the APM server URL (`ELASTIC_APM_SERVER_URL`) and secret token
60
+ (`ELASTIC_APM_SECRET_TOKEN`) are both required configuration. If either of these
61
+ are not present, the APM agent will be disabled.
62
+
63
+ ### Dotenv
64
+
65
+ If you wish to use `dotenv`, be sure it is installed and imported in `setup.js`:
66
+
67
+ ```
68
+ npm i dotenv
69
+ ```
70
+
71
+ ```diff
72
+ // setup.js
73
+ + import 'dotenv/config';
74
+ import apm from 'elastic-apm-node';
75
+
76
+ // Elastic APM setup
77
+ apm.start({
78
+ ...
79
+ ```
80
+
81
+ ### Plugin Configurations
82
+
83
+ The Gasket plugin provides some additional setup helpers. These can be
84
+ configured under `elasticAPM` in the `gasket.js`.
85
+
86
+ - **`sensitiveCookies`** - (string[]) A list of sensitive cookies to filter
87
+
88
+ #### Filtering Sensitive Cookies
89
+
90
+ If your application’s users send session credentials or any other sensitive
91
+ information in their cookies, you may wish to filter them out before they are
92
+ stored in Elasticsearch. Specify a list of cookie names to redact in
93
+ `gasket.js`:
94
+
95
+ ```js
96
+ export default makeGasket({
97
+ elasticAPM: {
98
+ sensitiveCookies: ['my_jwt', 'userFullName']
99
+ }
100
+ });
101
+ ```
102
+
103
+ #### Custom Filtering Sensitive Fields
104
+
105
+ If your application’s users send session credentials or any other sensitive
106
+ information in their cookies, you may wish to filter them out before they are
107
+ stored in Elasticsearch. Specify a list of cookie names to redact in
108
+ `setup.js` using the [sanitizeFieldNames] configuration option:
109
+
110
+ ```diff
111
+ // setup.js
112
+ import apm from 'elastic-apm-node';
113
+
114
+ // Elastic APM setup
115
+ apm.start({
116
+ + sanitizeFieldNames: ['foo', 'bar', '*token*']
117
+ ...
118
+ ```
119
+
120
+ The `sanitizeFieldNames` config option can be used for:
121
+
122
+ - request and response HTTP headers
123
+ - HTTP request cookies
124
+ - any form field captured during an `application/x-www-form-urlencoded` data request
125
+
126
+ To filter out other data, use the [APM Add Filter API].
127
+
128
+ ### Custom Filters
129
+
130
+ According to the [Elastic APM docs], the _Elastic APM agent for Node.js is a
131
+ singleton_.
132
+ This means that you can import and configure the singleton in various
133
+ hooks of your Gasket app, such as with the [init] or [middleware] lifecycles.
134
+
135
+ ## Actions
136
+
137
+ ### getApmTransaction
138
+
139
+ Use the `getApmTransaction` action to access and decorate the current APM
140
+ transaction. This action is available in any lifecycle hook or server-side code.
141
+
142
+ ```js
143
+ // example-plugin.js
144
+
145
+ export default {
146
+ name: 'example-plugin',
147
+ hooks: {
148
+ express(gasket, app) {
149
+ app.use(async (req, res, next) => {
150
+ const transaction = await gasket.actions.getApmTransaction(req);
151
+ const locale = await gasket.actions.getIntlLocale(req);
152
+ transaction.setLabel('locale', locale);
153
+ next();
154
+ });
155
+ }
156
+ }
157
+ }
158
+ ```
159
+
160
+ In the above example, we are hooking the express lifecycle to add middleware
161
+ to decorate the transaction.
162
+ Calling `getApmTransaction` will also allow other plugins to decorate the
163
+ transaction by hooking the `apmTransaction` lifecycle discussed next.
164
+
165
+ At a minimum, the `getApmTransaction` action must be invoked to execute
166
+ the `apmTransaction` lifecycle described below.
167
+ This can be adjusted to only run for specific requests.
168
+
169
+ ```js
170
+ export default {
171
+ name: 'example-plugin',
172
+ hooks: {
173
+ express(gasket, app) {
174
+ app.use(async (req, res, next) => {
175
+ // Only decorate APM transaction for non-API requests
176
+ if(!req.path.startsWith('/api')) {
177
+ await gasket.actions.getApmTransaction(req);
178
+ }
179
+ next();
180
+ });
181
+ }
182
+ }
183
+ }
184
+ ```
185
+
186
+ ## Lifecycles
187
+
188
+ ### apmTransaction
189
+
190
+ Enables customizing an APM transaction. Hooks receive the current APM
191
+ [Transaction] and details about the request. Hooks may be asynchronous. The
192
+ request details are as follows:
193
+
194
+ | Property | Description |
195
+ |----------|-------------|
196
+ | `req` | The HTTP request or framework-specific wrapper around it |
197
+ | `res` | The HTTP response or framework-specific wrapper around it |
198
+
199
+ ```javascript
200
+ // example-plugin.js
201
+
202
+ export default {
203
+ name: 'example-plugin',
204
+ hooks: {
205
+ apmTransaction(gasket, transaction, { req, res }) => {
206
+ transaction.setLabel('language', req.headers['accept-language']);
207
+ }
208
+ }
209
+ }
210
+ ```
211
+
212
+ ## How it works
213
+
214
+ This plugin hooks the Gasket [configure] lifecycle to set additional filtering,
215
+ such as for sensitive cookies.
216
+
217
+ ## License
218
+
219
+ [MIT](./LICENSE.md)
220
+
221
+ <!-- LINKS -->
222
+
223
+ [init]:/packages/gasket-core/README.md#init
224
+ [middleware]:/packages/gasket-plugin-middleware/README.md#middleware
225
+ [configuration options documentation]:https://www.elastic.co/guide/en/apm/agent/nodejs/current/configuration.html
226
+ [start recommendations]:https://www.elastic.co/guide/en/apm/agent/nodejs/master/agent-api.html#apm-start
227
+ [Elastic APM docs]:https://www.elastic.co/guide/en/apm/agent/nodejs/master/agent-api.html
228
+ [sanitizeFieldNames]:https://www.elastic.co/guide/en/apm/agent/nodejs/4.x/configuration.html#sanitize-field-names
229
+ [APM Add Filter API]:https://www.elastic.co/guide/en/apm/agent/nodejs/4.x/agent-api.html#apm-add-filter
230
+ [Transaction]:https://www.elastic.co/guide/en/apm/agent/nodejs/current/transaction-api.html
package/lib/actions.js ADDED
@@ -0,0 +1,25 @@
1
+ const { withGasketRequestCache } = require('@gasket/request');
2
+
3
+ /** @type {import('@gasket/core').ActionHandler<'getApmTransaction'>} */
4
+ const getApmTransaction = withGasketRequestCache(
5
+ async function getApmTransaction(gasket, req) {
6
+ const apm = require('elastic-apm-node');
7
+
8
+ if (!apm?.isStarted()) {
9
+ return;
10
+ }
11
+
12
+ const transaction = apm.currentTransaction;
13
+ if (!transaction) {
14
+ return;
15
+ }
16
+
17
+ await gasket.exec('apmTransaction', transaction, { req });
18
+
19
+ return transaction;
20
+ }
21
+ );
22
+
23
+ module.exports = {
24
+ getApmTransaction
25
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Determines if the Elastic APM agent has sufficient config to be active
3
+ * @param {import('./index').ExtendedAgentConfigOptions} config Apm agent config
4
+ * @param {NodeJS.ProcessEnv} env Environment variables
5
+ * @returns {boolean} A combined config object
6
+ */
7
+ const isActive = (config, env) => {
8
+ const { active, serverUrl, secretToken } = config;
9
+
10
+ if (active || env.ELASTIC_APM_ACTIVE) {
11
+ return true;
12
+ }
13
+
14
+ const combined = {
15
+ serverUrl: serverUrl || env.ELASTIC_APM_SERVER_URL,
16
+ secretToken: secretToken || env.ELASTIC_APM_SECRET_TOKEN
17
+ };
18
+
19
+ if (combined.serverUrl && combined.secretToken) {
20
+ return true;
21
+ }
22
+
23
+ return false;
24
+ };
25
+
26
+ /** @type {import('@gasket/core').HookHandler<'configure'>} */
27
+ module.exports = function configure(gasket, config) {
28
+ config.elasticAPM = config.elasticAPM || {};
29
+
30
+ // eslint-disable-next-line no-process-env
31
+ config.elasticAPM.active = isActive(config.elasticAPM, process.env);
32
+
33
+ return { ...config };
34
+ };
package/lib/cookies.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Returns an array of cookie names which are considered sensitive because they
3
+ * may contain session credential or PII
4
+ * @param {import('@gasket/core').GasketConfig} config the Gasket config
5
+ * @returns {string[]} an array of cookie names
6
+ */
7
+ const sensitiveCookies = (config) => {
8
+ if (
9
+ typeof config.elasticAPM === 'undefined' ||
10
+ typeof config.elasticAPM.sensitiveCookies === 'undefined'
11
+ ) {
12
+ return [];
13
+ }
14
+
15
+ return config.elasticAPM.sensitiveCookies;
16
+ };
17
+
18
+ /**
19
+ * Redacts the contents of user-specified sensitive cookies
20
+ * @type {import('.').filterSensitiveCookies}
21
+ */
22
+ const filterSensitiveCookies = function (config) {
23
+ return function (payload) {
24
+ const cookiesToRedact = sensitiveCookies(config);
25
+
26
+ if (
27
+ payload.context &&
28
+ payload.context.request &&
29
+ payload.context.request.headers &&
30
+ payload.context.request.headers.cookie
31
+ ) {
32
+ let cookie = payload.context.request.headers.cookie;
33
+ cookiesToRedact.forEach((sc) => {
34
+ cookie = cookie.replace(
35
+ new RegExp(sc + '=([^;]+)'),
36
+ sc + '=[REDACTED]'
37
+ );
38
+ });
39
+
40
+ payload.context.request.headers.cookie = cookie;
41
+ }
42
+
43
+ if (payload.context &&
44
+ payload.context.request &&
45
+ payload.context.request.cookies
46
+ ) {
47
+ cookiesToRedact.forEach((sc) => {
48
+ if (sc in payload.context.request.cookies) {
49
+ payload.context.request.cookies[sc] = '[REDACTED]';
50
+ }
51
+ });
52
+ }
53
+
54
+ return payload;
55
+ };
56
+ };
57
+
58
+ module.exports = {
59
+ filterSensitiveCookies,
60
+ sensitiveCookies
61
+ };
package/lib/create.js ADDED
@@ -0,0 +1,24 @@
1
+ const { name, version, devDependencies } = require('../package.json');
2
+
3
+ /** @type {import('@gasket/core').HookHandler<'create'>} */
4
+ module.exports = function create(gasket, { pkg, files, gasketConfig }) {
5
+ const generatorDir = `${__dirname}/../generator`;
6
+
7
+ gasketConfig.addPlugin('pluginElasticApm', name);
8
+
9
+ pkg.add('dependencies', {
10
+ [name]: `^${version}`,
11
+ 'dotenv': devDependencies.dotenv,
12
+ 'elastic-apm-node': devDependencies['elastic-apm-node']
13
+ });
14
+
15
+ pkg.extend((current) => {
16
+ return {
17
+ scripts: {
18
+ start: `NODE_OPTIONS=--import=./setup.js ${current.scripts.start}`
19
+ }
20
+ };
21
+ });
22
+
23
+ files.add(`${generatorDir}/*`);
24
+ };
package/lib/index.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { AgentConfigOptions, Transaction, Payload, Agent } from 'elastic-apm-node';
2
+ import type { GasketConfig, Plugin, MaybeAsync } from '@gasket/core';
3
+ import type { RequestLike, GasketRequest } from '@gasket/request';
4
+
5
+ export function filterSensitiveCookies(config: GasketConfig): (Payload) => Payload;
6
+
7
+ export interface ExtendedAgentConfigOptions extends AgentConfigOptions {
8
+ sensitiveCookies?: Array<string>;
9
+ }
10
+
11
+ declare module '@gasket/core' {
12
+ export interface GasketConfig {
13
+ elasticAPM?: ExtendedAgentConfigOptions;
14
+ }
15
+
16
+ export interface Gasket {
17
+ apm?: Agent;
18
+ }
19
+
20
+ export interface GasketActions {
21
+ getApmTransaction(
22
+ req: RequestLike
23
+ ): Promise<Transaction | void>
24
+ }
25
+
26
+ export interface HookExecTypes {
27
+ apmTransaction(
28
+ transaction: Transaction,
29
+ context: {
30
+ req: import('@gasket/request').GasketRequest; // TS is getting confused with the GasketRequest from @gasket/core
31
+ }
32
+ ): MaybeAsync<void>;
33
+ }
34
+ }
35
+
36
+ declare const plugin: Plugin;
37
+
38
+ export default plugin;
package/lib/index.js ADDED
@@ -0,0 +1,61 @@
1
+ /// <reference types="create-gasket-app" />
2
+ /// <reference types="@gasket/plugin-metadata" />
3
+
4
+ const actions = require('./actions');
5
+ const create = require('./create');
6
+ const configure = require('./configure');
7
+ const {
8
+ name,
9
+ version,
10
+ description
11
+ } = require('../package.json');
12
+
13
+ /** @type {import('@gasket/core').Plugin} */
14
+ const plugin = {
15
+ name,
16
+ version,
17
+ description,
18
+ actions,
19
+ hooks: {
20
+ configure,
21
+ create,
22
+ metadata(gasket, meta) {
23
+ return {
24
+ ...meta,
25
+ actions: [
26
+ {
27
+ name: 'getApmTransaction',
28
+ description: 'Get the APM transaction data',
29
+ link: 'README.md#getApmTransaction'
30
+ }
31
+ ],
32
+ configurations: [
33
+ {
34
+ name: 'elasticAPM',
35
+ link: 'README.md#configuration',
36
+ description: 'Configuration to provide additional setup helpers',
37
+ type: 'object'
38
+ },
39
+ {
40
+ name: 'elasticAPM.sensitiveCookies',
41
+ link: 'README.md#configuration',
42
+ description: 'List of sensitive cookies to filter',
43
+ type: 'string[]',
44
+ default: '[]'
45
+ }
46
+ ],
47
+ lifecycles: [
48
+ {
49
+ name: 'apmTransaction',
50
+ method: 'exec',
51
+ description: 'Modify the APM transaction',
52
+ link: 'README.md#apmtransaction',
53
+ parent: 'middleware'
54
+ }
55
+ ]
56
+ };
57
+ }
58
+ }
59
+ };
60
+
61
+ module.exports = plugin;
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@gasket/plugin-elastic-apm",
3
+ "version": "0.0.0-canary-20250922152503",
4
+ "description": "Adds Elastic APM instrumentation to your application",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "files": [
8
+ "lib",
9
+ "EXAMPLES.md"
10
+ ],
11
+ "repository": "godaddy/gasket.git",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "keywords": [
16
+ "apm",
17
+ "elastic",
18
+ "gasket",
19
+ "plugin"
20
+ ],
21
+ "author": "GoDaddy Operating Company, LLC",
22
+ "license": "MIT",
23
+ "bugs": "https://github.com/godaddy/gasket/issues",
24
+ "homepage": "https://github.com/godaddy/gasket/tree/main/packages/gasket-plugin-elastic-apm",
25
+ "dependencies": {
26
+ "@gasket/request": "^0.0.0-canary-20250922152503"
27
+ },
28
+ "devDependencies": {
29
+ "dotenv": "^16.4.7",
30
+ "elastic-apm-node": "^4.11.0",
31
+ "jest": "^29.7.0",
32
+ "nyc": "^15.1.0",
33
+ "create-gasket-app": "^0.0.0-canary-20250922152503",
34
+ "@gasket/plugin-metadata": "^0.0.0-canary-20250922152503",
35
+ "@gasket/core": "^0.0.0-canary-20250922152503"
36
+ },
37
+ "jest": {
38
+ "testEnvironment": "node"
39
+ },
40
+ "scripts": {
41
+ "lint": "eslint .",
42
+ "lint:fix": "pnpm run lint --fix",
43
+ "posttest": "pnpm run lint && pnpm run typecheck",
44
+ "test": "cross-env NODE_OPTIONS='--unhandled-rejections=strict' jest",
45
+ "test:coverage": "pnpm run test --coverage",
46
+ "test:watch": "pnpm run test --watch",
47
+ "typecheck": "tsc",
48
+ "typecheck:watch": "tsc --watch"
49
+ }
50
+ }