unshared-clientjs-sdk 1.0.13 → 2.0.0-rc.10

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 (58) hide show
  1. package/README.md +135 -67
  2. package/dist/client.d.ts +175 -183
  3. package/dist/client.js +1 -1
  4. package/dist/esm/client.d.mts +199 -0
  5. package/dist/esm/client.mjs +1 -0
  6. package/dist/esm/index.d.mts +6 -0
  7. package/dist/esm/index.mjs +1 -0
  8. package/dist/esm/middleware/index.d.mts +50 -0
  9. package/dist/esm/middleware/index.mjs +1 -0
  10. package/dist/esm/middleware/injection/fingerprint-script.d.mts +10 -0
  11. package/dist/esm/middleware/injection/fingerprint-script.mjs +1 -0
  12. package/dist/esm/middleware/rate-limit-backoff.d.mts +14 -0
  13. package/dist/esm/middleware/rate-limit-backoff.mjs +1 -0
  14. package/dist/esm/middleware/response-interceptor.d.mts +13 -0
  15. package/dist/esm/middleware/response-interceptor.mjs +1 -0
  16. package/dist/esm/middleware/routes/submit-fp.d.mts +24 -0
  17. package/dist/esm/middleware/routes/submit-fp.mjs +1 -0
  18. package/dist/esm/middleware/routes/verify.d.mts +28 -0
  19. package/dist/esm/middleware/routes/verify.mjs +1 -0
  20. package/dist/esm/middleware/utils/content-type.d.mts +6 -0
  21. package/dist/esm/middleware/utils/content-type.mjs +1 -0
  22. package/dist/esm/middleware/utils/is-bot.d.mts +5 -0
  23. package/dist/esm/middleware/utils/is-bot.mjs +1 -0
  24. package/dist/esm/middleware/utils/skip-paths.d.mts +5 -0
  25. package/dist/esm/middleware/utils/skip-paths.mjs +1 -0
  26. package/dist/esm/middleware/verdict-cache.d.mts +36 -0
  27. package/dist/esm/middleware/verdict-cache.mjs +1 -0
  28. package/dist/esm/middleware.d.mts +73 -0
  29. package/dist/esm/middleware.mjs +1 -0
  30. package/dist/esm/util.d.mts +1 -0
  31. package/dist/esm/util.mjs +1 -0
  32. package/dist/index.d.ts +6 -0
  33. package/dist/index.js +1 -0
  34. package/dist/middleware/index.d.ts +50 -0
  35. package/dist/middleware/index.js +1 -0
  36. package/dist/middleware/injection/fingerprint-script.d.ts +10 -0
  37. package/dist/middleware/injection/fingerprint-script.js +1 -0
  38. package/dist/middleware/rate-limit-backoff.d.ts +14 -0
  39. package/dist/middleware/rate-limit-backoff.js +1 -0
  40. package/dist/middleware/response-interceptor.d.ts +13 -0
  41. package/dist/middleware/response-interceptor.js +1 -0
  42. package/dist/middleware/routes/submit-fp.d.ts +24 -0
  43. package/dist/middleware/routes/submit-fp.js +1 -0
  44. package/dist/middleware/routes/verify.d.ts +28 -0
  45. package/dist/middleware/routes/verify.js +1 -0
  46. package/dist/middleware/utils/content-type.d.ts +6 -0
  47. package/dist/middleware/utils/content-type.js +1 -0
  48. package/dist/middleware/utils/is-bot.d.ts +5 -0
  49. package/dist/middleware/utils/is-bot.js +1 -0
  50. package/dist/middleware/utils/skip-paths.d.ts +5 -0
  51. package/dist/middleware/utils/skip-paths.js +1 -0
  52. package/dist/middleware/verdict-cache.d.ts +36 -0
  53. package/dist/middleware/verdict-cache.js +1 -0
  54. package/dist/middleware.d.ts +73 -0
  55. package/dist/middleware.js +1 -0
  56. package/dist/util.d.ts +1 -2
  57. package/dist/util.js +1 -1
  58. package/package.json +41 -4
