unshared-clientjs-sdk 2.0.0-rc.21 → 2.0.0-rc.22

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 (85) hide show
  1. package/dist/client.d.ts +29 -0
  2. package/dist/client.js +1 -1
  3. package/dist/esm/client.d.mts +29 -0
  4. package/dist/esm/client.mjs +1 -1
  5. package/dist/esm/index.d.mts +2 -0
  6. package/dist/esm/index.mjs +1 -1
  7. package/dist/esm/middleware/dispatch-dedupe.d.mts +11 -0
  8. package/dist/esm/middleware/dispatch-dedupe.mjs +1 -0
  9. package/dist/esm/middleware/index.d.mts +26 -11
  10. package/dist/esm/middleware/index.mjs +1 -1
  11. package/dist/esm/middleware/injection/fingerprint-script.mjs +1 -1
  12. package/dist/esm/middleware/response-interceptor.d.mts +2 -2
  13. package/dist/esm/middleware/routes/submit-fp.d.mts +14 -7
  14. package/dist/esm/middleware/routes/submit-fp.mjs +1 -1
  15. package/dist/esm/middleware/routes/verify.d.mts +11 -6
  16. package/dist/esm/middleware/routes/verify.mjs +1 -1
  17. package/dist/esm/middleware/utils/client-ip.d.mts +4 -4
  18. package/dist/esm/middleware/utils/client-ip.mjs +1 -1
  19. package/dist/esm/middleware/utils/cookies.d.mts +2 -2
  20. package/dist/esm/middleware/utils/device-id.d.mts +17 -3
  21. package/dist/esm/middleware/utils/device-id.mjs +1 -1
  22. package/dist/esm/middleware/utils/http-helpers.d.mts +21 -0
  23. package/dist/esm/middleware/utils/http-helpers.mjs +1 -0
  24. package/dist/esm/middleware/utils/include-path.d.mts +6 -0
  25. package/dist/esm/middleware/utils/include-path.mjs +1 -0
  26. package/dist/esm/middleware/utils/is-bot.mjs +1 -1
  27. package/dist/esm/middleware/utils/secure.d.mts +2 -2
  28. package/dist/esm/middleware/utils/secure.mjs +1 -1
  29. package/dist/esm/middleware/utils/sentinel-user-id.d.mts +10 -0
  30. package/dist/esm/middleware/utils/sentinel-user-id.mjs +1 -0
  31. package/dist/esm/middleware.d.mts +11 -8
  32. package/dist/esm/middleware.mjs +1 -1
  33. package/dist/esm/types.d.mts +44 -0
  34. package/dist/esm/types.mjs +1 -0
  35. package/dist/esm/web/index.d.mts +17 -0
  36. package/dist/esm/web/index.mjs +1 -0
  37. package/dist/esm/web/protection-handler.d.mts +28 -0
  38. package/dist/esm/web/protection-handler.mjs +1 -0
  39. package/dist/esm/web/submit-handler.d.mts +27 -0
  40. package/dist/esm/web/submit-handler.mjs +1 -0
  41. package/dist/esm/web/types.d.mts +110 -0
  42. package/dist/esm/web/types.mjs +1 -0
  43. package/dist/esm/web/web-helpers.d.mts +55 -0
  44. package/dist/esm/web/web-helpers.mjs +1 -0
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.js +1 -1
  47. package/dist/middleware/dispatch-dedupe.d.ts +11 -0
  48. package/dist/middleware/dispatch-dedupe.js +1 -0
  49. package/dist/middleware/index.d.ts +26 -11
  50. package/dist/middleware/index.js +1 -1
  51. package/dist/middleware/injection/fingerprint-script.js +1 -1
  52. package/dist/middleware/response-interceptor.d.ts +2 -2
  53. package/dist/middleware/routes/submit-fp.d.ts +14 -7
  54. package/dist/middleware/routes/submit-fp.js +1 -1
  55. package/dist/middleware/routes/verify.d.ts +11 -6
  56. package/dist/middleware/routes/verify.js +1 -1
  57. package/dist/middleware/utils/client-ip.d.ts +4 -4
  58. package/dist/middleware/utils/client-ip.js +1 -1
  59. package/dist/middleware/utils/cookies.d.ts +2 -2
  60. package/dist/middleware/utils/device-id.d.ts +17 -3
  61. package/dist/middleware/utils/device-id.js +1 -1
  62. package/dist/middleware/utils/http-helpers.d.ts +21 -0
  63. package/dist/middleware/utils/http-helpers.js +1 -0
  64. package/dist/middleware/utils/include-path.d.ts +6 -0
  65. package/dist/middleware/utils/include-path.js +1 -0
  66. package/dist/middleware/utils/is-bot.js +1 -1
  67. package/dist/middleware/utils/secure.d.ts +2 -2
  68. package/dist/middleware/utils/secure.js +1 -1
  69. package/dist/middleware/utils/sentinel-user-id.d.ts +10 -0
  70. package/dist/middleware/utils/sentinel-user-id.js +1 -0
  71. package/dist/middleware.d.ts +11 -8
  72. package/dist/middleware.js +1 -1
  73. package/dist/types.d.ts +44 -0
  74. package/dist/types.js +1 -0
  75. package/dist/web/index.d.ts +17 -0
  76. package/dist/web/index.js +1 -0
  77. package/dist/web/protection-handler.d.ts +28 -0
  78. package/dist/web/protection-handler.js +1 -0
  79. package/dist/web/submit-handler.d.ts +27 -0
  80. package/dist/web/submit-handler.js +1 -0
  81. package/dist/web/types.d.ts +110 -0
  82. package/dist/web/types.js +1 -0
  83. package/dist/web/web-helpers.d.ts +55 -0
  84. package/dist/web/web-helpers.js +1 -0
  85. package/package.json +7 -10
package/dist/client.d.ts CHANGED
@@ -20,6 +20,26 @@ export interface UnsharedLabsClientConfig {
20
20
  * @default 3
21
21
  */
22
22
  maxRetries?: number;
23
+ /**
24
+ * Custom fetch implementation. Use this to configure connection pooling,
25
+ * custom HTTP agents, or proxies. Defaults to the global `fetch`.
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * import { Agent, fetch as undiciFetch } from 'undici';
30
+ *
31
+ * const agent = new Agent({
32
+ * keepAliveTimeout: 30_000,
33
+ * connections: 50,
34
+ * });
35
+ *
36
+ * const client = new UnsharedLabsClient({
37
+ * apiKey: 'usk_...',
38
+ * fetch: (url, init) => undiciFetch(url, { ...init, dispatcher: agent }),
39
+ * });
40
+ * ```
41
+ */
42
+ fetch?: typeof globalThis.fetch;
23
43
  }
