@webority/server-timing 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## [0.1.1] - 01-Nov-2026
4
+
5
+ ### Changed
6
+
7
+ - First release through the package publisher, with provenance.
8
+ - Published as a minified bundle in `dist/`; the entry points and exports are the same as 0.1.0's source.
9
+ - The server span carries `webority.sample_rate`, so sampled traffic counts true.
10
+
11
+ ## [0.1.0]
12
+
13
+ ### Added
14
+
15
+ - Token-only `Server-Timing` for Express, NestJS and Next.js server routes: a request without the token gets no timing, trace or `traceparent`.
16
+ - OpenTelemetry tracing to App Insights, with the server span carrying the `webority.timing.*` and `webority.runtime.*` readings.
17
+ - Outgoing `node:http` and `https` calls (axios included) forward the token and `traceparent` to our hosts only, checked again on every redirect hop.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ Copyright (c) Webority Technologies. All rights reserved.
2
+
3
+ This software and its NuGet packages are the proprietary and confidential property
4
+ of Webority Technologies. They are published publicly only for the convenience of
5
+ Webority's own projects and internal consumption.
6
+
7
+ No license or right to use, copy, modify, merge, publish, distribute, sublicense,
8
+ or create derivative works is granted to any third party. Unauthorized use,
9
+ reproduction, or distribution is prohibited.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # @webority/server-timing
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
+ Token-only `Server-Timing` and OpenTelemetry tracing for Node servers. Without the `Webority-Timing-Token` request header a response carries no timing at all. Every rule is in [CONTRACT.md](../CONTRACT.md).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i @webority/server-timing
9
+ ```
10
+
11
+ ## Start
12
+
13
+ Load the package before your app with Node's `--import` flag:
14
+
15
+ ```bash
16
+ node --import @webority/server-timing/register server.js
17
+ ```
18
+
19
+ With pm2, pass the same flag through `node_args`:
20
+
21
+ ```js
22
+ module.exports = {
23
+ apps: [
24
+ {
25
+ name: 'api',
26
+ script: 'server.js',
27
+ node_args: '--import @webority/server-timing/register',
28
+ },
29
+ ],
30
+ };
31
+ ```
32
+
33
+ ## Settings
34
+
35
+ The five settings are in [CONTRACT.md section 2](../CONTRACT.md#2-configuration). The adapter refuses to start when one is missing or malformed, and its error names the setting, never the value.
36
+
37
+ | Setting | Purpose |
38
+ |---|---|
39
+ | `WEBORITY_TIMING_TOKEN_SHA256` | SHA-256 fingerprint of the timing token. Two, comma separated, only during a rotation. |
40
+ | `WEBORITY_TIMING_SERVICE` | The service's short name, used as the prefix of every entry. |
41
+ | `WEBORITY_TIMING_FORWARD_HOSTS` | Our own hosts this service calls, comma separated, or `none`. |
42
+ | `APPLICATIONINSIGHTS_CONNECTION_STRING` | Where traces are exported. |
43
+ | `WEBORITY_TRACE_SAMPLE_RATIO` | A number from 0 to 1: the share of untokened requests that are traced. |
44
+
45
+ Keep the token itself in the product's secret store. The server holds only the fingerprint.
46
+
47
+ ## Frameworks
48
+
49
+ - **Express:** start with the `--import` flag above.
50
+ - **NestJS:** start the compiled entry point with the same flag, for example `node --import @webority/server-timing/register dist/main.js`.
51
+ - **Next.js:** set the flag through `NODE_OPTIONS` and run `next start`:
52
+
53
+ ```bash
54
+ NODE_OPTIONS="--import @webority/server-timing/register" next start
55
+ ```
56
+
57
+ Static and incrementally regenerated pages are served from Next's cache and are not timed for authorised requests; only dynamic renders are.
58
+
59
+ ## Outgoing calls
60
+
61
+ Calls made with `fetch` (Node's built-in undici), `node:http` or `https` are covered, and axios sends its calls through `node:http`. A call to a host in `WEBORITY_TIMING_FORWARD_HOSTS` carries the token and `traceparent` on that hop only; a redirect to any other host drops both.
62
+
63
+ ## Cache bypass
64
+
65
+ A cache in front of the server must not serve or store an authorised response. In nginx, bypass the cache on the token header:
66
+
67
+ ```nginx
68
+ proxy_cache_bypass $http_webority_timing_token;
69
+ proxy_no_cache $http_webority_timing_token;
70
+ ```
@@ -0,0 +1 @@
1
+ import{createHash as D,timingSafeEqual as G}from"node:crypto";var j=/^[0-9a-f]{64}$/,F=/^[a-z][a-z0-9-]{0,19}$/,W=/^[a-z0-9][a-z0-9.-]*$/,U=/^(?:\d+(?:\.\d+)?|\.\d+)$/,z=40,K=2048,V=500,T="private, no-store",Y=new Set(["server-timing","traceparent","traceresponse"]);function m(e){return{ok:!1,setting:e}}function c(e){return Math.round(Math.round(e*1e9)/1e9*10)/10}var h=e=>e!=null;function N(e){return Math.max(0,e.totalMs-(e.dbMs??0)-(e.cacheMs??0)-(e.extMs??0)-(e.renderMs??0))}var X=/'(?:[^'\\]|\\.|'')*'/g,Q=/"(?:[^"\\]|\\.)*"/g,Z=/(?<![A-Za-z0-9_$])-?(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g,J=/\b(IN)(\s*)\(\s*\?(?:\s*,\s*\?)*\s*\)/gi;function M(e){return e.replace(X,"?").replace(Q,"?").replace(Z,"?").replace(J,"$1$2(?)")}function je(e){let r="WEBORITY_TIMING_TOKEN_SHA256",t=(e[r]??"").split(",");if(t.length>2||!t.every(l=>j.test(l)))return m(r);let n=e.WEBORITY_TIMING_SERVICE??"";if(!F.test(n))return m("WEBORITY_TIMING_SERVICE");let s="WEBORITY_TIMING_FORWARD_HOSTS",o=e[s],i;if(o==="none")i=[];else if(i=(o??"").split(",").map(l=>l.trim().toLowerCase()),!i.every(l=>W.test(l)))return m(s);let a=e.APPLICATIONINSIGHTS_CONNECTION_STRING??"";if(a.trim()==="")return m("APPLICATIONINSIGHTS_CONNECTION_STRING");let u="WEBORITY_TRACE_SAMPLE_RATIO",d=e[u]??"";if(!U.test(d)||Number(d)>1)return m(u);let p={tokenFingerprints:t,service:n,forwardHosts:i,sampleRatio:Number(d)};return Object.defineProperty(p,"connectionString",{value:a,enumerable:!1}),{ok:!0,config:p}}function $(e,r){if(!r)return!1;let t=Buffer.from(D("sha256").update(r,"utf8").digest("hex"));return e.some(n=>{let s=Buffer.from(n);return s.length===t.length&&G(s,t)})}function y(e,r){let t=r,n=[`${e}.total;dur=${c(t.totalMs)}`,`${e}.app;dur=${c(N(t))}`];if(t.dbCount>0&&n.push(`${e}.db;dur=${c(t.dbMs)};desc="${t.dbCount} queries"`),t.cacheMs>0){let o=t.cacheResult?`;desc="${t.cacheResult}"`:"";n.push(`${e}.cache;dur=${c(t.cacheMs)}${o}`)}t.extCount>0&&n.push(`${e}.ext;dur=${c(t.extMs)};desc="${t.extCount} calls"`),t.renderMs!==void 0&&n.push(`${e}.render;dur=${c(t.renderMs)}`),t.queueMs!==void 0&&n.push(`${e}.queue;dur=${c(t.queueMs)}`),t.bootMs!==void 0&&n.push(`${e}.boot;dur=${c(t.bootMs)}`),t.pluginsMs!==void 0&&n.push(`${e}.plugins;dur=${c(t.pluginsMs)};desc="${t.pluginCount} plugins"`);let s=Object.keys(t.runtime??{}).sort();if(s.length>0){let o=s.map(i=>`${i}=${c(t.runtime[i])}`).join(" ");n.push(`${e}.runtime;desc="${o}"`)}return n.push(`trace;desc="${t.traceId}"`),n.join(", ")}function A(e){let r=new Map,t=null;for(let o of e){let i=M(o.sql);r.set(i,(r.get(i)??0)+1),h(o.rows)&&(t===null||o.rows>t)&&(t=o.rows)}let n=0,s=null;for(let[o,i]of r)i>n&&(n=i,s=o);return{dbCount:e.length,dbRepeatMax:n,dbRepeatSql:s===null?null:s.slice(0,V),dbRowsMax:t}}function ee(e,r){return e||r>=1||r<=0?1:Math.round(1e4/r)/1e4}function O(e,r,t){let n=e,s={"webority.timing.authorised":r,"webority.sample_rate":ee(r,t),"webority.timing.total_ms":c(n.totalMs),"webority.timing.app_ms":c(N(n))},o={db_ms:n.dbMs,cache_ms:n.cacheMs,ext_ms:n.extMs,render_ms:n.renderMs,queue_ms:n.queueMs,boot_ms:n.bootMs,plugins_ms:n.pluginsMs};for(let[a,u]of Object.entries(o))h(u)&&(s[`webority.timing.${a}`]=c(u));let i={db_count:n.dbCount,ext_count:n.extCount,plugin_count:n.pluginCount,db_repeat_max:n.dbRepeatMax,db_repeat_sql:n.dbRepeatSql,db_rows_max:n.dbRowsMax,cache_result:n.cacheResult};for(let[a,u]of Object.entries(i))h(u)&&(s[`webority.timing.${a}`]=u);h(n.memPeakKb)&&(s["webority.mem.peak_kb"]=n.memPeakKb),h(n.cpuMs)&&(s["webority.cpu_ms"]=c(n.cpuMs));for(let[a,u]of Object.entries(n.runtime??{}))s[`webority.runtime.${a}`]=c(u);return s}function C(e){let r=[],t="",n=!1;for(let s of e)s==='"'&&(n=!n),s===","&&!n?(r.push(t.trim()),t=""):t+=s;return r.push(t.trim()),r.filter(s=>s.length>0)}var g=e=>e.startsWith("trace;");function H(e,r){let t=C(e),n=t.filter(g),s=t.filter(u=>!g(u)),o=r.flatMap(C).filter(u=>!g(u)),i=()=>[...s,...o,...n],a=i();for(;o.length>0&&(a.length>z||a.join(", ").length>K);)o.pop(),a=i();return a.join(", ")}function k(e,r,t){if(!r||!t)return!1;let n=String(t).toLowerCase().replace(/:\d+$/,"");return e.includes(n)}function q(e,r){if(!r)return e.filter(([s])=>!Y.has(s.toLowerCase()));let t=[],n=!1;for(let[s,o]of e)s.toLowerCase()!=="cache-control"?t.push([s,o]):n||(t.push(["Cache-Control",T]),n=!0);return n||t.push(["Cache-Control",T]),t}import{createRequire as re,syncBuiltinESMExports as ne}from"node:module";import{NodeSDK as se}from"@opentelemetry/sdk-node";import{BatchSpanProcessor as oe,TraceIdRatioBasedSampler as ie,SamplingDecision as ae}from"@opentelemetry/sdk-trace-base";import{resourceFromAttributes as ue}from"@opentelemetry/resources";import{ATTR_SERVICE_NAME as ce}from"@opentelemetry/semantic-conventions";import{SpanKind as v,trace as fe}from"@opentelemetry/api";import{HttpInstrumentation as de}from"@opentelemetry/instrumentation-http";import{MongoDBInstrumentation as pe}from"@opentelemetry/instrumentation-mongodb";import{IORedisInstrumentation as le}from"@opentelemetry/instrumentation-ioredis";import{RedisInstrumentation as me}from"@opentelemetry/instrumentation-redis";import{MySQL2Instrumentation as he}from"@opentelemetry/instrumentation-mysql2";import{PgInstrumentation as be}from"@opentelemetry/instrumentation-pg";import{UndiciInstrumentation as Se}from"@opentelemetry/instrumentation-undici";import{AzureMonitorTraceExporter as Me}from"@azure/monitor-opentelemetry-exporter";import{AsyncLocalStorage as te}from"node:async_hooks";var b=new te,f=()=>b.getStore();var L="Webority-Timing-Token",ge=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,_=["db.statement","db.query.text"],we="db.response.returned_rows",P=new WeakMap,w=([e,r])=>e*1e3+r/1e6,R=class{inject(){}extract(r,t,n){let s=n.get(t,"traceparent"),o=Array.isArray(s)?s[0]:s,i=typeof o=="string"?ge.exec(o):null;return!i||!/[1-9a-f]/.test(i[1])||!/[1-9a-f]/.test(i[2])?r:fe.setSpanContext(r,{traceId:i[1],spanId:i[2],traceFlags:parseInt(i[3],16),isRemote:!0})}fields(){return["traceparent"]}};function _e(e){if(!_.some(t=>typeof e.attributes[t]=="string"))return e;let r={...e.attributes};for(let t of _)typeof r[t]=="string"&&(r[t]=M(r[t]));return Object.create(e,{attributes:{value:r,enumerable:!0}})}function Re(e){for(let r of _){let t=e.attributes[r];if(typeof t=="string")return t}return e.name}var I=class{constructor(r){this.inner=r}export(r,t){this.inner.export(r.map(_e),t)}shutdown(){return this.inner.shutdown()}forceFlush(){return this.inner.forceFlush?.()??Promise.resolve()}},E=class{onStart(r){let t=b.getStore();t&&(r.kind===v.SERVER&&!t.serverSpan&&(t.serverSpan=r,r.setAttribute("webority.timing.authorised",t.authorised)),P.set(r,t))}onEnd(r){let t=P.get(r);if(!t)return;let n=r.instrumentationScope.name;if(n.includes("mongodb")||n.includes("mysql2")||n.includes("pg")){t.dbMs+=w(r.duration);let s={sql:M(Re(r))},o=r.attributes[we];typeof o=="number"&&(s.rows=o),t.statements.push(s)}else n.includes("ioredis")||n.includes("redis")?(t.cacheMs+=w(r.duration),t.cacheCount+=1):r.kind===v.CLIENT&&(n.includes("instrumentation-http")||n.includes("instrumentation-undici"))&&(t.extMs+=w(r.duration),t.extCount+=1)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}};function Ie(e){let r=new ie(e);return{shouldSample(t,n,s,o,i,a){return f()?.authorised?{decision:ae.RECORD_AND_SAMPLED}:r.shouldSample(t,n,s,o,i,a)},toString(){return"WeborityTimingSampler"}}}function B(e){let{traceId:r,spanId:t,traceFlags:n}=e.spanContext();return`00-${r}-${t}-${n.toString(16).padStart(2,"0")}`}function ut(e){let r=s=>k(e.forwardHosts,!!f()?.authorised,s),t=new se({resource:ue({[ce]:e.service}),sampler:Ie(e.sampleRatio),spanProcessors:[new oe(new I(new Me({connectionString:e.connectionString}))),new E],textMapPropagator:new R,instrumentations:[new de({requestHook(s,o){r(o.host)&&(o.setHeader(L,f().token),o.setHeader("traceparent",B(s)))},responseHook(s,o){let i=o.headers["server-timing"];i&&r(o.req?.host)&&f().inner.push(i)}}),new Se({requestHook(s,o){r(new URL(o.origin).hostname)&&(o.addHeader(L,f().token),o.addHeader("traceparent",B(s)))},responseHook(s,{request:o,response:i}){if(!r(new URL(o.origin).hostname))return;let a=i.headers;for(let u=0;u+1<a.length;u+=2)a[u].toString("latin1").toLowerCase()==="server-timing"&&f().inner.push(a[u+1].toString("latin1"))}}),new pe({enhancedDatabaseReporting:!1}),new le,new me,new he,new be({enhancedDatabaseReporting:!1})]});t.start();let n=re(import.meta.url);return n("node:http"),n("node:https"),ne(),t}import Ee from"node:http";import xe from"node:https";import{getHeapStatistics as Te}from"node:v8";import{monitorEventLoopDelay as Ce}from"node:perf_hooks";var x=1024*1024,Ne=6e4,$e=/^t=(\d+\.\d+)$/,ye=/^t=(\d+)$/,S;function Ae(e,r){if(typeof e!="string")return;let t=$e.exec(e),n=ye.exec(e),s;if(t)s=Number(t[1])*1e3;else if(n)s=Number(n[1])/1e3;else return;let o=r-s;return o<0||o>Ne?void 0:o}function Oe(e,r,t){let n={authorised:e,queueMs:t,startNs:process.hrtime.bigint(),dbMs:0,cacheMs:0,cacheCount:0,extMs:0,extCount:0,statements:[],inner:[],serverSpan:void 0};return e&&Object.defineProperty(n,"token",{value:r,enumerable:!1}),n}function He(){let e=Te();return{eventloop_p99_ms:S.percentile(99)/1e6,heap_used_mb:e.used_heap_size/x,heap_limit_mb:e.heap_size_limit/x,rss_mb:process.memoryUsage.rss()/x}}function ke(e){let r=A(e.statements);return{totalMs:Number(process.hrtime.bigint()-e.startNs)/1e6,dbMs:e.dbMs,dbCount:r.dbCount,dbRepeatMax:r.dbRepeatMax,dbRepeatSql:r.dbRepeatSql,dbRowsMax:r.dbRowsMax,cacheMs:e.cacheCount>0?e.cacheMs:void 0,extMs:e.extMs,extCount:e.extCount,queueMs:e.queueMs,runtime:He(),traceId:e.serverSpan.spanContext().traceId}}function qe(e){let r=e.route?.path;return typeof r=="string"?`${e.baseUrl??""}${r}`:void 0}function ve(e){let r=[];for(let t=0;t<e.length;t+=2)r.push([String(e[t]),e[t+1]]);return r}function Le(e,r){let t=e.getRawHeaderNames().map(o=>[o,e.getHeader(o)]);if(!r)return t;let n=Array.isArray(r)?ve(r):Object.entries(r),s=new Set(n.map(([o])=>o.toLowerCase()));return[...t.filter(([o])=>!s.has(o.toLowerCase())),...n]}function Pe(e,r){let t=new Map;for(let[n,s]of r){let o=n.toLowerCase(),i=t.get(o)??{name:n,values:[]};i.values.push(...Array.isArray(s)?s:[s]),t.set(o,i)}for(let n of e.getRawHeaderNames())e.removeHeader(n);for(let{name:n,values:s}of t.values())e.setHeader(n,s.length===1?s[0]:s)}function Be(e,r,t,n){if(!r.serverSpan){if(r.authorised)throw new Error("Webority server timing: an authorised request has no server span");return n}let s=ke(r),o=qe(e);if(r.serverSpan.updateName(o===void 0?e.method:`${e.method} ${o}`),r.serverSpan.setAttribute("http.route",o??"unmatched"),r.serverSpan.setAttributes(O(s,r.authorised,t.sampleRatio)),!r.authorised)return n;let i=H(y(t.service,s),r.inner);return[...n.filter(([a])=>a.toLowerCase()!=="server-timing"),["Server-Timing",i]]}function De(e,r,t,n){let s=r.writeHead;r.writeHead=function(o,...i){if(r.headersSent)return s.call(this,o,...i);let a=typeof i[0]=="string"?1:0,u=q(Le(r,i[a]),t.authorised);return o>=200&&(u=Be(e,t,n,u)),Pe(r,u),s.call(this,o,...i.slice(0,a))}}function bt(e){if(!S){S=Ce({resolution:20}),S.enable(),setInterval(()=>S.reset(),1e4).unref();for(let r of[Ee.Server,xe.Server]){let t=r.prototype.emit;r.prototype.emit=function(s,...o){if(s!=="request")return t.call(this,s,...o);let[i,a]=o,u=i.headers["webority-timing-token"],d=$(e.tokenFingerprints,u),p=Oe(d,u,Ae(i.headers["x-request-start"],Date.now()));return De(i,a,p,e),b.run(p,()=>t.call(this,s,...o))}}}}export{M as a,je as b,$ as c,y as d,H as e,k as f,q as g,ut as h,bt as i};
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{a as r,b as o,c as e,d as t,e as a,f as s,g as m,h as f,i as p}from"./chunk-2WCL47IT.js";export{e as authorise,t as format,p as installHttpHook,r as maskSql,a as merge,o as readConfig,m as scrubResponseHeaders,s as shouldForward,f as startTracing};
@@ -0,0 +1 @@
1
+ import{b as i,h as o,i as t}from"./chunk-2WCL47IT.js";var r=i(process.env);if(!r.ok)throw new Error(`Webority server timing: ${r.setting} is missing or invalid`);o(r.config);t(r.config);
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@webority/server-timing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "engines": {
7
+ "node": ">=20"
8
+ },
9
+ "exports": {
10
+ ".": "./dist/index.js",
11
+ "./register": "./dist/register.js"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "CHANGELOG.md",
16
+ "LICENSE"
17
+ ],
18
+ "dependencies": {
19
+ "@azure/monitor-opentelemetry-exporter": "1.0.0-beta.32",
20
+ "@opentelemetry/api": "1.10.0",
21
+ "@opentelemetry/instrumentation-http": "0.300.0",
22
+ "@opentelemetry/instrumentation-ioredis": "0.72.0",
23
+ "@opentelemetry/instrumentation-mongodb": "0.77.0",
24
+ "@opentelemetry/instrumentation-mysql2": "0.70.0",
25
+ "@opentelemetry/instrumentation-pg": "0.77.0",
26
+ "@opentelemetry/instrumentation-redis": "0.72.0",
27
+ "@opentelemetry/instrumentation-undici": "0.34.0",
28
+ "@opentelemetry/resources": "3.0.0",
29
+ "@opentelemetry/sdk-node": "0.300.0",
30
+ "@opentelemetry/sdk-trace-base": "2.12.0",
31
+ "@opentelemetry/semantic-conventions": "1.44.0"
32
+ },
33
+ "devDependencies": {
34
+ "esbuild": "0.28.2"
35
+ },
36
+ "scripts": {
37
+ "build": "node build.mjs",
38
+ "test": "node --test test/core.test.mjs test/http-hook.test.mjs"
39
+ }
6
40
  }