@steadphast/connector-nextjs 0.5.3 → 0.6.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.
package/dist/server.js ADDED
@@ -0,0 +1,293 @@
1
+ // src/collector-render.ts
2
+ import { headers } from "next/headers";
3
+ import { createElement } from "react";
4
+
5
+ // src/collector/bundle.ts
6
+ var COLLECTOR_SOURCE = `(function(G,ce){var ue=2e3,le=1500,fe=250,de=500,pe=Date.now(),me=typeof performance<"u"?performance.now():0;function J(e,n){var a=typeof globalThis<"u"?globalThis:self,o=a.navigator,i={},v=[],t=null,L=!1,_=/^function (?:get |set )?[\\w$]*\\(\\) \\{\\s*\\[native code\\]\\s*\\}$/;function u(s,c){try{return s()}catch{return c}}function w(){L||(L=!0,clearTimeout(t),n(i))}function d(s,c){if(typeof c=="function"){var l=Function.prototype.toString,p=!1,A,k,U=!1,P=!1;try{_.test(l.call(c))||(p=!0),A=Reflect.ownKeys(c),(A.length!==2||A.indexOf("length")===-1||A.indexOf("name")===-1)&&(p=!0),k=Object.getOwnPropertyDescriptor(c,"name"),(!k||k.writable!==!1)&&(p=!0);try{new c}catch(h){U=h instanceof TypeError}U||(p=!0);try{Object.setPrototypeOf(c,c)}catch{P=!0}P||(p=!0,Object.setPrototypeOf(c,Function.prototype))}catch{p=!0}p&&v.push(s)}}function Oe(s,c){var l=s?Object.getOwnPropertyDescriptor(s.prototype,c):void 0;return l?l.get:void 0}function j(s,c){return s?s.prototype[c]:void 0}i.ua=u(()=>String(o.userAgent)),i.platform=u(()=>String(o.platform)),i.languages=u(()=>Array.prototype.slice.call(o.languages,0,8).map(String)),i.tz=u(()=>Intl.DateTimeFormat().resolvedOptions().timeZone),i.cores=u(()=>o.hardwareConcurrency),i.memory=u(()=>o.deviceMemory),i.brands=u(()=>o.userAgentData.brands.map(s=>s.brand+" "+s.version)),i.webdriver=u(()=>o.webdriver),i.webdriver_own=u(()=>Object.prototype.hasOwnProperty.call(o,"webdriver")),i.headless_ua=u(()=>/HeadlessChrome|PhantomJS|SlimerJS/.test(o.userAgent)),i.clock={date_native:u(()=>_.test(Function.prototype.toString.call(Date.now))),perf_native:u(()=>_.test(Function.prototype.toString.call(a.performance.now)))},i.webgl=u(()=>{var s=e==="worker"?new OffscreenCanvas(8,8):a.document.createElement("canvas"),c=s.getContext("webgl")||s.getContext("webgl2");if(!c)return{ctx:!1};var l=c.getExtension("WEBGL_debug_renderer_info");return{vendor:l?c.getParameter(l.UNMASKED_VENDOR_WEBGL):void 0,renderer:l?c.getParameter(l.UNMASKED_RENDERER_WEBGL):void 0,ctx:!0}},{ctx:!1});var xe=e==="worker"?a.WorkerNavigator:a.Navigator;d("Function.prototype.toString",Function.prototype.toString),d("Date.now",Date.now),d("performance.now",a.performance&&a.performance.now),["webdriver","plugins","languages","hardwareConcurrency","deviceMemory","platform","userAgent"].forEach(s=>{d((e==="worker"?"WorkerNavigator.":"Navigator.")+s+"#get",Oe(xe,s))}),e!=="worker"&&(d("WebGLRenderingContext.getParameter",j(a.WebGLRenderingContext,"getParameter")),d("Permissions.query",j(a.Permissions,"query")),d("HTMLCanvasElement.toDataURL",j(a.HTMLCanvasElement,"toDataURL")),d("CanvasRenderingContext2D.getImageData",j(a.CanvasRenderingContext2D,"getImageData"))),e!=="worker"&&(i.plugins=u(()=>o.plugins.length),i.screen=u(()=>({w:a.screen.width,h:a.screen.height,dpr:a.devicePixelRatio,outer_zero:a.outerWidth===0||a.outerHeight===0}))),e==="main"&&(i.chrome=u(()=>typeof a.chrome=="object"&&a.chrome!==null),i.rtt=u(()=>o.connection.rtt),i.pdf_viewer=u(()=>o.pdfViewerEnabled),i.share=u(()=>typeof o.share=="function"),i.feature_major=Ce(a),i.os_fonts=u(()=>De(a.document))),i.proto=v;var B=u(()=>o.userAgentData.getHighEntropyValues(["architecture","bitness","platformVersion","fullVersionList"]));return B&&typeof B.then=="function"?(t=setTimeout(w,300),B.then(s=>{i.uach={arch:s.architecture,bitness:s.bitness,platform_version:s.platformVersion,full_version_list:(s.fullVersionList||[]).map(c=>c.brand+" "+c.version)},w()},()=>{w()})):w(),()=>{L=!0,clearTimeout(t)};function Ce(s){for(var c=[[141,()=>typeof Math.sumPrecise=="function"],[140,()=>typeof Uint8Array.fromBase64=="function"],[136,()=>typeof RegExp.escape=="function"],[135,()=>typeof s.Float16Array=="function"],[134,()=>typeof Error.isError=="function"],[128,()=>typeof Promise.try=="function"],[126,()=>typeof URL.parse=="function"],[122,()=>typeof Set.prototype.union=="function"],[122,()=>typeof s.Iterator=="function"&&typeof s.Iterator.prototype.map=="function"],[121,()=>typeof Array.fromAsync=="function"],[120,()=>typeof URL.canParse=="function"],[119,()=>typeof Promise.withResolvers=="function"],[117,()=>typeof Object.groupBy=="function"],[110,()=>typeof Array.prototype.toSorted=="function"],[98,()=>typeof s.structuredClone=="function"]],l=0;l<c.length;l+=1)if(u(c[l][1],!1))return c[l][0];return 0}function De(s){var c={mac:["Helvetica Neue","Menlo","Monaco","Apple Color Emoji","SF Pro","Geneva","Avenir"],win:["Segoe UI","Calibri","Consolas","Tahoma","Cambria","Candara"],linux:["DejaVu Sans","Liberation Sans","Ubuntu","Noto Sans","Cantarell","Liberation Mono"]},l=s.createElement("canvas"),p=l.getContext("2d"),A="mmmmmmmmmmlli WAVE 0123 @#%",k=["monospace","sans-serif","serif"],U=k.map(h=>(p.font="24px "+h,p.measureText(A).width)),P={};return Object.keys(c).forEach(h=>{var se=0;c[h].forEach(Re=>{var Le=k.some((Pe,Me)=>(p.font="24px '"+Re+"', "+Pe,p.measureText(A).width!==U[Me]));Le&&(se+=1)}),P[h]=se}),P}}var r={v:1,nonce:G,t:{}},y=null,O=null,x=null,z=!1,C=!1,g=!1,H=!1,K=0,q=0,Z=0,$=!1,D=null,b=null,M=null,f=null,W=null,Y=[],Q=[],F=null,X,ee=m(()=>document.currentScript.nonce,""),te=/^[A-Za-z0-9+/_-]+={0,2}$/.test(ee)?ee:G,ve=document.scripts.length,ge=document.styleSheets.length,re=m(()=>Object.getOwnPropertyNames(window),[]);function m(e,n){try{return e()}catch{return n}}function N(e,n){Y.push(setTimeout(()=>{g||e()},n))}function S(e,n,a,o){e.addEventListener(n,a,o),Q.push([e,n,a,o])}function we(){Y.forEach(clearTimeout),Q.forEach(e=>{e[0].removeEventListener(e[1],e[2],e[3])}),F!==null&&m(()=>cancelAnimationFrame(F)),D&&D.disconnect(),W&&W(),b&&b.terminate(),M&&URL.revokeObjectURL(M),f&&f.parentNode&&f.parentNode.removeChild(f)}var he=/pptr:|__puppeteer_evaluation_script__|__pyppeteer_evaluation_script__|puppeteer-extra|playwright|__playwright_utility_world__|utility|selenium|webdriver/i,ye=/cdc_|selenium|webdriver|__nightmare|callPhantom|domAutomationController|__pw|__playwright|_phantom|__fxdriver|__driver|__lastWatirAlert|__webdriver_script|puppeteer|_Selenium_IDE_Recorder/i,V=[];function T(e){var n=m(()=>String(new Error().stack||""),"");he.test(n)&&V.indexOf(e)===-1&&V.push(e)}T("sync"),m(()=>{var e={};Object.defineProperty(e,"marker",{get:()=>(T("getter"),0)}),e.marker}),N(()=>{T("timeout")},0),m(()=>{F=requestAnimationFrame(()=>{T("raf")})}),m(()=>{var e=new Proxy({},{ownKeys:()=>(K+=1,[])});console.debug(e)}),m(()=>{D=new MutationObserver(e=>{q+=e.length}),D.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),N(()=>{D.disconnect()},de)}),S(window,"click",e=>{e.isTrusted===!1&&(Z+=1)},!0),["keydown","pointerdown","mousedown","touchstart","input"].forEach(e=>{S(window,e,n=>{n.isTrusted&&($=!0)},!0)}),W=J("main",e=>{g||(y=e,E())});var ne="("+J.toString()+")";if(typeof Worker!="function"||typeof Blob!="function"||typeof URL.createObjectURL!="function")z=!0;else try{var be="var s=Date.now()-"+Date.now()+";"+ne+'("worker",function(r){r.started=s;r.clock_delta=Date.now();postMessage(r)})';M=URL.createObjectURL(new Blob([be],{type:"text/javascript"})),b=new Worker(M),b.onmessage=e=>{if(!g){var n=e.data;n.clock_delta-=Date.now(),n.started=Math.max(0,n.started),O=n,b.terminate(),E()}},b.onerror=()=>{g||(C=!0,b.terminate(),E())}}catch{C=!0}try{f=document.createElement("iframe"),f.setAttribute("sandbox","allow-scripts"),f.style.display="none",f.setAttribute("aria-hidden","true");var _e='var b=document.createElement("script");b.text="window.__sp_t0_csp=1";document.head.appendChild(b);var bypass=window.__sp_t0_csp===1;delete window.__sp_t0_csp;b.parentNode.removeChild(b);'+ne+'("iframe",function(r){r.clock_delta=Date.now();parent.postMessage({__sp_t0:r,csp_bypass:bypass},"*")})';f.srcdoc=\`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-\`+te+\`'"><script nonce="\`+te+'">'+_e+"<\\/script>",S(window,"message",e=>{if(!(g||e.source!==f.contentWindow||!e.data||!e.data.__sp_t0)){var n=e.data.__sp_t0;n.clock_delta-=Date.now(),x=n,typeof e.data.csp_bypass=="boolean"&&(X=e.data.csp_bypass),E()}}),f.onerror=()=>{g||(C=!0,E())},(document.body||document.documentElement).appendChild(f)}catch{C=!0}function ae(){H=!0,N(R,fe),E()}document.readyState==="loading"?S(window,"DOMContentLoaded",ae):ae(),N(R,le),S(window,"pagehide",()=>R("early-exit"));function oe(){document.visibilityState==="hidden"&&R("background-tab")}S(document,"visibilitychange",oe),oe();function E(){H&&y&&O&&x&&R()}function Ae(e,n,a){var o=[];if(!e)return o;function i(t,L,_){t&&Object.keys(_).forEach(u=>{var w=_[u](e),d=_[u](t);w!=null&&d!==void 0&&d!==null&&JSON.stringify(w)!==JSON.stringify(d)&&o.push(L+u)})}var v={platform:t=>t.platform,languages:t=>t.languages,hardwareConcurrency:t=>t.cores,deviceMemory:t=>t.memory,brands:t=>t.brands};return i(n,"A7.",v),i(n,"",{"A10.vendor":t=>t.webgl&&t.webgl.vendor,"A10.renderer":t=>t.webgl&&t.webgl.renderer,"A3w.userAgent":t=>t.ua,"A29w.timeZone":t=>t.tz,"A4w.architecture":t=>t.uach&&t.uach.arch,"A4w.bitness":t=>t.uach&&t.uach.bitness,"A4w.platformVersion":t=>t.uach&&t.uach.platform_version,"A4w.fullVersionList":t=>t.uach&&t.uach.full_version_list}),i(a,"A8.",v),i(a,"",{"A8.userAgent":t=>t.ua,"A8.webdriver":t=>t.webdriver,"A8.timeZone":t=>t.tz,"A8.plugins":t=>t.plugins,"A8.dpr":t=>t.screen&&t.screen.dpr,"A8.screenW":t=>t.screen&&t.screen.w,"A8.renderer":t=>t.webgl&&t.webgl.renderer}),o}function ie(e){return!e||!y||["ua","uach","webgl"].forEach(n=>{JSON.stringify(e[n])===JSON.stringify(y[n])&&delete e[n]}),e}function I(e){if(e){var n=e.proto;return delete e.proto,n}}function Se(){var e=m(()=>{var v=Object.getOwnPropertyNames(window);return v.filter(t=>re.indexOf(t)===-1)},[]),n=m(()=>re.concat(e,Object.getOwnPropertyNames(document)).filter(v=>ye.test(v)),[]),a=I(y),o=I(O),i=I(x);r.t.exec=Math.max(0,Math.round(me)),r.t.sent=Math.max(0,Date.now()-pe),r.main=y||void 0,r.worker=ie(O)||void 0,r.iframe=ie(x)||void 0,r.proto={main:a||[],worker:o,iframe:i},r.globals={late:e.slice(0,32),automation:n.slice(0,16)},r.markers={stack:V,console_trap:K,csp_bypass:X},r.dom={mutations_500:q,sheets_added:Math.max(0,document.styleSheets.length-ge),scripts_added:Math.max(0,document.scripts.length-ve)},r.events={untrusted_clicks:Z,any_input:$}}function Ee(e){for(var n=0,a=0;a<e.length;a+=1){var o=e.charCodeAt(a);o<128?n+=1:o<2048?n+=2:o>=55296&&o<=56319?(n+=4,a+=1):n+=3}return n}function ke(){function e(){return r.xrealm=Ae(r.main,r.worker,r.iframe),JSON.stringify(r)}for(var n=e(),a=[()=>{r.globals.late=r.globals.late.slice(0,8)},()=>{r.iframe&&delete r.iframe.uach},()=>{r.worker&&delete r.worker.uach},()=>{r.main&&r.main.uach&&delete r.main.uach.full_version_list},()=>{r.iframe&&delete r.iframe.webgl},()=>{r.worker&&delete r.worker.webgl},()=>{r.iframe&&delete r.iframe.ua},()=>{r.worker&&delete r.worker.ua},()=>{r.proto.main=r.proto.main.slice(0,4)},()=>{delete r.iframe},()=>{delete r.worker},()=>{r.main&&delete r.main.webgl},()=>{r.main&&delete r.main.ua},()=>{delete r.globals},()=>{delete r.main},()=>{delete r.proto}],o=0;o<a.length&&Ee(n)>ue;o+=1)a[o](),r.availability==="available"&&(r.availability="insufficient-observation"),n=e();return n}function R(e){if(!g){g=!0,r.availability=e||(document.visibilityState==="hidden"?"background-tab":z?"unsupported-api":C?"script-failure":y&&O&&x?"available":"insufficient-observation"),we(),Se();var n=ke();m(()=>{fetch(ce,{method:"POST",body:n,keepalive:!0,credentials:"omit",headers:{"content-type":"text/plain"}}).catch(()=>{})})}}})`;
7
+
8
+ // ../connector-core/src/api-environment.ts
9
+ var STEADPHAST_API_KEY_ENV_VAR = "STEADPHAST_API_KEY";
10
+ var LEGACY_DISCOVER_API_KEY_ENV_VAR = "DISCOVER_API_KEY";
11
+ function resolveApiEnvironmentValue(canonicalValue, legacyValue) {
12
+ return canonicalValue ?? legacyValue;
13
+ }
14
+
15
+ // src/config.ts
16
+ var ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
17
+ var BEACON_PATHNAME = "/v1/client/t0";
18
+ var COLLECTOR_HEADER_PREFIX = "x-steadphast-collector-";
19
+ var COLLECTOR_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}context`;
20
+ var LEGACY_CANONICAL_INGEST_PATHNAME = "/v1/events";
21
+ var DiscoverConfigError = class extends TypeError {
22
+ name = "DiscoverConfigError";
23
+ };
24
+ function validateApiKeyEnvVar(apiKeyEnvVar) {
25
+ if (apiKeyEnvVar?.startsWith("NEXT_PUBLIC_")) {
26
+ throw new DiscoverConfigError(
27
+ "Steadphast connector apiKeyEnvVar must reference a server-only environment variable."
28
+ );
29
+ }
30
+ }
31
+ function resolveProductionIngestUrl(apiUrl) {
32
+ const url = parseStrictUrl(apiUrl, "apiUrl");
33
+ if (url.protocol !== "https:") {
34
+ throw new DiscoverConfigError(
35
+ "Steadphast connector apiUrl must use the https scheme."
36
+ );
37
+ }
38
+ if (url.pathname === LEGACY_CANONICAL_INGEST_PATHNAME) {
39
+ throw new DiscoverConfigError(
40
+ `Steadphast connector apiUrl must not target the canonical-event ingest route; use the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
41
+ );
42
+ }
43
+ if (url.pathname !== "/" && url.pathname !== ENVELOPE_INGEST_PATHNAME) {
44
+ throw new DiscoverConfigError(
45
+ `Steadphast connector apiUrl must be the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
46
+ );
47
+ }
48
+ return `${url.origin}${ENVELOPE_INGEST_PATHNAME}`;
49
+ }
50
+ function parseStrictUrl(value, setting) {
51
+ if (typeof value !== "string" || value.length === 0) {
52
+ throw new DiscoverConfigError(
53
+ `Steadphast connector ${setting} must be a non-empty absolute URL string.`
54
+ );
55
+ }
56
+ if (value.includes("?") || value.includes("#")) {
57
+ throw new DiscoverConfigError(
58
+ `Steadphast connector ${setting} must not contain a query or fragment.`
59
+ );
60
+ }
61
+ if (value.includes("@")) {
62
+ throw new DiscoverConfigError(
63
+ `Steadphast connector ${setting} must not contain userinfo.`
64
+ );
65
+ }
66
+ let url;
67
+ try {
68
+ url = new URL(value);
69
+ } catch {
70
+ throw new DiscoverConfigError(
71
+ `Steadphast connector ${setting} must be an absolute URL.`
72
+ );
73
+ }
74
+ if (url.hostname.length === 0) {
75
+ throw new DiscoverConfigError(
76
+ `Steadphast connector ${setting} must contain a host.`
77
+ );
78
+ }
79
+ if (url.username.length > 0 || url.password.length > 0) {
80
+ throw new DiscoverConfigError(
81
+ `Steadphast connector ${setting} must not contain userinfo.`
82
+ );
83
+ }
84
+ return url;
85
+ }
86
+ function resolveApiKey(customEnvVar) {
87
+ const runtime = globalThis;
88
+ const env = runtime.process?.env;
89
+ return customEnvVar !== void 0 ? env?.[customEnvVar] : resolveApiEnvironmentValue(
90
+ env?.[STEADPHAST_API_KEY_ENV_VAR],
91
+ env?.[LEGACY_DISCOVER_API_KEY_ENV_VAR]
92
+ );
93
+ }
94
+
95
+ // src/nonce.ts
96
+ var LAYOUT_VERSION = 1;
97
+ var API_KEY_VERIFIER_DOMAIN = "steadphast-discover:api-key:v1";
98
+ var NONCE_KEY_SALT = "steadphast-discover/client-nonce/v1/salt";
99
+ var NONCE_KEY_INFO = "steadphast-discover/client-nonce/v1";
100
+ var RENDER_CONTEXT_DOMAIN = "steadphast-discover/collector-render/v1";
101
+ var MAX_RID_BYTES = 512;
102
+ var MAX_KEY_ID_BYTES = 64;
103
+ var TAG_BYTES = 32;
104
+ var UTF8 = new TextEncoder();
105
+ function parseApiKey(apiKey) {
106
+ const separator = apiKey.indexOf(".");
107
+ if (separator <= 0 || separator === apiKey.length - 1) {
108
+ return void 0;
109
+ }
110
+ const keyId = apiKey.slice(0, separator);
111
+ const secret = apiKey.slice(separator + 1);
112
+ if (UTF8.encode(keyId).byteLength > MAX_KEY_ID_BYTES) {
113
+ return void 0;
114
+ }
115
+ return { keyId, secret };
116
+ }
117
+ function createNonceMinter(apiKey) {
118
+ const parsed = parseApiKey(apiKey);
119
+ if (parsed === void 0) {
120
+ return void 0;
121
+ }
122
+ const keyIdBytes = utf8(parsed.keyId);
123
+ let nonceKey;
124
+ return {
125
+ async mintRenderContext(rid, servedAtMs) {
126
+ const header = encodeHeader(rid, servedAtMs, keyIdBytes);
127
+ if (header === void 0) return void 0;
128
+ nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
129
+ const tag = new Uint8Array(
130
+ await crypto.subtle.sign(
131
+ "HMAC",
132
+ await nonceKey,
133
+ concat(utf8(RENDER_CONTEXT_DOMAIN), header)
134
+ )
135
+ );
136
+ const context = bytes(header.byteLength + TAG_BYTES);
137
+ context.set(header);
138
+ context.set(tag, header.byteLength);
139
+ return base64UrlNoPad(context);
140
+ },
141
+ async nonceFromRenderContext(context) {
142
+ if (context.length > 850 || !/^[A-Za-z0-9_-]+$/.test(context)) {
143
+ return void 0;
144
+ }
145
+ let decoded;
146
+ try {
147
+ const binary = atob(context.replace(/-/g, "+").replace(/_/g, "/"));
148
+ decoded = bytes(binary.length);
149
+ for (let i = 0; i < binary.length; i++)
150
+ decoded[i] = binary.charCodeAt(i);
151
+ } catch {
152
+ return void 0;
153
+ }
154
+ if (decoded.byteLength <= TAG_BYTES) return void 0;
155
+ const header = decoded.subarray(0, -TAG_BYTES);
156
+ nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
157
+ if (!await crypto.subtle.verify(
158
+ "HMAC",
159
+ await nonceKey,
160
+ decoded.subarray(-TAG_BYTES),
161
+ concat(utf8(RENDER_CONTEXT_DOMAIN), header)
162
+ ))
163
+ return void 0;
164
+ const tag = new Uint8Array(
165
+ await crypto.subtle.sign("HMAC", await nonceKey, header)
166
+ );
167
+ decoded.set(tag, header.byteLength);
168
+ return base64UrlNoPad(decoded);
169
+ }
170
+ };
171
+ }
172
+ function encodeHeader(rid, servedAtMs, keyIdBytes) {
173
+ const ridBytes = utf8(rid);
174
+ if (ridBytes.byteLength === 0 || ridBytes.byteLength > MAX_RID_BYTES || !Number.isSafeInteger(servedAtMs) || servedAtMs < 0) {
175
+ return void 0;
176
+ }
177
+ const header = bytes(
178
+ 1 + 2 + ridBytes.byteLength + 8 + 1 + keyIdBytes.byteLength
179
+ );
180
+ const view = new DataView(header.buffer);
181
+ let offset = 0;
182
+ header[offset] = LAYOUT_VERSION;
183
+ offset += 1;
184
+ view.setUint16(offset, ridBytes.byteLength);
185
+ offset += 2;
186
+ header.set(ridBytes, offset);
187
+ offset += ridBytes.byteLength;
188
+ view.setBigUint64(offset, BigInt(servedAtMs));
189
+ offset += 8;
190
+ header[offset] = keyIdBytes.byteLength;
191
+ offset += 1;
192
+ header.set(keyIdBytes, offset);
193
+ return header;
194
+ }
195
+ async function deriveNonceKey(parsed, keyIdBytes) {
196
+ const secretKey = await crypto.subtle.importKey(
197
+ "raw",
198
+ utf8(parsed.secret),
199
+ { name: "HMAC", hash: "SHA-256" },
200
+ false,
201
+ ["sign"]
202
+ );
203
+ const ikm = await crypto.subtle.sign(
204
+ "HMAC",
205
+ secretKey,
206
+ concat(utf8(API_KEY_VERIFIER_DOMAIN), keyIdBytes)
207
+ );
208
+ const hkdfKey = await crypto.subtle.importKey("raw", ikm, "HKDF", false, [
209
+ "deriveBits"
210
+ ]);
211
+ const nonceKeyBits = await crypto.subtle.deriveBits(
212
+ {
213
+ name: "HKDF",
214
+ hash: "SHA-256",
215
+ salt: utf8(NONCE_KEY_SALT),
216
+ info: concat(utf8(NONCE_KEY_INFO), keyIdBytes)
217
+ },
218
+ hkdfKey,
219
+ TAG_BYTES * 8
220
+ );
221
+ return crypto.subtle.importKey(
222
+ "raw",
223
+ nonceKeyBits,
224
+ { name: "HMAC", hash: "SHA-256" },
225
+ false,
226
+ ["sign", "verify"]
227
+ );
228
+ }
229
+ function bytes(length) {
230
+ return new Uint8Array(new ArrayBuffer(length));
231
+ }
232
+ function utf8(text) {
233
+ return UTF8.encode(text);
234
+ }
235
+ function concat(prefix, suffix) {
236
+ const out = bytes(prefix.byteLength + 1 + suffix.byteLength);
237
+ out.set(prefix, 0);
238
+ out[prefix.byteLength] = 0;
239
+ out.set(suffix, prefix.byteLength + 1);
240
+ return out;
241
+ }
242
+ function base64UrlNoPad(bytes2) {
243
+ let binary = "";
244
+ for (const byte of bytes2) {
245
+ binary += String.fromCharCode(byte);
246
+ }
247
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
248
+ }
249
+ var NonceMinterCache = class {
250
+ #apiKey;
251
+ #minter;
252
+ for(apiKey) {
253
+ if (this.#apiKey !== apiKey) {
254
+ this.#apiKey = apiKey;
255
+ this.#minter = createNonceMinter(apiKey);
256
+ }
257
+ return this.#minter;
258
+ }
259
+ };
260
+
261
+ // src/collector-render.ts
262
+ var minters = new NonceMinterCache();
263
+ function collectorScript(nonce, endpoint) {
264
+ const embed = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
265
+ return `${COLLECTOR_SOURCE}(${embed(nonce)},${embed(endpoint)});`;
266
+ }
267
+ async function renderCollector(config, endpoint, cspNonce) {
268
+ if (config.collector !== true) return null;
269
+ validateApiKeyEnvVar(config.apiKeyEnvVar);
270
+ const context = (await headers()).get(COLLECTOR_CONTEXT_HEADER);
271
+ if (context === null) return null;
272
+ const apiKey = resolveApiKey(config.apiKeyEnvVar);
273
+ if (apiKey === void 0) return null;
274
+ const minter = minters.for(apiKey);
275
+ if (minter === void 0) return null;
276
+ const nonce = await minter.nonceFromRenderContext(context);
277
+ if (nonce === void 0) return null;
278
+ return createElement("script", {
279
+ nonce: cspNonce ?? nonce,
280
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: package-owned collector with JSON-encoded, script-escaped arguments; no visitor nonce or destination is used.
281
+ dangerouslySetInnerHTML: { __html: collectorScript(nonce, endpoint) }
282
+ });
283
+ }
284
+
285
+ // src/server.ts
286
+ async function DiscoverCollector(props = {}) {
287
+ if (props.config?.collector !== true) return null;
288
+ const endpoint = `${new URL(resolveProductionIngestUrl(props.config.apiUrl)).origin}${BEACON_PATHNAME}`;
289
+ return renderCollector(props.config, endpoint, props.nonce);
290
+ }
291
+ export {
292
+ DiscoverCollector
293
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@steadphast/connector-nextjs",
3
3
  "description": "Next.js Middleware and Proxy connector for Steadphast: captures request metadata before it reaches your app and sends it to Steadphast for AI and bot traffic classification, without touching the response.",
4
- "version": "0.5.3",
4
+ "version": "0.6.0",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Steadphast",
7
7
  "homepage": "https://steadphast.ai",
@@ -25,18 +25,21 @@
25
25
  "dist/index.d.ts",
26
26
  "dist/config.d.ts",
27
27
  "dist/middleware.d.ts",
28
+ "dist/server.js",
29
+ "dist/server.d.ts",
28
30
  "LICENSE",
29
31
  "NOTICE",
30
32
  "README.md"
31
33
  ],
32
34
  "scripts": {
33
- "build": "rm -rf dist && tsc -p tsconfig.build.json && esbuild src/index.ts src/internal-loopback.ts --bundle --format=esm --platform=neutral --target=es2022 --outdir=dist --external:next/server",
35
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && esbuild src/index.ts src/server.ts src/internal-loopback.ts src/internal-loopback-server.ts --bundle --format=esm --platform=neutral --target=es2022 --outdir=dist --external:next/server --external:next/headers --external:react",
34
36
  "prepublishOnly": "node -e \"if(process.env.STEADPHAST_CONNECTOR_RELEASE!=='1'){console.error('refusing to publish: only the publish-connector-nextjs workflow releases this package (it sets STEADPHAST_CONNECTOR_RELEASE=1 after every gate passes).');process.exit(1)}\"",
35
37
  "typecheck": "tsc -p tsconfig.json --noEmit",
36
- "lint": "biome check src package.json tsconfig.json tsconfig.build.json vitest.config.ts",
38
+ "lint": "biome check src scripts package.json tsconfig.json tsconfig.build.json vitest.config.ts",
37
39
  "test": "vitest run",
38
40
  "test:coverage": "vitest run --coverage",
39
- "test:perf": "vitest run --reporter=verbose --slowTestThreshold=300"
41
+ "test:perf": "vitest run --reporter=verbose --slowTestThreshold=300",
42
+ "build:collector": "node scripts/build-collector.mjs"
40
43
  },
41
44
  "main": "./dist/index.js",
42
45
  "types": "./dist/index.d.ts",
@@ -45,19 +48,27 @@
45
48
  "types": "./dist/index.d.ts",
46
49
  "import": "./dist/index.js",
47
50
  "default": "./dist/index.js"
51
+ },
52
+ "./server": {
53
+ "types": "./dist/server.d.ts",
54
+ "import": "./dist/server.js",
55
+ "default": "./dist/server.js"
48
56
  }
49
57
  },
50
58
  "peerDependencies": {
51
- "next": "^15.0.0 || ^16.0.0"
59
+ "next": "^15.0.0 || ^16.0.0",
60
+ "react": "^19.0.0"
52
61
  },
53
62
  "devDependencies": {
54
63
  "@discover/connector-core": "workspace:*",
55
64
  "@edge-runtime/vm": "5.0.0",
56
- "@vitest/coverage-v8": "4.1.10",
57
- "esbuild": "0.28.1",
58
- "next": "15.5.23",
65
+ "@types/react": "19.2.18",
66
+ "@types/react-dom": "19.2.4",
67
+ "@vitest/coverage-v8": "4.1.12",
68
+ "esbuild": "0.28.2",
69
+ "next": "15.5.28",
59
70
  "react": "19.2.8",
60
71
  "react-dom": "19.2.8",
61
- "vitest": "4.1.10"
72
+ "vitest": "4.1.12"
62
73
  }
63
74
  }