@watchtowerobservability/node 0.7.2 → 0.7.3

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/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.7.3
6
+
7
+ - URL scrubbing is narrower: only secret-looking path segments are redacted (UUIDs, hex runs >= 16, JWTs, digit runs >= 16, random-looking tokens >= 16 chars mixing letters and digits). Hosts are never touched (also scheme-relative `//host`); readable words, kebab/snake slugs and short ids stay (`/atlas/.well-known/jwks.json`, `/gallery/legal-consultation-intake`, `/config/a1b2c3d4`). Behaviour change: 10 to 15 character ids that used to be redacted now show. Same rule as the browser SDK and the gateway. `looksSecret` is now `isSecretSegment`.
8
+ - `wt-next-sourcemaps --inject` / `uploadSourcemaps({ inject: true })`: writes a debug id into every `.next/static/**/*.js` chunk that has a map (`//# debugId=<uuid>` and a registration for the browser SDK) and into its map (`debugId`), then uploads with `debug_id`. Stable across rebuilds (hash of the chunk).
9
+ - README: custom-queue recipe names `job_queue_jobs` as the depth metric the Queues page and queue alerts read.
10
+
5
11
  ## 0.7.2
6
12
 
7
13
  - `wt-next-sourcemaps` / `uploadSourcemaps()`: default API is `https://watchtowerops.net` (the old default did not resolve); one env name `WT_API_URL` (`WT_API` still works with a warning); a bad host fails fast naming it. Uploads run 8 at a time, retry 429/5xx honoring `Retry-After`, continue past failures, print `{uploaded, skipped, failed}` and exit 1 when any failed. Each map is sent with `for=<chunk path>`. Bodies are sent gzipped. `uploadSourcemaps()` now resolves `{uploaded, skipped, failed}` instead of throwing on a failed map.
package/README.md CHANGED
@@ -39,9 +39,9 @@ wt.log('info', 'started', { port: 3000 }); // OTLP log, linked to the active
39
39
  flushes and exits with code 1 like Node does, only when no other handler is registered.
40
40
  Request bodies, headers and query arguments are never recorded. URLs are scrubbed on every span, including spans other
41
41
  libraries create (Next.js, `node:http`, `fetch`): the query string is dropped (`url.query` is removed) and path segments
42
- that look like secrets or ids (24 characters or more, or 10 or more mixing letters and digits; UUIDs included) become
43
- `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names; `http.route` is kept.
44
- `/api/feed/<token>/csv?since=x` is recorded as `/api/feed/:redacted/csv`. Plain words, numbers and short ids stay readable.
42
+ that look like secrets (UUIDs, hex runs of 16 or more, JWTs, digit runs of 16 or more, or random-looking tokens of 16 or more
43
+ characters mixing letters and digits) become `:redacted`; the host never changes, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names; `http.route` is kept.
44
+ `/api/feed/<token>/csv?since=x` is recorded as `/api/feed/:redacted/csv`. Plain words, kebab and snake slugs (`legal-consultation-intake`), short ids (`/config/a1b2c3d4`) and file names stay readable.
45
45
  Pass `urlScrubbing: false` to record URLs as the instrumentation produced them. Your `redact` hook sees scrubbed values.
46
46
 
47
47
  ## Auto-instrumentation and preload
@@ -299,6 +299,8 @@ with `error.type`; the error message is not recorded.
299
299
  runs a PRODUCER span and hands you the `traceparent` headers to store in the job row (a `headers jsonb` column).
300
300
  The worker does `consume('orders process', { ...same attrs }, [row.headers], () => handle(row))`: a CONSUMER span
301
301
  linked to (and, with one carrier, a child of) the producer, so the trace runs from request to job.
302
+ For depth on the Queues page, record the gauge `job_queue_jobs{framework="my-queue", queue="orders", state="waiting"}` (states `waiting`, `active`, `dead`);
303
+ that is the metric the page and the built-in queue alerts read (`messaging.queue.depth` is read too, but the alerts ignore it).
302
304
 
303
305
  - **kafkajs**: upstream `@opentelemetry/instrumentation-kafkajs` already covers it.
304
306
 
@@ -69,8 +69,8 @@ export interface InitOptions {
69
69
  exporter?: unknown;
70
70
  /**
71
71
  * Scrub URLs on every span, including spans other libraries create (Next.js, node:http, fetch): the query string is dropped
72
- * (`url.query` removed) and path segments that look like secrets or ids (>= 24 chars, or >= 10 chars mixing letters and digits,
73
- * UUIDs included) become `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names.
72
+ * (`url.query` removed) and path segments that look like secrets (UUIDs, hex runs, JWTs, long digit runs, random tokens of >= 16 chars;
73
+ * hosts, readable words, slugs and short ids stay) become `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names.
74
74
  * `http.route` is kept. Default true; `false` records URLs as the instrumentation produced them.
75
75
  */
76
76
  urlScrubbing?: boolean;
@@ -11,6 +11,8 @@ export interface SourcemapOptions {
11
11
  release?: string;
12
12
  /** Keep the .map files after a successful upload (default: delete them so they are never served). */
13
13
  keep?: boolean;
14
+ /** Before uploading, write a debug id into each chunk (`//# debugId=` plus a runtime registration) and its map (`debugId`), so errors resolve by id instead of release + file name. Default false (`--inject` on the CLI). */
15
+ inject?: boolean;
14
16
  fetch?: typeof fetch;
