@voight-trace/voighttrace-sdk 0.0.0-stage → 1.0.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 (4) hide show
  1. package/README.md +228 -2
  2. package/index.d.ts +141 -0
  3. package/index.js +614 -0
  4. package/package.json +26 -4
package/README.md CHANGED
@@ -1,3 +1,229 @@
1
- # Temporary Holding Version
1
+ # Voight Trace — Official SDK Collector (`voighttrace-sdk`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/badge/version-1.0.0-blue.svg)](https://voighttrace.com)
4
+ [![license](https://img.shields.io/badge/license-Apache--2.0-green.svg)](https://voighttrace.com)
5
+
6
+ Official SDK Collector for **Voight Trace** (`@voight-trace/voighttrace-sdk`). It provides non-blocking, asynchronous telemetry capture to detect, classify, and audit AI Agents, LLM crawlers (OpenAI GPTBot, ClaudeBot, PerplexityBot, ByteDance Bytespider), and human visitors recommended by generative AI platforms.
7
+
8
+ ---
9
+
10
+ ## 🚀 Quickstart & Framework Integrations
11
+
12
+ ### 1. Installation
13
+ ```bash
14
+ npm install @voight-trace/voighttrace-sdk
15
+ # or
16
+ yarn add @voight-trace/voighttrace-sdk
17
+ # or
18
+ pnpm add @voight-trace/voighttrace-sdk
19
+ ```
20
+
21
+ ---
22
+
23
+ ### 2. Next.js Integration (App Router & Pages Router)
24
+
25
+ In Next.js, create or edit `middleware.ts` (or `middleware.js`) in your project root or `src/` directory:
26
+
27
+ ```typescript
28
+ // middleware.ts
29
+ import { NextResponse } from 'next/server';
30
+ import type { NextRequest } from 'next/server';
31
+ import { VoightTraceCollector } from '@voight-trace/voighttrace-sdk';
32
+
33
+ const tracker = new VoightTraceCollector({
34
+ apiKey: process.env.VOIGHT_TRACE_API_KEY, // e.g. "vt_live_9a8f4c2e..."
35
+ siteId: process.env.VOIGHT_TRACE_SITE_ID // e.g. "018f2d5e-7a91..."
36
+ });
37
+
38
+ // Non-blocking Next.js middleware wrapper (zero latency impact)
39
+ export const middleware = tracker.nextMiddleware(async (request: NextRequest) => {
40
+ // Your custom routing or auth logic here
41
+ return NextResponse.next();
42
+ });
43
+
44
+ // Match all requests except static files, images and favicon
45
+ export const config = {
46
+ matcher: ['/((?!_next/static|_next/image|favicon.ico).*)']
47
+ };
48
+ ```
49
+
50
+ ---
51
+
52
+ ### 3. Express.js Integration
53
+
54
+ ```javascript
55
+ import express from 'express';
56
+ import { VoightTraceCollector } from '@voight-trace/voighttrace-sdk';
57
+
58
+ const app = express();
59
+
60
+ const tracker = new VoightTraceCollector({
61
+ apiKey: process.env.VOIGHT_TRACE_API_KEY,
62
+ siteId: process.env.VOIGHT_TRACE_SITE_ID
63
+ });
64
+
65
+ // Register non-blocking middleware BEFORE your route handlers
66
+ app.use(tracker.middleware());
67
+
68
+ app.get('/pricing', (req, res) => {
69
+ res.json({ plan: 'enterprise', price: 499 });
70
+ });
71
+
72
+ app.listen(3000, () => {
73
+ console.log('App running on port 3000 with Voight Trace active.');
74
+ });
75
+ ```
76
+
77
+ ---
78
+
79
+ ### 4. Fastify Integration
80
+
81
+ ```javascript
82
+ import Fastify from 'fastify';
83
+ import { VoightTraceCollector } from '@voight-trace/voighttrace-sdk';
84
+
85
+ const fastify = Fastify({ logger: true });
86
+
87
+ const tracker = new VoightTraceCollector({
88
+ apiKey: process.env.VOIGHT_TRACE_API_KEY,
89
+ siteId: process.env.VOIGHT_TRACE_SITE_ID
90
+ });
91
+
92
+ // Register Fastify plugin hook
93
+ fastify.register(tracker.fastifyPlugin());
94
+
95
+ fastify.get('/products', async (request, reply) => {
96
+ return { status: 'active', items: ['SaaS', 'API'] };
97
+ });
98
+
99
+ fastify.listen({ port: 3000 });
100
+ ```
101
+
102
+ ---
103
+
104
+ ### 5. NestJS Integration
105
+
106
+ In NestJS, apply the middleware in your root `AppModule` using `NestModule`:
107
+
108
+ ```typescript
109
+ // app.module.ts
110
+ import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
111
+ import { VoightTraceCollector } from '@voight-trace/voighttrace-sdk';
112
+
113
+ const tracker = new VoightTraceCollector({
114
+ apiKey: process.env.VOIGHT_TRACE_API_KEY,
115
+ siteId: process.env.VOIGHT_TRACE_SITE_ID
116
+ });
117
+
118
+ @Module({
119
+ imports: [],
120
+ controllers: [],
121
+ providers: []
122
+ })
123
+ export class AppModule implements NestModule {
124
+ configure(consumer: MiddlewareConsumer) {
125
+ consumer
126
+ .apply(tracker.middleware())
127
+ .forRoutes('*');
128
+ }
129
+ }
130
+ ```
131
+
132
+ ---
133
+
134
+ ### 6. Hono Integration (Node.js, Deno & Edge)
135
+
136
+ ```typescript
137
+ import { Hono } from 'hono';
138
+ import { VoightTraceCollector } from '@voight-trace/voighttrace-sdk';
139
+
140
+ const app = new Hono();
141
+
142
+ const tracker = new VoightTraceCollector({
143
+ apiKey: process.env.VOIGHT_TRACE_API_KEY,
144
+ siteId: process.env.VOIGHT_TRACE_SITE_ID
145
+ });
146
+
147
+ // Register non-blocking Hono middleware
148
+ app.use('*', tracker.honoMiddleware());
149
+
150
+ app.get('/api/health', (c) => c.json({ status: 'healthy' }));
151
+
152
+ export default app;
153
+ ```
154
+
155
+ ---
156
+
157
+ ### 7. Koa Integration
158
+
159
+ ```javascript
160
+ import Koa from 'koa';
161
+ import { VoightTraceCollector } from '@voight-trace/voighttrace-sdk';
162
+
163
+ const app = new Koa();
164
+
165
+ const tracker = new VoightTraceCollector({
166
+ apiKey: process.env.VOIGHT_TRACE_API_KEY,
167
+ siteId: process.env.VOIGHT_TRACE_SITE_ID
168
+ });
169
+
170
+ // Register Koa middleware
171
+ app.use(tracker.koaMiddleware());
172
+
173
+ app.use(async (ctx) => {
174
+ ctx.body = { message: 'Hello from Koa with Voight Trace active' };
175
+ });
176
+
177
+ app.listen(3000);
178
+ ```
179
+
180
+ ---
181
+
182
+ ### 8. Configuration Options
183
+
184
+ | Option | Type | Default | Description |
185
+ | :--- | :--- | :--- | :--- |
186
+ | `apiKey` | `string` | `process.env.VOIGHT_TRACE_API_KEY` | **Required.** Secret Ingestion Key (`vt_live_...` or `vt_test_...`). |
187
+ | `siteId` | `string` | `process.env.VOIGHT_TRACE_SITE_ID` | **Required.** Site ID registered in the Voight dashboard. |
188
+ | `tenantId` | `string` | `siteId` | Optional tenant UUID. |
189
+ | `ingestUrl` | `string` | `https://api.voighttrace.com/api/v1/ingestion/events` | Custom Ingestion API URL. |
190
+ | `batchSize` | `number` | `20` | Max events before triggering an immediate flush. |
191
+ | `flushIntervalMs` | `number` | `3000` | Timer interval to flush queued events. |
192
+ | `sampleRate` | `number` | `1.0` | Sampling rate between `0.0` (0%) and `1.0` (100%). |
193
+ | `debug` | `boolean` | `false` | Enables diagnostic logs to stdout. |
194
+ | `disabled` | `boolean` | `false` | Disables telemetry collection (useful in testing). |
195
+
196
+ ---
197
+
198
+ ## 🔒 Privacy & Security by Design (Header & Credential Sanitization)
199
+
200
+ To ensure maximum security and strict compliance with global privacy regulations (GDPR, LGPD) and enterprise SOC2 audits, **`voighttrace-sdk` enforces a strict Header Allowlist policy (`SAFE_AUDIT_HEADERS`)**.
201
+
202
+ The collector **never** collects, stores, or transmits client credentials, session tokens, or sensitive authentication headers.
203
+
204
+ ### 🚫 Prohibited Headers — NEVER Collected
205
+ Any request header capable of carrying private credentials or personally identifiable authentication tokens is **strictly filtered out at the collector layer**:
206
+ * ❌ `Authorization` / `Proxy-Authorization` (Bearer tokens, JWTs, Basic Auth)
207
+ * ❌ `Cookie` / `Set-Cookie` (User sessions, auth cookies, tracking identifiers)
208
+ * ❌ `X-Api-Key` / `Api-Key` / `X-Auth-Token` / `X-Access-Token` (Customer private API keys)
209
+ * ❌ Passwords, custom secret headers, or private payload bodies
210
+
211
+ ### ✅ Permitted Headers (`SAFE_AUDIT_HEADERS`)
212
+ Only standardized, technical context headers strictly required for AI crawler classification, browser architecture detection, and content negotiation are extracted:
213
+ * **Core AI & Traffic Identification:** `user-agent` (identifies AI crawlers & LLM agents), `referer` (detects human referrals from ChatGPT, Claude, Perplexity), `host`, `origin`
214
+ * **Content Negotiation:** `accept`, `accept-encoding`, `accept-language`, `content-type`
215
+ * **Client Hints (Browser Architecture & Device Detection):** `sec-ch-ua`, `sec-ch-ua-mobile`, `sec-ch-ua-platform`, `sec-ch-ua-platform-version`, `sec-ch-ua-model`, `sec-ch-ua-arch`
216
+ * **Browser Request Metadata:** `sec-fetch-dest`, `sec-fetch-mode`, `sec-fetch-site`, `sec-fetch-user`
217
+
218
+ ### 🔍 How to Audit in Code
219
+ The allowlist and sanitization logic are deliberately centralized and exported for transparent security inspection:
220
+ * **Allowlist Constant:** `export const SAFE_AUDIT_HEADERS` in [`index.js`](./index.js) (Line 20)
221
+ * **Sanitizer Function:** `export function filterSafeHeaders(headers)` in [`index.js`](./index.js) (Line 45)
222
+ * Every framework adapter (`Express`, `Fastify`, `Next.js`, `Koa`, `Hono`) routes request headers through this function before enqueueing telemetry.
223
+
224
+ ---
225
+
226
+ ## ⚡ Non-Blocking Guarantee & Performance
227
+ - **Zero Latency Impact:** Observations are queued in-memory and dispatched in background batches via `res.on('finish')`.
228
+ - **Fault-Tolerant:** If the Voight ingestion server or network is temporarily unreachable, events are retried with an in-memory ceiling to prevent memory leaks.
229
+ - **Fail-Safe:** Telemetry collection errors never interrupt or delay the client's HTTP response.
package/index.d.ts ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * List of allowlisted, non-sensitive headers extracted by Voight Trace.
3
+ * Sensitive headers (Authorization, Cookie, X-Api-Key) are strictly excluded.
4
+ */
5
+ export declare const SAFE_AUDIT_HEADERS: readonly string[];
6
+
7
+ /**
8
+ * Extracts only safe, allowlisted headers from an incoming headers object or Headers instance.
9
+ */
10
+ export declare function filterSafeHeaders(headers: any): Record<string, string>;
11
+
12
+ export interface VoightTraceConfig {
13
+ /**
14
+ * Voight Trace Ingestion API Key (starts with vt_live_ or vt_test_)
15
+ */
16
+ apiKey: string;
17
+
18
+ /**
19
+ * Site UUID registered in the Voight dashboard
20
+ */
21
+ siteId: string;
22
+
23
+ /**
24
+ * Tenant UUID (defaults to siteId if omitted)
25
+ */
26
+ tenantId?: string;
27
+
28
+ /**
29
+ * Custom collector instance identifier
30
+ */
31
+ collectorId?: string;
32
+
33
+ /**
34
+ * Ingestion endpoint URL (defaults to https://api.voighttrace.com/api/v1/ingestion/events)
35
+ */
36
+ ingestUrl?: string;
37
+
38
+ /**
39
+ * Maximum events per HTTP dispatch (default: 20)
40
+ */
41
+ batchSize?: number;
42
+
43
+ /**
44
+ * Queue flush interval in milliseconds (default: 3000)
45
+ */
46
+ flushIntervalMs?: number;
47
+
48
+ /**
49
+ * Sampling rate between 0.0 (0%) and 1.0 (100%) (default: 1.0)
50
+ */
51
+ sampleRate?: number;
52
+
53
+ /**
54
+ * Enable verbose diagnostic logging
55
+ */
56
+ debug?: boolean;
57
+
58
+ /**
59
+ * Disable telemetry collection entirely
60
+ */
61
+ disabled?: boolean;
62
+ }
63
+
64
+ export interface TelemetryEvent {
65
+ event_id: string;
66
+ event_type: string;
67
+ schema_version: number;
68
+ tenant_id: string;
69
+ site_id: string;
70
+ collector_id: string;
71
+ collector_type: 'nodejs_sdk';
72
+ observation_id: string;
73
+ correlation_id: string;
74
+ occurred_at: string;
75
+ request: {
76
+ method: string;
77
+ scheme: string;
78
+ host: string;
79
+ path: string;
80
+ query_params: Record<string, any>;
81
+ referer: string;
82
+ user_agent: string;
83
+ selected_headers: Record<string, string>;
84
+ };
85
+ network: {
86
+ ip_hash: string;
87
+ country: string;
88
+ asn: number;
89
+ };
90
+ response: {
91
+ status_code: number;
92
+ duration_ms: number;
93
+ bytes_sent: number;
94
+ };
95
+ }
96
+
97
+ export declare class VoightTraceCollector {
98
+ constructor(config?: VoightTraceConfig);
99
+
100
+ /**
101
+ * Standard Express / Connect / Morgan middleware
102
+ */
103
+ middleware(): (req: any, res: any, next: (err?: any) => void) => void;
104
+
105
+ /**
106
+ * Fastify plugin hook
107
+ */
108
+ fastifyPlugin(): (fastify: any, opts: any, done: (err?: any) => void) => void;
109
+
110
+ /**
111
+ * Next.js Middleware wrapper (App Router & Pages Router)
112
+ */
113
+ nextMiddleware(customHandler?: (request: any, event?: any) => Promise<any> | any): (request: any, event?: any) => Promise<any>;
114
+
115
+ /**
116
+ * Koa framework middleware
117
+ */
118
+ koaMiddleware(): (ctx: any, next: () => Promise<any>) => Promise<void>;
119
+
120
+ /**
121
+ * Hono / Web Standard Fetch middleware
122
+ */
123
+ honoMiddleware(): (c: any, next: () => Promise<void>) => Promise<void>;
124
+
125
+ /**
126
+ * Directly enqueues an event observation
127
+ */
128
+ enqueue(event: TelemetryEvent): void;
129
+
130
+ /**
131
+ * Flushes in-flight observations to the Ingestion API
132
+ */
133
+ flush(): Promise<void>;
134
+
135
+ /**
136
+ * Cleans up timers and flushes all pending events
137
+ */
138
+ shutdown(): Promise<void>;
139
+ }
140
+
141
+ export default VoightTraceCollector;
package/index.js ADDED
@@ -0,0 +1,614 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ /**
4
+ * ============================================================================
5
+ * SECURITY & PRIVACY AUDIT: ALLOWLISTED SAFE HEADERS
6
+ * ============================================================================
7
+ * Under ZERO circumstances does Voight Trace capture sensitive client headers.
8
+ *
9
+ * EXPLICITLY FORBIDDEN / NEVER COLLECTED:
10
+ * - authorization / proxy-authorization (Bearer tokens, JWTs, Basic Auth)
11
+ * - cookie / set-cookie (Session identifiers, tracking cookies)
12
+ * - x-api-key / api-key / x-auth-token / x-access-token
13
+ * - any custom credentials, secrets, or password headers
14
+ *
15
+ * ONLY the following deterministic, non-sensitive headers strictly necessary
16
+ * for AI bot classification, client hints, content negotiation, and routing
17
+ * are extracted. All others are completely filtered out at the collector level.
18
+ */
19
+ export const SAFE_AUDIT_HEADERS = Object.freeze([
20
+ // Core AI & Traffic Identification (Required for bot classification & GEO referrals)
21
+ 'user-agent',
22
+ 'referer',
23
+ 'host',
24
+ 'origin',
25
+
26
+ // Content Negotiation
27
+ 'accept',
28
+ 'accept-encoding',
29
+ 'accept-language',
30
+ 'content-type',
31
+
32
+ // Client Hints (Browser & Device Architecture)
33
+ 'sec-ch-ua',
34
+ 'sec-ch-ua-mobile',
35
+ 'sec-ch-ua-platform',
36
+ 'sec-ch-ua-platform-version',
37
+ 'sec-ch-ua-model',
38
+ 'sec-ch-ua-arch',
39
+
40
+ // Request & Fetch Context
41
+ 'sec-fetch-dest',
42
+ 'sec-fetch-mode',
43
+ 'sec-fetch-site',
44
+ 'sec-fetch-user'
45
+ ]);
46
+
47
+ /**
48
+ * Extracts ONLY safe, allowlisted headers from an incoming headers structure.
49
+ * Guaranteed to never capture authorization tokens, cookies, or credentials.
50
+ *
51
+ * @param {Object|Headers|Map} headers - Incoming HTTP request headers
52
+ * @returns {Record<string, string>} Sanitized allowlisted headers
53
+ */
54
+ export function filterSafeHeaders(headers) {
55
+ if (!headers) return {};
56
+ const filtered = {};
57
+
58
+ // Fetch API / Web Standard Headers instance (e.g. Next.js, Fetch, Hono)
59
+ if (typeof headers.get === 'function') {
60
+ for (const name of SAFE_AUDIT_HEADERS) {
61
+ const val = headers.get(name);
62
+ if (val) filtered[name] = val;
63
+ }
64
+ return filtered;
65
+ }
66
+
67
+ // Node.js / Express / Fastify / Koa headers object
68
+ for (const name of SAFE_AUDIT_HEADERS) {
69
+ const val = headers[name];
70
+ if (val !== undefined && val !== null && val !== '') {
71
+ filtered[name] = Array.isArray(val) ? val.join(', ') : String(val);
72
+ }
73
+ }
74
+ return filtered;
75
+ }
76
+
77
+ /**
78
+ * Voight Trace — Official Voight Trace SDK Collector
79
+ * Package: @voight-trace/voighttrace-sdk
80
+ * Reference: docs/technical/03_service_spec_trace_and_ingestion.md
81
+ *
82
+ * Lightweight, non-blocking telemetry collector for Node.js backends, Express, Fastify, and Next.js.
83
+ * Operates with asynchronous batching and never degrades host application latency or stability.
84
+ */
85
+ export class VoightTraceCollector {
86
+ /**
87
+ * @param {Object} config
88
+ * @param {string} config.apiKey - Voight Trace API Key (starts with vt_live_ or vt_test_)
89
+ * @param {string} config.siteId - UUID or site identifier registered in the Voight dashboard
90
+ * @param {string} [config.tenantId] - Optional tenant UUID (defaults to siteId if omitted)
91
+ * @param {string} [config.collectorId] - Custom collector instance ID (generated automatically if omitted)
92
+ * @param {string} [config.ingestUrl] - Custom Ingestion API endpoint
93
+ * @param {number} [config.batchSize=20] - Maximum number of observations dispatched per HTTP batch
94
+ * @param {number} [config.flushIntervalMs=3000] - Interval between automatic queue flushes in milliseconds
95
+ * @param {number} [config.sampleRate=1.0] - Sampling rate between 0.0 (0%) and 1.0 (100%)
96
+ * @param {boolean} [config.debug=false] - Enables diagnostic logging to stdout
97
+ * @param {boolean} [config.disabled=false] - Disables collection completely (useful for local unit tests)
98
+ */
99
+ constructor(config = {}) {
100
+ this.apiKey = config.apiKey || process.env.VOIGHT_TRACE_API_KEY || '';
101
+ this.siteId = config.siteId || process.env.VOIGHT_TRACE_SITE_ID || '';
102
+ this.tenantId = config.tenantId || process.env.VOIGHT_TRACE_TENANT_ID || this.siteId || 'default_tenant';
103
+ this.collectorId = config.collectorId || process.env.VOIGHT_TRACE_COLLECTOR_ID || `collector_${crypto.randomUUID().slice(0, 8)}`;
104
+ this.ingestUrl = config.ingestUrl || process.env.VOIGHT_TRACE_INGEST_URL || 'https://api.voighttrace.com/api/v1/ingestion/events';
105
+ this.batchSize = Number(config.batchSize || 20);
106
+ this.flushIntervalMs = Number(config.flushIntervalMs || 3000);
107
+ this.sampleRate = typeof config.sampleRate === 'number' ? config.sampleRate : 1.0;
108
+ this.debug = Boolean(config.debug || process.env.VOIGHT_TRACE_DEBUG === 'true');
109
+ this.disabled = Boolean(config.disabled || process.env.VOIGHT_TRACE_DISABLED === 'true');
110
+
111
+ this.queue = [];
112
+ this.timer = null;
113
+ this.isFlushing = false;
114
+
115
+ // Validate required credentials
116
+ if (!this.disabled && !this.apiKey) {
117
+ console.warn('[Voight Trace SDK] Warning: VOIGHT_TRACE_API_KEY is not configured. Telemetry is paused.');
118
+ }
119
+ if (!this.disabled && !this.siteId) {
120
+ console.warn('[Voight Trace SDK] Warning: VOIGHT_TRACE_SITE_ID is not configured. Telemetry is paused.');
121
+ }
122
+
123
+ // Start background flush timer if active
124
+ if (!this.disabled && this.flushIntervalMs > 0) {
125
+ this.timer = setInterval(() => {
126
+ this.flush().catch((err) => {
127
+ if (this.debug) console.error('[Voight Trace SDK Timer Error]', err.message);
128
+ });
129
+ }, this.flushIntervalMs);
130
+
131
+ // unref allows Node to exit naturally without waiting for the timer
132
+ if (this.timer && typeof this.timer.unref === 'function') {
133
+ this.timer.unref();
134
+ }
135
+ }
136
+
137
+ // Register process termination handlers to flush in-flight observations
138
+ if (typeof process !== 'undefined' && typeof process.once === 'function') {
139
+ process.once('beforeExit', () => {
140
+ if (this.queue.length > 0) {
141
+ this.flush().catch(() => {});
142
+ }
143
+ });
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Express / Connect / Morgan compatible HTTP middleware
149
+ * Usage: app.use(tracker.middleware());
150
+ */
151
+ middleware() {
152
+ return (req, res, next) => {
153
+ if (this.disabled || !this.apiKey || !this.siteId) {
154
+ return next();
155
+ }
156
+
157
+ // Check sampling rate
158
+ if (this.sampleRate < 1.0 && Math.random() > this.sampleRate) {
159
+ return next();
160
+ }
161
+
162
+ const startTime = Date.now();
163
+
164
+ // Manage and propagate correlation ID
165
+ let correlationId = req.headers['x-voight-trace-correlation-id'];
166
+ if (!correlationId) {
167
+ correlationId = `vgt_${crypto.randomUUID()}`;
168
+ req.headers['x-voight-trace-correlation-id'] = correlationId;
169
+ }
170
+ res.setHeader('x-voight-trace-correlation-id', correlationId);
171
+
172
+ // Hook into response finish event for zero-latency impact on response time
173
+ res.on('finish', () => {
174
+ try {
175
+ const durationMs = Date.now() - startTime;
176
+ const host = (req.headers['host'] || req.hostname || 'localhost').split(':')[0];
177
+ const referer = req.headers['referer'] || '';
178
+ const userAgent = req.headers['user-agent'] || '';
179
+
180
+ // Determine client IP safely
181
+ const clientIp =
182
+ req.headers['cf-connecting-ip'] ||
183
+ req.headers['x-real-ip'] ||
184
+ (req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',')[0].trim() : null) ||
185
+ req.socket?.remoteAddress ||
186
+ '127.0.0.1';
187
+
188
+ // Allowlisted headers only (security & privacy — audit safe)
189
+ const selectedHeaders = filterSafeHeaders(req.headers);
190
+
191
+ // Parse normalized path and clean query parameters
192
+ const rawUrl = req.originalUrl || req.url || '/';
193
+ const [pathname, queryString] = rawUrl.split('?');
194
+ const queryParams = req.query || this._parseQueryString(queryString);
195
+
196
+ const observationId = crypto.randomUUID();
197
+ const eventId = crypto.randomUUID();
198
+
199
+ const payload = {
200
+ event_id: eventId,
201
+ event_type: 'http.request',
202
+ schema_version: 1,
203
+ tenant_id: this.tenantId,
204
+ site_id: this.siteId,
205
+ collector_id: this.collectorId,
206
+ collector_type: 'nodejs_sdk',
207
+ observation_id: observationId,
208
+ request_id: req.headers['x-request-id'] || null,
209
+ correlation_id: correlationId,
210
+ occurred_at: new Date().toISOString(),
211
+ request: {
212
+ method: req.method ? req.method.toUpperCase() : 'GET',
213
+ scheme: req.secure || req.headers['x-forwarded-proto'] === 'https' ? 'https' : 'http',
214
+ host,
215
+ path: pathname || '/',
216
+ query_params: queryParams,
217
+ referer,
218
+ user_agent: userAgent,
219
+ selected_headers: selectedHeaders
220
+ },
221
+ network: {
222
+ ip_hash: clientIp,
223
+ country: (req.headers['cf-ipcountry'] || 'XX').toUpperCase(),
224
+ asn: Number(req.headers['x-asn'] || 0)
225
+ },
226
+ response: {
227
+ status_code: res.statusCode || 200,
228
+ duration_ms: durationMs,
229
+ bytes_sent: Number(res.getHeader('content-length') || 0)
230
+ }
231
+ };
232
+
233
+ this.enqueue(payload);
234
+ } catch (err) {
235
+ // Never impact or compromise host application runtime (RNF-012)
236
+ if (this.debug) {
237
+ console.error('[Voight Trace SDK Capture Error]', err);
238
+ }
239
+ }
240
+ });
241
+
242
+ next();
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Fastify Plugin integration
248
+ * Usage: fastify.register(tracker.fastifyPlugin());
249
+ */
250
+ fastifyPlugin() {
251
+ return (fastify, _opts, done) => {
252
+ fastify.addHook('onRequest', (request, reply, next) => {
253
+ let correlationId = request.headers['x-voight-trace-correlation-id'];
254
+ if (!correlationId) {
255
+ correlationId = `vgt_${crypto.randomUUID()}`;
256
+ request.headers['x-voight-trace-correlation-id'] = correlationId;
257
+ }
258
+ reply.header('x-voight-trace-correlation-id', correlationId);
259
+ request.voightStartTime = Date.now();
260
+ next();
261
+ });
262
+
263
+ fastify.addHook('onResponse', (request, reply, doneHook) => {
264
+ try {
265
+ if (!this.disabled && this.apiKey && this.siteId) {
266
+ const durationMs = Date.now() - (request.voightStartTime || Date.now());
267
+ const clientIp = request.headers['cf-connecting-ip'] || request.headers['x-real-ip'] || request.ip || '127.0.0.1';
268
+
269
+ const payload = {
270
+ event_id: crypto.randomUUID(),
271
+ event_type: 'http.request',
272
+ schema_version: 1,
273
+ tenant_id: this.tenantId,
274
+ site_id: this.siteId,
275
+ collector_id: this.collectorId,
276
+ collector_type: 'nodejs_sdk',
277
+ observation_id: crypto.randomUUID(),
278
+ request_id: request.headers['x-request-id'] || null,
279
+ correlation_id: request.headers['x-voight-trace-correlation-id'] || `vgt_${crypto.randomUUID()}`,
280
+ occurred_at: new Date().toISOString(),
281
+ request: {
282
+ method: request.method,
283
+ scheme: request.protocol,
284
+ host: request.hostname || 'localhost',
285
+ path: request.routerPath || request.url.split('?')[0],
286
+ query_params: request.query || {},
287
+ referer: request.headers['referer'] || '',
288
+ user_agent: request.headers['user-agent'] || '',
289
+ selected_headers: filterSafeHeaders(request.headers)
290
+ },
291
+ network: {
292
+ ip_hash: clientIp,
293
+ country: (request.headers['cf-ipcountry'] || 'XX').toUpperCase(),
294
+ asn: 0
295
+ },
296
+ response: {
297
+ status_code: reply.statusCode,
298
+ duration_ms: durationMs,
299
+ bytes_sent: Number(reply.getHeader('content-length') || 0)
300
+ }
301
+ };
302
+
303
+ this.enqueue(payload);
304
+ }
305
+ } catch (err) {
306
+ if (this.debug) console.error('[Voight Trace Fastify Error]', err);
307
+ }
308
+ doneHook();
309
+ });
310
+
311
+ done();
312
+ };
313
+ }
314
+
315
+ /**
316
+ * Next.js Middleware integration (App Router & Pages Router)
317
+ * Usage in middleware.ts:
318
+ * export const middleware = tracker.nextMiddleware();
319
+ */
320
+ nextMiddleware(customHandler) {
321
+ return async (request, event) => {
322
+ const startTime = Date.now();
323
+ let correlationId = request.headers.get('x-voight-trace-correlation-id');
324
+ if (!correlationId) {
325
+ correlationId = `vgt_${crypto.randomUUID()}`;
326
+ }
327
+
328
+ // Execute custom handler if provided
329
+ let response;
330
+ if (typeof customHandler === 'function') {
331
+ response = await customHandler(request, event);
332
+ }
333
+
334
+ // Default response fallback
335
+ if (!response) {
336
+ response = new Response(null, { status: 200, headers: new Headers() });
337
+ }
338
+
339
+ // Asynchronously queue telemetry without blocking the response
340
+ if (!this.disabled && this.apiKey && this.siteId) {
341
+ try {
342
+ const durationMs = Date.now() - startTime;
343
+ const url = new URL(request.url);
344
+ const clientIp =
345
+ request.headers.get('cf-connecting-ip') ||
346
+ request.headers.get('x-forwarded-for')?.split(',')[0].trim() ||
347
+ request.ip ||
348
+ '127.0.0.1';
349
+
350
+ const payload = {
351
+ event_id: crypto.randomUUID(),
352
+ event_type: 'http.request',
353
+ schema_version: 1,
354
+ tenant_id: this.tenantId,
355
+ site_id: this.siteId,
356
+ collector_id: this.collectorId,
357
+ collector_type: 'nodejs_sdk',
358
+ observation_id: crypto.randomUUID(),
359
+ correlation_id: correlationId,
360
+ occurred_at: new Date().toISOString(),
361
+ request: {
362
+ method: request.method,
363
+ scheme: url.protocol.replace(':', ''),
364
+ host: url.hostname,
365
+ path: url.pathname,
366
+ query_params: Object.fromEntries(url.searchParams.entries()),
367
+ referer: request.headers.get('referer') || '',
368
+ user_agent: request.headers.get('user-agent') || '',
369
+ selected_headers: filterSafeHeaders(request.headers)
370
+ },
371
+ network: {
372
+ ip_hash: clientIp,
373
+ country: (request.headers.get('cf-ipcountry') || 'XX').toUpperCase(),
374
+ asn: 0
375
+ },
376
+ response: {
377
+ status_code: response.status || 200,
378
+ duration_ms: durationMs,
379
+ bytes_sent: 0
380
+ }
381
+ };
382
+
383
+ this.enqueue(payload);
384
+ } catch (err) {
385
+ if (this.debug) console.error('[Voight Trace Next.js Error]', err);
386
+ }
387
+ }
388
+
389
+ // Set correlation ID header in response
390
+ try {
391
+ response.headers.set('x-voight-trace-correlation-id', correlationId);
392
+ } catch {
393
+ // In case response headers are immutable
394
+ }
395
+
396
+ return response;
397
+ };
398
+ }
399
+
400
+ /**
401
+ * Koa framework middleware
402
+ * Usage: app.use(tracker.koaMiddleware());
403
+ */
404
+ koaMiddleware() {
405
+ return async (ctx, next) => {
406
+ if (this.disabled || !this.apiKey || !this.siteId) {
407
+ return next();
408
+ }
409
+
410
+ const startTime = Date.now();
411
+ let correlationId = ctx.get('x-voight-trace-correlation-id');
412
+ if (!correlationId) {
413
+ correlationId = `vgt_${crypto.randomUUID()}`;
414
+ ctx.set('x-voight-trace-correlation-id', correlationId);
415
+ }
416
+
417
+ await next();
418
+
419
+ try {
420
+ const durationMs = Date.now() - startTime;
421
+ const clientIp = ctx.get('cf-connecting-ip') || ctx.get('x-forwarded-for')?.split(',')[0].trim() || ctx.ip || '127.0.0.1';
422
+
423
+ const payload = {
424
+ event_id: crypto.randomUUID(),
425
+ event_type: 'http.request',
426
+ schema_version: 1,
427
+ tenant_id: this.tenantId,
428
+ site_id: this.siteId,
429
+ collector_id: this.collectorId,
430
+ collector_type: 'nodejs_sdk',
431
+ observation_id: crypto.randomUUID(),
432
+ correlation_id: correlationId,
433
+ occurred_at: new Date().toISOString(),
434
+ request: {
435
+ method: ctx.method,
436
+ scheme: ctx.protocol,
437
+ host: ctx.host.split(':')[0],
438
+ path: ctx.path,
439
+ query_params: ctx.query || {},
440
+ referer: ctx.get('referer') || '',
441
+ user_agent: ctx.get('user-agent') || '',
442
+ selected_headers: filterSafeHeaders(ctx.headers || ctx.header)
443
+ },
444
+ network: {
445
+ ip_hash: clientIp,
446
+ country: (ctx.get('cf-ipcountry') || 'XX').toUpperCase(),
447
+ asn: 0
448
+ },
449
+ response: {
450
+ status_code: ctx.status || 200,
451
+ duration_ms: durationMs,
452
+ bytes_sent: Number(ctx.length || 0)
453
+ }
454
+ };
455
+
456
+ this.enqueue(payload);
457
+ } catch (err) {
458
+ if (this.debug) console.error('[Voight Trace Koa Error]', err);
459
+ }
460
+ };
461
+ }
462
+
463
+ /**
464
+ * Hono / Web Fetch API middleware
465
+ * Usage: app.use('*', tracker.honoMiddleware());
466
+ */
467
+ honoMiddleware() {
468
+ return async (c, next) => {
469
+ const startTime = Date.now();
470
+ let correlationId = c.req.header('x-voight-trace-correlation-id');
471
+ if (!correlationId) {
472
+ correlationId = `vgt_${crypto.randomUUID()}`;
473
+ }
474
+
475
+ await next();
476
+
477
+ if (!this.disabled && this.apiKey && this.siteId) {
478
+ try {
479
+ const durationMs = Date.now() - startTime;
480
+ const url = new URL(c.req.url);
481
+ const clientIp = c.req.header('cf-connecting-ip') || c.req.header('x-forwarded-for')?.split(',')[0].trim() || '127.0.0.1';
482
+
483
+ const payload = {
484
+ event_id: crypto.randomUUID(),
485
+ event_type: 'http.request',
486
+ schema_version: 1,
487
+ tenant_id: this.tenantId,
488
+ site_id: this.siteId,
489
+ collector_id: this.collectorId,
490
+ collector_type: 'nodejs_sdk',
491
+ observation_id: crypto.randomUUID(),
492
+ correlation_id: correlationId,
493
+ occurred_at: new Date().toISOString(),
494
+ request: {
495
+ method: c.req.method,
496
+ scheme: url.protocol.replace(':', ''),
497
+ host: url.hostname,
498
+ path: url.pathname,
499
+ query_params: Object.fromEntries(url.searchParams.entries()),
500
+ referer: c.req.header('referer') || '',
501
+ user_agent: c.req.header('user-agent') || '',
502
+ selected_headers: filterSafeHeaders(c.req.raw?.headers || c.req.header())
503
+ },
504
+ network: {
505
+ ip_hash: clientIp,
506
+ country: (c.req.header('cf-ipcountry') || 'XX').toUpperCase(),
507
+ asn: 0
508
+ },
509
+ response: {
510
+ status_code: c.res.status || 200,
511
+ duration_ms: durationMs,
512
+ bytes_sent: 0
513
+ }
514
+ };
515
+
516
+ this.enqueue(payload);
517
+ } catch (err) {
518
+ if (this.debug) console.error('[Voight Trace Hono Error]', err);
519
+ }
520
+ }
521
+
522
+ c.res.headers.set('x-voight-trace-correlation-id', correlationId);
523
+ };
524
+ }
525
+
526
+ /**
527
+ * Enqueues an observation into the in-memory buffer
528
+ * @param {Object} event
529
+ */
530
+ enqueue(event) {
531
+ this.queue.push(event);
532
+
533
+ if (this.debug) {
534
+ console.log(`[Voight Trace SDK] Enqueued observation: ${event.request.method} ${event.request.path} (Queue: ${this.queue.length})`);
535
+ }
536
+
537
+ if (this.queue.length >= this.batchSize) {
538
+ this.flush().catch((err) => {
539
+ if (this.debug) console.error('[Voight Trace SDK Batch Flush Error]', err);
540
+ });
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Dispatches pending observations to the Ingestion API
546
+ */
547
+ async flush() {
548
+ if (this.queue.length === 0 || !this.apiKey || this.isFlushing) {
549
+ return;
550
+ }
551
+
552
+ this.isFlushing = true;
553
+ const batch = this.queue.splice(0, this.batchSize);
554
+
555
+ try {
556
+ if (this.debug) {
557
+ console.log(`[Voight Trace SDK] Dispatching batch of ${batch.length} events to ${this.ingestUrl}`);
558
+ }
559
+
560
+ const response = await fetch(this.ingestUrl, {
561
+ method: 'POST',
562
+ headers: {
563
+ 'Content-Type': 'application/json',
564
+ 'Authorization': `Bearer ${this.apiKey}`,
565
+ 'x-voight-collector-type': 'nodejs_sdk',
566
+ 'x-voight-collector-version': '2.4.0'
567
+ },
568
+ body: JSON.stringify({ events: batch })
569
+ });
570
+
571
+ if (!response.ok) {
572
+ const errorText = await response.text();
573
+ console.error(`[Voight Trace SDK] Ingestion rejected HTTP ${response.status}: ${errorText}`);
574
+ } else if (this.debug) {
575
+ const result = await response.json();
576
+ console.log(`[Voight Trace SDK] Batch accepted successfully:`, result);
577
+ }
578
+ } catch (err) {
579
+ // Re-queue in case of transient network failure (up to 200 items max to prevent memory leaks)
580
+ if (this.queue.length < 200) {
581
+ this.queue.unshift(...batch);
582
+ }
583
+ if (this.debug) {
584
+ console.error('[Voight Trace SDK Network Error]', err.message);
585
+ }
586
+ } finally {
587
+ this.isFlushing = false;
588
+ }
589
+ }
590
+
591
+ /**
592
+ * Stops the background timer and flushes any pending queue items
593
+ */
594
+ async shutdown() {
595
+ if (this.timer) {
596
+ clearInterval(this.timer);
597
+ this.timer = null;
598
+ }
599
+ await this.flush();
600
+ }
601
+
602
+ _parseQueryString(queryString) {
603
+ if (!queryString) return {};
604
+ const params = {};
605
+ const pairs = queryString.split('&');
606
+ for (const pair of pairs) {
607
+ const [key, value] = pair.split('=');
608
+ if (key) params[decodeURIComponent(key)] = decodeURIComponent(value || '');
609
+ }
610
+ return params;
611
+ }
612
+ }
613
+
614
+ export default VoightTraceCollector;
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@voight-trace/voighttrace-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Official Voight Trace SDK Collector — AI Traffic Intelligence & GEO Observability",
5
+ "main": "index.js",
6
+ "module": "index.js",
7
+ "types": "index.d.ts",
8
+ "type": "module",
9
+ "scripts": {
10
+ "test": "node test.js"
11
+ },
12
+ "keywords": [
13
+ "voight-trace",
14
+ "ai-agents",
15
+ "bot-detection",
16
+ "llm-crawler",
17
+ "geo",
18
+ "chatgpt",
19
+ "claude",
20
+ "perplexity",
21
+ "observability"
22
+ ],
23
+ "author": "Voight Trace Core Team",
24
+ "license": "Apache-2.0",
25
+ "engines": {
26
+ "node": ">=18.0.0"
27
+ }
28
+ }