@@ -0,0 +1,199 @@
1
+ import type { FingerprintWireFormat } from '@unshared-labs/shared-types';
2
+ export interface UnsharedLabsClientConfig {
3
+ /**
4
+ * Secret API key. Must be kept server-side.
5
+ * Format: usk_…
6
+ */
7
+ apiKey: string;
8
+ /**
9
+ * Base URL of the Unshared Labs V2 ingress.
10
+ * @default "https://api-ingress.unsharedlabs.com"
11
+ */
12
+ baseUrl?: string;
13
+ /**
14
+ * Per-request timeout in milliseconds.
15
+ * @default 10_000
16
+ */
17
+ timeout?: number;
18
+ /**
19
+ * Max retries for 5xx / network failures after the first attempt.
20
+ * @default 3
21
+ */
22
+ maxRetries?: number;
23
+ }
24
+ export interface UnsharedLabsError {
25
+ code: string;
26
+ message: string;
27
+ details?: Record<string, unknown>;
28
+ /**
29
+ * Seconds to wait before retrying. Populated on 429 RATE_LIMIT_EXCEEDED
30
+ * responses by reading the `Retry-After` HTTP response header.
31
+ * Falls back to `details.retry_after_seconds` if the header is absent.
32
+ */
33
+ retryAfter?: number;
34
+ }
35
+ export interface ApiResult<T = unknown> {
36
+ success: boolean;
37
+ data?: T;
38
+ error?: UnsharedLabsError;
39
+ status: number;
40
+ }
41
+ export interface SubmitFingerprintOptions {
42
+ userId?: string;
43
+ sessionHash?: string;
44
+ eventType?: string;
45
+ /** SDK encrypts before sending. */
46
+ ipAddress?: string;
47
+ }
48
+ export interface SubmitFingerprintResult {
49
+ hash: string;
50
+ stable_hash: string;
51
+ collected_at: string;
52
+ /** Always present; set to "unknown" by the server if not provided. */
53
+ version: string;
54
+ }
55
+ export interface ProcessUserEventParams {
56
+ eventType: string;
57
+ /** SDK encrypts before sending. */
58
+ userId: string;
59
+ /** SDK encrypts before sending. */
60
+ ipAddress: string;
61
+ /** SDK encrypts before sending. */
62
+ deviceId: string;
63
+ sessionHash: string;
64
+ /** SDK encrypts before sending. */
65
+ userAgent: string;
66
+ /** SDK encrypts before sending. */
67
+ emailAddress: string;
68
+ /** SDK encrypts before sending. */
69
+ fingerprintId?: string;
70
+ subscriptionStatus?: string | null;
71
+ eventDetails?: Record<string, unknown> | null;
72
+ }
73
+ export interface ProcessUserEventResult {
74
+ event: {
75
+ event_type: string;
76
+ user_id: string;
77
+ email_address: string;
78
+ ip_address: string;
79
+ device_id: string;
80
+ session_hash: string;
81
+ user_agent: string;
82
+ event_details?: string;
83
+ subscription_status?: string;
84
+ };
85
+ analysis: {
86
+ status: 'success' | 'error';
87
+ is_user_flagged: boolean;
88
+ status_details?: string;
89
+ };
90
+ }
91
+ export interface CheckUserResult {
92
+ is_user_flagged: boolean;
93
+ }
94
+ export interface TriggerEmailVerificationResult {
95
+ message: string;
96
+ }
97
+ export interface VerifyResult {
98
+ verified: boolean;
99
+ reason?: 'not_found' | 'code_mismatch' | 'code_expired';
100
+ }
101
+ export interface VerificationFlowStep {
102
+ type: 'message' | 'email_input' | 'otp_input' | 'support_link';
103
+ title: string;
104
+ body: string;
105
+ buttonText?: string;
106
+ url?: string;
107
+ }
108
+ export interface VerificationFlowConfigResult {
109
+ steps: VerificationFlowStep[];
110
+ branding?: {
111
+ companyName?: string;
112
+ logoUrl?: string;
113
+ primaryColor?: string;
114
+ supportEmail?: string;
115
+ };
116
+ }
117
+ export declare class UnsharedLabsClient {
118
+ private readonly _apiKey;
119
+ private readonly _baseUrl;
120
+ private readonly _timeout;
121
+ private readonly _maxRetries;
122
+ private readonly _encryptionKey;
123
+ constructor(config: UnsharedLabsClientConfig);
124
+ private _encrypt;
125
+ /**
126
+ * Core HTTP method with retry logic.
127
+ * - 2xx → success result
128
+ * - 4xx → non-retryable, error result returned immediately
129
+ * - 5xx → retried up to maxRetries, last error result returned
130
+ * - Network/timeout → retried, NETWORK_ERROR result returned
131
+ */
132
+ private _fetch;
133
+ /**
134
+ * Submit a browser fingerprint event. Publishes asynchronously via Pub/Sub.
135
+ * Maps to: POST /v2/submit-fingerprint-event
136
+ */
137
+ submitFingerprintEvent(fingerprint: FingerprintWireFormat, opts?: SubmitFingerprintOptions): Promise<ApiResult<SubmitFingerprintResult>>;
138
+ /**
139
+ * Record a user event and receive naughty-list analysis.
140
+ * Maps to: POST /v2/process-user-event
141
+ */
142
+ processUserEvent(params: ProcessUserEventParams): Promise<ApiResult<ProcessUserEventResult>>;
143
+ /**
144
+ * Check if a user is flagged in the naughty list.
145
+ * Maps to: GET /v2/check-user
146
+ *
147
+ * **Defensive default:** On any failure (network error, 4xx, 5xx, timeout) this
148
+ * method returns `{ success: true, data: { is_user_flagged: false } }` rather
149
+ * than surfacing the error. This ensures a backend outage never incorrectly
150
+ * blocks a legitimate user. As a consequence, a complete API outage is
151
+ * **invisible** to the caller — you cannot distinguish "user is clean" from
152
+ * "request failed" by inspecting the return value. Monitor API availability
153
+ * through your infrastructure metrics, not through this method's return value.
154
+ */
155
+ checkUser(emailAddress: string, deviceId: string): Promise<ApiResult<CheckUserResult>>;
156
+ checkUser(emailAddress: string, opts: {
157
+ deviceId?: string;
158
+ fingerprintId?: string;
159
+ }): Promise<ApiResult<CheckUserResult>>;
160
+ /**
161
+ * Send a 6-digit verification code to the user's email address.
162
+ * Maps to: POST /v2/trigger-email-verification
163
+ */
164
+ triggerEmailVerification(emailAddress: string, deviceId: string, opts?: {
165
+ fingerprintId?: string;
166
+ }): Promise<ApiResult<TriggerEmailVerificationResult>>;
167
+ /**
168
+ * Verify a 6-digit code submitted by the user.
169
+ * Maps to: POST /v2/verify
170
+ *
171
+ * `result.success` reliably indicates whether verification succeeded:
172
+ * - `success: true` → code was correct, user is verified
173
+ * - `success: false, error.code: "VERIFICATION_FAILED"` → wrong or expired code
174
+ * - `success: false, error.code: "DELIVERY_FAILED"` → network/server error
175
+ *
176
+ * ```typescript
177
+ * const result = await client.verify(email, deviceId, code);
178
+ * if (!result.success) {
179
+ * if (result.error?.code === 'VERIFICATION_FAILED') { /* bad code *\/ }
180
+ * else { /* transport error *\/ }
181
+ * } else { /* verified *\/ }
182
+ * ```
183
+ */
184
+ verify(emailAddress: string, deviceId: string, code: string, opts?: {
185
+ fingerprintId?: string;
186
+ }): Promise<ApiResult<VerifyResult>>;
187
+ /**
188
+ * Fetch the verification flow configuration for this company.
189
+ * Maps to: GET /v2/verification-flow-config
190
+ *
191
+ * Returns the flow steps and branding configured by the Unshared Labs
192
+ * team for this company. The middleware uses this to render the
193
+ * verification overlay.
194
+ *
195
+ * Returns `null` on any failure (network error, 4xx, 5xx) so the
196
+ * middleware can fall back to the default flow.
197
+ */
198
+ getVerificationFlowConfig(): Promise<VerificationFlowConfigResult | null>;
199
+ }
@@ -0,0 +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?.sessionHash&&(t.session_hash=s.sessionHash),null!=s?.eventType&&(t.event_type=s.eventType),null!=s?.ipAddress&&(t.ip_address=this.l(s.ipAddress)),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}}
@@ -0,0 +1,6 @@
1
+ export { UnsharedLabsClient } from './client';
2
+ export { createUnsharedMiddleware, assertTrustProxy } from './middleware';
3
+ export type { MiddlewareOptions } from './middleware';
4
+ export { unsharedBoundToUser, VerdictCache, } from './middleware/index';
5
+ export type { ProtectionConfig, Verdict } from './middleware/index';
6
+ export type { UnsharedLabsClientConfig, ApiResult, UnsharedLabsError, SubmitFingerprintOptions, SubmitFingerprintResult, ProcessUserEventParams, ProcessUserEventResult, CheckUserResult, TriggerEmailVerificationResult, VerifyResult, VerificationFlowStep, VerificationFlowConfigResult, } from './client';
@@ -0,0 +1 @@
1
+ export{UnsharedLabsClient}from"./client";export{createUnsharedMiddleware,assertTrustProxy}from"./middleware";export{unsharedBoundToUser,VerdictCache}from"./middleware/index";
@@ -0,0 +1,50 @@
1
+ import type { Request, Response, NextFunction } from 'express';
2
+ import type { UnsharedLabsClient } from '../client';
3
+ import { VerdictCache } from './verdict-cache';
4
+ import type { Verdict } from './verdict-cache';
5
+ export interface ProtectionConfig {
6
+ /**
7
+ * Required. Resolves the current user's ID from the request.
8
+ * Return undefined for anonymous/logged-out visitors.
9
+ */
10
+ userId: (req: Request) => string | undefined;
11
+ /**
12
+ * Resolves the current user's email address from the request.
13
+ * Required in Tier 2 (backend-only). Recommended in Tier 1.
14
+ * Falls back to HttpOnly cookie → req.body.email when not configured.
15
+ */
16
+ emailAddress?: (req: Request) => string | undefined;
17
+ /** Route prefix for internal routes. @default "/__unshared" */
18
+ routePrefix?: string;
19
+ /** Allowed CORS origins for /__unshared/* routes. */
20
+ corsOrigins?: string | string[];
21
+ /** Verdict cache TTL in ms. @default 60000 */
22
+ cacheTTL?: number;
23
+ /** Paths to skip entirely (static assets, health checks). */
24
+ skipPaths?: string[];
25
+ /** Resolves a custom session ID. Falls back to __unshared_sid cookie. */
26
+ sessionId?: (req: Request) => string | undefined;
27
+ /**
28
+ * Resolves a device ID from the request.
29
+ * Falls back to __unshared_fp_id cookie → X-Device-Id header.
30
+ */
31
+ deviceId?: (req: Request) => string | undefined;
32
+ /**
33
+ * Called when a flagged, unverified user makes a request.
34
+ * You own the response — block, redirect, or call next() to let it through.
35
+ *
36
+ * If not provided, flagged requests pass through (data collection only).
37
+ * Exceptions are caught and swallowed — the request passes through on error.
38
+ */
39
+ onFlagged?: (context: {
40
+ userId: string;
41
+ emailAddress: string;
42
+ verdict: Verdict;
43
+ req: Request;
44
+ res: Response;
45
+ next: NextFunction;
46
+ }) => void;
47
+ }
48
+ export type { Verdict };
49
+ export { VerdictCache };
50
+ export declare function unsharedBoundToUser(client: UnsharedLabsClient, config: ProtectionConfig): (req: Request, res: Response, next: NextFunction) => void;
@@ -0,0 +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";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,sessionId:c,deviceId:a,onFlagged:l}=t,u=new VerdictCache(s),p=new RateLimitBackoff,f=Date.now().toString(36),m=generateFingerprintScript(n,f);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:u,rateLimitBackoff:p,resolveUserId:r,resolveEmailAddress:i,resolveSessionId:c,resolveDeviceId:a}),C=handleVerifyTrigger({client:e,verdictCache:u,resolveEmailAddress:i,resolveDeviceId:a}),g=handleVerify({client:e,verdictCache:u,resolveEmailAddress:i,resolveDeviceId:a}),I=o?Array.isArray(o)?o:[o]:null,y=`${n}/fp.js`,k=`${n}/submit-fp`,S=`${n}/verify-trigger`,_=`${n}/verify`;return function(t,o,s){const f=t.path;if(f.startsWith(n+"/"))return function(e,t){if(!I)return;const r=e.headers.origin??"",i=I.includes("*");(i||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?void o.status(204).end():"GET"===t.method&&f===y?(o.setHeader("Content-Type","application/javascript"),o.setHeader("Cache-Control","public, max-age=3600"),void o.status(200).end(h)):"POST"===t.method&&f===k?void v(t,o):"POST"===t.method&&f===S?void C(t,o):"POST"===t.method&&f===_?void g(t,o):void o.status(404).json({success:!1,error:{code:"NOT_FOUND",message:"Unknown route"}});if(shouldSkipPath(f,d))return void s();let A;try{A=r(t)}catch{}if(!A)return clearEmailCookieIfPresent(t,o),interceptForInjection(t,o,m),void s();const T=resolveEmail(t,i);if(setUserIdCookie(o,A),T&&setEmailCookie(o,T),!T)return interceptForInjection(t,o,m),void s();const E=extractSessionId(t,c),x=extractDeviceId(t,a),F=extractFingerprintId(t),w=t.headers["user-agent"]??"",P=t.ip??"";if(isBot(w))return void s();p.isPaused()||dispatchUserEvent(e,u,p,{userId:A,emailAddress:T,sessionId:E,deviceId:x,fingerprintId:F,userAgent:w,ipAddress:P,eventType:`${t.method} ${t.path}`});const O=u.get(A);O?(u.isStale(A)&&!u.isRefreshing(A)&&(u.markRefreshing(A),fetchAndCacheVerdict(e,u,A,T,x,F,E).finally(()=>u.clearRefreshing(A))),applyVerdict(O,A,T,t,o,s,m,l)):fetchAndCacheVerdict(e,u,A,T,x,F,E).then(e=>{applyVerdict(e,A,T,t,o,s,m,l)}).catch(()=>{interceptForInjection(t,o,m),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 preventHtmlCaching(e,t){delete e.headers["if-none-match"],delete e.headers["if-modified-since"];const r=t.writeHead.bind(t);t.writeHead=function(e,...i){const n=t.getHeader("content-type");return n&&String(n).includes("text/html")&&(t.setHeader("Cache-Control","no-store"),t.removeHeader("ETag"),t.removeHeader("Last-Modified")),r(e,...i)}}function interceptForInjection(e,t,r){preventHtmlCaching(e,t),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)})}function dispatchUserEvent(e,t,r,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&&t.update(i.userId,{isFlagged:e.data.analysis.is_user_flagged}),!e.success&&e.error?.retryAfter&&r.pause(1e3*e.error.retryAfter)}).catch(()=>{})}async function fetchAndCacheVerdict(e,t,r,i,n,o,s){const d={};n&&"unknown"!==n&&(d.deviceId=n),o&&(d.fingerprintId=o);const c=await Promise.race([e.checkUser(i,d),new Promise(e=>setTimeout(()=>e(null),500))]);if(!c)return{isFlagged:!1,isVerified:!1,emailAddress:i,sessionId:s,cachedAt:0,ttl:0};const a=c.data?.is_user_flagged??!1;return t.set(r,{isFlagged:a,isVerified:!1,emailAddress:i,sessionId:s}),t.get(r)}function parseCookie(e,t){const r=e.headers.cookie;if(!r)return;const i=r.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return i?decodeURIComponent(i[1]):void 0}function extractSessionId(e,t){if(t)try{const r=t(e);if(r)return r}catch{}return parseCookie(e,"__unshared_sid")??"unknown"}function extractDeviceId(e,t){if(t)try{const r=t(e);if(r)return r}catch{}const r=parseCookie(e,"__unshared_fp_id");if(r)return r;const i=e.headers["x-device-id"];return"string"==typeof i&&i?i:"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){appendSetCookie(e,`__unshared_uid=${encodeURIComponent(t)}; Path=/; SameSite=Lax`)}function setEmailCookie(e,t){appendSetCookie(e,`__unshared_email=${encodeURIComponent(t)}; HttpOnly; Path=/; SameSite=Lax`)}function clearEmailCookieIfPresent(e,t){parseCookie(e,"__unshared_email")&&appendSetCookie(t,"__unshared_email=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0")}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Generates a small inline loader script that:
3
+ * 1. Loads the real fingerprint SDK from /__unshared/fp.js
4
+ * 2. Collects a full fingerprint (31+ signals, MurmurHash3 Merkle tree)
5
+ * 3. POSTs the result to /__unshared/submit-fp
6
+ *
7
+ * The actual SDK UMD bundle is served by the middleware at /__unshared/fp.js.
8
+ * This keeps the injected HTML small (~500 bytes) while using the full library.
9
+ */
10
+ export declare function generateFingerprintScript(routePrefix: string, version?: string): string;
@@ -0,0 +1 @@
1
+ export function generateFingerprintScript(e,n){const t=n?`?v=${escapeJavaScript(n)}`:"";return`<script>\n(function(){\ntry{\nvar pfx="${escapeJavaScript(e)}";\n\n// Session cookie helpers\nfunction getCookie(n){var m=document.cookie.match(new RegExp("(?:^|; )"+n+"=([^;]*)"));return m?decodeURIComponent(m[1]):null}\nfunction setCookie(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"}\n\n// UUID helper\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// Ensure session ID cookie exists\nvar sid=getCookie("__unshared_sid");\nif(!sid){sid=uuid();setCookie("__unshared_sid",sid,365)}\n\n// Persistent device ID (survives across sessions via localStorage)\nvar did="";\ntry{did=localStorage.getItem("__unshared_device_id")||"";if(!did){did=uuid();localStorage.setItem("__unshared_device_id",did)}}catch(e){did=did||uuid()}\n\nvar uid=getCookie("__unshared_uid")||"";\n\n// Collect on every page load if a userId is present\nif(uid){\n var s=document.createElement("script");\n s.src=pfx+"/fp.js${t}";\n s.onload=function(){\n try{\n var client=new UnsharedLabsBrowser.UnsharedLabsBrowser({baseUrl:""});\n client.collect({exclude:["timing","navigatorConnection"]}).then(function(fp){\n var body={\n hash:fp.full_hash,\n stable_hash:fp.fingerprint_id,\n collected_at:fp.timestamp,\n is_incognito:fp.isIncognito,\n components:fp.components,\n version:fp.version,\n session_id:sid,\n user_id:uid\n };\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 }catch(e){}\n };\n document.head.appendChild(s);\n}\n}catch(e){}\n})();\n<\/script>`}function escapeJavaScript(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'")}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Global rate-limit backoff for processUserEvent calls.
3
+ *
4
+ * When the Unshared API returns 429 with a Retry-After header,
5
+ * the middleware pauses processUserEvent calls for the specified duration.
6
+ * checkUser calls are not affected — enforcement takes priority.
7
+ */
8
+ export declare class RateLimitBackoff {
9
+ private _resumeAtTimestamp;
10
+ /** Pause processUserEvent calls for the given duration. */
11
+ pause(durationMs: number): void;
12
+ /** Returns true if processUserEvent calls should be skipped. */
13
+ isPaused(): boolean;
14
+ }
@@ -0,0 +1 @@
1
+ export class RateLimitBackoff{constructor(){this.t=0}pause(t){const s=Date.now()+t;s>this.t&&(this.t=s)}isPaused(){return Date.now()<this.t}}
@@ -0,0 +1,13 @@
1
+ import type { Response } from 'express';
2
+ /**
3
+ * Intercepts the response body by wrapping res.write() and res.end().
4
+ *
5
+ * Collects all chunks written to the response. When res.end() is called,
6
+ * invokes the `transform` callback with the complete body buffer and the
7
+ * Content-Type header. The transform can return modified content or null
8
+ * to pass through unchanged.
9
+ *
10
+ * Does NOT monkey-patch res.send — uses the lower-level write/end API
11
+ * as required by the spec.
12
+ */
13
+ export declare function interceptResponse(res: Response, transform: (body: Buffer, contentType: string | undefined) => Buffer | string | null): void;
@@ -0,0 +1 @@
1
+ export function interceptResponse(n,t){const f=[],e=n.write.bind(n),u=n.end.bind(n);let o=!1;n.write=function(n,t,e){if(null!=n){const e=Buffer.isBuffer(n)?n:Buffer.from(n,"string"==typeof t?t:"utf8");f.push(e)}return"function"==typeof t&&t(null),"function"==typeof e&&e(null),!0},n.end=function(r,c,l){if(o)return n;if(o=!0,null!=r){const n=Buffer.isBuffer(r)?r:Buffer.from(r,"string"==typeof c?c:"utf8");f.push(n)}const i=Buffer.concat(f),s=n.getHeader("content-type");let p;try{p=t(i,s)}catch{p=null}if(null!=p){const t=Buffer.isBuffer(p)?p:Buffer.from(p,"utf8");n.setHeader("Content-Length",t.length),n.removeHeader("Content-Encoding"),e(t)}else i.length>0&&e(i);const y="function"==typeof c?c:l;return y?u(y):u(),n}}
@@ -0,0 +1,24 @@
1
+ import type { Request, Response } from 'express';
2
+ import type { UnsharedLabsClient } from '../../client';
3
+ import type { VerdictCache } from '../verdict-cache';
4
+ import type { RateLimitBackoff } from '../rate-limit-backoff';
5
+ export interface SubmitFingerprintDependencies {
6
+ client: UnsharedLabsClient;
7
+ verdictCache: VerdictCache;
8
+ 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;
13
+ }
14
+ /**
15
+ * Handles POST /__unshared/submit-fp
16
+ *
17
+ * Receives fingerprint data from the injected inline script and:
18
+ * 1. Forwards to Unshared API via client.submitFingerprintEvent() (fire-and-forget)
19
+ * 2. Calls processUserEvent with cache side-effect (fire-and-forget)
20
+ * 3. Sets __unshared_email HttpOnly cookie when email is resolved from body
21
+ *
22
+ * Always returns 200 (fire-and-forget from browser's perspective).
23
+ */
24
+ export declare function handleSubmitFingerprint(dependencies: SubmitFingerprintDependencies): (req: Request, res: Response) => Promise<void>;
@@ -0,0 +1 @@
1
+ import{isBot}from"../utils/is-bot";export function handleSubmitFingerprint(e){return async(t,n)=>{try{const i=t.body??{},o={full_hash:i.hash??"",fingerprint_id:i.stable_hash??"",timestamp:i.collected_at??(new Date).toISOString(),isIncognito:i.is_incognito??!1,components:i.components??{},version:i.version??"inline-1.0.0"};let s,r,c;try{s=e.resolveUserId?e.resolveUserId(t):void 0}catch{}s=s??i.user_id??void 0;try{r=e.resolveEmailAddress?e.resolveEmailAddress(t):void 0}catch{}r=r??parseCookie(t,"__unshared_email")??i.email??void 0;try{c=e.resolveSessionId?e.resolveSessionId(t):void 0}catch{}c=c??i.session_id??parseCookie(t,"__unshared_sid");const a=t.ip??"",d=t.headers["user-agent"]??"";if(isBot(d))return void n.status(200).json({success:!0});const u=extractDeviceId(t,e.resolveDeviceId),_=o.fingerprint_id||void 0,p=[];if(_&&!parseCookie(t,"__unshared_fingerprint_id")&&p.push(`__unshared_fingerprint_id=${encodeURIComponent(_)}; HttpOnly; Path=/; SameSite=Lax`),r&&!parseCookie(t,"__unshared_email")&&p.push(`__unshared_email=${encodeURIComponent(r)}; HttpOnly; Path=/; SameSite=Lax`),p.length>0){const e=n.getHeader("Set-Cookie");if(e){const t=Array.isArray(e)?[...e]:[String(e)];t.push(...p),n.setHeader("Set-Cookie",t)}else n.setHeader("Set-Cookie",p)}s&&e.client.submitFingerprintEvent(o,{userId:s,sessionHash:c,eventType:"auto_collect",ipAddress:a}).catch(()=>{}),s&&r&&!e.rateLimitBackoff.isPaused()&&e.client.processUserEvent({eventType:"auto_collect",userId:s,emailAddress:r,ipAddress:a,deviceId:u,fingerprintId:_,sessionHash:c??"unknown",userAgent:d}).then(t=>{t.success&&t.data?.analysis&&e.verdictCache.update(s,{isFlagged:t.data.analysis.is_user_flagged}),!t.success&&t.error?.retryAfter&&e.rateLimitBackoff.pause(1e3*t.error.retryAfter)}).catch(()=>{}),n.status(200).json({success:!0})}catch{n.status(200).json({success:!0})}}}function extractDeviceId(e,t){if(t)try{const n=t(e);if(n)return n}catch{}const n=parseCookie(e,"__unshared_fp_id");if(n)return n;const i=e.headers["x-device-id"];return"string"==typeof i&&i?i:"unknown"}function parseCookie(e,t){const n=e.headers.cookie;if(!n)return;const i=n.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return i?decodeURIComponent(i[1]):void 0}
@@ -0,0 +1,28 @@
1
+ import type { Request, Response } from 'express';
2
+ import type { UnsharedLabsClient } from '../../client';
3
+ import type { VerdictCache } from '../verdict-cache';
4
+ export interface VerificationDependencies {
5
+ client: UnsharedLabsClient;
6
+ verdictCache: VerdictCache;
7
+ resolveEmailAddress?: (req: Request) => string | undefined;
8
+ resolveDeviceId?: (req: Request) => string | undefined;
9
+ }
10
+ /**
11
+ * POST /__unshared/verify-trigger
12
+ * Triggers email verification. Called by the blocker overlay UI.
13
+ *
14
+ * Body: { email: string }
15
+ *
16
+ * The deviceId is resolved via extractDeviceId (same as the middleware).
17
+ */
18
+ export declare function handleVerifyTrigger(dependencies: VerificationDependencies): (req: Request, res: Response) => Promise<void>;
19
+ /**
20
+ * POST /__unshared/verify
21
+ * Validates OTP code. Called by the blocker overlay UI.
22
+ *
23
+ * Body: { email: string, code: string }
24
+ *
25
+ * On successful verification, updates the verdict cache to mark
26
+ * the user as verified so subsequent requests pass through.
27
+ */
28
+ export declare function handleVerify(dependencies: VerificationDependencies): (req: Request, res: Response) => Promise<void>;
@@ -0,0 +1 @@
1
+ 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 n=extractDeviceId(r,e.resolveDeviceId),o=parseCookie(r,"__unshared_fingerprint_id")||void 0,t=await e.client.triggerEmailVerification(s,n,{fingerprintId:o});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??{},n=resolveEmail(r,s,e.resolveEmailAddress),o=s.code;if(!n||!o)return void i.status(400).json({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(n,t,o,{fingerprintId:c});if(a.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:a.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 n=r.email;return"string"==typeof n&&n?n:void 0}function extractDeviceId(e,r){if(r)try{const i=r(e);if(i)return i}catch{}const i=parseCookie(e,"__unshared_fp_id");if(i)return i;const s=e.headers["x-device-id"];return"string"==typeof s&&s?s:"unknown"}function parseCookie(e,r){const i=e.headers.cookie;if(!i)return;const s=i.match(new RegExp(`(?:^|; )${r}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}
@@ -0,0 +1,6 @@
1
+ /** Check if a Content-Type header value indicates HTML. */
2
+ export declare function isHtmlContentType(contentType: string | undefined): boolean;
3
+ /** Check if a Content-Type header value indicates JSON. */
4
+ export declare function isJsonContentType(contentType: string | undefined): boolean;
5
+ /** Check if a Content-Type indicates a static asset (images, fonts, etc). */
6
+ export declare function isStaticContentType(contentType: string | undefined): boolean;
@@ -0,0 +1 @@
1
+ export function isHtmlContentType(t){return!!t&&t.includes("text/html")}export function isJsonContentType(t){return!!t&&t.includes("application/json")}export function isStaticContentType(t){return!!t&&["image/","font/","audio/","video/","application/javascript","text/javascript","text/css","application/wasm"].some(n=>t.includes(n))}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Returns true if the User-Agent string matches a known bot, crawler,
3
+ * scanner, or HTTP client library pattern.
4
+ */
5
+ export declare function isBot(userAgent: string): boolean;
@@ -0,0 +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)}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Returns true if the request path looks like a static asset and should be
3
+ * skipped by the middleware (no fingerprint injection, no verdict checks).
4
+ */
5
+ export declare function shouldSkipPath(path: string, customSkipPaths?: string[]): boolean;
@@ -0,0 +1 @@
1
+ const STATIC_EXTENSIONS=new Set([".js",".mjs",".cjs",".css",".map",".png",".jpg",".jpeg",".gif",".svg",".ico",".webp",".avif",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".webm",".ogg",".wasm",".json",".xml",".txt",".pdf"]),STATIC_PATH_PREFIXES=["/static/","/assets/","/public/","/_next/","/__vite/","/favicon"];export function shouldSkipPath(t,f){if(f)for(const o of f)if(t.startsWith(o))return!0;const o=t.lastIndexOf(".");if(-1!==o){const f=t.slice(o).toLowerCase().split("?")[0];if(STATIC_EXTENSIONS.has(f))return!0}for(const f of STATIC_PATH_PREFIXES)if(t.startsWith(f))return!0;return!1}
@@ -0,0 +1,36 @@
1
+ export interface Verdict {
2
+ isFlagged: boolean;
3
+ isVerified: boolean;
4
+ emailAddress: string;
5
+ sessionId: string;
6
+ cachedAt: number;
7
+ ttl: number;
8
+ }
9
+ export declare class VerdictCache {
10
+ private readonly _entries;
11
+ private readonly _activeRefreshes;
12
+ private readonly _defaultTtlMs;
13
+ constructor(defaultTTL?: number);
14
+ get(userId: string): Verdict | undefined;
15
+ set(userId: string, verdict: Omit<Verdict, 'cachedAt' | 'ttl'>, ttl?: number): void;
16
+ /**
17
+ * Update an existing cache entry (e.g. from webhook).
18
+ * If the user is not in cache, creates a new entry.
19
+ */
20
+ update(userId: string, partial: Partial<Pick<Verdict, 'isFlagged' | 'isVerified'>>): void;
21
+ delete(userId: string): void;
22
+ /**
23
+ * Returns true if the entry exists but is past its TTL.
24
+ * Stale entries are served while a background refresh happens.
25
+ */
26
+ isStale(userId: string): boolean;
27
+ /**
28
+ * Returns true if a background refresh is already in flight for this user.
29
+ */
30
+ isRefreshing(userId: string): boolean;
31
+ markRefreshing(userId: string): void;
32
+ clearRefreshing(userId: string): void;
33
+ /** Number of cached entries. */
34
+ get size(): number;
35
+ clear(): void;
36
+ }
@@ -0,0 +1 @@
1
+ export class VerdictCache{constructor(t=6e4){this.t=new Map,this.i=new Set,this.h=t}get(t){return this.t.get(t)}set(t,e,s){this.t.set(t,{...e,cachedAt:Date.now(),ttl:s??this.h})}update(t,e){const s=this.t.get(t);s?(void 0!==e.isFlagged&&(s.isFlagged=e.isFlagged),void 0!==e.isVerified&&(s.isVerified=e.isVerified),s.cachedAt=Date.now()):this.t.set(t,{isFlagged:e.isFlagged??!1,isVerified:e.isVerified??!1,emailAddress:"",sessionId:"",cachedAt:Date.now(),ttl:this.h})}delete(t){this.t.delete(t),this.i.delete(t)}isStale(t){const e=this.t.get(t);return!!e&&Date.now()-e.cachedAt>e.ttl}isRefreshing(t){return this.i.has(t)}markRefreshing(t){this.i.add(t)}clearRefreshing(t){this.i.delete(t)}get size(){return this.t.size}clear(){this.t.clear(),this.i.clear()}}
@@ -0,0 +1,73 @@
1
+ import type { Request, Response, NextFunction, Application } from 'express';
2
+ import type { UnsharedLabsClient } from './client';
3
+ export interface MiddlewareOptions {
4
+ /** Override userId extractor. Falls back to req.body.user_id. */
5
+ userIdExtractor?: (req: Request) => string | undefined;
6
+ /** Override eventType extractor. Falls back to req.body.event_type. */
7
+ eventTypeExtractor?: (req: Request) => string | undefined;
8
+ /** Override sessionId extractor. Falls back to X-Session-Id header, then req.body.session_id. */
9
+ sessionIdExtractor?: (req: Request) => string | undefined;
10
+ /** Override IP address extractor. Falls back to req.ip. */
11
+ ipAddressExtractor?: (req: Request) => string | undefined;
12
+ /** Default event type when none is extractable. @default "browser_event" */
13
+ defaultEventType?: string;
14
+ /**
15
+ * Route prefix the middleware is mounted under.
16
+ * @default "/unshared"
17
+ */
18
+ routePrefix?: string;
19
+ /**
20
+ * Allowed CORS origins for the fingerprint route.
21
+ * Use `"*"` to allow all origins, or pass a specific origin / array of origins.
22
+ * The middleware handles OPTIONS preflight automatically when this is set.
23
+ * @example corsOrigins: "https://app.example.com"
24
+ * @example corsOrigins: ["https://app.example.com", "https://staging.example.com"]
25
+ */
26
+ corsOrigins?: string | string[];
27
+ }
28
+ /**
29
+ * Asserts that Express `trust proxy` is configured on the app.
30
+ * Call this once during application startup, before mounting any middleware.
31
+ *
32
+ * Throws synchronously if the setting is missing, killing the process before
33
+ * any requests are served.
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * assertTrustProxy(app); // throws at startup if not set
38
+ * app.use(express.json());
39
+ * app.use(createUnsharedMiddleware(client, options));
40
+ * ```
41
+ */
42
+ export declare function assertTrustProxy(app: Application): void;
43
+ /**
44
+ * Creates an Express middleware that proxies browser fingerprint events to
45
+ * Unshared Labs. Mount this to handle the browser fingerprint route contract (§4 of spec).
46
+ *
47
+ * Handles POST <routePrefix>/submit-fingerprint-event.
48
+ * Passes all other requests to next().
49
+ *
50
+ * **Prerequisites:**
51
+ * - Mount `express.json()` (or equivalent body-parser) **before** this middleware,
52
+ * otherwise `req.body` will be undefined and every request will return 400.
53
+ * - For cross-origin frontends, pass `corsOrigins` instead of configuring CORS
54
+ * separately — the middleware handles OPTIONS preflight automatically.
55
+ * - `user_id` is automatically scrubbed from `req.body` after it is read, so
56
+ * downstream logging middleware will not capture plaintext PII.
57
+ *
58
+ * **Error contract:** Never returns 5xx to the browser. Upstream failures are
59
+ * returned as HTTP 200 with { success: false, error: { code: "UPSTREAM_ERROR" } }.
60
+ * Standard HTTP-level monitoring will not surface proxy errors — monitor the
61
+ * rate of `success: false` responses in your application layer instead.
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * import { createUnsharedMiddleware } from "@unshared-labs/sdk/middleware";
66
+ *
67
+ * app.use(express.json()); // must come first
68
+ * app.use(createUnsharedMiddleware(client, {
69
+ * userIdExtractor: (req) => req.user?.id,
70
+ * }));
71
+ * ```
72
+ */
73
+ export declare function createUnsharedMiddleware(client: UnsharedLabsClient, options?: MiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
@@ -0,0 +1 @@
1
+ export function assertTrustProxy(e){if(!e.get("trust proxy"))throw new Error('[unshared-labs] Express "trust proxy" is not set. Add `app.set("trust proxy", 1)` before calling assertTrustProxy, otherwise req.ip will reflect the proxy\'s IP instead of the real client IP.')}export function createUnsharedMiddleware(e,r){const{userIdExtractor:s,eventTypeExtractor:t,sessionIdExtractor:o,ipAddressExtractor:i,defaultEventType:n="browser_event",routePrefix:c="/unshared",corsOrigins:d}=r??{},a=`${c}/submit-fingerprint-event`,l=d?Array.isArray(d)?d:[d]:null;let u=!1;return async(r,c,d)=>{if(!u&&(u=!0,r.app&&!r.app.get("trust proxy")))throw new Error('[unshared-labs] Express "trust proxy" is not set. Add `app.set("trust proxy", 1)` before mounting this middleware, otherwise req.ip will reflect the proxy\'s IP instead of the real client IP.');if(l&&r.path===a){const e=r.headers.origin??"",s=l.includes("*");if((s||l.includes(e))&&(c.setHeader("Access-Control-Allow-Origin",s?"*":e),c.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),c.setHeader("Access-Control-Allow-Headers","Content-Type, X-Idempotency-Key, X-Session-Id")),"OPTIONS"===r.method)return void c.status(204).end()}if("POST"===r.method&&r.path===a)try{const d=r.body??{};if(!d.hash||!d.stable_hash||!d.collected_at)return void c.status(400).json({success:!1,error:{code:"VALIDATION_ERROR",message:"Missing required fingerprint fields: hash, stable_hash, collected_at"}});if(!r.headers["x-session-id"])return void c.status(400).json({success:!1,error:{code:"VALIDATION_ERROR",message:"Missing required header: X-Session-Id"}});const a={full_hash:d.hash,fingerprint_id:d.stable_hash,timestamp:d.collected_at,isIncognito:d.is_incognito??!1,components:d.components??{},version:d.version??"unknown"};let l,u,p,f;try{l=(s?s(r):void 0)??d.user_id}catch{l=d.user_id}if(r.body&&"object"==typeof r.body&&"user_id"in r.body&&delete r.body.user_id,!l)return void c.status(400).json({success:!1,error:{code:"VALIDATION_ERROR",message:"Missing required field: user_id"}});try{u=(t?t(r):void 0)??d.event_type??n}catch{u=d.event_type??n}try{p=(o?o(r):void 0)??r.headers["x-session-id"]?.toString()??d.session_id}catch{p=r.headers["x-session-id"]?.toString()??d.session_id}try{f=(i?i(r):void 0)??r.ip}catch{f=r.ip}const h=await e.submitFingerprintEvent(a,{userId:l,sessionHash:p,eventType:u,ipAddress:f});if(!h.success)return void c.status(200).json({success:!1,error:{code:"UPSTREAM_ERROR",message:h.error?.message??"Upstream request failed"}});c.status(202).json({success:!0,data:h.data})}catch(e){c.status(200).json({success:!1,error:{code:"MIDDLEWARE_ERROR",message:e instanceof Error?e.message:"Middleware error"}})}else d()}}
@@ -0,0 +1 @@
1
+ export declare function encryptData(data: string, key: Buffer): string;
@@ -0,0 +1 @@
1
+ import{createCipheriv,randomBytes}from"crypto";export function encryptData(e,t){const r=randomBytes(12),a=createCipheriv("aes-256-gcm",t,r);let o=a.update(e,"utf8","base64");o+=a.final("base64");const s=a.getAuthTag();return r.toString("base64")+":"+s.toString("base64")+":"+o}
@@ -0,0 +1,6 @@
1
+ export { UnsharedLabsClient } from './client';
2
+ export { createUnsharedMiddleware, assertTrustProxy } from './middleware';
3
+ export type { MiddlewareOptions } from './middleware';
4
+ export { unsharedBoundToUser, VerdictCache, } from './middleware/index';
5
+ export type { ProtectionConfig, Verdict } from './middleware/index';
6
+ export type { UnsharedLabsClientConfig, ApiResult, UnsharedLabsError, SubmitFingerprintOptions, SubmitFingerprintResult, ProcessUserEventParams, ProcessUserEventResult, CheckUserResult, TriggerEmailVerificationResult, VerifyResult, VerificationFlowStep, VerificationFlowConfigResult, } from './client';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"t",{value:!0}),exports.VerdictCache=exports.unsharedBoundToUser=exports.assertTrustProxy=exports.createUnsharedMiddleware=exports.UnsharedLabsClient=void 0;var client_1=require("./client");Object.defineProperty(exports,"UnsharedLabsClient",{enumerable:!0,get:function(){return client_1.UnsharedLabsClient}});var middleware_1=require("./middleware");Object.defineProperty(exports,"createUnsharedMiddleware",{enumerable:!0,get:function(){return middleware_1.createUnsharedMiddleware}}),Object.defineProperty(exports,"assertTrustProxy",{enumerable:!0,get:function(){return middleware_1.assertTrustProxy}});var index_1=require("./middleware/index");Object.defineProperty(exports,"unsharedBoundToUser",{enumerable:!0,get:function(){return index_1.unsharedBoundToUser}}),Object.defineProperty(exports,"VerdictCache",{enumerable:!0,get:function(){return index_1.VerdictCache}});