15
17
  log?: (line: string) => void;
16
18
  }
@@ -39,6 +39,7 @@ exports.uploadSourcemaps = uploadSourcemaps;
39
39
  const fs = __importStar(require("node:fs"));
40
40
  const nodePath = __importStar(require("node:path"));
41
41
  const zlib = __importStar(require("node:zlib"));
42
+ const next_debugid_js_1 = require("./next-debugid.js");
42
43
  /**
43
44
  * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
44
45
  * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
@@ -116,6 +117,9 @@ async function uploadSourcemaps(o = {}) {
116
117
  await sleep(Number.isFinite(ra) && ra > 0 ? Math.min(ra, 30) * 1000 : Math.min(250 * 2 ** attempt, 8000));
117
118
  }
118
119
  };
120
+ const ids = o.inject && fs.existsSync(dir) ? (0, next_debugid_js_1.injectDebugIds)(dir) : new Map();
121
+ if (o.inject)
122
+ log(`debug ids written for ${ids.size} chunks`);
119
123
  const files = fs.existsSync(dir) ? [...maps(dir)] : [];
120
124
  // release create fails fast: no retry, so a bad host or key surfaces at once
121
125
  const rel = await send('/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ version: release }) }, 0);
@@ -130,6 +134,9 @@ async function uploadSourcemaps(o = {}) {
130
134
  const chunk = chunkFor(file, name);
131
135
  if (chunk)
132
136
  q.for = chunk;
137
+ const id = ids.get(file);
138
+ if (id)
139
+ q.debug_id = id;
133
140
  try {
134
141
  const res = await send(`/artifacts?${new URLSearchParams(q)}`, {
135
142
  method: 'POST', headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip' },
@@ -0,0 +1,8 @@
1
+ /** SHA-256 of the JS bytes, first 16 as a v4-shaped UUID: the same chunk always gets the same id, so rebuilds are stable. */
2
+ export declare function debugIdFor(js: string): string;
3
+ /**
4
+ * For every `<chunk>.js` with a sibling `<chunk>.js.map` under `dir`: append the runtime registration (so the browser SDK sends the id with
5
+ * error frames) and `//# debugId=<uuid>` to the chunk, and set `"debugId"` in the map. Chunks that already carry an id keep it. Returns map path to id.
6
+ * `urlPrefix` is the served path of `dir` (default `/_next/static`).
7
+ */
8
+ export declare function injectDebugIds(dir: string, urlPrefix?: string): Map<string, string>;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.debugIdFor = debugIdFor;
37
+ exports.injectDebugIds = injectDebugIds;
38
+ // Debug ids for Next builds: same convention as the browser SDK's bundler plugins (`//# debugId=<uuid>` in the chunk, `"debugId"` in its map).
39
+ const crypto = __importStar(require("node:crypto"));
40
+ const fs = __importStar(require("node:fs"));
41
+ const nodePath = __importStar(require("node:path"));
42
+ const COMMENT = /^\/\/# debugId=([0-9a-f-]{36})\s*$/m;
43
+ /** SHA-256 of the JS bytes, first 16 as a v4-shaped UUID: the same chunk always gets the same id, so rebuilds are stable. */
44
+ function debugIdFor(js) {
45
+ const h = crypto.createHash('sha256').update(js).digest();
46
+ h[6] = (h[6] & 0x0f) | 0x40;
47
+ h[8] = (h[8] & 0x3f) | 0x80;
48
+ const x = h.subarray(0, 16).toString('hex');
49
+ return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;
50
+ }
51
+ function* jsFiles(dir) {
52
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
53
+ const p = nodePath.join(dir, e.name);
54
+ if (e.isDirectory())
55
+ yield* jsFiles(p);
56
+ else if (e.name.endsWith('.js'))
57
+ yield p;
58
+ }
59
+ }
60
+ /**
61
+ * For every `<chunk>.js` with a sibling `<chunk>.js.map` under `dir`: append the runtime registration (so the browser SDK sends the id with
62
+ * error frames) and `//# debugId=<uuid>` to the chunk, and set `"debugId"` in the map. Chunks that already carry an id keep it. Returns map path to id.
63
+ * `urlPrefix` is the served path of `dir` (default `/_next/static`).
64
+ */
65
+ function injectDebugIds(dir, urlPrefix = '/_next/static') {
66
+ const out = new Map();
67
+ for (const js of jsFiles(dir)) {
68
+ const mapFile = `${js}.map`;
69
+ if (!fs.existsSync(mapFile))
70
+ continue;
71
+ let src = fs.readFileSync(js, 'utf8');
72
+ const old = COMMENT.exec(src);
73
+ const id = old ? old[1] : debugIdFor(src);
74
+ if (!old) {
75
+ const url = `${urlPrefix}/${nodePath.relative(dir, js).split(nodePath.sep).join('/')}`;
76
+ const snippet = `;(function(){try{var w=typeof window!=="undefined"?window:globalThis;(w._wtDebugIds=w._wtDebugIds||{})[${JSON.stringify(url)}]="${id}"}catch(e){}})();`;
77
+ const m = /\n?\/\/[#@] sourceMappingURL=[^\n]*\s*$/.exec(src);
78
+ const body = m ? src.slice(0, m.index) : src;
79
+ src = `${body}\n${snippet}${m ? `\n${m[0].trim()}` : ''}\n//# debugId=${id}\n`;
80
+ fs.writeFileSync(js, src);
81
+ }
82
+ const map = JSON.parse(fs.readFileSync(mapFile, 'utf8'));
83
+ if (map.debugId !== id)
84
+ fs.writeFileSync(mapFile, JSON.stringify({ ...map, debugId: id }));
85
+ out.set(mapFile, id);
86
+ }
87
+ return out;
88
+ }
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- // `wt-next-sourcemaps [dir]`: upload .next/static source maps after `next build` (env: WT_API_KEY, WT_PROJECT, WT_RELEASE, WT_API_URL), then delete them.
4
+ // `wt-next-sourcemaps [--inject] [dir]`: upload .next/static source maps after `next build` (env: WT_API_KEY, WT_PROJECT, WT_RELEASE, WT_API_URL), then delete them. `--inject` first writes a debug id into every chunk and map.
5
5
  const next_build_js_1 = require("./integrations/next-build.js");
6
- (0, next_build_js_1.uploadSourcemaps)({ dir: process.argv[2], log: (l) => console.log(`[watchtower] ${l}`) }).then((r) => { if (r.failed > 0)
6
+ const args = process.argv.slice(2);
7
+ (0, next_build_js_1.uploadSourcemaps)({ dir: args.find((a) => !a.startsWith('--')), inject: args.includes('--inject'), log: (l) => console.log(`[watchtower] ${l}`) }).then((r) => { if (r.failed > 0)
7
8
  process.exit(1); }).catch((e) => {
8
9
  console.error(`[watchtower] source map upload failed: ${e.message}`);
9
10
  process.exit(1);
@@ -1,8 +1,12 @@
1
1
  // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
2
  import type { SpanProcessor } from '@opentelemetry/sdk-trace';
3
- /** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
4
- export declare function looksSecret(seg: string): boolean;
5
- /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
3
+ /**
4
+ * A path segment that looks like a secret: UUID, hex run >= 16, JWT, digit run >= 16, or an opaque token (>= 16 chars of
5
+ * [A-Za-z0-9_+=-] with a letter and a digit that is not a readable kebab/snake slug). Words, slugs, short ids and file names stay.
6
+ * Same rule in the browser SDK and the gateway (`redact.ScrubURL`).
7
+ */
8
+ export declare function isSecretSegment(s: string): boolean;
9
+ /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. The scheme and host are never touched. */
6
10
  export declare function scrubUrl(value: string): string;
7
11
  /** Span processor: scrubs URL attributes (query dropped, `url.query` removed, secret path segments redacted) and URLs inside the span name. `http.route` is kept. */
8
12
  export declare function urlScrubber(): SpanProcessor;
package/dist/cjs/scrub.js CHANGED
@@ -1,19 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.looksSecret = looksSecret;
3
+ exports.isSecretSegment = isSecretSegment;
4
4
  exports.scrubUrl = scrubUrl;
5
5
  exports.urlScrubber = urlScrubber;
6
6
  const URL_KEYS = ['http.target', 'url.full', 'url.path', 'http.url', 'http.request.url'];
7
7
  const QUERY_KEYS = ['url.query'];
8
- /** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
9
- function looksSecret(seg) {
10
- return seg.length >= 24 || (seg.length >= 10 && /[A-Za-z]/.test(seg) && /\d/.test(seg));
8
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
+ const HEX = /^[0-9a-f]{16,}$/i;
10
+ const JWT = /^eyJ[\w-]*\.[\w-]+\.[\w-]*$/;
11
+ const DIGITS = /^\d{16,}$/;
12
+ const TOKEN = /^[A-Za-z0-9_+=-]{16,}$/;
13
+ // readable word-ish part of a kebab/snake slug: `legal`, `Intake`, `q1`, `2024`
14
+ const PART = /^([A-Za-z][a-z]*\d{0,2}|\d{1,4})$/;
15
+ /**
16
+ * A path segment that looks like a secret: UUID, hex run >= 16, JWT, digit run >= 16, or an opaque token (>= 16 chars of
17
+ * [A-Za-z0-9_+=-] with a letter and a digit that is not a readable kebab/snake slug). Words, slugs, short ids and file names stay.
18
+ * Same rule in the browser SDK and the gateway (`redact.ScrubURL`).
19
+ */
20
+ function isSecretSegment(s) {
21
+ return UUID.test(s) || HEX.test(s) || JWT.test(s) || DIGITS.test(s) || (TOKEN.test(s) && /\d/.test(s) && /[a-z]/i.test(s) && !s.split(/[-_]/).every((p) => PART.test(p)));
11
22
  }
12
- /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
23
+ /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. The scheme and host are never touched. */
13
24
  function scrubUrl(value) {
14
- const m = /^(?:([a-z][a-z0-9+.-]*:\/\/)([^/?#]*))?([^?#]*)/i.exec(value);
15
- const origin = m[1] ? m[1] + m[2].replace(/^[^@]*@/, '') : '';
16
- return origin + m[3].split('/').map((s) => (looksSecret(s) ? ':redacted' : s)).join('/');
25
+ const m = /^(?:([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*))?([^?#]*)/i.exec(value);
26
+ const origin = m[2] === undefined ? '' : `${m[1] ?? ''}//${m[2].replace(/^[^@]*@/, '')}`;
27
+ return origin + m[3].split('/').map((s) => (isSecretSegment(s) ? ':redacted' : s)).join('/');
17
28
  }
18
29
  function scrubName(name) {
19
30
  return name.split(' ').map((t) => (/^(https?:\/\/|\/)/i.test(t) ? scrubUrl(t) : t)).join(' ');
@@ -1,2 +1,2 @@
1
1
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
2
- export declare const VERSION = "0.7.2";
2
+ export declare const VERSION = "0.7.3";
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
4
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
5
- exports.VERSION = '0.7.2';
5
+ exports.VERSION = '0.7.3';
@@ -69,8 +69,8 @@ export interface InitOptions {
69
69
  exporter?: unknown;
70
70
  /**
71
71
  * Scrub URLs on every span, including spans other libraries create (Next.js, node:http, fetch): the query string is dropped
72
- * (`url.query` removed) and path segments that look like secrets or ids (>= 24 chars, or >= 10 chars mixing letters and digits,
73
- * UUIDs included) become `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names.
72
+ * (`url.query` removed) and path segments that look like secrets (UUIDs, hex runs, JWTs, long digit runs, random tokens of >= 16 chars;
73
+ * hosts, readable words, slugs and short ids stay) become `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names.
74
74
  * `http.route` is kept. Default true; `false` records URLs as the instrumentation produced them.
75
75
  */
76
76
  urlScrubbing?: boolean;
@@ -11,6 +11,8 @@ export interface SourcemapOptions {
11
11
  release?: string;
12
12
  /** Keep the .map files after a successful upload (default: delete them so they are never served). */
13
13
  keep?: boolean;
14
+ /** Before uploading, write a debug id into each chunk (`//# debugId=` plus a runtime registration) and its map (`debugId`), so errors resolve by id instead of release + file name. Default false (`--inject` on the CLI). */
15
+ inject?: boolean;
14
16
  fetch?: typeof fetch;
15
17
  log?: (line: string) => void;
16
18
  }
@@ -2,6 +2,7 @@
2
2
  import * as fs from 'node:fs';
3
3
  import * as nodePath from 'node:path';
4
4
  import * as zlib from 'node:zlib';
5
+ import { injectDebugIds } from './next-debugid.js';
5
6
  /**
6
7
  * `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`: turns on `productionBrowserSourceMaps` so
7
8
  * `next build` writes client maps (works with webpack and Turbopack). Then run `wt-next-sourcemaps` after the build
@@ -79,6 +80,9 @@ export async function uploadSourcemaps(o = {}) {
79
80
  await sleep(Number.isFinite(ra) && ra > 0 ? Math.min(ra, 30) * 1000 : Math.min(250 * 2 ** attempt, 8000));
80
81
  }
81
82
  };
83
+ const ids = o.inject && fs.existsSync(dir) ? injectDebugIds(dir) : new Map();
84
+ if (o.inject)
85
+ log(`debug ids written for ${ids.size} chunks`);
82
86
  const files = fs.existsSync(dir) ? [...maps(dir)] : [];
83
87
  // release create fails fast: no retry, so a bad host or key surfaces at once
84
88
  const rel = await send('/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ version: release }) }, 0);
@@ -93,6 +97,9 @@ export async function uploadSourcemaps(o = {}) {
93
97
  const chunk = chunkFor(file, name);
94
98
  if (chunk)
95
99
  q.for = chunk;
100
+ const id = ids.get(file);
101
+ if (id)
102
+ q.debug_id = id;
96
103
  try {
97
104
  const res = await send(`/artifacts?${new URLSearchParams(q)}`, {
98
105
  method: 'POST', headers: { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip' },
@@ -0,0 +1,8 @@
1
+ /** SHA-256 of the JS bytes, first 16 as a v4-shaped UUID: the same chunk always gets the same id, so rebuilds are stable. */
2
+ export declare function debugIdFor(js: string): string;
3
+ /**
4
+ * For every `<chunk>.js` with a sibling `<chunk>.js.map` under `dir`: append the runtime registration (so the browser SDK sends the id with
5
+ * error frames) and `//# debugId=<uuid>` to the chunk, and set `"debugId"` in the map. Chunks that already carry an id keep it. Returns map path to id.
6
+ * `urlPrefix` is the served path of `dir` (default `/_next/static`).
7
+ */
8
+ export declare function injectDebugIds(dir: string, urlPrefix?: string): Map<string, string>;
@@ -0,0 +1,51 @@
1
+ // Debug ids for Next builds: same convention as the browser SDK's bundler plugins (`//# debugId=<uuid>` in the chunk, `"debugId"` in its map).
2
+ import * as crypto from 'node:crypto';
3
+ import * as fs from 'node:fs';
4
+ import * as nodePath from 'node:path';
5
+ const COMMENT = /^\/\/# debugId=([0-9a-f-]{36})\s*$/m;
6
+ /** SHA-256 of the JS bytes, first 16 as a v4-shaped UUID: the same chunk always gets the same id, so rebuilds are stable. */
7
+ export function debugIdFor(js) {
8
+ const h = crypto.createHash('sha256').update(js).digest();
9
+ h[6] = (h[6] & 0x0f) | 0x40;
10
+ h[8] = (h[8] & 0x3f) | 0x80;
11
+ const x = h.subarray(0, 16).toString('hex');
12
+ return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;
13
+ }
14
+ function* jsFiles(dir) {
15
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
16
+ const p = nodePath.join(dir, e.name);
17
+ if (e.isDirectory())
18
+ yield* jsFiles(p);
19
+ else if (e.name.endsWith('.js'))
20
+ yield p;
21
+ }
22
+ }
23
+ /**
24
+ * For every `<chunk>.js` with a sibling `<chunk>.js.map` under `dir`: append the runtime registration (so the browser SDK sends the id with
25
+ * error frames) and `//# debugId=<uuid>` to the chunk, and set `"debugId"` in the map. Chunks that already carry an id keep it. Returns map path to id.
26
+ * `urlPrefix` is the served path of `dir` (default `/_next/static`).
27
+ */
28
+ export function injectDebugIds(dir, urlPrefix = '/_next/static') {
29
+ const out = new Map();
30
+ for (const js of jsFiles(dir)) {
31
+ const mapFile = `${js}.map`;
32
+ if (!fs.existsSync(mapFile))
33
+ continue;
34
+ let src = fs.readFileSync(js, 'utf8');
35
+ const old = COMMENT.exec(src);
36
+ const id = old ? old[1] : debugIdFor(src);
37
+ if (!old) {
38
+ const url = `${urlPrefix}/${nodePath.relative(dir, js).split(nodePath.sep).join('/')}`;
39
+ const snippet = `;(function(){try{var w=typeof window!=="undefined"?window:globalThis;(w._wtDebugIds=w._wtDebugIds||{})[${JSON.stringify(url)}]="${id}"}catch(e){}})();`;
40
+ const m = /\n?\/\/[#@] sourceMappingURL=[^\n]*\s*$/.exec(src);
41
+ const body = m ? src.slice(0, m.index) : src;
42
+ src = `${body}\n${snippet}${m ? `\n${m[0].trim()}` : ''}\n//# debugId=${id}\n`;
43
+ fs.writeFileSync(js, src);
44
+ }
45
+ const map = JSON.parse(fs.readFileSync(mapFile, 'utf8'));
46
+ if (map.debugId !== id)
47
+ fs.writeFileSync(mapFile, JSON.stringify({ ...map, debugId: id }));
48
+ out.set(mapFile, id);
49
+ }
50
+ return out;
51
+ }
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // `wt-next-sourcemaps [dir]`: upload .next/static source maps after `next build` (env: WT_API_KEY, WT_PROJECT, WT_RELEASE, WT_API_URL), then delete them.
2
+ // `wt-next-sourcemaps [--inject] [dir]`: upload .next/static source maps after `next build` (env: WT_API_KEY, WT_PROJECT, WT_RELEASE, WT_API_URL), then delete them. `--inject` first writes a debug id into every chunk and map.
3
3
  import { uploadSourcemaps } from './integrations/next-build.js';
4
- uploadSourcemaps({ dir: process.argv[2], log: (l) => console.log(`[watchtower] ${l}`) }).then((r) => { if (r.failed > 0)
4
+ const args = process.argv.slice(2);
5
+ uploadSourcemaps({ dir: args.find((a) => !a.startsWith('--')), inject: args.includes('--inject'), log: (l) => console.log(`[watchtower] ${l}`) }).then((r) => { if (r.failed > 0)
5
6
  process.exit(1); }).catch((e) => {
6
7
  console.error(`[watchtower] source map upload failed: ${e.message}`);
7
8
  process.exit(1);
@@ -1,8 +1,12 @@
1
1
  // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
2
2
  import type { SpanProcessor } from '@opentelemetry/sdk-trace';
3
- /** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
4
- export declare function looksSecret(seg: string): boolean;
5
- /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
3
+ /**
4
+ * A path segment that looks like a secret: UUID, hex run >= 16, JWT, digit run >= 16, or an opaque token (>= 16 chars of
5
+ * [A-Za-z0-9_+=-] with a letter and a digit that is not a readable kebab/snake slug). Words, slugs, short ids and file names stay.
6
+ * Same rule in the browser SDK and the gateway (`redact.ScrubURL`).
7
+ */
8
+ export declare function isSecretSegment(s: string): boolean;
9
+ /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. The scheme and host are never touched. */
6
10
  export declare function scrubUrl(value: string): string;
7
11
  /** Span processor: scrubs URL attributes (query dropped, `url.query` removed, secret path segments redacted) and URLs inside the span name. `http.route` is kept. */
8
12
  export declare function urlScrubber(): SpanProcessor;
package/dist/esm/scrub.js CHANGED
@@ -1,14 +1,25 @@
1
1
  const URL_KEYS = ['http.target', 'url.full', 'url.path', 'http.url', 'http.request.url'];
2
2
  const QUERY_KEYS = ['url.query'];
3
- /** A path segment that reads like a secret or an opaque id: >= 24 chars, or >= 10 chars mixing a letter and a digit (UUIDs included). */
4
- export function looksSecret(seg) {
5
- return seg.length >= 24 || (seg.length >= 10 && /[A-Za-z]/.test(seg) && /\d/.test(seg));
3
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
+ const HEX = /^[0-9a-f]{16,}$/i;
5
+ const JWT = /^eyJ[\w-]*\.[\w-]+\.[\w-]*$/;
6
+ const DIGITS = /^\d{16,}$/;
7
+ const TOKEN = /^[A-Za-z0-9_+=-]{16,}$/;
8
+ // readable word-ish part of a kebab/snake slug: `legal`, `Intake`, `q1`, `2024`
9
+ const PART = /^([A-Za-z][a-z]*\d{0,2}|\d{1,4})$/;
10
+ /**
11
+ * A path segment that looks like a secret: UUID, hex run >= 16, JWT, digit run >= 16, or an opaque token (>= 16 chars of
12
+ * [A-Za-z0-9_+=-] with a letter and a digit that is not a readable kebab/snake slug). Words, slugs, short ids and file names stay.
13
+ * Same rule in the browser SDK and the gateway (`redact.ScrubURL`).
14
+ */
15
+ export function isSecretSegment(s) {
16
+ return UUID.test(s) || HEX.test(s) || JWT.test(s) || DIGITS.test(s) || (TOKEN.test(s) && /\d/.test(s) && /[a-z]/i.test(s) && !s.split(/[-_]/).every((p) => PART.test(p)));
6
17
  }
7
- /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. */
18
+ /** Drop the query string and fragment, strip `user:pass@`, and replace secret-looking path segments with `:redacted`. The scheme and host are never touched. */
8
19
  export function scrubUrl(value) {
9
- const m = /^(?:([a-z][a-z0-9+.-]*:\/\/)([^/?#]*))?([^?#]*)/i.exec(value);
10
- const origin = m[1] ? m[1] + m[2].replace(/^[^@]*@/, '') : '';
11
- return origin + m[3].split('/').map((s) => (looksSecret(s) ? ':redacted' : s)).join('/');
20
+ const m = /^(?:([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*))?([^?#]*)/i.exec(value);
21
+ const origin = m[2] === undefined ? '' : `${m[1] ?? ''}//${m[2].replace(/^[^@]*@/, '')}`;
22
+ return origin + m[3].split('/').map((s) => (isSecretSegment(s) ? ':redacted' : s)).join('/');
12
23
  }
13
24
  function scrubName(name) {
14
25
  return name.split(' ').map((t) => (/^(https?:\/\/|\/)/i.test(t) ? scrubUrl(t) : t)).join(' ');
@@ -1,2 +1,2 @@
1
1
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
2
- export declare const VERSION = "0.7.2";
2
+ export declare const VERSION = "0.7.3";
@@ -1,2 +1,2 @@
1
1
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
2
- export const VERSION = '0.7.2';
2
+ export const VERSION = '0.7.3';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@watchtowerobservability/node",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/watchtowerobservability/watchtower-node.git"