24
44
  export interface UnsharedLabsError {
25
45
  code: string;
@@ -48,6 +68,14 @@ export interface SubmitFingerprintOptions {
48
68
  ipAddress?: string;
49
69
  /** SDK encrypts before sending. */
50
70
  userAgent?: string;
71
+ /**
72
+ * Client-supplied idempotency key. Forwarded verbatim as X-Idempotency-Key
73
+ * so the backend's ON CONFLICT (idempotency_key) catches duplicates across
74
+ * reloads, tabs, and concurrent SDK instances. When omitted, a fresh UUID
75
+ * is generated (best-effort dedup only within a single submitFingerprintEvent
76
+ * call's retries).
77
+ */
78
+ idempotencyKey?: string;
51
79
  }
52
80
  export interface SubmitFingerprintResult {
53
81
  hash: string;
@@ -124,6 +152,7 @@ export declare class UnsharedLabsClient {
124
152
  private readonly _timeout;
125
153
  private readonly _maxRetries;
126
154
  private readonly _encryptionKey;
155
+ private readonly _customFetch;
127
156
  constructor(config: UnsharedLabsClientConfig);
128
157
  private _encrypt;
129
158
  /**
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"t",{value:!0}),exports.UnsharedLabsClient=void 0;const crypto_1=require("crypto"),util_1=require("./util"),DEFAULT_BASE_URL="https://api-ingress.unsharedlabs.com",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3;function sleep(e){return new Promise(s=>setTimeout(s,e))}function retryDelay(e){const s=Math.min(1e3*Math.pow(2,e-1),3e4),t=s*(.5*Math.random()-.25);return Math.max(0,s+t)}async function parseErrorBody(e){const s=await e.text().catch(()=>"");try{const t=JSON.parse(s);return t?.error?.code?{code:t.error.code,message:t.error.message??"Unknown error",details:t.error.details}:{code:"UNKNOWN_ERROR",message:s||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:s||e.statusText}}}class UnsharedLabsClient{constructor(e){if(!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");this.i=e.apiKey,this.o=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this.h=e.timeout??1e4,this.u=e.maxRetries??3,this.l=(0,crypto_1.createHash)("sha256").update(e.apiKey).digest()}_(e){return(0,util_1.encryptData)(e,this.l)}async p(e,s){const t=this.u+1;let r={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let i=1;i<=t;i++){i>1&&await sleep(retryDelay(i-1));const t=new AbortController,n=setTimeout(()=>t.abort(),this.h);try{const i=await fetch(e,{method:s.method,headers:{"X-API-Key":this.i,...s.headers},body:s.body,signal:t.signal});if(clearTimeout(n),i.ok){const e=await i.text().catch(()=>"{}");let s;try{s=JSON.parse(e)}catch{s={}}const t="data"in s?s.data:s;return{success:!0,status:i.status,data:t}}const a=await parseErrorBody(i);if(i.status>=400&&i.status<500){if(429===i.status){const e=i.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(a.retryAfter=s)}}return{success:!1,status:i.status,error:a}}r={success:!1,status:i.status,error:a}}catch(e){clearTimeout(n),r={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}}return r}async submitFingerprintEvent(e,s){const t={hash:e.full_hash,stable_hash:e.fingerprint_id,collected_at:e.timestamp,is_incognito:e.isIncognito,components:e.components,version:e.version};return null!=s?.userId&&(t.user_id=this._(s.userId)),null!=s?.emailAddress&&(t.email_address=this._(s.emailAddress)),null!=s?.sessionHash&&(t.session_hash=s.sessionHash),null!=s?.eventType&&(t.event_type=s.eventType),null!=s?.ipAddress&&(t.ip_address=this._(s.ipAddress)),null!=s?.userAgent&&(t.user_agent=this._(s.userAgent)),this.p(`${this.o}/v2/submit-fingerprint-event`,{method:"POST",headers:{"Content-Type":"application/json","X-Idempotency-Key":(0,crypto_1.randomUUID)()},body:JSON.stringify(t)})}async processUserEvent(e){const s={event_type:e.eventType,user_id:this._(e.userId),ip_address:this._(e.ipAddress),device_id:this._(e.deviceId),session_hash:e.sessionHash,user_agent:this._(e.userAgent),email_address:this._(e.emailAddress)};return null!=e.fingerprintId&&(s.fingerprint_id=this._(e.fingerprintId)),null!=e.subscriptionStatus&&(s.subscription_status=e.subscriptionStatus),null!=e.eventDetails&&(s.event_details=e.eventDetails),this.p(`${this.o}/v2/process-user-event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}async checkUser(e,s){const t="string"==typeof s?{deviceId:s}:s;if(!t.deviceId&&!t.fingerprintId)return{success:!0,status:200,data:{is_user_flagged:!1}};const r=new URLSearchParams;r.set("email_address",this._(e)),t.deviceId&&r.set("device_id",this._(t.deviceId)),t.fingerprintId&&r.set("fingerprint_id",this._(t.fingerprintId));const i=await this.p(`${this.o}/v2/check-user?${r}`,{method:"GET"});return i.success?i:{success:!0,status:200,data:{is_user_flagged:!1}}}async triggerEmailVerification(e,s,t){const r={email_address:this._(e),device_id:this._(s)};t?.fingerprintId&&(r.fingerprint_id=this._(t.fingerprintId));const i=await this.p(`${this.o}/v2/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return!i.success&&(0===i.status||i.status>=500)?{success:!1,status:i.status,error:{code:"DELIVERY_FAILED",message:i.error?.message??"Delivery failed"}}:i}async verify(e,s,t,r){const i={email_address:this._(e),device_id:this._(s),code:this._(t)};r?.fingerprintId&&(i.fingerprint_id=this._(r.fingerprintId));const n=await this.p(`${this.o}/v2/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return!n.success&&(0===n.status||n.status>=500)?{success:!1,status:n.status,error:{code:"DELIVERY_FAILED",message:n.error?.message??"Delivery failed"}}:n.success&&!1===n.data?.verified?{success:!1,status:n.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:n.data.reason?{reason:n.data.reason}:void 0}}:n}async getVerificationFlowConfig(){const e=await this.p(`${this.o}/v2/verification-flow-config`,{method:"GET"});return e.success&&e.data?e.data:null}}exports.UnsharedLabsClient=UnsharedLabsClient;
1
+ "use strict";Object.defineProperty(exports,"t",{value:!0}),exports.UnsharedLabsClient=void 0;const crypto_1=require("crypto"),util_1=require("./util"),DEFAULT_BASE_URL="https://api-ingress.unsharedlabs.com",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3;function sleep(e){return new Promise(s=>setTimeout(s,e))}function retryDelay(e){const s=Math.min(1e3*Math.pow(2,e-1),3e4),t=s*(.5*Math.random()-.25);return Math.max(0,s+t)}async function parseErrorBody(e){const s=await e.text().catch(()=>"");try{const t=JSON.parse(s);return t?.error?.code?{code:t.error.code,message:t.error.message??"Unknown error",details:t.error.details}:{code:"UNKNOWN_ERROR",message:s||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:s||e.statusText}}}class UnsharedLabsClient{constructor(e){if(!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");this.i=e.apiKey,this.o=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this.h=e.timeout??1e4,this.u=e.maxRetries??3,this.l=(0,crypto_1.createHash)("sha256").update(e.apiKey).digest(),this._=e.fetch}p(e){return(0,util_1.encryptData)(e,this.l)}async m(e,s){const t=this.u+1;let i={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let r=1;r<=t;r++){r>1&&await sleep(retryDelay(r-1));const t=new AbortController,n=setTimeout(()=>t.abort(),this.h);try{const r=this._??globalThis.fetch,a=await r(e,{method:s.method,headers:{"X-API-Key":this.i,...s.headers},body:s.body,signal:t.signal});if(clearTimeout(n),a.ok){const e=await a.text().catch(()=>"{}");let s;try{s=JSON.parse(e)}catch{s={}}const t="data"in s?s.data:s;return{success:!0,status:a.status,data:t}}const o=await parseErrorBody(a);if(a.status>=400&&a.status<500){if(429===a.status){const e=a.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(o.retryAfter=s)}}return{success:!1,status:a.status,error:o}}i={success:!1,status:a.status,error:o}}catch(e){clearTimeout(n),i={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}}return i}async submitFingerprintEvent(e,s){const t={hash:e.full_hash,stable_hash:e.fingerprint_id,collected_at:e.timestamp,is_incognito:e.isIncognito,components:e.components,version:e.version};return null!=s?.userId&&(t.user_id=this.p(s.userId)),null!=s?.emailAddress&&(t.email_address=this.p(s.emailAddress)),null!=s?.sessionHash&&(t.session_hash=s.sessionHash),null!=s?.eventType&&(t.event_type=s.eventType),null!=s?.ipAddress&&(t.ip_address=this.p(s.ipAddress)),null!=s?.userAgent&&(t.user_agent=this.p(s.userAgent)),this.m(`${this.o}/v2/submit-fingerprint-event`,{method:"POST",headers:{"Content-Type":"application/json","X-Idempotency-Key":s?.idempotencyKey??(0,crypto_1.randomUUID)()},body:JSON.stringify(t)})}async processUserEvent(e){const s={event_type:e.eventType,user_id:this.p(e.userId),ip_address:this.p(e.ipAddress),device_id:this.p(e.deviceId),session_hash:e.sessionHash,user_agent:this.p(e.userAgent),email_address:this.p(e.emailAddress)};return null!=e.fingerprintId&&(s.fingerprint_id=this.p(e.fingerprintId)),null!=e.subscriptionStatus&&(s.subscription_status=e.subscriptionStatus),null!=e.eventDetails&&(s.event_details=e.eventDetails),this.m(`${this.o}/v2/process-user-event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}async checkUser(e,s){const t="string"==typeof s?{deviceId:s}:s;if(!t.deviceId&&!t.fingerprintId)return{success:!0,status:200,data:{is_user_flagged:!1}};const i=new URLSearchParams;i.set("email_address",this.p(e)),t.deviceId&&i.set("device_id",this.p(t.deviceId)),t.fingerprintId&&i.set("fingerprint_id",this.p(t.fingerprintId));const r=await this.m(`${this.o}/v2/check-user?${i}`,{method:"GET"});return r.success?r:{success:!0,status:200,data:{is_user_flagged:!1}}}async triggerEmailVerification(e,s,t){const i={email_address:this.p(e),device_id:this.p(s)};t?.fingerprintId&&(i.fingerprint_id=this.p(t.fingerprintId));const r=await this.m(`${this.o}/v2/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return!r.success&&(0===r.status||r.status>=500)?{success:!1,status:r.status,error:{code:"DELIVERY_FAILED",message:r.error?.message??"Delivery failed"}}:r}async verify(e,s,t,i){const r={email_address:this.p(e),device_id:this.p(s),code:this.p(t)};i?.fingerprintId&&(r.fingerprint_id=this.p(i.fingerprintId));const n=await this.m(`${this.o}/v2/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return!n.success&&(0===n.status||n.status>=500)?{success:!1,status:n.status,error:{code:"DELIVERY_FAILED",message:n.error?.message??"Delivery failed"}}:n.success&&!1===n.data?.verified?{success:!1,status:n.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:n.data.reason?{reason:n.data.reason}:void 0}}:n}async getVerificationFlowConfig(){const e=await this.m(`${this.o}/v2/verification-flow-config`,{method:"GET"});return e.success&&e.data?e.data:null}}exports.UnsharedLabsClient=UnsharedLabsClient;
@@ -20,6 +20,26 @@ export interface UnsharedLabsClientConfig {
20
20
  * @default 3
21
21
  */
22
22
  maxRetries?: number;
23
+ /**
24
+ * Custom fetch implementation. Use this to configure connection pooling,
25
+ * custom HTTP agents, or proxies. Defaults to the global `fetch`.
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * import { Agent, fetch as undiciFetch } from 'undici';
30
+ *
31
+ * const agent = new Agent({
32
+ * keepAliveTimeout: 30_000,
33
+ * connections: 50,
34
+ * });
35
+ *
36
+ * const client = new UnsharedLabsClient({
37
+ * apiKey: 'usk_...',
38
+ * fetch: (url, init) => undiciFetch(url, { ...init, dispatcher: agent }),
39
+ * });
40
+ * ```
41
+ */
42
+ fetch?: typeof globalThis.fetch;
23
43
  }
24
44
  export interface UnsharedLabsError {
25
45
  code: string;
@@ -48,6 +68,14 @@ export interface SubmitFingerprintOptions {
48
68
  ipAddress?: string;
49
69
  /** SDK encrypts before sending. */
50
70
  userAgent?: string;
71
+ /**
72
+ * Client-supplied idempotency key. Forwarded verbatim as X-Idempotency-Key
73
+ * so the backend's ON CONFLICT (idempotency_key) catches duplicates across
74
+ * reloads, tabs, and concurrent SDK instances. When omitted, a fresh UUID
75
+ * is generated (best-effort dedup only within a single submitFingerprintEvent
76
+ * call's retries).
77
+ */
78
+ idempotencyKey?: string;
51
79
  }
52
80
  export interface SubmitFingerprintResult {
53
81
  hash: string;
@@ -124,6 +152,7 @@ export declare class UnsharedLabsClient {
124
152
  private readonly _timeout;
125
153
  private readonly _maxRetries;
126
154
  private readonly _encryptionKey;
155
+ private readonly _customFetch;
127
156
  constructor(config: UnsharedLabsClientConfig);
128
157
  private _encrypt;
129
158
  /**
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"crypto";import{encryptData}from"./util";const DEFAULT_BASE_URL="https://api-ingress.unsharedlabs.com",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3;function sleep(e){return new Promise(s=>setTimeout(s,e))}function retryDelay(e){const s=Math.min(1e3*Math.pow(2,e-1),3e4),t=s*(.5*Math.random()-.25);return Math.max(0,s+t)}async function parseErrorBody(e){const s=await e.text().catch(()=>"");try{const t=JSON.parse(s);return t?.error?.code?{code:t.error.code,message:t.error.message??"Unknown error",details:t.error.details}:{code:"UNKNOWN_ERROR",message:s||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:s||e.statusText}}}export class UnsharedLabsClient{constructor(e){if(!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");this.t=e.apiKey,this.i=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this.o=e.timeout??1e4,this.h=e.maxRetries??3,this.u=createHash("sha256").update(e.apiKey).digest()}l(e){return encryptData(e,this.u)}async _(e,s){const t=this.h+1;let r={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let i=1;i<=t;i++){i>1&&await sleep(retryDelay(i-1));const t=new AbortController,a=setTimeout(()=>t.abort(),this.o);try{const i=await fetch(e,{method:s.method,headers:{"X-API-Key":this.t,...s.headers},body:s.body,signal:t.signal});if(clearTimeout(a),i.ok){const e=await i.text().catch(()=>"{}");let s;try{s=JSON.parse(e)}catch{s={}}const t="data"in s?s.data:s;return{success:!0,status:i.status,data:t}}const n=await parseErrorBody(i);if(i.status>=400&&i.status<500){if(429===i.status){const e=i.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(n.retryAfter=s)}}return{success:!1,status:i.status,error:n}}r={success:!1,status:i.status,error:n}}catch(e){clearTimeout(a),r={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}}return r}async submitFingerprintEvent(e,s){const t={hash:e.full_hash,stable_hash:e.fingerprint_id,collected_at:e.timestamp,is_incognito:e.isIncognito,components:e.components,version:e.version};return null!=s?.userId&&(t.user_id=this.l(s.userId)),null!=s?.emailAddress&&(t.email_address=this.l(s.emailAddress)),null!=s?.sessionHash&&(t.session_hash=s.sessionHash),null!=s?.eventType&&(t.event_type=s.eventType),null!=s?.ipAddress&&(t.ip_address=this.l(s.ipAddress)),null!=s?.userAgent&&(t.user_agent=this.l(s.userAgent)),this._(`${this.i}/v2/submit-fingerprint-event`,{method:"POST",headers:{"Content-Type":"application/json","X-Idempotency-Key":randomUUID()},body:JSON.stringify(t)})}async processUserEvent(e){const s={event_type:e.eventType,user_id:this.l(e.userId),ip_address:this.l(e.ipAddress),device_id:this.l(e.deviceId),session_hash:e.sessionHash,user_agent:this.l(e.userAgent),email_address:this.l(e.emailAddress)};return null!=e.fingerprintId&&(s.fingerprint_id=this.l(e.fingerprintId)),null!=e.subscriptionStatus&&(s.subscription_status=e.subscriptionStatus),null!=e.eventDetails&&(s.event_details=e.eventDetails),this._(`${this.i}/v2/process-user-event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}async checkUser(e,s){const t="string"==typeof s?{deviceId:s}:s;if(!t.deviceId&&!t.fingerprintId)return{success:!0,status:200,data:{is_user_flagged:!1}};const r=new URLSearchParams;r.set("email_address",this.l(e)),t.deviceId&&r.set("device_id",this.l(t.deviceId)),t.fingerprintId&&r.set("fingerprint_id",this.l(t.fingerprintId));const i=await this._(`${this.i}/v2/check-user?${r}`,{method:"GET"});return i.success?i:{success:!0,status:200,data:{is_user_flagged:!1}}}async triggerEmailVerification(e,s,t){const r={email_address:this.l(e),device_id:this.l(s)};t?.fingerprintId&&(r.fingerprint_id=this.l(t.fingerprintId));const i=await this._(`${this.i}/v2/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return!i.success&&(0===i.status||i.status>=500)?{success:!1,status:i.status,error:{code:"DELIVERY_FAILED",message:i.error?.message??"Delivery failed"}}:i}async verify(e,s,t,r){const i={email_address:this.l(e),device_id:this.l(s),code:this.l(t)};r?.fingerprintId&&(i.fingerprint_id=this.l(r.fingerprintId));const a=await this._(`${this.i}/v2/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return!a.success&&(0===a.status||a.status>=500)?{success:!1,status:a.status,error:{code:"DELIVERY_FAILED",message:a.error?.message??"Delivery failed"}}:a.success&&!1===a.data?.verified?{success:!1,status:a.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:a.data.reason?{reason:a.data.reason}:void 0}}:a}async getVerificationFlowConfig(){const e=await this._(`${this.i}/v2/verification-flow-config`,{method:"GET"});return e.success&&e.data?e.data:null}}
1
+ import{createHash,randomUUID}from"crypto";import{encryptData}from"./util";const DEFAULT_BASE_URL="https://api-ingress.unsharedlabs.com",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3;function sleep(e){return new Promise(s=>setTimeout(s,e))}function retryDelay(e){const s=Math.min(1e3*Math.pow(2,e-1),3e4),t=s*(.5*Math.random()-.25);return Math.max(0,s+t)}async function parseErrorBody(e){const s=await e.text().catch(()=>"");try{const t=JSON.parse(s);return t?.error?.code?{code:t.error.code,message:t.error.message??"Unknown error",details:t.error.details}:{code:"UNKNOWN_ERROR",message:s||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:s||e.statusText}}}export class UnsharedLabsClient{constructor(e){if(!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");this.t=e.apiKey,this.i=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this.o=e.timeout??1e4,this.h=e.maxRetries??3,this.u=createHash("sha256").update(e.apiKey).digest(),this.l=e.fetch}_(e){return encryptData(e,this.u)}async m(e,s){const t=this.h+1;let r={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let i=1;i<=t;i++){i>1&&await sleep(retryDelay(i-1));const t=new AbortController,a=setTimeout(()=>t.abort(),this.o);try{const i=this.l??globalThis.fetch,n=await i(e,{method:s.method,headers:{"X-API-Key":this.t,...s.headers},body:s.body,signal:t.signal});if(clearTimeout(a),n.ok){const e=await n.text().catch(()=>"{}");let s;try{s=JSON.parse(e)}catch{s={}}const t="data"in s?s.data:s;return{success:!0,status:n.status,data:t}}const o=await parseErrorBody(n);if(n.status>=400&&n.status<500){if(429===n.status){const e=n.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(o.retryAfter=s)}}return{success:!1,status:n.status,error:o}}r={success:!1,status:n.status,error:o}}catch(e){clearTimeout(a),r={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}}return r}async submitFingerprintEvent(e,s){const t={hash:e.full_hash,stable_hash:e.fingerprint_id,collected_at:e.timestamp,is_incognito:e.isIncognito,components:e.components,version:e.version};return null!=s?.userId&&(t.user_id=this._(s.userId)),null!=s?.emailAddress&&(t.email_address=this._(s.emailAddress)),null!=s?.sessionHash&&(t.session_hash=s.sessionHash),null!=s?.eventType&&(t.event_type=s.eventType),null!=s?.ipAddress&&(t.ip_address=this._(s.ipAddress)),null!=s?.userAgent&&(t.user_agent=this._(s.userAgent)),this.m(`${this.i}/v2/submit-fingerprint-event`,{method:"POST",headers:{"Content-Type":"application/json","X-Idempotency-Key":s?.idempotencyKey??randomUUID()},body:JSON.stringify(t)})}async processUserEvent(e){const s={event_type:e.eventType,user_id:this._(e.userId),ip_address:this._(e.ipAddress),device_id:this._(e.deviceId),session_hash:e.sessionHash,user_agent:this._(e.userAgent),email_address:this._(e.emailAddress)};return null!=e.fingerprintId&&(s.fingerprint_id=this._(e.fingerprintId)),null!=e.subscriptionStatus&&(s.subscription_status=e.subscriptionStatus),null!=e.eventDetails&&(s.event_details=e.eventDetails),this.m(`${this.i}/v2/process-user-event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}async checkUser(e,s){const t="string"==typeof s?{deviceId:s}:s;if(!t.deviceId&&!t.fingerprintId)return{success:!0,status:200,data:{is_user_flagged:!1}};const r=new URLSearchParams;r.set("email_address",this._(e)),t.deviceId&&r.set("device_id",this._(t.deviceId)),t.fingerprintId&&r.set("fingerprint_id",this._(t.fingerprintId));const i=await this.m(`${this.i}/v2/check-user?${r}`,{method:"GET"});return i.success?i:{success:!0,status:200,data:{is_user_flagged:!1}}}async triggerEmailVerification(e,s,t){const r={email_address:this._(e),device_id:this._(s)};t?.fingerprintId&&(r.fingerprint_id=this._(t.fingerprintId));const i=await this.m(`${this.i}/v2/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return!i.success&&(0===i.status||i.status>=500)?{success:!1,status:i.status,error:{code:"DELIVERY_FAILED",message:i.error?.message??"Delivery failed"}}:i}async verify(e,s,t,r){const i={email_address:this._(e),device_id:this._(s),code:this._(t)};r?.fingerprintId&&(i.fingerprint_id=this._(r.fingerprintId));const a=await this.m(`${this.i}/v2/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return!a.success&&(0===a.status||a.status>=500)?{success:!1,status:a.status,error:{code:"DELIVERY_FAILED",message:a.error?.message??"Delivery failed"}}:a.success&&!1===a.data?.verified?{success:!1,status:a.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:a.data.reason?{reason:a.data.reason}:void 0}}:a}async getVerificationFlowConfig(){const e=await this.m(`${this.i}/v2/verification-flow-config`,{method:"GET"});return e.success&&e.data?e.data:null}}
@@ -4,3 +4,5 @@ export type { MiddlewareOptions } from './middleware';
4
4
  export { unsharedBoundToUser, VerdictCache, } from './middleware/index';
5
5
  export type { ProtectionConfig, Verdict } from './middleware/index';
6
6
  export type { UnsharedLabsClientConfig, ApiResult, UnsharedLabsError, SubmitFingerprintOptions, SubmitFingerprintResult, ProcessUserEventParams, ProcessUserEventResult, CheckUserResult, TriggerEmailVerificationResult, VerifyResult, VerificationFlowStep, VerificationFlowConfigResult, } from './client';
7
+ export type { UnsharedRequest, UnsharedResponse, UnsharedNextFunction } from './types';
8
+ export { sendJson } from './middleware/utils/http-helpers';
@@ -1 +1 @@
1
- export{UnsharedLabsClient}from"./client";export{createUnsharedMiddleware,assertTrustProxy}from"./middleware";export{unsharedBoundToUser,VerdictCache}from"./middleware/index";
1
+ export{UnsharedLabsClient}from"./client";export{createUnsharedMiddleware,assertTrustProxy}from"./middleware";export{unsharedBoundToUser,VerdictCache}from"./middleware/index";export{sendJson}from"./middleware/utils/http-helpers";
@@ -0,0 +1,11 @@
1
+ export declare class DispatchDedupe {
2
+ private readonly _entries;
3
+ private readonly _ttlMs;
4
+ constructor(ttlMs?: number);
5
+ private _key;
6
+ mark(userId: string, eventType: string): void;
7
+ wasRecentlyDispatched(userId: string, eventType: string): boolean;
8
+ clear(): void;
9
+ get size(): number;
10
+ private _sweep;
11
+ }
@@ -0,0 +1 @@
1
+ const DEFAULT_TTL_MS=1e4,SWEEP_THRESHOLD=1e3;export class DispatchDedupe{constructor(t=1e4){this.t=new Map,this.i=t}h(t,s){return`${t}|${s}`}mark(t,s){this.t.set(this.h(t,s),Date.now()),this.t.size>1e3&&this.o()}wasRecentlyDispatched(t,s){const e=this.h(t,s),i=this.t.get(e);return!(void 0===i||Date.now()-i>this.i&&(this.t.delete(e),1))}clear(){this.t.clear()}get size(){return this.t.size}o(){const t=Date.now()-this.i;for(const[s,e]of this.t)e<t&&this.t.delete(s)}}
@@ -1,19 +1,19 @@
1
- import type { Request, Response, NextFunction } from 'express';
1
+ import type { UnsharedRequest, UnsharedResponse, UnsharedNextFunction } from '../types';
2
2
  import type { UnsharedLabsClient } from '../client';
3
3
  import { VerdictCache } from './verdict-cache';
4
4
  import type { Verdict } from './verdict-cache';
5
- export interface ProtectionConfig {
5
+ export interface ProtectionConfig<TReq extends UnsharedRequest = UnsharedRequest> {
6
6
  /**
7
7
  * Required. Resolves the current user's ID from the request.
8
8
  * Return undefined for anonymous/logged-out visitors.
9
9
  */
10
- userId: (req: Request) => string | undefined;
10
+ userId: (req: TReq) => string | undefined;
11
11
  /**
12
12
  * Resolves the current user's email address from the request.
13
13
  * Required in Tier 2 (backend-only). Recommended in Tier 1.
14
14
  * Falls back to HttpOnly cookie → req.body.email when not configured.
15
15
  */
16
- emailAddress?: (req: Request) => string | undefined;
16
+ emailAddress?: (req: TReq) => string | undefined;
17
17
  /** Route prefix for internal routes. @default "/__unshared" */
18
18
  routePrefix?: string;
19
19
  /** Allowed CORS origins for /__unshared/* routes. */
@@ -22,13 +22,15 @@ export interface ProtectionConfig {
22
22
  cacheTTL?: number;
23
23
  /** Paths to skip entirely (static assets, health checks). */
24
24
  skipPaths?: string[];
25
+ /** When set, only paths matching one of these prefixes get events dispatched and checkUser called. */
26
+ includePathPrefix?: string[];
25
27
  /** Resolves a custom session ID. Falls back to __unshared_sid cookie. */
26
- sessionId?: (req: Request) => string | undefined;
28
+ sessionId?: (req: TReq) => string | undefined;
27
29
  /**
28
30
  * Resolves a device ID from the request.
29
- * Falls back to __unshared_fp_id cookie → X-Device-Id header.
31
+ * Falls back to X-Device-Id header → __unshared_fp_id cookie.
30
32
  */
31
- deviceId?: (req: Request) => string | undefined;
33
+ deviceId?: (req: TReq) => string | undefined;
32
34
  /**
33
35
  * Called when a flagged, unverified user makes a request.
34
36
  * You own the response — block, redirect, or call next() to let it through.
@@ -40,11 +42,24 @@ export interface ProtectionConfig {
40
42
  userId: string;
41
43
  emailAddress: string;
42
44
  verdict: Verdict;
43
- req: Request;
44
- res: Response;
45
- next: NextFunction;
45
+ req: TReq;
46
+ res: UnsharedResponse;
47
+ next: UnsharedNextFunction;
48
+ }) => void;
49
+ /**
50
+ * Called when a background SDK operation fails (fire-and-forget API calls,
51
+ * verdict refreshes, etc.). Use this to pipe errors to your logging or
52
+ * monitoring system for observability.
53
+ *
54
+ * Without this callback, background errors are silently swallowed (fail-open).
55
+ * The middleware never blocks requests due to these errors regardless.
56
+ */
57
+ onError?: (error: unknown, context: {
58
+ operation: 'processUserEvent' | 'submitFingerprintEvent' | 'checkUser' | 'verifyTrigger' | 'verify';
59
+ userId?: string;
60
+ emailAddress?: string;
46
61
  }) => void;
47
62
  }
48
63
  export type { Verdict };
49
64
  export { VerdictCache };
50
- export declare function unsharedBoundToUser(client: UnsharedLabsClient, config: ProtectionConfig): (req: Request, res: Response, next: NextFunction) => void;
65
+ export declare function unsharedBoundToUser<TReq extends UnsharedRequest = UnsharedRequest>(client: UnsharedLabsClient, config: ProtectionConfig<TReq>): (req: TReq, res: UnsharedResponse, next: UnsharedNextFunction) => void;
@@ -1 +1 @@
1
- import{readFileSync}from"fs";import{VerdictCache}from"./verdict-cache";import{RateLimitBackoff}from"./rate-limit-backoff";import{interceptResponse}from"./response-interceptor";import{generateFingerprintScript}from"./injection/fingerprint-script";import{handleSubmitFingerprint}from"./routes/submit-fp";import{handleVerifyTrigger,handleVerify}from"./routes/verify";import{isHtmlContentType}from"./utils/content-type";import{shouldSkipPath}from"./utils/skip-paths";import{isBot}from"./utils/is-bot";import{extractClientIp}from"./utils/client-ip";import{parseCookie}from"./utils/cookies";import{extractDeviceId}from"./utils/device-id";import{isSecureRequest}from"./utils/secure";export{VerdictCache};const CHECK_USER_TIMEOUT_MS=500;export function unsharedBoundToUser(e,r){if(!r.userId)throw new Error("[Unshared] userId resolver is required");if(!r.emailAddress){let e=!1;try{require.resolve("unshared-frontend-sdk"),e=!0}catch{}e||console.warn("[Unshared] Warning: emailAddress resolver is not configured and unshared-frontend-sdk is not installed.\nNo user events will be submitted. Either install unshared-frontend-sdk (Tier 1) or\nprovide emailAddress in your middleware config (Tier 2).")}const{userId:t,emailAddress:i,routePrefix:n="/__unshared",corsOrigins:o,cacheTTL:s=6e4,skipPaths:c,sessionId:d,deviceId:a,onFlagged:u}=r,l=new VerdictCache(s),f=new RateLimitBackoff,p=Date.now().toString(36),m=generateFingerprintScript(n,p);let h="";try{const e=require.resolve("unshared-frontend-sdk/dist/index.umd.js");h=readFileSync(e,"utf8")}catch{}const v=handleSubmitFingerprint({client:e,verdictCache:l,rateLimitBackoff:f,resolveUserId:t,resolveEmailAddress:i,resolveSessionId:d,resolveDeviceId:a}),C=handleVerifyTrigger({client:e,verdictCache:l,resolveEmailAddress:i,resolveDeviceId:a}),I=handleVerify({client:e,verdictCache:l,resolveEmailAddress:i,resolveDeviceId:a}),S=o?Array.isArray(o)?o:[o]:null,g=`${n}/fp.js`,k=`${n}/submit-fp`,y=`${n}/verify-trigger`,_=`${n}/verify`,A=`${n}/status`;return function(r,o,s){const p=r.path;if(p.startsWith(n+"/")){if(function(e,r){if(!S)return;const t=e.headers.origin??"",i=S.includes("*");(i||S.includes(t))&&(r.setHeader("Access-Control-Allow-Origin",i?"*":t),r.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, X-Idempotency-Key, X-Session-Id, X-Device-Id"),r.setHeader("Access-Control-Allow-Credentials","true"))}(r,o),"OPTIONS"===r.method)return void o.status(204).end();if("GET"===r.method&&p===g)return o.setHeader("Content-Type","application/javascript"),o.setHeader("Cache-Control","public, max-age=3600"),void o.status(200).end(h);if("POST"===r.method&&p===k)return void v(r,o);if("POST"===r.method&&p===y)return void C(r,o);if("POST"===r.method&&p===_)return void I(r,o);if("GET"===r.method&&p===A){let e;try{e=t(r)}catch{}if(!e)return void o.status(200).json({status:"anonymous"});const n=resolveEmail(r,i),s=l.get(e);return void(s&&s.isFlagged&&!s.isVerified&&u&&n?o.status(403).json({error:"account_flagged",email:n}):o.status(200).json({status:"ok"}))}return void o.status(404).json({success:!1,error:{code:"NOT_FOUND",message:"Unknown route"}})}if(shouldSkipPath(p,c))return void s();let T;try{T=t(r)}catch{}if(!T)return clearUserIdCookieIfPresent(r,o),clearEmailCookieIfPresent(r,o),interceptForInjection(r,o,m),void s();const x=resolveEmail(r,i);if(setUserIdCookie(r,o,T),x&&setEmailCookie(r,o,x),!x)return interceptForInjection(r,o,m),void s();const P=extractSessionId(r,d),E=extractDeviceId(r,a),F=extractFingerprintId(r),w=r.headers["user-agent"]??"",U=extractClientIp(r);if(isBot(w))return void s();if("unknown"===P)return interceptForInjection(r,o,m),void s();f.isPaused()||dispatchUserEvent(e,l,f,{userId:T,emailAddress:x,sessionId:P,deviceId:E,fingerprintId:F,userAgent:w,ipAddress:U,eventType:`${r.method} ${r.path}`});const O=l.get(T);O?(l.isStale(T)&&!l.isRefreshing(T)&&(l.markRefreshing(T),fetchAndCacheVerdict(e,l,T,x,E,F,P).finally(()=>l.clearRefreshing(T))),applyVerdict(O,T,x,r,o,s,m,u)):fetchAndCacheVerdict(e,l,T,x,E,F,P).then(e=>{applyVerdict(e,T,x,r,o,s,m,u)}).catch(()=>{interceptForInjection(r,o,m),s()})}}function resolveEmail(e,r){if(r)try{const t=r(e);if(t)return t}catch{}const t=parseCookie(e,"__unshared_email");if(t)return t;const i=e.body?.email;return"string"==typeof i&&i?i:void 0}function applyVerdict(e,r,t,i,n,o,s,c){if(interceptForInjection(i,n,s),e.isFlagged&&!e.isVerified&&c)try{c({userId:r,emailAddress:t,verdict:e,req:i,res:n,next:o})}catch{o()}else o()}function interceptForInjection(e,r,t){delete e.headers["if-none-match"],delete e.headers["if-modified-since"],interceptResponse(r,(e,r)=>{if(!isHtmlContentType(r))return null;const i=e.toString("utf8"),n=i.lastIndexOf("</body>");return-1===n?i+t:i.slice(0,n)+t+i.slice(n)},{preventCaching:!0})}function dispatchUserEvent(e,r,t,i){e.processUserEvent({eventType:i.eventType,userId:i.userId,emailAddress:i.emailAddress,ipAddress:i.ipAddress,deviceId:i.deviceId,fingerprintId:i.fingerprintId,sessionHash:i.sessionId,userAgent:i.userAgent}).then(e=>{e.success&&e.data?.analysis&&r.update(i.userId,{isFlagged:e.data.analysis.is_user_flagged}),!e.success&&e.error?.retryAfter&&t.pause(1e3*e.error.retryAfter)}).catch(()=>{})}async function fetchAndCacheVerdict(e,r,t,i,n,o,s){const c={};let d;n&&"unknown"!==n&&(c.deviceId=n),o&&(c.fingerprintId=o);const a=await Promise.race([e.checkUser(i,c),new Promise(e=>{d=setTimeout(()=>e(null),500)})]);if(clearTimeout(d),!a)return{isFlagged:!1,isVerified:!1,emailAddress:i,sessionId:s,cachedAt:0,ttl:0};const u=a.data?.is_user_flagged??!1;return r.set(t,{isFlagged:u,isVerified:!1,emailAddress:i,sessionId:s}),r.get(t)}function extractSessionId(e,r){if(r)try{const t=r(e);if(t)return t}catch{}return parseCookie(e,"__unshared_sid")??"unknown"}function extractFingerprintId(e){return parseCookie(e,"__unshared_fingerprint_id")||void 0}function appendSetCookie(e,r){const t=e.getHeader("Set-Cookie");if(t){const i=Array.isArray(t)?[...t]:[String(t)];i.push(r),e.setHeader("Set-Cookie",i)}else e.setHeader("Set-Cookie",r)}function setUserIdCookie(e,r,t){const i=isSecureRequest(e)?"; Secure":"";appendSetCookie(r,`__unshared_uid=${encodeURIComponent(t)}; Path=/; SameSite=Lax${i}`)}function setEmailCookie(e,r,t){const i=isSecureRequest(e)?"; Secure":"";appendSetCookie(r,`__unshared_email=${encodeURIComponent(t)}; HttpOnly; Path=/; SameSite=Lax${i}`)}function clearUserIdCookieIfPresent(e,r){parseCookie(e,"__unshared_uid")&&appendSetCookie(r,"__unshared_uid=; Path=/; SameSite=Lax; Max-Age=0"+(isSecureRequest(e)?"; Secure":""))}function clearEmailCookieIfPresent(e,r){parseCookie(e,"__unshared_email")&&appendSetCookie(r,"__unshared_email=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0"+(isSecureRequest(e)?"; Secure":""))}
1
+ import{readFileSync}from"fs";import{VerdictCache}from"./verdict-cache";import{RateLimitBackoff}from"./rate-limit-backoff";import{DispatchDedupe}from"./dispatch-dedupe";import{interceptResponse}from"./response-interceptor";import{generateFingerprintScript}from"./injection/fingerprint-script";import{handleSubmitFingerprint}from"./routes/submit-fp";import{handleVerifyTrigger,handleVerify}from"./routes/verify";import{sendJson,sendEmpty,sendBody,getRequestPath}from"./utils/http-helpers";import{isHtmlContentType}from"./utils/content-type";import{shouldSkipPath}from"./utils/skip-paths";import{shouldIncludePath}from"./utils/include-path";import{isBot}from"./utils/is-bot";import{extractClientIp}from"./utils/client-ip";import{parseCookie}from"./utils/cookies";import{extractDeviceIdOrUndefined}from"./utils/device-id";import{isSecureRequest}from"./utils/secure";import{isSentinelUserId,SENTINEL_STICKINESS_TTL_MS}from"./utils/sentinel-user-id";export{VerdictCache};const CHECK_USER_TIMEOUT_MS=500;export function unsharedBoundToUser(e,t){if(!t.userId)throw new Error("[Unshared] userId resolver is required");if(!t.emailAddress){let e=!1;try{require.resolve("unshared-frontend-sdk"),e=!0}catch{}e||console.warn("[Unshared] Warning: emailAddress resolver is not configured and unshared-frontend-sdk is not installed.\nNo user events will be submitted. Either install unshared-frontend-sdk (Tier 1) or\nprovide emailAddress in your middleware config (Tier 2).")}const{userId:r,emailAddress:i,routePrefix:n="/__unshared",corsOrigins:o,cacheTTL:s=6e4,skipPaths:d,includePathPrefix:c,sessionId:a,deviceId:u,onFlagged:l,onError:p}=t,f=new VerdictCache(s),m=new RateLimitBackoff,h=new DispatchDedupe,I=Date.now().toString(36),v=generateFingerprintScript(n,I);let S="";try{const e=require.resolve("unshared-frontend-sdk/dist/index.umd.js");S=readFileSync(e,"utf8")}catch{}const C=handleSubmitFingerprint({client:e,verdictCache:f,rateLimitBackoff:m,dispatchDedupe:h,resolveUserId:r,resolveEmailAddress:i,resolveSessionId:a,resolveDeviceId:u,onError:p}),g=handleVerifyTrigger({client:e,verdictCache:f,resolveEmailAddress:i,resolveDeviceId:u,onError:p}),y=handleVerify({client:e,verdictCache:f,resolveEmailAddress:i,resolveDeviceId:u,onError:p}),_=o?Array.isArray(o)?o:[o]:null,k=`${n}/fp.js`,A=`${n}/submit-fp`,T=`${n}/verify-trigger`,E=`${n}/verify`,x=`${n}/status`;return function(t,o,s){const I=getRequestPath(t.url),F=t.url||I;if(I.startsWith(n+"/")){if(function(e,t){if(!_)return;const r=e.headers.origin??"",i=_.includes("*");(i||_.includes(r))&&(t.setHeader("Access-Control-Allow-Origin",i?"*":r),t.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, X-Idempotency-Key, X-Session-Id, X-Device-Id"),t.setHeader("Access-Control-Allow-Credentials","true"))}(t,o),"OPTIONS"===t.method)return void sendEmpty(o,204);if("GET"===t.method&&I===k)return o.setHeader("Content-Type","application/javascript"),o.setHeader("Cache-Control","public, max-age=3600"),void sendBody(o,200,S);if("POST"===t.method&&(I===A||I===T||I===E))return void 0===t.body?void sendJson(o,400,{success:!1,error:{code:"BODY_PARSER_MISSING",message:"req.body is undefined. Mount a JSON body-parsing middleware (e.g., express.json()) before the Unshared middleware."}}):I===A?void C(t,o):I===T?void g(t,o):void y(t,o);if("GET"===t.method&&I===x){let n;try{n=r(t)}catch{}if(!n)return void sendJson(o,200,{status:"anonymous"});const s=resolveEmail(t,i);return void(async()=>{let r=f.get(n);if((!r||f.isStale(n))&&s&&!m.isPaused()&&!f.isRefreshing(n)){f.markRefreshing(n);try{const i=extractDeviceIdOrUndefined(t,u),o=extractFingerprintId(t),d=extractSessionId(t,a),c=i??o??"unknown";await fetchAndCacheVerdict(e,f,n,s,c,o,d),r=f.get(n)}catch(e){p&&p(e,{operation:"checkUser",userId:n,emailAddress:s})}finally{f.clearRefreshing(n)}}r&&r.isFlagged&&!r.isVerified&&l&&s?sendJson(o,200,{status:"flagged",email:s}):sendJson(o,200,{status:"ok"})})()}return void sendJson(o,404,{success:!1,error:{code:"NOT_FOUND",message:"Unknown route"}})}if(shouldSkipPath(I,d))return void s();if(!shouldIncludePath(I,c))return interceptForInjection(t,o,v),void s();let U;try{U=r(t)}catch{}if(isSentinelUserId(U)){const e=parseCookie(t,"__unshared_uid"),r=parseCookie(t,"__unshared_uid_at"),i=r?Number(r):NaN,n=Number.isFinite(i)&&Date.now()-i<=SENTINEL_STICKINESS_TTL_MS;U=e&&n?e:void 0}if(!U)return interceptForInjection(t,o,v),void s();const w=resolveEmail(t,i);if(setUserIdCookie(t,o,U),w&&setEmailCookie(t,o,w),!w)return interceptForInjection(t,o,v),void s();const P=extractSessionId(t,a),D=extractDeviceIdOrUndefined(t,u),N=extractFingerprintId(t),O=t.headers["user-agent"]??"",V=extractClientIp(t);if(isBot(O))return void s();if("unknown"===P)return interceptForInjection(t,o,v),void s();const b=D??N;if(!b)return interceptForInjection(t,o,v),void s();m.isPaused()||dispatchUserEvent(e,f,m,h,{userId:U,emailAddress:w,sessionId:P,deviceId:b,fingerprintId:N,userAgent:O,ipAddress:V,eventType:F},p);const R=f.get(U);R?(f.isStale(U)&&!f.isRefreshing(U)&&(f.markRefreshing(U),fetchAndCacheVerdict(e,f,U,w,b,N,P).finally(()=>f.clearRefreshing(U))),applyVerdict(R,U,w,t,o,s,v,l)):fetchAndCacheVerdict(e,f,U,w,b,N,P).then(e=>{applyVerdict(e,U,w,t,o,s,v,l)}).catch(()=>{interceptForInjection(t,o,v),s()})}}function resolveEmail(e,t){if(t)try{const r=t(e);if(r)return r}catch{}const r=parseCookie(e,"__unshared_email");if(r)return r;const i=e.body?.email;return"string"==typeof i&&i?i:void 0}function applyVerdict(e,t,r,i,n,o,s,d){if(interceptForInjection(i,n,s),e.isFlagged&&!e.isVerified&&d)try{d({userId:t,emailAddress:r,verdict:e,req:i,res:n,next:o})}catch{o()}else o()}function interceptForInjection(e,t,r){delete e.headers["if-none-match"],delete e.headers["if-modified-since"],interceptResponse(t,(e,t)=>{if(!isHtmlContentType(t))return null;const i=e.toString("utf8"),n=i.lastIndexOf("</body>");return-1===n?i+r:i.slice(0,n)+r+i.slice(n)},{preventCaching:!0})}function dispatchUserEvent(e,t,r,i,n,o){i.mark(n.userId,n.eventType),e.processUserEvent({eventType:n.eventType,userId:n.userId,emailAddress:n.emailAddress,ipAddress:n.ipAddress,deviceId:n.deviceId,fingerprintId:n.fingerprintId,sessionHash:n.sessionId,userAgent:n.userAgent}).then(e=>{e.success&&e.data?.analysis&&t.update(n.userId,{isFlagged:e.data.analysis.is_user_flagged}),!e.success&&e.error?.retryAfter&&r.pause(1e3*e.error.retryAfter)}).catch(e=>{o&&o(e,{operation:"processUserEvent",userId:n.userId,emailAddress:n.emailAddress})})}async function fetchAndCacheVerdict(e,t,r,i,n,o,s){const d={};let c;n&&"unknown"!==n&&(d.deviceId=n),o&&(d.fingerprintId=o);const a=await Promise.race([e.checkUser(i,d),new Promise(e=>{c=setTimeout(()=>e(null),500)})]);if(clearTimeout(c),!a)return{isFlagged:!1,isVerified:!1,emailAddress:i,sessionId:s,cachedAt:0,ttl:0};const u=a.data?.is_user_flagged??!1;return t.set(r,{isFlagged:u,isVerified:!1,emailAddress:i,sessionId:s}),t.get(r)}function extractSessionId(e,t){if(t)try{const r=t(e);if(r)return r}catch{}return parseCookie(e,"__unshared_sid")??"unknown"}function extractFingerprintId(e){return parseCookie(e,"__unshared_fingerprint_id")||void 0}function appendSetCookie(e,t){const r=e.getHeader("Set-Cookie");if(r){const i=Array.isArray(r)?[...r]:[String(r)];i.push(t),e.setHeader("Set-Cookie",i)}else e.setHeader("Set-Cookie",t)}function setUserIdCookie(e,t,r){const i=isSecureRequest(e)?"; Secure":"";appendSetCookie(t,`__unshared_uid=${encodeURIComponent(r)}; Path=/; SameSite=Lax${i}`),appendSetCookie(t,`__unshared_uid_at=${Date.now()}; Path=/; SameSite=Lax${i}`)}function setEmailCookie(e,t,r){const i=isSecureRequest(e)?"; Secure":"";appendSetCookie(t,`__unshared_email=${encodeURIComponent(r)}; HttpOnly; Path=/; SameSite=Lax${i}`)}
@@ -1 +1 @@
1
- export function generateFingerprintScript(e,n){const t=n?`?v=${escapeJavaScript(n)}`:"";return`<script>\n(function(){\ntry{\nvar pfx="${escapeJavaScript(e)}";\nvar SS_FP="__unshared_fp";\n\n// --- Helpers ---\nfunction gC(n){var m=document.cookie.match(new RegExp("(?:^|; )"+n+"=([^;]*)"));return m?decodeURIComponent(m[1]):null}\nfunction sC(n,v,d){var e="";if(d){var dt=new Date();dt.setTime(dt.getTime()+d*864e5);e="; expires="+dt.toUTCString()}document.cookie=n+"="+encodeURIComponent(v)+e+"; path=/; SameSite=Lax"}\nfunction uuid(){return(typeof crypto!=="undefined"&&crypto.randomUUID)?crypto.randomUUID():("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;return(c==="x"?r:r&0x3|0x8).toString(16)}))}\n\n// --- Session + device IDs ---\nvar sid=gC("__unshared_sid");\nif(!sid){sid=uuid();sC("__unshared_sid",sid,365)}\nvar did="";\ntry{did=localStorage.getItem("__unshared_device_id")||"";if(!did){did=uuid();localStorage.setItem("__unshared_device_id",did)}}catch(e){did=did||uuid()}\nsC("__unshared_fp_id",did,365);\n\n// --- Fingerprint cache (sessionStorage) ---\nfunction getFP(){try{var r=sessionStorage.getItem(SS_FP);return r?JSON.parse(r):null}catch(e){return null}}\nfunction setFP(fp){try{sessionStorage.setItem(SS_FP,JSON.stringify(fp))}catch(e){}}\n\n// --- Submit fingerprint to backend ---\nfunction submitFP(fp,evType){\n var uid=gC("__unshared_uid");\n if(!uid)return;\n var body={hash:fp.full_hash,stable_hash:fp.fingerprint_id,collected_at:fp.timestamp,is_incognito:fp.isIncognito,components:fp.components,version:fp.version,session_id:sid,user_id:uid,event_type:evType||"page_load"};\n var xhr=new XMLHttpRequest();\n xhr.open("POST",pfx+"/submit-fp",true);\n xhr.setRequestHeader("Content-Type","application/json");\n xhr.setRequestHeader("X-Session-Id",sid);\n xhr.setRequestHeader("X-Device-Id",did);\n xhr.send(JSON.stringify(body));\n}\n\n// --- Collect fingerprint (loads fp.js if needed) then submit ---\nvar fpReady=false;\nfunction collectAndSubmit(evType){\n var uid=gC("__unshared_uid");\n if(!uid)return;\n var cached=getFP();\n if(cached){submitFP(cached,evType);return}\n if(!fpReady)return;\n try{\n var c=new UnsharedLabsBrowser.UnsharedLabsBrowser({baseUrl:""});\n c.collect({exclude:["timing","navigatorConnection","speech"]}).then(function(fp){setFP(fp);submitFP(fp,evType)});\n }catch(e){}\n}\n\n// --- Load fp.js (always — browser caches it for 1h) ---\n// Submit cached FP immediately if available; load fp.js for fresh collection\nvar pageLoadSubmitted=false;\nif(getFP()&&gC("__unshared_uid")){submitFP(getFP(),"page_load");pageLoadSubmitted=true;deferredCheck()}\nvar s=document.createElement("script");\ns.src=pfx+"/fp.js${t}";\ns.onload=function(){fpReady=true;if(!pageLoadSubmitted){collectAndSubmit("page_load");deferredCheck()}};\ndocument.head.appendChild(s);\n\n// --- Deferred verdict check ---\n// After fingerprint submission, the backend processes the event async.\n// If the user was just flagged, the initial page load may have beaten\n// the verdict update. Re-check after a delay so newly flagged sessions\n// get caught without waiting for user interaction.\n// Uses the patched fetch so the 403 interceptor picks up the response.\nfunction deferredCheck(){\n var uid=gC("__unshared_uid");\n if(!uid)return;\n setTimeout(function(){\n try{fetch(pfx+"/status",{method:"GET",credentials:"same-origin"}).catch(function(){})}catch(e){}\n },5000);\n}\n\n// --- SPA route change tracking (History API + popstate) ---\nvar oPush=history.pushState,oReplace=history.replaceState;\nhistory.pushState=function(){oPush.apply(this,arguments);try{collectAndSubmit("route_change")}catch(e){}};\nhistory.replaceState=function(){oReplace.apply(this,arguments);try{collectAndSubmit("route_change")}catch(e){}};\nwindow.addEventListener("popstate",function(){try{collectAndSubmit("route_change")}catch(e){}});\n\n// --- 403 interception: dispatch "unshared:flagged" event ---\nfunction emitFlagged(body){\n try{window.dispatchEvent(new CustomEvent("unshared:flagged",{detail:{email:body.email||""}}))}catch(e){}\n}\n\n// Patch fetch\nvar oFetch=window.fetch;\nif(oFetch){window.fetch=function(){return oFetch.apply(this,arguments).then(function(r){if(r.status===403){try{var cl=r.clone();cl.json().then(function(b){if(b&&b.error==="account_flagged")emitFlagged(b)}).catch(function(){})}catch(e){}}return r})}}\n\n// Patch XMLHttpRequest\nvar oXSend=XMLHttpRequest.prototype.send;\nXMLHttpRequest.prototype.send=function(){var x=this;x.addEventListener("load",function(){if(x.status===403){try{var b=JSON.parse(x.responseText);if(b&&b.error==="account_flagged")emitFlagged(b)}catch(e){}}});return oXSend.apply(this,arguments)};\n\n}catch(e){}\n})();\n<\/script>`}function escapeJavaScript(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'")}
1
+ export function generateFingerprintScript(e,t){const n=t?`?v=${escapeJavaScript(t)}`:"";return`<script>\n(function(){\ntry{\n// --- Bot drop (defense-in-depth) ---\n// Must be the first statement: we do not want to write cookies, localStorage,\n// session IDs, or any network requests for known-bot traffic. Mirrors the\n// regex in unshared-fingerprint-lib/src/detect/bot.ts and Node middleware\n// utils/is-bot.ts. Keep all three in sync.\nvar BOT_RE=/googlebot|bingbot|slurp|baiduspider|duckduckbot|yandex|sogou|exabot|ia_archiver|curl|wget|python-requests|python-urllib|axios|node-fetch|go-http-client|java\\/|libwww-perl|okhttp|apache-httpclient|http_request|httpie|headlesschrome|phantomjs|puppeteer|playwright|cypress|selenium|webdriver|electron|jsdom|vercel-screenshot|screenshot|prerender|lighthouse|chrome-lighthouse|pagespeed|gtmetrix|pingdom|nessus|nikto|sqlmap|burp|zap|qualys|openvas|nmap|masscan|facebookexternalhit|twitterbot|linkedinbot|whatsapp|telegrambot|slackbot|discordbot|bot|crawl|spider|scrape|fetch|scan/i;\nif(typeof navigator!=="undefined"&&navigator.userAgent&&BOT_RE.test(navigator.userAgent))return;\n\nvar pfx="${escapeJavaScript(e)}";\nvar SS_FP="__unshared_fp";\nvar SS_LAST_SUBMIT="__unshared_last_submit";\n\n// Dedup state: skip submit if (user_id + URL) matches last submission.\n// Modern SPAs (Next.js App Router, React Router, etc.) call replaceState\n// 3-5 times during hydration with the same URL — without this guard,\n// each call generates a redundant FP row with identical stable_hash.\n// Persisted to sessionStorage so hard reloads and framework double-boots\n// inside the same tab still dedupe (the in-memory value resets on reload).\nvar lastSubmitKey="";\ntry{lastSubmitKey=sessionStorage.getItem(SS_LAST_SUBMIT)||""}catch(e){}\n\n// --- Helpers ---\nfunction gC(n){var m=document.cookie.match(new RegExp("(?:^|; )"+n+"=([^;]*)"));return m?decodeURIComponent(m[1]):null}\nfunction sC(n,v,d){var e="";if(d){var dt=new Date();dt.setTime(dt.getTime()+d*864e5);e="; expires="+dt.toUTCString()}document.cookie=n+"="+encodeURIComponent(v)+e+"; path=/; SameSite=Lax"}\nfunction uuid(){return(typeof crypto!=="undefined"&&crypto.randomUUID)?crypto.randomUUID():("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;return(c==="x"?r:r&0x3|0x8).toString(16)}))}\n// Sentinel user IDs that must never be treated as real users. Mirrors\n// the Set in sentinel-user-id.ts — keep in sync. Empty string is handled\n// by the separate !uid checks below.\nvar SENTINEL_UIDS={"__pre_auth__":1,"anonymous":1,"guest":1,"undefined":1,"null":1};\nfunction isSentinelUid(v){return typeof v==="string"&&SENTINEL_UIDS.hasOwnProperty(v)}\n\n// --- Session + device IDs ---\n// Session ID is a UUID because it's supposed to be tab-scoped and random.\n// Device ID is intentionally NOT a UUID — Issue 9: random UUIDs wrote\n// meaningless device_ids to every fingerprint row. Instead we read the\n// stable fingerprint hash from localStorage if a previous submission\n// already persisted it; otherwise we leave did empty and let submitFP()\n// reconcile on the first successful collection. The Node middleware's\n// Issue 8 bootstrap-skip branch handles the empty-device_id window so we\n// never dispatch with a random or "unknown" value.\nvar sid=gC("__unshared_sid");\nif(!sid){sid=uuid();sC("__unshared_sid",sid,365)}\nvar did="";\ntry{did=localStorage.getItem("__unshared_device_id")||""}catch(e){}\nif(did){sC("__unshared_fp_id",did,365)}\n\n// --- Fingerprint cache (sessionStorage) ---\nfunction getFP(){try{var r=sessionStorage.getItem(SS_FP);return r?JSON.parse(r):null}catch(e){return null}}\nfunction setFP(fp){try{sessionStorage.setItem(SS_FP,JSON.stringify(fp))}catch(e){}}\n\n// --- Submit fingerprint to backend ---\nfunction submitFP(fp){\n var uid=gC("__unshared_uid");\n if(!uid||isSentinelUid(uid))return;\n // Issue 9: reconcile device_id to the stable fingerprint hash. This runs\n // before we send the X-Device-Id header so the very first submission\n // already carries the real value. Persist to localStorage so other tabs\n // (and future reloads) pick up the same stable ID without needing to\n // re-collect the fingerprint.\n if(fp.fingerprint_id){\n did=fp.fingerprint_id;\n try{localStorage.setItem("__unshared_device_id",did)}catch(e){}\n sC("__unshared_fp_id",did,365);\n }\n // event_type is the SPA route, not a fixed enum. Page-level event names\n // (page_load/route_change) collapsed every row into one of two buckets;\n // the URL is more useful for analytics and matches the frontend SDK.\n var route=(location.pathname||"/")+(location.search||"");\n var key=uid+"|"+route;\n if(key===lastSubmitKey)return;\n lastSubmitKey=key;\n try{sessionStorage.setItem(SS_LAST_SUBMIT,key)}catch(e){}\n // collected_at is stamped fresh at submit time rather than carried from fp.timestamp,\n // because fp is cached per-tab in sessionStorage — reusing its original timestamp would\n // freeze collected_at at first load and drift against server created_at as the tab ages.\n // The server authoritatively overwrites this value again on ingress.\n var body={hash:fp.full_hash,stable_hash:fp.fingerprint_id,collected_at:(new Date()).toISOString(),is_incognito:fp.isIncognito,components:fp.components,version:fp.version,session_id:sid,user_id:uid,event_type:route};\n // Deterministic idempotency key: (stable_hash, user_id, event_type) fully\n // identifies one logical submission. A stable key lets the backend's\n // ON CONFLICT (idempotency_key) DO NOTHING actually catch duplicates across\n // reloads, tabs, and concurrent SDK instances — a fresh UUID could not.\n var idem=fp.fingerprint_id+"|"+uid+"|"+route;\n var xhr=new XMLHttpRequest();\n xhr.open("POST",pfx+"/submit-fp",true);\n xhr.setRequestHeader("Content-Type","application/json");\n xhr.setRequestHeader("X-Session-Id",sid);\n if(did)xhr.setRequestHeader("X-Device-Id",did);\n xhr.setRequestHeader("X-Idempotency-Key",idem);\n xhr.send(JSON.stringify(body));\n}\n\n// --- Collect fingerprint (loads fp.js if needed) then submit ---\nvar fpReady=false;\nfunction collectAndSubmit(){\n var uid=gC("__unshared_uid");\n if(!uid||isSentinelUid(uid))return;\n var cached=getFP();\n if(cached){submitFP(cached);return}\n if(!fpReady)return;\n try{\n var c=new UnsharedLabsBrowser.UnsharedLabsBrowser({baseUrl:""});\n c.collect({exclude:["timing","speech"]}).then(function(fp){setFP(fp);submitFP(fp)});\n }catch(e){}\n}\n\n// --- Load fp.js (always — browser caches it for 1h) ---\n// Submit cached FP immediately if available; load fp.js for fresh collection\nvar pageLoadSubmitted=false;\nvar _boot_uid=gC("__unshared_uid");\nif(getFP()&&_boot_uid&&!isSentinelUid(_boot_uid)){submitFP(getFP());pageLoadSubmitted=true;deferredCheck()}\nvar s=document.createElement("script");\ns.src=pfx+"/fp.js${n}";\ns.onload=function(){fpReady=true;if(!pageLoadSubmitted){collectAndSubmit();deferredCheck()}};\ndocument.head.appendChild(s);\n\n// --- Deferred verdict check ---\n// After fingerprint submission, the backend processes the event async.\n// If the user was just flagged, the initial page load may have beaten\n// the verdict update. Re-check after a delay so newly flagged sessions\n// get caught without waiting for user interaction.\n// The endpoint always returns 200 so browsers don't log a scary red\n// network error — we inspect the body and dispatch the flagged event\n// ourselves when status==="flagged".\nfunction deferredCheck(){\n var uid=gC("__unshared_uid");\n if(!uid||isSentinelUid(uid))return;\n setTimeout(function(){\n try{fetch(pfx+"/status",{method:"GET",credentials:"same-origin"}).then(function(r){return r.json()}).then(function(b){if(b&&b.status==="flagged")emitFlagged(b)}).catch(function(){})}catch(e){}\n },500);\n}\n\n// --- SPA route change tracking (History API + popstate) ---\nvar oPush=history.pushState,oReplace=history.replaceState;\nhistory.pushState=function(){oPush.apply(this,arguments);try{collectAndSubmit()}catch(e){}};\nhistory.replaceState=function(){oReplace.apply(this,arguments);try{collectAndSubmit()}catch(e){}};\nwindow.addEventListener("popstate",function(){try{collectAndSubmit()}catch(e){}});\n\n// --- 403 interception: dispatch "unshared:flagged" event ---\nfunction emitFlagged(body){\n try{window.dispatchEvent(new CustomEvent("unshared:flagged",{detail:{email:body.email||""}}))}catch(e){}\n}\n\n// Patch fetch\nvar oFetch=window.fetch;\nif(oFetch){window.fetch=function(){return oFetch.apply(this,arguments).then(function(r){if(r.status===403){try{var cl=r.clone();cl.json().then(function(b){if(b&&b.error==="account_flagged")emitFlagged(b)}).catch(function(){})}catch(e){}}return r})}}\n\n// Patch XMLHttpRequest\nvar oXSend=XMLHttpRequest.prototype.send;\nXMLHttpRequest.prototype.send=function(){var x=this;x.addEventListener("load",function(){if(x.status===403){try{var b=JSON.parse(x.responseText);if(b&&b.error==="account_flagged")emitFlagged(b)}catch(e){}}});return oXSend.apply(this,arguments)};\n\n}catch(e){}\n})();\n<\/script>`}function escapeJavaScript(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'")}
@@ -1,4 +1,4 @@
1
- import type { Response } from 'express';
1
+ import type { UnsharedResponse } from '../types';
2
2
  /**
3
3
  * Intercepts the response body by wrapping res.write() and res.end().
4
4
  *
@@ -10,6 +10,6 @@ import type { Response } from 'express';
10
10
  * callback with the complete body buffer and the Content-Type header.
11
11
  * The transform can return modified content or null to pass through unchanged.
12
12
  */
13
- export declare function interceptResponse(res: Response, transform: (body: Buffer, contentType: string | undefined) => Buffer | string | null, options?: {
13
+ export declare function interceptResponse(res: UnsharedResponse, transform: (body: Buffer, contentType: string | undefined) => Buffer | string | null, options?: {
14
14
  preventCaching?: boolean;
15
15
  }): void;
@@ -1,15 +1,22 @@
1
- import type { Request, Response } from 'express';
1
+ import type { UnsharedRequest, UnsharedResponse } from '../../types';
2
2
  import type { UnsharedLabsClient } from '../../client';
3
3
  import type { VerdictCache } from '../verdict-cache';
4
4
  import type { RateLimitBackoff } from '../rate-limit-backoff';
5
- export interface SubmitFingerprintDependencies {
5
+ import type { DispatchDedupe } from '../dispatch-dedupe';
6
+ export interface SubmitFingerprintDependencies<TReq extends UnsharedRequest = UnsharedRequest> {
6
7
  client: UnsharedLabsClient;
7
8
  verdictCache: VerdictCache;
8
9
  rateLimitBackoff: RateLimitBackoff;
9
- resolveUserId?: (req: Request) => string | undefined;
10
- resolveEmailAddress?: (req: Request) => string | undefined;
11
- resolveSessionId?: (req: Request) => string | undefined;
12
- resolveDeviceId?: (req: Request) => string | undefined;
10
+ dispatchDedupe: DispatchDedupe;
11
+ resolveUserId?: (req: TReq) => string | undefined;
12
+ resolveEmailAddress?: (req: TReq) => string | undefined;
13
+ resolveSessionId?: (req: TReq) => string | undefined;
14
+ resolveDeviceId?: (req: TReq) => string | undefined;
15
+ onError?: (error: unknown, context: {
16
+ operation: 'processUserEvent' | 'submitFingerprintEvent' | 'checkUser' | 'verifyTrigger' | 'verify';
17
+ userId?: string;
18
+ emailAddress?: string;
19
+ }) => void;
13
20
  }
14
21
  /**
15
22
  * Handles POST /__unshared/submit-fp
@@ -21,4 +28,4 @@ export interface SubmitFingerprintDependencies {
21
28
  *
22
29
  * Always returns 200 (fire-and-forget from browser's perspective).
23
30
  */
24
- export declare function handleSubmitFingerprint(dependencies: SubmitFingerprintDependencies): (req: Request, res: Response) => Promise<void>;
31
+ export declare function handleSubmitFingerprint<TReq extends UnsharedRequest = UnsharedRequest>(dependencies: SubmitFingerprintDependencies<TReq>): (req: TReq, res: UnsharedResponse) => Promise<void>;
@@ -1 +1 @@
1
- import{isBot}from"../utils/is-bot";import{extractClientIp}from"../utils/client-ip";import{parseCookie}from"../utils/cookies";import{extractDeviceId}from"../utils/device-id";import{isSecureRequest}from"../utils/secure";export function handleSubmitFingerprint(e){return async(i,t)=>{try{const s=i.body??{},o={full_hash:s.hash??"",fingerprint_id:s.stable_hash??"",timestamp:s.collected_at??(new Date).toISOString(),isIncognito:s.is_incognito??!1,components:s.components??{},version:s.version??"inline-1.0.0"};let r,n,c;try{r=e.resolveUserId?e.resolveUserId(i):void 0}catch{}r=r??s.user_id??void 0;try{n=e.resolveEmailAddress?e.resolveEmailAddress(i):void 0}catch{}n=n??parseCookie(i,"__unshared_email")??s.email??void 0;try{c=e.resolveSessionId?e.resolveSessionId(i):void 0}catch{}c=c??s.session_id??parseCookie(i,"__unshared_sid");const a=extractClientIp(i),d=i.headers["user-agent"]??"";if(isBot(d))return void t.status(200).json({success:!0});const u=extractDeviceId(i,e.resolveDeviceId),p=o.fingerprint_id||void 0,l=isSecureRequest(i)?"; Secure":"",_=[];if(p&&!parseCookie(i,"__unshared_fingerprint_id")&&_.push(`__unshared_fingerprint_id=${encodeURIComponent(p)}; HttpOnly; Path=/; SameSite=Lax${l}`),n&&!parseCookie(i,"__unshared_email")&&_.push(`__unshared_email=${encodeURIComponent(n)}; HttpOnly; Path=/; SameSite=Lax${l}`),_.length>0){const e=t.getHeader("Set-Cookie");if(e){const i=Array.isArray(e)?[...e]:[String(e)];i.push(..._),t.setHeader("Set-Cookie",i)}else t.setHeader("Set-Cookie",_)}r&&e.client.submitFingerprintEvent(o,{userId:r,emailAddress:n,sessionHash:c,eventType:"auto_collect",ipAddress:a,userAgent:d}).catch(()=>{}),r&&n&&!e.rateLimitBackoff.isPaused()&&e.client.processUserEvent({eventType:"auto_collect",userId:r,emailAddress:n,ipAddress:a,deviceId:u,fingerprintId:p,sessionHash:c??"unknown",userAgent:d}).then(i=>{i.success&&i.data?.analysis&&e.verdictCache.update(r,{isFlagged:i.data.analysis.is_user_flagged}),!i.success&&i.error?.retryAfter&&e.rateLimitBackoff.pause(1e3*i.error.retryAfter)}).catch(()=>{}),t.status(200).json({success:!0})}catch{t.status(200).json({success:!0})}}}
1
+ import{isBot}from"../utils/is-bot";import{extractClientIp}from"../utils/client-ip";import{parseCookie}from"../utils/cookies";import{extractDeviceId}from"../utils/device-id";import{isSecureRequest}from"../utils/secure";import{isSentinelUserId}from"../utils/sentinel-user-id";import{sendJson}from"../utils/http-helpers";export function handleSubmitFingerprint(e){return async(i,s)=>{try{const t=i.body??{},n={full_hash:t.hash??"",fingerprint_id:t.stable_hash??"",timestamp:t.collected_at??(new Date).toISOString(),isIncognito:t.is_incognito??!1,components:t.components??{},version:t.version??"inline-1.0.0"};let o,r,d;try{const s=e.resolveUserId?e.resolveUserId(i):void 0;s&&!isSentinelUserId(s)&&(o=s)}catch{}if(!o){const e="string"==typeof t.user_id?t.user_id:void 0;e&&!isSentinelUserId(e)&&(o=e)}if(!o){const e=parseCookie(i,"__unshared_uid");e&&!isSentinelUserId(e)&&(o=e)}try{r=e.resolveEmailAddress?e.resolveEmailAddress(i):void 0}catch{}r=r??parseCookie(i,"__unshared_email")??t.email??void 0;try{d=e.resolveSessionId?e.resolveSessionId(i):void 0}catch{}d=d??t.session_id??parseCookie(i,"__unshared_sid");const a=extractClientIp(i),c=i.headers["user-agent"]??"";if(isBot(c))return void sendJson(s,200,{success:!0});const p=(n.fingerprint_id&&n.fingerprint_id.length>0?n.fingerprint_id:void 0)??extractDeviceId(i,e.resolveDeviceId),u=n.fingerprint_id||void 0,l=isSecureRequest(i)?"; Secure":"",m=[];if(u&&!parseCookie(i,"__unshared_fingerprint_id")&&m.push(`__unshared_fingerprint_id=${encodeURIComponent(u)}; HttpOnly; Path=/; SameSite=Lax${l}`),u){const e=parseCookie(i,"__unshared_fp_id");e&&e===u||m.push(`__unshared_fp_id=${encodeURIComponent(u)}; Path=/; SameSite=Lax; Max-Age=31536000${l}`)}if(r&&!parseCookie(i,"__unshared_email")&&m.push(`__unshared_email=${encodeURIComponent(r)}; HttpOnly; Path=/; SameSite=Lax${l}`),m.length>0){const e=s.getHeader("Set-Cookie");if(e){const i=Array.isArray(e)?[...e]:[String(e)];i.push(...m),s.setHeader("Set-Cookie",i)}else s.setHeader("Set-Cookie",m)}let _;if("string"==typeof t.event_type&&t.event_type)_=t.event_type;else{const e=i.headers.referer??i.headers.referrer;let s="unknown";if("string"==typeof e&&e.length>0)try{const i=new URL(e);s=(i.pathname||"/")+(i.search||"")}catch{}_=s}const f=i.headers["x-idempotency-key"],h=("string"==typeof f&&f.length>0?f:void 0)??(u&&o?`${u}|${o}|${_}`:void 0);if(o&&e.client.submitFingerprintEvent(n,{userId:o,emailAddress:r,sessionHash:d,eventType:_,ipAddress:a,userAgent:c,idempotencyKey:h}).catch(i=>{e.onError&&e.onError(i,{operation:"submitFingerprintEvent",userId:o,emailAddress:r})}),o&&r&&!e.rateLimitBackoff.isPaused()&&!e.dispatchDedupe.wasRecentlyDispatched(o,_)){e.dispatchDedupe.mark(o,_);try{const i=await e.client.processUserEvent({eventType:_,userId:o,emailAddress:r,ipAddress:a,deviceId:p,fingerprintId:u,sessionHash:d??"unknown",userAgent:c});i.success&&i.data?.analysis&&e.verdictCache.update(o,{isFlagged:i.data.analysis.is_user_flagged}),!i.success&&i.error?.retryAfter&&e.rateLimitBackoff.pause(1e3*i.error.retryAfter)}catch(i){e.onError&&e.onError(i,{operation:"processUserEvent",userId:o,emailAddress:r})}}sendJson(s,200,{success:!0})}catch{sendJson(s,200,{success:!0})}}}
@@ -1,11 +1,16 @@
1
- import type { Request, Response } from 'express';
1
+ import type { UnsharedRequest, UnsharedResponse } from '../../types';
2
2
  import type { UnsharedLabsClient } from '../../client';
3
3
  import type { VerdictCache } from '../verdict-cache';
4
- export interface VerificationDependencies {
4
+ export interface VerificationDependencies<TReq extends UnsharedRequest = UnsharedRequest> {
5
5
  client: UnsharedLabsClient;
6
6
  verdictCache: VerdictCache;
7
- resolveEmailAddress?: (req: Request) => string | undefined;
8
- resolveDeviceId?: (req: Request) => string | undefined;
7
+ resolveEmailAddress?: (req: TReq) => string | undefined;
8
+ resolveDeviceId?: (req: TReq) => string | undefined;
9
+ onError?: (error: unknown, context: {
10
+ operation: 'processUserEvent' | 'submitFingerprintEvent' | 'checkUser' | 'verifyTrigger' | 'verify';
11
+ userId?: string;
12
+ emailAddress?: string;
13
+ }) => void;
9
14
  }
10
15
  /**
11
16
  * POST /__unshared/verify-trigger
@@ -15,7 +20,7 @@ export interface VerificationDependencies {
15
20
  *
16
21
  * The deviceId is resolved via extractDeviceId (same as the middleware).
17
22
  */
18
- export declare function handleVerifyTrigger(dependencies: VerificationDependencies): (req: Request, res: Response) => Promise<void>;
23
+ export declare function handleVerifyTrigger<TReq extends UnsharedRequest = UnsharedRequest>(dependencies: VerificationDependencies<TReq>): (req: TReq, res: UnsharedResponse) => Promise<void>;
19
24
  /**
20
25
  * POST /__unshared/verify
21
26
  * Validates OTP code. Called by the blocker overlay UI.
@@ -25,4 +30,4 @@ export declare function handleVerifyTrigger(dependencies: VerificationDependenci
25
30
  * On successful verification, updates the verdict cache to mark
26
31
  * the user as verified so subsequent requests pass through.
27
32
  */
28
- export declare function handleVerify(dependencies: VerificationDependencies): (req: Request, res: Response) => Promise<void>;
33
+ export declare function handleVerify<TReq extends UnsharedRequest = UnsharedRequest>(dependencies: VerificationDependencies<TReq>): (req: TReq, res: UnsharedResponse) => Promise<void>;
@@ -1 +1 @@
1
- import{parseCookie}from"../utils/cookies";import{extractDeviceId}from"../utils/device-id";export function handleVerifyTrigger(e){return async(r,i)=>{try{const s=resolveEmail(r,r.body??{},e.resolveEmailAddress);if(!s)return void i.status(400).json({success:!1,error:{code:"VALIDATION_ERROR",message:"Email is required"}});const o=extractDeviceId(r,e.resolveDeviceId),c=parseCookie(r,"__unshared_fingerprint_id")||void 0,t=await e.client.triggerEmailVerification(s,o,{fingerprintId:c});t.success?i.status(200).json({success:!0,data:t.data}):i.status(200).json({success:!1,error:t.error??{code:"TRIGGER_FAILED",message:"Failed to send verification email"}})}catch{i.status(200).json({success:!1,error:{code:"INTERNAL_ERROR",message:"Failed to trigger verification"}})}}}export function handleVerify(e){return async(r,i)=>{try{const s=r.body??{},o=resolveEmail(r,s,e.resolveEmailAddress),c=s.code;if(!o||!c)return void i.status(400).json({success:!1,error:{code:"VALIDATION_ERROR",message:"Email and code are required"}});const t=extractDeviceId(r,e.resolveDeviceId),a=parseCookie(r,"__unshared_fingerprint_id")||void 0,n=await e.client.verify(o,t,c,{fingerprintId:a});if(n.success){const s=parseCookie(r,"__unshared_uid");s&&e.verdictCache.update(s,{isVerified:!0}),i.status(200).json({success:!0,data:{verified:!0}})}else i.status(200).json({success:!1,error:n.error??{code:"VERIFICATION_FAILED",message:"Verification failed"}})}catch{i.status(200).json({success:!1,error:{code:"INTERNAL_ERROR",message:"Verification failed"}})}}}function resolveEmail(e,r,i){if(i)try{const r=i(e);if(r)return r}catch{}const s=parseCookie(e,"__unshared_email");if(s)return s;const o=r.email;return"string"==typeof o&&o?o:void 0}
1
+ import{parseCookie}from"../utils/cookies";import{extractDeviceId}from"../utils/device-id";import{sendJson}from"../utils/http-helpers";export function handleVerifyTrigger(e){return async(r,s)=>{try{const i=resolveEmail(r,r.body??{},e.resolveEmailAddress);if(!i)return void sendJson(s,400,{success:!1,error:{code:"VALIDATION_ERROR",message:"Email is required"}});const o=extractDeviceId(r,e.resolveDeviceId),n=parseCookie(r,"__unshared_fingerprint_id")||void 0,t=await e.client.triggerEmailVerification(i,o,{fingerprintId:n});t.success?sendJson(s,200,{success:!0,data:t.data}):sendJson(s,200,{success:!1,error:t.error??{code:"TRIGGER_FAILED",message:"Failed to send verification email"}})}catch(r){e.onError&&e.onError(r,{operation:"verifyTrigger"}),sendJson(s,200,{success:!1,error:{code:"INTERNAL_ERROR",message:"Failed to trigger verification"}})}}}export function handleVerify(e){return async(r,s)=>{try{const i=r.body??{},o=resolveEmail(r,i,e.resolveEmailAddress),n=i.code;if(!o||!n)return void sendJson(s,400,{success:!1,error:{code:"VALIDATION_ERROR",message:"Email and code are required"}});const t=extractDeviceId(r,e.resolveDeviceId),c=parseCookie(r,"__unshared_fingerprint_id")||void 0,a=await e.client.verify(o,t,n,{fingerprintId:c});if(a.success){const i=parseCookie(r,"__unshared_uid");i&&e.verdictCache.update(i,{isVerified:!0}),sendJson(s,200,{success:!0,data:{verified:!0}})}else sendJson(s,200,{success:!1,error:a.error??{code:"VERIFICATION_FAILED",message:"Verification failed"}})}catch(r){e.onError&&e.onError(r,{operation:"verify"}),sendJson(s,200,{success:!1,error:{code:"INTERNAL_ERROR",message:"Verification failed"}})}}}function resolveEmail(e,r,s){if(s)try{const r=s(e);if(r)return r}catch{}const i=parseCookie(e,"__unshared_email");if(i)return i;const o=r.email;return"string"==typeof o&&o?o:void 0}
@@ -1,6 +1,6 @@
1
- import type { Request } from 'express';
1
+ import type { UnsharedRequest } from '../../types';
2
2
  /**
3
- * Extract the real client IP from proxy headers, falling back to req.ip.
4
- * Checked in order: CF-Connecting-IP (Cloudflare) → X-Real-IP (nginx/ALB) → req.ip.
3
+ * Extract the real client IP from proxy headers, falling back to req.ip or socket address.
4
+ * Checked in order: CF-Connecting-IP (Cloudflare) → X-Real-IP (nginx/ALB) → req.ip → socket.
5
5
  */
6
- export declare function extractClientIp(req: Request): string;
6
+ export declare function extractClientIp(req: UnsharedRequest): string;
@@ -1 +1 @@
1
- export function extractClientIp(t){const n=t.headers["cf-connecting-ip"];if("string"==typeof n&&n)return n;const r=t.headers["x-real-ip"];return"string"==typeof r&&r?r:t.ip??""}
1
+ export function extractClientIp(t){const n=t.headers["cf-connecting-ip"];if("string"==typeof n&&n)return n;const r=t.headers["x-real-ip"];return"string"==typeof r&&r?r:t.ip??t.socket?.remoteAddress??""}
@@ -1,6 +1,6 @@
1
- import type { Request } from 'express';
1
+ import type { UnsharedRequest } from '../../types';
2
2
  /**
3
3
  * Reads a single cookie value from the raw Cookie header.
4
4
  * Works without cookie-parser middleware.
5
5
  */
6
- export declare function parseCookie(req: Request, name: string): string | undefined;
6
+ export declare function parseCookie(req: UnsharedRequest, name: string): string | undefined;
@@ -1,5 +1,19 @@
1
- import type { Request } from 'express';
1
+ import type { UnsharedRequest } from '../../types';
2
2
  /**
3
- * Resolves device ID from: custom resolver → __unshared_fp_id cookie → X-Device-Id header.
3
+ * Resolves device ID from: custom resolver → X-Device-Id header → __unshared_fp_id cookie.
4
+ *
5
+ * Returns the literal string `"unknown"` when no source provides a value.
6
+ * Callers that can tolerate a tri-state should use `extractDeviceIdOrUndefined`
7
+ * instead — the "unknown" sentinel polluted 19% of FP rows in production
8
+ * because it was being dispatched as-if-real during the first request of a
9
+ * session, before the inline script had a chance to set `__unshared_fp_id`.
10
+ * Kept for API compatibility.
4
11
  */
5
- export declare function extractDeviceId(req: Request, resolveDeviceId?: (req: Request) => string | undefined): string;
12
+ export declare function extractDeviceId<TReq extends UnsharedRequest = UnsharedRequest>(req: TReq, resolveDeviceId?: (req: TReq) => string | undefined): string;
13
+ /**
14
+ * Resolves device ID from: custom resolver → X-Device-Id header → __unshared_fp_id cookie.
15
+ * Returns `undefined` when nothing is available. Use this at any call site
16
+ * that can take a "skip dispatch" branch during the bootstrap window, so we
17
+ * stop writing `device_id="unknown"` rows to the analytics table on first request.
18
+ */
19
+ export declare function extractDeviceIdOrUndefined<TReq extends UnsharedRequest = UnsharedRequest>(req: TReq, resolveDeviceId?: (req: TReq) => string | undefined): string | undefined;
@@ -1 +1 @@
1
- import{parseCookie}from"./cookies";export function extractDeviceId(o,r){if(r)try{const t=r(o);if(t)return t}catch{}const t=parseCookie(o,"__unshared_fp_id");if(t)return t;const e=o.headers["x-device-id"];return"string"==typeof e&&e?e:"unknown"}
1
+ import{parseCookie}from"./cookies";export function extractDeviceId(e,r){return extractDeviceIdOrUndefined(e,r)??"unknown"}export function extractDeviceIdOrUndefined(e,r){if(r)try{const t=r(e);if(t)return t}catch{}const t=e.headers["x-device-id"];if("string"==typeof t&&t)return t;return parseCookie(e,"__unshared_fp_id")||void 0}
@@ -0,0 +1,21 @@
1
+ import type { UnsharedResponse } from '../../types';
2
+ /**
3
+ * Send a JSON response. Framework-agnostic replacement for Express's
4
+ * `res.status(code).json(data)`.
5
+ */
6
+ export declare function sendJson(res: UnsharedResponse, statusCode: number, data: unknown): void;
7
+ /**
8
+ * Send an empty response with a status code. Replacement for Express's
9
+ * `res.status(code).end()`.
10
+ */
11
+ export declare function sendEmpty(res: UnsharedResponse, statusCode: number): void;
12
+ /**
13
+ * Send a response with a specific body. Replacement for Express's
14
+ * `res.status(code).end(body)`.
15
+ */
16
+ export declare function sendBody(res: UnsharedResponse, statusCode: number, body: string | Buffer): void;
17
+ /**
18
+ * Extract the pathname from a request URL, stripping query string.
19
+ * Framework-agnostic replacement for Express's `req.path`.
20
+ */
21
+ export declare function getRequestPath(url: string | undefined): string;
@@ -0,0 +1 @@
1
+ export function sendJson(n,t,o){const e=JSON.stringify(o);n.statusCode=t,n.setHeader("Content-Type","application/json"),n.end(e)}export function sendEmpty(n,t){n.statusCode=t,n.end()}export function sendBody(n,t,o){n.statusCode=t,n.end(o)}export function getRequestPath(n){if(!n)return"/";const t=n.indexOf("?");return-1===t?n:n.slice(0,t)}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Returns true if the path matches at least one of the includePathPrefix entries.
3
+ * When includePathPrefix is undefined, returns true (all paths match — preserves default behavior).
4
+ * When includePathPrefix is an empty array, returns false (no paths match).
5
+ */
6
+ export declare function shouldIncludePath(path: string, includePathPrefix?: string[]): boolean;
@@ -0,0 +1 @@
1
+ export function shouldIncludePath(n,t){return!t||t.some(t=>n.startsWith(t))}
@@ -1 +1 @@
1
- const BOT_PATTERNS=["googlebot","bingbot","slurp","baiduspider","duckduckbot","yandex","sogou","exabot","ia_archiver","curl","wget","python-requests","python-urllib","axios","node-fetch","go-http-client","java/","libwww-perl","okhttp","apache-httpclient","http_request","httpie","headlesschrome","phantomjs","nessus","nikto","sqlmap","burp","zap","qualys","openvas","nmap","masscan","facebookexternalhit","twitterbot","linkedinbot","whatsapp","telegrambot","slackbot","discordbot","bot","crawl","spider","scrape","fetch","scan"],BOT_RE=new RegExp(BOT_PATTERNS.join("|"),"i");export function isBot(t){return!!t&&BOT_RE.test(t)}
1
+ const BOT_PATTERNS=["googlebot","bingbot","slurp","baiduspider","duckduckbot","yandex","sogou","exabot","ia_archiver","curl","wget","python-requests","python-urllib","axios","node-fetch","go-http-client","java/","libwww-perl","okhttp","apache-httpclient","http_request","httpie","headlesschrome","phantomjs","puppeteer","playwright","cypress","selenium","webdriver","electron","jsdom","vercel-screenshot","screenshot","prerender","lighthouse","chrome-lighthouse","pagespeed","gtmetrix","pingdom","nessus","nikto","sqlmap","burp","zap","qualys","openvas","nmap","masscan","facebookexternalhit","twitterbot","linkedinbot","whatsapp","telegrambot","slackbot","discordbot","bot","crawl","spider","scrape","fetch","scan"],BOT_RE=new RegExp(BOT_PATTERNS.join("|"),"i");export function isBot(e){return!!e&&BOT_RE.test(e)}
@@ -1,3 +1,3 @@
1
- import type { Request } from 'express';
1
+ import type { UnsharedRequest } from '../../types';
2
2
  /** Returns true if the request arrived over HTTPS (direct or via reverse proxy). */
3
- export declare function isSecureRequest(req: Request): boolean;
3
+ export declare function isSecureRequest(req: UnsharedRequest): boolean;
@@ -1 +1 @@
1
- export function isSecureRequest(e){return e.secure||"https"===e.headers["x-forwarded-proto"]}
1
+ export function isSecureRequest(e){return!!e.socket?.encrypted||"https"===e.headers["x-forwarded-proto"]}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Stickiness window: if the resolver returns a sentinel but the
3
+ * `__unshared_uid` cookie was set within this many milliseconds, we prefer
4
+ * the cookie value (assuming it's a hydration race on the same tab).
5
+ * Outside the window, the cookie is considered stale and we fall through
6
+ * to the "no userId" branch — without clearing the cookie, because clearing
7
+ * on every hydration blip is exactly the bug we're fixing.
8
+ */
9
+ export declare const SENTINEL_STICKINESS_TTL_MS = 30000;
10
+ export declare function isSentinelUserId(value: string | undefined | null): boolean;