unshared-clientjs-sdk 2.3.0 → 3.0.0-rc.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +349 -152
- package/dist/client.d.ts +54 -25
- package/dist/client.js +1 -1
- package/dist/esm/client.d.mts +54 -25
- package/dist/esm/client.mjs +1 -1
- package/dist/esm/index.d.mts +8 -8
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/middleware/dispatch-processing.d.mts +11 -5
- package/dist/esm/middleware/dispatch-processing.mjs +1 -1
- package/dist/esm/middleware/index.d.mts +10 -6
- package/dist/esm/middleware/index.mjs +1 -1
- package/dist/esm/middleware/injection/fingerprint-script.d.mts +9 -0
- package/dist/esm/middleware/injection/fingerprint-script.mjs +1 -1
- package/dist/esm/middleware/injection/fp-bundle-source.d.mts +5 -4
- package/dist/esm/middleware/injection/fp-bundle-source.mjs +1 -1
- package/dist/esm/middleware/response-interceptor.d.mts +1 -1
- package/dist/esm/middleware/routes/interstitial.d.mts +2 -2
- package/dist/esm/middleware/routes/interstitial.mjs +1 -1
- package/dist/esm/middleware/routes/submit-fp.d.mts +5 -5
- package/dist/esm/middleware/routes/submit-fp.mjs +1 -1
- package/dist/esm/middleware/routes/verify.d.mts +5 -4
- package/dist/esm/middleware/routes/verify.mjs +1 -1
- package/dist/esm/middleware/utils/client-ip.d.mts +1 -1
- package/dist/esm/middleware/utils/cookies.d.mts +1 -1
- package/dist/esm/middleware/utils/device-id.d.mts +5 -3
- package/dist/esm/middleware/utils/device-id.mjs +1 -1
- package/dist/esm/middleware/utils/flagged-response.mjs +1 -1
- package/dist/esm/middleware/utils/http-helpers.d.mts +1 -1
- package/dist/esm/middleware/utils/permanent-device-id.d.mts +7 -0
- package/dist/esm/middleware/utils/permanent-device-id.mjs +1 -0
- package/dist/esm/middleware/utils/read-json-body.d.mts +3 -0
- package/dist/esm/middleware/utils/read-json-body.mjs +1 -0
- package/dist/esm/middleware/utils/secure.d.mts +1 -1
- package/dist/esm/middleware.d.mts +5 -6
- package/dist/esm/middleware.mjs +1 -1
- package/dist/esm/shared-types.d.mts +148 -0
- package/dist/esm/web/index.d.mts +6 -6
- package/dist/esm/web/index.mjs +1 -1
- package/dist/esm/web/protection-handler.d.mts +5 -5
- package/dist/esm/web/protection-handler.mjs +1 -1
- package/dist/esm/web/submit-handler.d.mts +2 -2
- package/dist/esm/web/submit-handler.mjs +1 -1
- package/dist/esm/web/types.d.mts +5 -3
- package/dist/esm/web/web-helpers.d.mts +13 -1
- package/dist/esm/web/web-helpers.mjs +1 -1
- package/dist/middleware/dispatch-processing.d.ts +8 -2
- package/dist/middleware/dispatch-processing.js +1 -1
- package/dist/middleware/index.d.ts +5 -1
- package/dist/middleware/index.js +1 -1
- package/dist/middleware/injection/fingerprint-script.d.ts +9 -0
- package/dist/middleware/injection/fingerprint-script.js +1 -1
- package/dist/middleware/injection/fp-bundle-source.d.ts +5 -4
- package/dist/middleware/injection/fp-bundle-source.js +1 -1
- package/dist/middleware/routes/submit-fp.js +1 -1
- package/dist/middleware/routes/verify.d.ts +2 -1
- package/dist/middleware/routes/verify.js +1 -1
- package/dist/middleware/utils/device-id.d.ts +4 -2
- package/dist/middleware/utils/device-id.js +1 -1
- package/dist/middleware/utils/permanent-device-id.d.ts +7 -0
- package/dist/middleware/utils/permanent-device-id.js +1 -0
- package/dist/middleware/utils/read-json-body.d.ts +3 -0
- package/dist/middleware/utils/read-json-body.js +1 -0
- package/dist/middleware.d.ts +3 -4
- package/dist/middleware.js +1 -1
- package/dist/shared-types.d.ts +148 -0
- package/dist/web/protection-handler.d.ts +1 -1
- package/dist/web/protection-handler.js +1 -1
- package/dist/web/submit-handler.js +1 -1
- package/dist/web/types.d.ts +4 -2
- package/dist/web/web-helpers.d.ts +13 -1
- package/dist/web/web-helpers.js +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
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{createFingerprintBundleSource}from"./injection/fp-bundle-source";import{handleSubmitFingerprint}from"./routes/submit-fp";import{handleVerifyTrigger,handleVerify}from"./routes/verify";import{handleGetInterstitialFlow}from"./routes/interstitial";import{generateGatePage}from"./injection/gate-page";import{runProcessUserEvent,DISPATCH_TIMEOUT_MS}from"./dispatch-processing";import{sendJson,sendEmpty,sendBodyForMethod,getRequestPath}from"./utils/http-helpers";import{isHtmlContentType,isHtmlNavigation}from"./utils/content-type";import{flaggedResponse}from"./utils/flagged-response";import{maskEmail}from"./utils/mask-email";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};export{flaggedResponse,ACCOUNT_FLAGGED_ERROR}from"./utils/flagged-response";const CHECK_USER_TIMEOUT_MS=1500,FAIL_OPEN_TTL_MS=5e3,_lastFailOpenWarn={};function warnFailOpenThrottled(e){const t=Date.now();t-(_lastFailOpenWarn[e.reason]??0)<6e4||(_lastFailOpenWarn[e.reason]=t,console.warn(`[Unshared] Failing open (reason=${e.reason}${null!=e.status?`, status=${e.status}`:""}). Detection is not enforced for this request. Configure onFailOpen to observe this directly.`))}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,maxCacheSize:a,streamingIdleMs:d=50,skipPaths:c,includePathPrefix:l,disableBotFilter:u=!1,checkUserTimeoutMs:p=CHECK_USER_TIMEOUT_MS,cacheMissStrategy:f="block",sessionId:m,deviceId:h,onFlagged:g,onError:I,onFailOpen:S,blockFlagged:v=!1,flaggedMode:_,autoInterstitial:C=!1,interstitialFlowType:y="email_verification"}=t,k=_??(v?"gate":void 0),T=C||"overlay"===k,A=e=>{if(S)try{S(e)}catch{}else"async_miss"!==e.reason&&warnFailOpenThrottled(e)},E=new VerdictCache(s,a),F=new RateLimitBackoff,U=new Map,x=new DispatchDedupe,w=Date.now().toString(36),O=generateFingerprintScript(n,w,{autoInterstitial:T,interstitialFlowType:y});let M="";try{const e=require.resolve("unshared-frontend-sdk/dist/index.umd.js");M=readFileSync(e,"utf8")}catch{}const P=createFingerprintBundleSource(),b=void 0!==k||T,D="gate"===k?"flaggedMode 'gate' (blockFlagged)":"overlay"===k?"flaggedMode 'overlay'":"autoInterstitial";if(b&&!M)throw new Error(`[Unshared] ${D} requires unshared-frontend-sdk to be installed (its UMD bundle renders the interstitial).`);if(b&&"/__unshared"!==n)throw new Error(`[Unshared] ${D} requires the default routePrefix ("/__unshared"); the browser SDK proxy routes are fixed to that prefix.`);const R="gate"===k?generateGatePage(n,w):"",N=handleSubmitFingerprint({client:e,verdictCache:E,rateLimitBackoff:F,dispatchDedupe:x,resolveUserId:r,resolveEmailAddress:i,resolveSessionId:m,resolveDeviceId:h,disableBotFilter:u,onError:I}),$=handleVerifyTrigger({client:e,verdictCache:E,resolveEmailAddress:i,resolveDeviceId:h,onError:I}),V=handleVerify({client:e,verdictCache:E,resolveUserId:r,resolveEmailAddress:i,resolveDeviceId:h,onError:I}),L=handleGetInterstitialFlow({client:e}),j=o?Array.isArray(o)?o:[o]:null,H=`${n}/fp.js`,B=`${n}/fingerprint.js`,q=`${n}/submit-fp`,G=`${n}/verify-trigger`,J=`${n}/verify`,K=`${n}/status`,X=`${n}/interstitial-flow`,W=function(t,o,s){const a=getRequestPath(t.url),S=t.url||a;if(a.startsWith(n+"/")){if(function(e,t){if(!j)return;const r=e.headers.origin??"";j.includes("*")?(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, X-Idempotency-Key, X-Session-Id, X-Device-Id")):j.includes(r)&&(t.setHeader("Access-Control-Allow-Origin",r),t.setHeader("Vary","Origin"),t.setHeader("Access-Control-Allow-Methods","GET, 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||"HEAD"===t.method)&&a===H)return o.setHeader("Content-Type","application/javascript"),o.setHeader("Cache-Control","public, max-age=3600"),void sendBodyForMethod(o,t.method,200,M);if(("GET"===t.method||"HEAD"===t.method)&&a===B){const e=P.get();return e?(o.setHeader("Content-Type","application/javascript"),o.setHeader("Cache-Control","public, max-age=3600"),void sendBodyForMethod(o,t.method,200,e)):void sendBodyForMethod(o,t.method,503,"/* fingerprint agent unavailable */")}if("POST"===t.method&&(a===q||a===G||a===J))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."}}):a===q?void N(t,o):a===G?void $(t,o):void V(t,o);if("GET"===t.method&&a===X)return void L(t,o);if("GET"===t.method&&a===K){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=E.get(n);if((!r||E.isStale(n))&&s&&!F.isPaused()&&!E.isRefreshing(n)){E.markRefreshing(n);try{const i=extractDeviceIdOrUndefined(t,h),o=extractFingerprintId(t),a=extractSessionId(t,m),d=i??o??"unknown";await fetchAndCacheVerdict(e,E,n,s,d,o,a,p,(e,t)=>A({operation:"checkUser",reason:e,status:t,userId:n,emailAddress:s})),r=E.get(n)}catch(e){I&&I(e,{operation:"checkUser",userId:n,emailAddress:s}),A({operation:"checkUser",reason:"exception",userId:n,emailAddress:s})}finally{E.clearRefreshing(n)}}r&&r.isFlagged&&!r.isVerified&&(void 0!==k||g)&&s?sendJson(o,200,{status:"flagged",email:maskEmail(s)}):sendJson(o,200,{status:"ok"})})()}return void sendJson(o,404,{success:!1,error:{code:"NOT_FOUND",message:"Unknown route"}})}if(shouldSkipPath(a,c,void 0!==k))return void s();if(!shouldIncludePath(a,l))return interceptForInjection(t,o,O,d),void s();let v;try{v=r(t)}catch{}if(isSentinelUserId(v)){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;v=e&&n?e:void 0}if(!v){const e=isSecureRequest(t)?"; Secure":"";return appendSetCookie(o,`__unshared_uid=; Path=/; SameSite=Lax; Max-Age=0${e}`),appendSetCookie(o,`__unshared_uid_at=; Path=/; SameSite=Lax; Max-Age=0${e}`),appendSetCookie(o,`__unshared_sid=; Path=/; SameSite=Lax; Max-Age=0${e}`),appendSetCookie(o,`__unshared_email=; Path=/; SameSite=Lax; Max-Age=0${e}`),interceptForInjection(t,o,O,d),void s()}const _=resolveEmail(t,i);if(setUserIdCookie(t,o,v),_&&setEmailCookie(t,o,_),!_)return interceptForInjection(t,o,O,d),void s();const C=extractSessionId(t,m),y=extractDeviceIdOrUndefined(t,h),T=extractFingerprintId(t),w=t.headers["user-agent"]??"",b=extractClientIp(t),D=y??T;if(!u&&isBot(w))return void s();const W=E.get(v);if(!W){if("async"===f)return E.isRefreshing(v)||(E.markRefreshing(v),fetchAndCacheVerdict(e,E,v,_,D??"unknown",T,C,p,(e,t)=>A({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:_})).catch(()=>A({operation:"checkUser",reason:"exception",userId:v,emailAddress:_})).finally(()=>E.clearRefreshing(v))),A({operation:"checkUser",reason:"async_miss",userId:v,emailAddress:_}),z(),interceptForInjection(t,o,O,d),void s();let r=U.get(v);return r||(r=fetchAndCacheVerdict(e,E,v,_,D??"unknown",T,C,p,(e,t)=>A({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:_})).finally(()=>U.delete(v)),U.set(v,r)),void r.then(e=>{e.isFlagged||z(),applyVerdict(e,v,_,t,o,s,O,g,k,R,d)}).catch(()=>{A({operation:"checkUser",reason:"exception",userId:v,emailAddress:_}),z(),interceptForInjection(t,o,O,d),s()})}function z(){"unknown"!==C&&D&&(F.isPaused()||dispatchUserEvent(e,E,F,x,{userId:v,emailAddress:_,sessionId:C,deviceId:D,fingerprintId:T,userAgent:w,ipAddress:b,eventType:S},I))}E.isStale(v)&&!E.isRefreshing(v)&&(E.markRefreshing(v),fetchAndCacheVerdict(e,E,v,_,D??"unknown",T,C,p,(e,t)=>A({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:_})).catch(()=>A({operation:"checkUser",reason:"exception",userId:v,emailAddress:_})).finally(()=>E.clearRefreshing(v))),W.isFlagged||z(),applyVerdict(W,v,_,t,o,s,O,g,k,R,d)};return W.destroy=()=>{E.destroy(),P.stop()},W}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,a,d,c,l){const u=e.isFlagged&&!e.isVerified;if("gate"===d&&u)isHtmlNavigation(i.method,i.headers.accept)?(n.statusCode=200,n.setHeader("Content-Type","text/html; charset=utf-8"),n.setHeader("Cache-Control","no-store"),n.end(c)):sendJson(n,403,flaggedResponse(r));else if("overlay"===d&&u)isHtmlNavigation(i.method,i.headers.accept)?(interceptForInjection(i,n,s,l),o()):sendJson(n,403,flaggedResponse(r));else if(interceptForInjection(i,n,s,l),e.isFlagged&&!e.isVerified&&a)try{a({userId:t,emailAddress:r,verdict:e,req:i,res:n,next:o})}catch{o()}else o()}function interceptForInjection(e,t,r,i){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,streamingIdleMs:i})}function dispatchUserEvent(e,t,r,i,n,o){i.mark(n.userId,n.eventType),runProcessUserEvent({client:e,cache:t,backoff:r,onError:o},{eventType:n.eventType,userId:n.userId,emailAddress:n.emailAddress,ipAddress:n.ipAddress,deviceId:n.deviceId,fingerprintId:n.fingerprintId,sessionHash:n.sessionId,userAgent:n.userAgent},DISPATCH_TIMEOUT_MS)}async function fetchAndCacheVerdict(e,t,r,i,n,o,s,a=CHECK_USER_TIMEOUT_MS,d){const c={timeoutMs:a,maxRetries:0},l=n&&"unknown"!==n?n:void 0,u=l??o,p=o??l;let f;u&&(c.deviceId=u),p&&(c.fingerprintId=p);const m=await Promise.race([e.checkUser(i,c),new Promise(e=>{f=setTimeout(()=>e(null),a)})]);return clearTimeout(f),m?m.failedOpen?(d?.(m.failedOpen.reason??"http_error",m.failedOpen.status),cacheFailOpenVerdict(t,r,i,s)):(t.set(r,{isFlagged:m.data?.is_user_flagged??!1,isVerified:!1,emailAddress:i,sessionId:s}),t.get(r)):(d?.("timeout"),cacheFailOpenVerdict(t,r,i,s))}function cacheFailOpenVerdict(e,t,r,i){const n=e.get(t);return e.set(t,{isFlagged:n?.isFlagged??!1,isVerified:n?.isVerified??!1,emailAddress:r,sessionId:i},5e3),e.get(t)}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
|
+
import{readFileSync}from"fs";import{readJsonBody}from"./utils/read-json-body.mjs";import{VerdictCache}from"./verdict-cache.mjs";import{RateLimitBackoff}from"./rate-limit-backoff.mjs";import{DispatchDedupe}from"./dispatch-dedupe.mjs";import{interceptResponse}from"./response-interceptor.mjs";import{generateFingerprintScript}from"./injection/fingerprint-script.mjs";import{createFingerprintBundleSource}from"./injection/fp-bundle-source.mjs";import{handleSubmitFingerprint}from"./routes/submit-fp.mjs";import{handleVerifyTrigger,handleVerify}from"./routes/verify.mjs";import{handleGetInterstitialFlow}from"./routes/interstitial.mjs";import{generateGatePage}from"./injection/gate-page.mjs";import{runProcessUserEvent,DISPATCH_TIMEOUT_MS}from"./dispatch-processing.mjs";import{sendJson,sendEmpty,sendBodyForMethod,getRequestPath}from"./utils/http-helpers.mjs";import{isHtmlContentType,isHtmlNavigation}from"./utils/content-type.mjs";import{flaggedResponse}from"./utils/flagged-response.mjs";import{maskEmail}from"./utils/mask-email.mjs";import{shouldSkipPath}from"./utils/skip-paths.mjs";import{shouldIncludePath}from"./utils/include-path.mjs";import{isBot}from"./utils/is-bot.mjs";import{extractClientIp}from"./utils/client-ip.mjs";import{parseCookie}from"./utils/cookies.mjs";import{extractDeviceIdOrUndefined}from"./utils/device-id.mjs";import{extractPermanentDeviceId}from"./utils/permanent-device-id.mjs";import{isSecureRequest}from"./utils/secure.mjs";import{isSentinelUserId,SENTINEL_STICKINESS_TTL_MS}from"./utils/sentinel-user-id.mjs";export{VerdictCache};export{flaggedResponse,ACCOUNT_FLAGGED_ERROR}from"./utils/flagged-response.mjs";const CHECK_USER_TIMEOUT_MS=1500,FAIL_OPEN_TTL_MS=5e3,_lastFailOpenWarn={};function warnFailOpenThrottled(e){const t=Date.now();t-(_lastFailOpenWarn[e.reason]??0)<6e4||(_lastFailOpenWarn[e.reason]=t,console.warn(`[Unshared] Failing open (reason=${e.reason}${null!=e.status?`, status=${e.status}`:""}). Detection is not enforced for this request. Configure onFailOpen to observe this directly.`))}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:s,cacheTTL:o=6e4,maxCacheSize:a,streamingIdleMs:d=50,skipPaths:c,includePathPrefix:l,disableBotFilter:u=!1,checkUserTimeoutMs:p=CHECK_USER_TIMEOUT_MS,cacheMissStrategy:m="block",sessionId:f,deviceId:h,onFlagged:g,onError:I,onFailOpen:_,blockFlagged:v=!1,flaggedMode:S,autoInterstitial:C=!1,interstitialFlowType:y="email_verification"}=t,k=S??(v?"gate":void 0),A=C||"overlay"===k,T=e=>{if(_)try{_(e)}catch{}else"async_miss"!==e.reason&&warnFailOpenThrottled(e)},E=new VerdictCache(o,a),x=new RateLimitBackoff,F=new Map,U=new DispatchDedupe,j=Date.now().toString(36),P=generateFingerprintScript(n,j,{autoInterstitial:A,interstitialFlowType:y,debug:t.debug,disableBotFilter:t.disableBotFilter});let M="";try{const e=require.resolve("unshared-frontend-sdk/dist/index.umd.js");M=readFileSync(e,"utf8")}catch{}const O=createFingerprintBundleSource({disabled:t.disableS3Fingerprint}),w=void 0!==k||A,D="gate"===k?"flaggedMode 'gate' (blockFlagged)":"overlay"===k?"flaggedMode 'overlay'":"autoInterstitial";if(w&&!M)throw new Error(`[Unshared] ${D} requires unshared-frontend-sdk to be installed (its UMD bundle renders the interstitial).`);if(w&&"/__unshared"!==n)throw new Error(`[Unshared] ${D} requires the default routePrefix ("/__unshared"); the browser SDK proxy routes are fixed to that prefix.`);const b="gate"===k?generateGatePage(n,j):"",R=handleSubmitFingerprint({client:e,verdictCache:E,rateLimitBackoff:x,dispatchDedupe:U,resolveUserId:r,resolveEmailAddress:i,resolveSessionId:f,resolveDeviceId:h,disableBotFilter:u,onError:I}),H=handleVerifyTrigger({client:e,verdictCache:E,resolveEmailAddress:i,resolveDeviceId:h,resolveSessionId:f,onError:I}),$=handleVerify({client:e,verdictCache:E,resolveUserId:r,resolveEmailAddress:i,resolveDeviceId:h,resolveSessionId:f,onError:I}),N=handleGetInterstitialFlow({client:e}),V=s?Array.isArray(s)?s:[s]:null,L=`${n}/fp.js`,B=`${n}/fingerprint.js`,q=`${n}/submit-fp`,G=`${n}/verify-trigger`,X=`${n}/verify`,J=`${n}/status`,K=`${n}/interstitial-flow`,W=function(t,s,o){const a=getRequestPath(t.url),_=t.url||a;if(a.startsWith(n+"/")){if(function(e,t){if(!V)return;const r=e.headers.origin??"";V.includes("*")?(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, X-Idempotency-Key, X-Session-Id, X-Device-Id, X-Permanent-Device-Id"),t.setHeader("Access-Control-Expose-Headers","X-Unshared-Enforcement-Reconciled")):V.includes(r)&&(t.setHeader("Access-Control-Allow-Origin",r),t.setHeader("Vary","Origin"),t.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, X-Idempotency-Key, X-Session-Id, X-Device-Id, X-Permanent-Device-Id"),t.setHeader("Access-Control-Expose-Headers","X-Unshared-Enforcement-Reconciled"),t.setHeader("Access-Control-Allow-Credentials","true"))}(t,s),"OPTIONS"===t.method)return void sendEmpty(s,204);if(("GET"===t.method||"HEAD"===t.method)&&a===L)return s.setHeader("Content-Type","application/javascript"),M?(s.setHeader("Cache-Control","public, max-age=3600"),void sendBodyForMethod(s,t.method,200,M)):(s.setHeader("Cache-Control","no-store"),void sendBodyForMethod(s,t.method,503,"/* fingerprint SDK unavailable */"));if(("GET"===t.method||"HEAD"===t.method)&&a===B)return void O.get().then(e=>{if(!e)return s.setHeader("Cache-Control","no-store"),void sendBodyForMethod(s,t.method,503,"/* fingerprint agent unavailable */");s.setHeader("Content-Type","application/javascript"),s.setHeader("Cache-Control","public, max-age=3600"),sendBodyForMethod(s,t.method,200,e)});if("POST"===t.method&&(a===q||a===G||a===X))return void readJsonBody(t,s).then(e=>{if(e)return a===q?R(t,s):a===G?H(t,s):$(t,s)}).catch(o);if("GET"===t.method&&a===K)return void N(t,s);if("GET"===t.method&&a===J){let n;try{n=r(t)}catch{}if(!n)return void sendJson(s,200,{status:"anonymous"});const o=resolveEmail(t,i);return void(async()=>{let r=E.get(n);if((!r||E.isStale(n))&&o&&!x.isPaused()&&!E.isRefreshing(n)){E.markRefreshing(n);try{const i=extractDeviceIdOrUndefined(t,h),s=extractFingerprintId(t),a=extractFullHash(t),d=extractPermanentDeviceId(t),c=extractSessionId(t,f);await fetchAndCacheVerdict(e,E,n,o,i,s,a,d,c,p,(e,t)=>T({operation:"checkUser",reason:e,status:t,userId:n,emailAddress:o})),r=E.get(n)}catch(e){I&&I(e,{operation:"checkUser",userId:n,emailAddress:o}),T({operation:"checkUser",reason:"exception",userId:n,emailAddress:o})}finally{E.clearRefreshing(n)}}r&&r.isFlagged&&!r.isVerified&&(void 0!==k||g)&&o?sendJson(s,200,{status:"flagged",email:maskEmail(o)}):sendJson(s,200,{status:"ok"})})()}return void sendJson(s,404,{success:!1,error:{code:"NOT_FOUND",message:"Unknown route"}})}if(shouldSkipPath(a,c,void 0!==k))return void o();let v;try{v=r(t)}catch{}if(isSentinelUserId(v)){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;v=e&&n?e:void 0}if(!v){const e=isSecureRequest(t)?"; Secure":"";return appendSetCookie(s,`__unshared_uid=; Path=/; SameSite=Lax; Max-Age=0${e}`),appendSetCookie(s,`__unshared_uid_at=; Path=/; SameSite=Lax; Max-Age=0${e}`),appendSetCookie(s,`__unshared_sid=; Path=/; SameSite=Lax; Max-Age=0${e}`),appendSetCookie(s,`__unshared_email=; Path=/; SameSite=Lax; Max-Age=0${e}`),appendSetCookie(s,`__unshared_verification_id=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0${e}`),interceptForInjection(t,s,P,d),void o()}const S=resolveEmail(t,i);if(setUserIdCookie(t,s,v),S&&setEmailCookie(t,s,S),!shouldIncludePath(a,l))return interceptForInjection(t,s,P,d),void o();if(!S)return interceptForInjection(t,s,P,d),void o();const C=extractSessionId(t,f),y=extractDeviceIdOrUndefined(t,h),A=extractFingerprintId(t),j=extractFullHash(t),w=extractPermanentDeviceId(t),D=t.headers["user-agent"]??"",W=extractClientIp(t);if(!u&&isBot(D))return void o();const z=E.get(v);if(!z){if("async"===m)return E.isRefreshing(v)||(E.markRefreshing(v),fetchAndCacheVerdict(e,E,v,S,y,A,j,w,C,p,(e,t)=>T({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:S})).catch(()=>T({operation:"checkUser",reason:"exception",userId:v,emailAddress:S})).finally(()=>E.clearRefreshing(v))),T({operation:"checkUser",reason:"async_miss",userId:v,emailAddress:S}),Q(),interceptForInjection(t,s,P,d),void o();let r=F.get(v);return r||(r=fetchAndCacheVerdict(e,E,v,S,y,A,j,w,C,p,(e,t)=>T({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:S})).finally(()=>F.delete(v)),F.set(v,r)),void r.then(e=>{e.isFlagged||Q(),applyVerdict(e,v,S,t,s,o,P,g,k,b,d)}).catch(()=>{T({operation:"checkUser",reason:"exception",userId:v,emailAddress:S}),Q(),interceptForInjection(t,s,P,d),o()})}function Q(){C&&"unknown"!==C&&(x.isPaused()||dispatchUserEvent(e,E,x,U,{userId:v,emailAddress:S,sessionId:C,deviceId:y,fingerprintId:A,fullHash:j,permanentDeviceId:w,userAgent:D,ipAddress:W,eventType:_},I))}E.isStale(v)&&!E.isRefreshing(v)&&(E.markRefreshing(v),fetchAndCacheVerdict(e,E,v,S,y,A,j,w,C,p,(e,t)=>T({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:S})).catch(()=>T({operation:"checkUser",reason:"exception",userId:v,emailAddress:S})).finally(()=>E.clearRefreshing(v))),z.isFlagged||Q(),applyVerdict(z,v,S,t,s,o,P,g,k,b,d)};return W.destroy=()=>{E.destroy(),O.stop()},W}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,s,o,a,d,c,l){const u=e.isFlagged&&!e.isVerified;if("gate"===d&&u)isHtmlNavigation(i.method,i.headers.accept)?(n.statusCode=200,n.setHeader("Content-Type","text/html; charset=utf-8"),n.setHeader("Cache-Control","no-store"),n.end(c)):sendJson(n,403,flaggedResponse(r));else if("overlay"===d&&u)isHtmlNavigation(i.method,i.headers.accept)?(interceptForInjection(i,n,o,l),s()):sendJson(n,403,flaggedResponse(r));else if(interceptForInjection(i,n,o,l),e.isFlagged&&!e.isVerified&&a)try{a({userId:t,emailAddress:r,verdict:e,req:i,res:n,next:s})}catch{s()}else s()}function interceptForInjection(e,t,r,i){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,streamingIdleMs:i})}function dispatchUserEvent(e,t,r,i,n,s){i.mark(n.userId,n.eventType),runProcessUserEvent({client:e,cache:t,backoff:r,onError:s},{eventType:n.eventType,userId:n.userId,emailAddress:n.emailAddress,ipAddress:n.ipAddress,deviceId:n.deviceId,fingerprintId:n.fingerprintId,fullHash:n.fullHash,permanentDeviceId:n.permanentDeviceId,sessionHash:n.sessionId,userAgent:n.userAgent},DISPATCH_TIMEOUT_MS)}async function fetchAndCacheVerdict(e,t,r,i,n,s,o,a,d,c=CHECK_USER_TIMEOUT_MS,l){const u={timeoutMs:c,maxRetries:0};let p;n&&"unknown"!==n&&(u.deviceId=n),s&&"unknown"!==s&&(u.fingerprintId=s),o&&"unknown"!==o&&(u.fullHash=o),a&&(u.permanentDeviceId=a),d&&"unknown"!==d&&(u.sessionHash=d);const m=await Promise.race([e.checkUser(i,u),new Promise(e=>{p=setTimeout(()=>e(null),c)})]);return clearTimeout(p),m?m.failedOpen?(l?.(m.failedOpen.reason??"http_error",m.failedOpen.status),cacheFailOpenVerdict(t,r,i,d)):(t.set(r,{isFlagged:m.data?.is_user_flagged??!1,isVerified:!1,emailAddress:i,sessionId:d}),t.get(r)):(l?.("timeout"),cacheFailOpenVerdict(t,r,i,d))}function cacheFailOpenVerdict(e,t,r,i){const n=e.get(t);return e.set(t,{isFlagged:n?.isFlagged??!1,isVerified:n?.isVerified??!1,emailAddress:r,sessionId:i},5e3),e.get(t)}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_stable_hash")||parseCookie(e,"__unshared_fp_id")||void 0}function extractFullHash(e){return parseCookie(e,"__unshared_full_hash")||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; Max-Age=31536000${i}`),appendSetCookie(t,`__unshared_uid_at=${Date.now()}; Path=/; SameSite=Lax; Max-Age=31536000${i}`)}function setEmailCookie(e,t,r){const i=isSecureRequest(e)?"; Secure":"";appendSetCookie(t,`__unshared_email=${encodeURIComponent(r)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=31536000${i}`)}
|
|
@@ -12,8 +12,17 @@
|
|
|
12
12
|
* window.addEventListener("unshared:flagged", (e) => {
|
|
13
13
|
* e.detail.email — the flagged user's email (from 403 response body)
|
|
14
14
|
* });
|
|
15
|
+
*
|
|
16
|
+
* Sticky-signal contract (ordering-proof alternative to the event): the signal
|
|
17
|
+
* is also recorded on the shared namespace, so listeners that attach AFTER the
|
|
18
|
+
* CustomEvent fired (late hydration, app crash-and-remount) can recover it:
|
|
19
|
+
* window.__unshared.flagged — { email } once flagged, else undefined
|
|
20
|
+
* window.__unshared.whenFlagged(cb) — subscribes cb AND replays immediately
|
|
21
|
+
* if the signal already fired
|
|
15
22
|
*/
|
|
16
23
|
export declare function generateFingerprintScript(routePrefix: string, version?: string, opts?: {
|
|
17
24
|
autoInterstitial?: boolean;
|
|
18
25
|
interstitialFlowType?: string;
|
|
26
|
+
debug?: boolean;
|
|
27
|
+
disableBotFilter?: boolean;
|
|
19
28
|
}): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function generateFingerprintScript(e,t,n){const r=t?`?v=${escapeJavaScript(t)}`:"",s=n?.autoInterstitial?`\nvar _isdk=new UnsharedBrowser.UnsharedBrowser({baseUrl:""});\nwindow.addEventListener("unshared:flagged",function(){try{_isdk.showInterstitial({flowType:"${escapeJavaScript(n?.interstitialFlowType??"email_verification")}",onComplete:function(){try{location.reload()}catch(e){}}})}catch(e){}});`:"";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// Page-scoped dedup state SHARED with the frontend SDK (browser.ts getSharedDedup).\n// On a Tier 1 page both this inline script and the SDK submit; each holds its own\n// in-memory lastSubmitKey, so both could pass the check below and POST. window.__unshared\n// is read+written synchronously in submitFP (no await between), so whichever fires\n// first claims the uid|route key and the other no-ops — killing the read-before-write\n// race that doubled events. KEEP IN SYNC with browser.ts: namespace, lastKey, key formula.\nvar shared=(window.__unshared=window.__unshared||{});\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"+(location.protocol==="https:"?"; Secure":"")}\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 // Check the shared window guard AND the in-memory key (last-key semantics, so an\n // SPA A->B->A revisit still submits the second A). The shared guard makes this\n // submitter and the frontend SDK see each other within the page.\n if(key===lastSubmitKey||shared.lastKey===key)return;\n shared.lastKey=key;\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,source:fp.source,session_id:sid,user_id:uid,event_type:route};\n // Idempotency key derived from (stable_hash, user_id, route), SHA-256-hashed\n // when WebCrypto is available so the user_id never appears in the platform's\n // stored idempotency_key column (raw fallback on non-secure contexts — the\n // middleware accepts both). NOTE: the middleware appends |Date.now() before\n // forwarding (submit-fp.ts), so the backend sees a unique value per\n // submission and dedups only PubSub redeliveries — NOT two distinct POSTs.\n // Cross-submitter / cross-reload dedup is client-side (the shared window\n // guard + sessionStorage above).\n var idem=fp.fingerprint_id+"|"+uid+"|"+route;\n function sendFP(idemKey){\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",idemKey);\n xhr.send(JSON.stringify(body));\n }\n if(window.crypto&&crypto.subtle&&window.TextEncoder){\n crypto.subtle.digest("SHA-256",new TextEncoder().encode(idem)).then(function(d){\n var a=new Uint8Array(d),s="";\n for(var i=0;i<a.length;i++){s+=("0"+a[i].toString(16)).slice(-2)}\n sendFP(s);\n }).catch(function(){sendFP(idem)});\n }else{sendFP(idem)}\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 UnsharedBrowser.UnsharedBrowser({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${r}";\ns.onload=function(){fpReady=true;${s}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 JSON.stringify(e).slice(1,-1).replace(/<\/(script)/gi,"<\\/$1").replace(new RegExp("\u2028","g"),"\\u2028").replace(new RegExp("\u2029","g"),"\\u2029")}
|
|
1
|
+
export function generateFingerprintScript(e,n,t){const r=n?`?v=${escapeJavaScript(n)}`:"",i=t?.autoInterstitial?`\nvar _isdk=new UnsharedBrowser.UnsharedBrowser({baseUrl:""});\nvar _isdkShow=function(){try{_isdk.showInterstitial({flowType:"${escapeJavaScript(t?.interstitialFlowType??"email_verification")}",onComplete:function(){try{location.reload()}catch(e){}}})}catch(e){}};\nwindow.addEventListener("unshared:flagged",_isdkShow);\nif(shared.flagged){_isdkShow()}`:"";return`<script>\n(function(){\nvar debug=${!0===t?.debug},shared;\n// Diagnostics are bounded and contain only reason codes and HTTP status, never user data.\nfunction decision(code,status){\n if(!debug)return;\n var d={code:code};if(typeof status==="number")d.status=status;\n try{var prev=shared.lastDecision;shared.lastDecision=d;if(prev&&prev.code===code&&prev.status===status)return}catch(e){}\n try{if(window.console&&typeof window.console.debug==="function")window.console.debug("[Unshared]",d)}catch(e){}\n}\ntry{\nshared=(window.__unshared=window.__unshared||{});\n// --- Bot drop (defense-in-depth) ---\n// Initialize diagnostics first, but do not write cookies, localStorage,\n// session IDs, or make 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(!${!0===t?.disableBotFilter}&&typeof navigator!=="undefined"&&navigator.userAgent&&BOT_RE.test(navigator.userAgent)){decision("BOT_SKIPPED");return}\n\nvar pfx="${escapeJavaScript(e)}";\nvar SS_FP="__unshared_fp";\nvar SS_FP_RAW="__unshared_fp_raw";\nvar SS_LAST_SUBMIT="__unshared_last_submit";\nvar CAPTURE_SESSION_KEYS=["__unshared_email","__unshared_last_submit","__unshared_verification_id"];\nvar MAX_REQUEST_BYTES=102400;\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).\ntry{if(!shared.generation&&shared.lastKey===undefined)shared.lastKey=sessionStorage.getItem(SS_LAST_SUBMIT)||undefined}catch(e){}\n\n// Page-scoped dedup state SHARED with the frontend SDK (browser.ts getSharedDedup).\n// On a Tier 1 page both this inline script and the SDK submit. window.__unshared\n// is read+written synchronously in submitFP (no await between), so whichever fires\n// first claims the uid|route key and the other no-ops — killing the read-before-write\n// race that doubled events. KEEP IN SYNC with browser.ts: namespace, lastKey, key formula.\n// Sticky flagged signal: emitFlagged() records shared.flagged and drains\n// shared.flaggedCbs, so listeners that attach AFTER the CustomEvent fired\n// (late hydration, fp.js still loading) can recover it via whenFlagged().\n// KEEP IN SYNC with browser.ts getSharedDedup: flagged, flaggedCbs, whenFlagged.\nshared.whenFlagged=shared.whenFlagged||function(cb){(shared.flaggedCbs=shared.flaggedCbs||[]).push(cb);if(shared.flagged){try{cb(shared.flagged)}catch(e){}}};\n\n// --- Helpers ---\nfunction gC(n){try{var m=document.cookie.match(new RegExp("(?:^|; )"+n+"=([^;]*)"));return m?decodeURIComponent(m[1]):null}catch(e){return null}}\nfunction sC(n,v,d){try{var dt=new Date();dt.setTime(dt.getTime()+d*864e5);document.cookie=n+"="+encodeURIComponent(v)+"; Max-Age="+(d*86400)+"; expires="+dt.toUTCString()+"; path=/; SameSite=Lax"+(location.protocol==="https:"?"; Secure":"")}catch(e){}}\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)}))}\nfunction validPid(v){return typeof v==="string"&&/^upid_[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v)}\nfunction bLen(v){return typeof TextEncoder!=="undefined"?new TextEncoder().encode(v).length:encodeURIComponent(v).replace(/%[0-9A-F]{2}/g,"x").length}\nfunction cCookies(){try{return document.cookie.split(";").map(function(v){return v.trim()}).filter(Boolean).map(function(v){var i=v.indexOf("="),n=i<0?v:v.slice(0,i),r=i<0?"":v.slice(i+1),d=r;try{d=decodeURIComponent(r)}catch(e){}return{name:n,value:d}}).sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0})}catch(e){return[]}}\nfunction cStorage(s,keys){try{var out=[];for(var i=0;i<keys.length;i++){var v=s.getItem(keys[i]);if(v!==null)out.push({name:keys[i],value:v})}return out.sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0})}catch(e){return[]}}\nfunction browserStorage(){var l=[],s=[];try{l=cStorage(localStorage,["__unshared_device_id"])}catch(e){}try{s=cStorage(sessionStorage,CAPTURE_SESSION_KEYS)}catch(e){}return{cookies:cCookies(),local_storage:l,session_storage:s}}\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// Permanent identity is independent of the collected stable hash. Keep an\n// in-memory fallback so blocked storage does not regenerate it on every route.\nvar sid=gC("__unshared_sid");\nvar did="",pid="";\n\n// --- Fingerprint cache (sessionStorage) ---\n// Old normalized-only caches cannot recover overwritten raw fields; recollect them.\n// Public page-memory fields match browser.ts and must not be property-mangled.\nfunction validFP(fp){return fp&&fp.wire&&typeof fp.wire.fingerprint_id==="string"&&typeof fp.wire.full_hash==="string"&&fp.raw&&typeof fp.raw==="object"&&!Array.isArray(fp.raw)}\nfunction getFP(){if(validFP(shared.collection))return shared.collection;if(shared.collectionPromise||shared.generation)return null;try{var w=sessionStorage.getItem(SS_FP),r=sessionStorage.getItem(SS_FP_RAW),fp=w&&r?{wire:JSON.parse(w),raw:JSON.parse(r)}:null;if(validFP(fp))return shared.collection=fp;return null}catch(e){return null}}\nfunction setFP(collected){shared.collection=collected;try{sessionStorage.removeItem(SS_FP_RAW);sessionStorage.setItem(SS_FP,JSON.stringify(collected.wire));sessionStorage.setItem(SS_FP_RAW,JSON.stringify(collected.raw))}catch(e){}}\n\n// --- Submit fingerprint to backend ---\nfunction submitFP(collected){\n var generation=shared.generation||0;\n var fp=collected.wire;\n var uid=gC("__unshared_uid");\n if(!uid){decision("MISSING_UID");return}\n if(isSentinelUid(uid)){decision("SENTINEL_UID");return}\n var storedPid="";try{storedPid=localStorage.getItem("__unshared_device_id")||""}catch(e){}\n var cookiePid=gC("__unshared_device_id");\n if(validPid(storedPid)){pid=storedPid}else if(validPid(cookiePid)){pid=cookiePid}else if(!validPid(pid)){pid="upid_"+uuid()}\n try{localStorage.setItem("__unshared_device_id",pid)}catch(e){}\n // Renew correlation cookies on eligible activity, even when submission dedups.\n sid=shared.sessionId||gC("__unshared_sid")||sid||uuid();shared.sessionId=sid;sC("__unshared_sid",sid,400);\n sC("__unshared_device_id",pid,400);\n if(fp.fingerprint_id){\n did=fp.fingerprint_id;\n sC("__unshared_fp_id",did,400);\n sC("__unshared_stable_hash",fp.fingerprint_id,400);\n }\n if(fp.full_hash)sC("__unshared_full_hash",fp.full_hash,400);\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 // Check the shared window guard (last-key semantics, so an\n // SPA A->B->A revisit still submits the second A). The shared guard makes this\n // submitter and the frontend SDK see each other within the page.\n if(shared.lastKey===key){decision("DEDUP_SKIPPED");return}\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={fingerprint:collected.raw,context:{sdk:{name:"unshared-inline-sdk",version:"3.0.0",agent_source:fp.source||"unknown"},identity:{user_id:uid},identifiers:{unshared_device_id:pid,device_id:did,stable_hash:fp.fingerprint_id||"",full_hash:fp.full_hash||"",session_hash:sid},browser_storage:browserStorage(),event:{type:route,collected_at:(new Date()).toISOString()}}};\n var payload=JSON.stringify(body);\n // Keep in sync with the structured browser builder: full, cookies only, core only.\n if(bLen(payload)>MAX_REQUEST_BYTES){body.context.browser_storage.local_storage=[];body.context.browser_storage.session_storage=[];payload=JSON.stringify(body);}\n if(bLen(payload)>MAX_REQUEST_BYTES){delete body.context.browser_storage;payload=JSON.stringify(body);}\n if(bLen(payload)>MAX_REQUEST_BYTES){decision("REQUEST_TOO_LARGE");try{if(window.console&&window.console.warn)window.console.warn("[Unshared] REQUEST_TOO_LARGE: Request body exceeds 100 KiB")}catch(e){}return;}\n shared.lastKey=key;\n try{sessionStorage.setItem(SS_LAST_SUBMIT,key)}catch(e){}\n // Idempotency key derived from (stable_hash, user_id, route), SHA-256-hashed\n // when WebCrypto is available so the user_id never appears in the platform's\n // stored idempotency_key column (raw fallback on non-secure contexts — the\n // middleware accepts both). NOTE: the middleware appends |Date.now() before\n // forwarding (submit-fp.ts), so the backend sees a unique value per\n // submission and dedups only PubSub redeliveries — NOT two distinct POSTs.\n // Cross-submitter / cross-reload dedup is client-side (the shared window\n // guard + sessionStorage above).\n var idem=fp.fingerprint_id+"|"+uid+"|"+route;\n function sendFP(idemKey){\n if(generation!==(shared.generation||0))return;\n try{\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 if(pid)xhr.setRequestHeader("X-Permanent-Device-Id",pid);\n xhr.setRequestHeader("X-Idempotency-Key",idemKey);\n xhr.addEventListener("load",function(){\n if(xhr.status<200||xhr.status>=300){decision("SUBMIT_HTTP_ERROR",xhr.status);return}\n var b;try{b=JSON.parse(xhr.responseText)}catch(e){decision("SUBMIT_INVALID_RESPONSE",xhr.status);return}\n if(b&&(b.success===false||b.accepted===false||(b.data&&(b.data.accepted===false||b.data.skipped===true)))){decision("SUBMIT_REJECTED",xhr.status);return}\n decision(b&&b.success===true&&b.data&&typeof b.data.event_id==="string"&&typeof b.data.collected_at==="string"&&b.data.endpoint_version==="v3"?"SUBMIT_SUCCESS":"SUBMIT_INVALID_RESPONSE",xhr.status);\n });\n xhr.addEventListener("error",function(){decision("SUBMIT_NETWORK_ERROR")});\n xhr.addEventListener("abort",function(){decision("SUBMIT_ABORTED")});\n xhr.addEventListener("timeout",function(){decision("SUBMIT_TIMEOUT")});\n decision("SUBMIT_STARTED");\n xhr.send(payload);\n }catch(e){decision("SUBMIT_FAILED")}\n }\n if(window.crypto&&crypto.subtle&&window.TextEncoder){\n crypto.subtle.digest("SHA-256",new TextEncoder().encode(idem)).then(function(d){\n var a=new Uint8Array(d),s="";\n for(var i=0;i<a.length;i++){s+=("0"+a[i].toString(16)).slice(-2)}\n sendFP(s);\n }).catch(function(){sendFP(idem)});\n }else{sendFP(idem)}\n}\n\n// --- Collect fingerprint (loads fp.js if needed) then submit ---\nvar fpReady=false;\nfunction collectAndSubmit(){\n var generation=shared.generation||0;\n var uid=gC("__unshared_uid");\n if(!uid){decision("MISSING_UID");return}\n if(isSentinelUid(uid)){decision("SENTINEL_UID");return}\n var cached=getFP();\n if(cached){submitFP(cached);return}\n try{\n var pending=shared.collectionPromise;\n if(!pending){\n if(!fpReady){decision("COLLECTOR_NOT_READY");return}\n var c=new UnsharedBrowser.UnsharedBrowser({baseUrl:""});\n decision("COLLECTION_STARTED");\n pending=c.collectWithMetadata({exclude:["timing","speech"]}).then(function(fp){\n if(generation!==(shared.generation||0)||shared.collectionPromise!==pending)throw new Error("Collection cancelled");\n if(!validFP(fp))throw new Error("Invalid collection");\n setFP(fp);return fp;\n });\n shared.collectionPromise=pending;\n var clear=function(){if(shared.collectionPromise===pending)delete shared.collectionPromise};\n pending.then(clear,clear);\n }\n pending.then(function(fp){if(generation===(shared.generation||0))submitFP(fp)}).catch(function(){if(generation===(shared.generation||0))decision("COLLECTION_ERROR")});\n }catch(e){decision("COLLECTION_ERROR")}\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()}else{collectAndSubmit()}\nvar s=document.createElement("script");\ns.src=pfx+"/fp.js${r}";\ns.onload=function(){fpReady=true;try{${i}if(!pageLoadSubmitted){collectAndSubmit();deferredCheck()}}catch(e){decision("OUTER_EXCEPTION")}};\ns.onerror=function(){decision("ASSET_LOAD_ERROR")};\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){decision("OUTER_EXCEPTION")}};\nhistory.replaceState=function(){oReplace.apply(this,arguments);try{collectAndSubmit()}catch(e){decision("OUTER_EXCEPTION")}};\nwindow.addEventListener("popstate",function(){try{collectAndSubmit()}catch(e){decision("OUTER_EXCEPTION")}});\n\n// --- 403 interception: record sticky state + dispatch "unshared:flagged" ---\nfunction emitFlagged(body){\n var d={email:body.email||""};\n shared.flagged=d;\n var cbs=shared.flaggedCbs||[];\n for(var i=0;i<cbs.length;i++){try{cbs[i](d)}catch(e){}}\n try{window.dispatchEvent(new CustomEvent("unshared:flagged",{detail:d}))}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){decision("OUTER_EXCEPTION")}\n})();\n<\/script>`}function escapeJavaScript(e){return JSON.stringify(e).slice(1,-1).replace(/<\/(script)/gi,"<\\/$1").replace(new RegExp("\u2028","g"),"\\u2028").replace(new RegExp("\u2029","g"),"\\u2029")}
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
export declare const S3_FINGERPRINT_URL = "https://unshared-public.s3.us-east-2.amazonaws.com/fingerprint@1/fingerprint.umd.js";
|
|
2
2
|
export interface FingerprintBundleSource {
|
|
3
|
-
/**
|
|
4
|
-
get(): string
|
|
3
|
+
/** Wait for the initial bounded S3 attempt, then return the cached UMD or fallback. */
|
|
4
|
+
get(): Promise<string>;
|
|
5
5
|
/** Run one refresh cycle now (also called by the background timer). */
|
|
6
6
|
refresh(): Promise<void>;
|
|
7
7
|
/** Stop the background timer. */
|
|
8
8
|
stop(): void;
|
|
9
9
|
}
|
|
10
10
|
export interface FingerprintBundleSourceOptions {
|
|
11
|
+
/** @internal Disable all remote fetches and serve only the bundled fallback. */
|
|
12
|
+
disabled?: boolean;
|
|
11
13
|
url?: string;
|
|
12
14
|
intervalMs?: number;
|
|
13
15
|
fetchTimeoutMs?: number;
|
|
@@ -18,8 +20,7 @@ export interface FingerprintBundleSourceOptions {
|
|
|
18
20
|
/**
|
|
19
21
|
* Start the background refresh timer + immediate boot fetch.
|
|
20
22
|
* @default true in production, false under NODE_ENV==='test' (so unit tests
|
|
21
|
-
*
|
|
22
|
-
* fallback and drive `refresh()` with an injected fetch).
|
|
23
|
+
* drive `get()` / `refresh()` with an injected fetch).
|
|
23
24
|
*/
|
|
24
25
|
autoStart?: boolean;
|
|
25
26
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";export const S3_FINGERPRINT_URL="https://unshared-public.s3.us-east-2.amazonaws.com/fingerprint@1/fingerprint.umd.js";const DEFAULT_REFRESH_INTERVAL_MS=9e5,DEFAULT_FETCH_TIMEOUT_MS=
|
|
1
|
+
import{readFileSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";export const S3_FINGERPRINT_URL="https://unshared-public.s3.us-east-2.amazonaws.com/fingerprint@1/fingerprint.umd.js";const DEFAULT_REFRESH_INTERVAL_MS=9e5,DEFAULT_FETCH_TIMEOUT_MS=1e3;function defaultLoadFallback(){try{const e=createRequire(import.meta.url).resolve("unshared-frontend-sdk/package.json"),t=createRequire(e).resolve("unshared-fingerprint-lib"),r=join(dirname(t),"fingerprint.umd.js");return readFileSync(r,"utf8")}catch{return""}}export function createFingerprintBundleSource(e={}){const t=e.disabled??!1,r=e.url??S3_FINGERPRINT_URL,n=e.intervalMs??9e5,o=e.fetchTimeoutMs??1e3,i=e.fetchImpl??globalThis.fetch;let a,s,c,u,l=(e.loadFallback??defaultLoadFallback)();function f(){if(t)return Promise.resolve();if(u)return u;const e=new AbortController;let n;const s=new Promise(t=>{n=setTimeout(()=>{e.abort(),t()},o)});return u=Promise.race([(async()=>{try{if(!i)return;const t={};a&&(t["If-None-Match"]=a);const n=await i(r,{headers:t,signal:e.signal});if(304===n.status||!n.ok)return;const o=await n.text();o&&!e.signal.aborted&&(l=o,a=n.headers.get("etag")??void 0)}catch{}})(),s]).finally(()=>{clearTimeout(n),u=void 0}),c??(c=u),u}return(e.autoStart??"test"!==process.env.NODE_ENV)&&!t&&(f(),s=setInterval(()=>{f()},n),"function"==typeof s.unref&&s.unref()),{get:async()=>(await(c??f()),l),refresh:f,stop:()=>{s&&clearInterval(s),s=void 0}}}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { UnsharedRequest, UnsharedResponse } from '../../types';
|
|
2
|
-
import type { UnsharedClient } from '../../client';
|
|
1
|
+
import type { UnsharedRequest, UnsharedResponse } from '../../types.mjs';
|
|
2
|
+
import type { UnsharedClient } from '../../client.mjs';
|
|
3
3
|
export interface InterstitialDependencies {
|
|
4
4
|
client: UnsharedClient;
|
|
5
5
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sendJson}from"../utils/http-helpers";function isPublishedFlow(s){return!!s&&"object"==typeof s&&Object.keys(s).length>0}const FLOW_NOT_PUBLISHED={code:"FLOW_NOT_PUBLISHED",message:"No interstitial flow is published for this company."};export function handleGetInterstitialFlow(s){return async(e,o)=>{try{const t=e.url&&e.url.includes("?")?e.url.slice(e.url.indexOf("?")+1):"",r=new URLSearchParams(t),n=r.get("flow_type")||void 0,i=r.get("platform")||void 0,a=await s.client.getInterstitialFlow({flowType:n,platform:i});a.success?isPublishedFlow(a.data)?sendJson(o,200,{success:!0,data:a.data}):sendJson(o,200,{success:!1,error:{...FLOW_NOT_PUBLISHED}}):404===a.status?sendJson(o,200,{success:!1,error:{...FLOW_NOT_PUBLISHED}}):sendJson(o,200,{success:!1,error:a.error??{code:"FLOW_FETCH_FAILED",message:"Failed to load interstitial flow"}})}catch{sendJson(o,200,{success:!1,error:{code:"INTERNAL_ERROR",message:"Failed to load interstitial flow"}})}}}
|
|
1
|
+
import{sendJson}from"../utils/http-helpers.mjs";function isPublishedFlow(s){return!!s&&"object"==typeof s&&Object.keys(s).length>0}const FLOW_NOT_PUBLISHED={code:"FLOW_NOT_PUBLISHED",message:"No interstitial flow is published for this company."};export function handleGetInterstitialFlow(s){return async(e,o)=>{try{const t=e.url&&e.url.includes("?")?e.url.slice(e.url.indexOf("?")+1):"",r=new URLSearchParams(t),n=r.get("flow_type")||void 0,i=r.get("platform")||void 0,a=await s.client.getInterstitialFlow({flowType:n,platform:i});a.success?isPublishedFlow(a.data)?sendJson(o,200,{success:!0,data:a.data}):sendJson(o,200,{success:!1,error:{...FLOW_NOT_PUBLISHED}}):404===a.status?sendJson(o,200,{success:!1,error:{...FLOW_NOT_PUBLISHED}}):sendJson(o,200,{success:!1,error:a.error??{code:"FLOW_FETCH_FAILED",message:"Failed to load interstitial flow"}})}catch{sendJson(o,200,{success:!1,error:{code:"INTERNAL_ERROR",message:"Failed to load interstitial flow"}})}}}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import type { UnsharedRequest, UnsharedResponse } from '../../types';
|
|
2
|
-
import type { UnsharedClient } from '../../client';
|
|
3
|
-
import type { VerdictCache } from '../verdict-cache';
|
|
4
|
-
import type { RateLimitBackoff } from '../rate-limit-backoff';
|
|
5
|
-
import type { DispatchDedupe } from '../dispatch-dedupe';
|
|
1
|
+
import type { UnsharedRequest, UnsharedResponse } from '../../types.mjs';
|
|
2
|
+
import type { UnsharedClient } from '../../client.mjs';
|
|
3
|
+
import type { VerdictCache } from '../verdict-cache.mjs';
|
|
4
|
+
import type { RateLimitBackoff } from '../rate-limit-backoff.mjs';
|
|
5
|
+
import type { DispatchDedupe } from '../dispatch-dedupe.mjs';
|
|
6
6
|
export interface SubmitFingerprintDependencies<TReq extends UnsharedRequest = UnsharedRequest> {
|
|
7
7
|
client: UnsharedClient;
|
|
8
8
|
verdictCache: VerdictCache;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sha256Hex}from"../../util";import{isBot}from"../utils/is-bot";import{extractClientIp}from"../utils/client-ip";import{parseCookie}from"../utils/cookies";import{
|
|
1
|
+
import{sha256Hex}from"../../util.mjs";import{isBot}from"../utils/is-bot.mjs";import{extractClientIp}from"../utils/client-ip.mjs";import{parseCookie}from"../utils/cookies.mjs";import{isSecureRequest}from"../utils/secure.mjs";import{isSentinelUserId}from"../utils/sentinel-user-id.mjs";import{sendJson}from"../utils/http-helpers.mjs";import{resolveOrCreatePermanentDeviceId}from"../utils/permanent-device-id.mjs";import{runCheckUser,SUBMIT_FP_TIMEOUT_MS}from"../dispatch-processing.mjs";function asRecord(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}export function handleSubmitFingerprint(e){return async(t,s)=>{try{const i=asRecord(t.body),n=asRecord(i.fingerprint??i),o=asRecord(i.context),r=asRecord(o.identity),a=asRecord(o.identifiers),d=asRecord(o.event),c={...n,full_hash:n.hash??n.full_hash??"",fingerprint_id:n.stableHash??n.stable_hash??n.fingerprint_id??"",timestamp:n.timestamp??n.collected_at??(new Date).toISOString(),isIncognito:n.isIncognito??n.is_incognito??!1,components:n.components??{},version:n.version??"unknown",..."remote"===n.source||"bundled"===n.source?{source:n.source}:{}};let p,_,u;try{const s=e.resolveUserId?e.resolveUserId(t):void 0;s&&!isSentinelUserId(s)&&(p=s)}catch{}if(!p){const e="string"==typeof r.user_id?r.user_id:"string"==typeof i.user_id?i.user_id:void 0;e&&!isSentinelUserId(e)&&(p=e)}if(!p){const e=parseCookie(t,"__unshared_uid");e&&!isSentinelUserId(e)&&(p=e)}try{_=e.resolveEmailAddress?e.resolveEmailAddress(t):void 0}catch{}_=_??parseCookie(t,"__unshared_email")??r.email_address??i.email??void 0;try{u=e.resolveSessionId?e.resolveSessionId(t):void 0}catch{}u=u??a.session_hash??i.session_id??parseCookie(t,"__unshared_sid");const m=extractClientIp(t),f=t.headers["user-agent"]??"";if(!e.disableBotFilter&&isBot(f))return void sendJson(s,200,{success:!0,data:{skipped:!0}});let h;try{h=e.resolveDeviceId?.(t)}catch{}const l=[h,t.headers["x-device-id"],a.device_id,c.fingerprint_id,parseCookie(t,"__unshared_stable_hash"),parseCookie(t,"__unshared_fp_id")].find(e=>"string"==typeof e&&""!==e.trim()&&"unknown"!==e.trim()),y=c.fingerprint_id||void 0,g=c.full_hash||void 0,S=resolveOrCreatePermanentDeviceId(t,a.unshared_device_id??i.permanent_device_id),v=isSecureRequest(t)?"; Secure":"",C=[];C.push(`__unshared_device_id=${encodeURIComponent(S.id)}; Path=/; SameSite=Lax; Max-Age=34560000${v}`);const k=parseCookie(t,"__unshared_fingerprint_id")||g;if(k&&C.push(`__unshared_fingerprint_id=${encodeURIComponent(k)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=34560000${v}`),g&&C.push(`__unshared_full_hash=${encodeURIComponent(g)}; Path=/; SameSite=Lax; Max-Age=34560000${v}`),y&&(C.push(`__unshared_fp_id=${encodeURIComponent(y)}; Path=/; SameSite=Lax; Max-Age=34560000${v}`),C.push(`__unshared_stable_hash=${encodeURIComponent(y)}; Path=/; SameSite=Lax; Max-Age=34560000${v}`)),_&&C.push(`__unshared_email=${encodeURIComponent(_)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=31536000${v}`),C.length>0){const e=s.getHeader("Set-Cookie");if(e){const t=Array.isArray(e)?[...e]:[String(e)];t.push(...C),s.setHeader("Set-Cookie",t)}else s.setHeader("Set-Cookie",C)}let I;if("string"==typeof d.type&&d.type)I=d.type;else if("string"==typeof i.event_type&&i.event_type)I=i.event_type;else{const e=t.headers.referer??t.headers.referrer;let s="unknown";if("string"==typeof e&&e.length>0)try{const t=new URL(e);s=(t.pathname||"/")+(t.search||"")}catch{}I=s}const x=t.headers["x-idempotency-key"],R="string"==typeof x&&x.length>0?x:void 0,$=Date.now(),b=R?`${R}|${$}`:y&&p?`${sha256Hex(`${y}|${p}|${I}`)}|${$}`:void 0,j={...a,unshared_device_id:S.id,...l&&"unknown"!==l?{device_id:l}:{},...y?{stable_hash:y}:{},...g?{full_hash:g}:{},...u?{session_hash:u}:{}};l||delete j.device_id;const U="string"==typeof asRecord(o.sdk).name?asRecord(o.sdk).name:void 0,A="string"==typeof U&&U.startsWith("unshared-")&&Object.prototype.hasOwnProperty.call(i,"fingerprint")&&i.context&&"object"==typeof i.context&&!Array.isArray(i.context)&&o.identity&&"object"==typeof o.identity&&!Array.isArray(o.identity)&&o.identifiers&&"object"==typeof o.identifiers&&!Array.isArray(o.identifiers)&&o.event&&"object"==typeof o.event&&!Array.isArray(o.event),M=!Object.prototype.hasOwnProperty.call(i,"context")&&"string"==typeof i.hash&&"string"==typeof i.stable_hash&&"string"==typeof i.collected_at&&i.components&&"object"==typeof i.components&&!Array.isArray(i.components),P=A||M?{...i,fingerprint:n,context:{...o,sdk:asRecord(o.sdk),identity:{...r,...p?{user_id:p}:{},..._?{email_address:_}:{}},identifiers:j,event:{...d,type:I,ip_address:m,user_agent:f}}}:i,w=await e.client.submitFingerprint(P,{idempotencyKey:b});w.success||e.onError?.(w.error,{operation:"submitFingerprintEvent",userId:p,emailAddress:_}),p&&_&&!e.rateLimitBackoff.isPaused()&&!e.dispatchDedupe.wasRecentlyDispatched(p,I)&&await runCheckUser({client:e.client,cache:e.verdictCache,backoff:e.rateLimitBackoff,onError:e.onError},{user_id:p,email_address:_,identifiers:j},p,_,SUBMIT_FP_TIMEOUT_MS),w.success?sendJson(s,200,{success:!0,data:w.data}):sendJson(s,200,{success:!1,error:w.error})}catch(t){e.onError&&e.onError(t,{operation:"submitFingerprintEvent"}),sendJson(s,200,{success:!0,data:{accepted:!1}})}}}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import type { UnsharedRequest, UnsharedResponse } from '../../types';
|
|
2
|
-
import type { UnsharedClient } from '../../client';
|
|
3
|
-
import type { VerdictCache } from '../verdict-cache';
|
|
1
|
+
import type { UnsharedRequest, UnsharedResponse } from '../../types.mjs';
|
|
2
|
+
import type { UnsharedClient } from '../../client.mjs';
|
|
3
|
+
import type { VerdictCache } from '../verdict-cache.mjs';
|
|
4
4
|
export interface VerificationDependencies<TReq extends UnsharedRequest = UnsharedRequest> {
|
|
5
5
|
client: UnsharedClient;
|
|
6
6
|
verdictCache: VerdictCache;
|
|
7
7
|
resolveEmailAddress?: (req: TReq) => string | undefined;
|
|
8
8
|
resolveDeviceId?: (req: TReq) => string | undefined;
|
|
9
|
+
resolveSessionId?: (req: TReq) => string | undefined;
|
|
9
10
|
resolveUserId?: (req: TReq) => string | undefined;
|
|
10
11
|
onError?: (error: unknown, context: {
|
|
11
12
|
operation: 'processUserEvent' | 'submitFingerprintEvent' | 'checkUser' | 'verifyTrigger' | 'verify';
|
|
@@ -19,7 +20,7 @@ export interface VerificationDependencies<TReq extends UnsharedRequest = Unshare
|
|
|
19
20
|
*
|
|
20
21
|
* Body: { email: string }
|
|
21
22
|
*
|
|
22
|
-
*
|
|
23
|
+
* Device and hash identifiers are resolved from the same sources as enforcement.
|
|
23
24
|
*/
|
|
24
25
|
export declare function handleVerifyTrigger<TReq extends UnsharedRequest = UnsharedRequest>(dependencies: VerificationDependencies<TReq>): (req: TReq, res: UnsharedResponse) => Promise<void>;
|
|
25
26
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseCookie}from"../utils/cookies";import{
|
|
1
|
+
import{parseCookie}from"../utils/cookies.mjs";import{extractDeviceIdOrUndefined}from"../utils/device-id.mjs";import{sendJson}from"../utils/http-helpers.mjs";import{extractPermanentDeviceId}from"../utils/permanent-device-id.mjs";import{isSecureRequest}from"../utils/secure.mjs";const VERIFICATION_COOKIE="__unshared_verification_id";function appendCookie(e,s){const i=e.getHeader("Set-Cookie"),r=i?Array.isArray(i)?[...i]:[String(i)]:[];r.push(s),e.setHeader("Set-Cookie",r)}export function handleVerifyTrigger(e){return async(s,i)=>{try{const r=resolveEmail(s,s.body??{},e.resolveEmailAddress);if(!r)return void sendJson(i,400,{success:!1,error:{code:"VALIDATION_ERROR",message:"Email is required"}});const n=extractDeviceIdOrUndefined(s,e.resolveDeviceId),o=parseCookie(s,"__unshared_stable_hash")||parseCookie(s,"__unshared_fp_id")||void 0,a=parseCookie(s,"__unshared_full_hash")||parseCookie(s,"__unshared_fingerprint_id")||void 0,t=extractPermanentDeviceId(s),d=resolveSessionHash(s,e.resolveSessionId),c=await e.client.triggerEmailVerification(r,n&&"unknown"!==n?n:"",{fingerprintId:"unknown"!==o?o:void 0,fullHash:"unknown"!==a?a:void 0,permanentDeviceId:t,sessionHash:d});if(c.success){if(c.data?.verification_id){const e=isSecureRequest(s)?"; Secure":"";appendCookie(i,`${VERIFICATION_COOKIE}=${encodeURIComponent(c.data.verification_id)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=600${e}`)}sendJson(i,200,{success:!0,data:c.data})}else sendJson(i,200,{success:!1,error:c.error??{code:"TRIGGER_FAILED",message:"Failed to send verification email"}})}catch(s){e.onError&&e.onError(s,{operation:"verifyTrigger"}),sendJson(i,200,{success:!1,error:{code:"INTERNAL_ERROR",message:"Failed to trigger verification"}})}}}export function handleVerify(e){return async(s,i)=>{try{const r=(s.body??{}).code,n=parseCookie(s,VERIFICATION_COOKIE);if(!n||!r)return void sendJson(i,400,{success:!1,error:{code:"VALIDATION_ERROR",message:"Verification ID and code are required"}});const o=await e.client.verifyEmail({verification_id:n,code:r});if(o.success&&o.data?.verified){let r,n=!1;try{r=e.resolveUserId?.(s)}catch{}const a=resolveEmail(s,{},e.resolveEmailAddress),t=extractDeviceIdOrUndefined(s,e.resolveDeviceId),d=parseCookie(s,"__unshared_stable_hash")||parseCookie(s,"__unshared_fp_id")||void 0,c=parseCookie(s,"__unshared_full_hash")||parseCookie(s,"__unshared_fingerprint_id")||void 0,u=extractPermanentDeviceId(s),_=resolveSessionHash(s,e.resolveSessionId);if(r&&a){const s={...t&&"unknown"!==t?{device_id:t}:{},...d&&"unknown"!==d?{stable_hash:d}:{},...c&&"unknown"!==c?{full_hash:c}:{},...u?{unshared_device_id:u}:{},..._?{session_hash:_}:{}},i=await e.client.checkUser({user_id:r,email_address:a,identifiers:s},{maxRetries:0});i.success&&i.data&&!i.failedOpen&&!i.data.is_user_flagged&&(e.verdictCache.update(r,{isVerified:!0}),n=!0)}const f=isSecureRequest(s)?"; Secure":"";appendCookie(i,`${VERIFICATION_COOKIE}=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0${f}`),n&&i.setHeader("X-Unshared-Enforcement-Reconciled","clean"),sendJson(i,200,{success:!0,data:o.data})}else o.success?sendJson(i,200,{success:!0,data:o.data}):sendJson(i,200,{success:!1,error:o.error??{code:"VERIFICATION_FAILED",message:"Verification failed"}})}catch(s){e.onError&&e.onError(s,{operation:"verify"}),sendJson(i,200,{success:!1,error:{code:"INTERNAL_ERROR",message:"Verification failed"}})}}}function resolveSessionHash(e,s){let i;try{i=s?.(e)}catch{}return i=i||parseCookie(e,"__unshared_sid"),i&&"unknown"!==i?i:void 0}function resolveEmail(e,s,i){if(i)try{const s=i(e);if(s)return s}catch{}const r=parseCookie(e,"__unshared_email");if(r)return r;const n=s.email;return"string"==typeof n&&n?n:void 0}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { UnsharedRequest } from '../../types';
|
|
1
|
+
import type { UnsharedRequest } from '../../types.mjs';
|
|
2
2
|
/**
|
|
3
3
|
* Extract the real client IP from proxy headers, falling back to req.ip or socket address.
|
|
4
4
|
* Checked in order: CF-Connecting-IP (Cloudflare) → X-Real-IP (nginx/ALB) → req.ip → socket.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import type { UnsharedRequest } from '../../types';
|
|
1
|
+
import type { UnsharedRequest } from '../../types.mjs';
|
|
2
2
|
/**
|
|
3
|
-
* Resolves device ID from
|
|
3
|
+
* Resolves device ID from the custom resolver, X-Device-Id header, then the
|
|
4
|
+
* canonical __unshared_stable_hash cookie or legacy __unshared_fp_id cookie.
|
|
4
5
|
*
|
|
5
6
|
* Returns the literal string `"unknown"` when no source provides a value.
|
|
6
7
|
* Callers that can tolerate a tri-state should use `extractDeviceIdOrUndefined`
|
|
@@ -11,7 +12,8 @@ import type { UnsharedRequest } from '../../types';
|
|
|
11
12
|
*/
|
|
12
13
|
export declare function extractDeviceId<TReq extends UnsharedRequest = UnsharedRequest>(req: TReq, resolveDeviceId?: (req: TReq) => string | undefined): string;
|
|
13
14
|
/**
|
|
14
|
-
* Resolves device ID from
|
|
15
|
+
* Resolves device ID from the custom resolver, X-Device-Id header, then the
|
|
16
|
+
* canonical __unshared_stable_hash cookie or legacy __unshared_fp_id cookie.
|
|
15
17
|
* Returns `undefined` when nothing is available. Use this at any call site
|
|
16
18
|
* that can take a "skip dispatch" branch during the bootstrap window, so we
|
|
17
19
|
* stop writing `device_id="unknown"` rows to the analytics table on first request.
|
|
@@ -1 +1 @@
|
|
|
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}
|
|
1
|
+
import{parseCookie}from"./cookies.mjs";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_stable_hash")||parseCookie(e,"__unshared_fp_id")||void 0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{maskEmail}from"./mask-email";export const ACCOUNT_FLAGGED_ERROR="account_flagged";export function flaggedResponse(a){return{error:"account_flagged",email:maskEmail(a)}}
|
|
1
|
+
import{maskEmail}from"./mask-email.mjs";export const ACCOUNT_FLAGGED_ERROR="account_flagged";export function flaggedResponse(a){return{error:"account_flagged",email:maskEmail(a)}}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { UnsharedRequest } from '../../types.mjs';
|
|
2
|
+
export declare function isPermanentDeviceId(value: unknown): value is string;
|
|
3
|
+
export declare function extractPermanentDeviceId(req: UnsharedRequest): string | undefined;
|
|
4
|
+
export declare function resolveOrCreatePermanentDeviceId(req: UnsharedRequest, candidate?: unknown): {
|
|
5
|
+
id: string;
|
|
6
|
+
shouldSetCookie: boolean;
|
|
7
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID}from"crypto";import{parseCookie}from"./cookies.mjs";const PERMANENT_DEVICE_ID_PATTERN=/^upid_[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;export function isPermanentDeviceId(e){return"string"==typeof e&&PERMANENT_DEVICE_ID_PATTERN.test(e)}export function extractPermanentDeviceId(e){const i=parseCookie(e,"__unshared_device_id");if(isPermanentDeviceId(i))return i;const r=e.headers["x-permanent-device-id"];return isPermanentDeviceId(r)?r:void 0}export function resolveOrCreatePermanentDeviceId(e,i){const r=parseCookie(e,"__unshared_device_id");if(isPermanentDeviceId(r))return{id:r,shouldSetCookie:!1};const n=e.headers["x-permanent-device-id"];return{id:isPermanentDeviceId(n)?n:isPermanentDeviceId(i)?i:`upid_${randomUUID()}`,shouldSetCookie:!0}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sendJson}from"./http-helpers.mjs";const MAX_REQUEST_BYTES=1<<20;export async function readJsonBody(e,t){const o=e,r=(e,r,s)=>{if(!o.destroyed&&!o.readableEnded&&o.resume&&o.once&&o.removeListener&&o.destroy){const e=setTimeout(()=>o.destroy(),3e4);e.unref();const t=()=>{clearTimeout(e),o.removeListener("end",t),o.removeListener("close",t),o.removeListener("error",t)};o.once("end",t),o.once("close",t),o.once("error",t),o.resume()}return sendJson(t,e,{success:!1,error:{code:r,message:s}}),!1},s=()=>r(413,"REQUEST_TOO_LARGE","Request body exceeds 1 MiB");if(void 0!==e.body)try{return!(Buffer.byteLength(JSON.stringify(e.body),"utf8")>1048576)||s()}catch{return r(400,"INVALID_JSON","Request body is not valid JSON.")}return o.on&&o.removeListener&&o.pause?o.destroyed||o.readableEnded?r(400,"INVALID_JSON","Request body is unavailable or incomplete."):Number(e.headers["content-length"])>1048576?s():e.headers["content-encoding"]&&"identity"!==e.headers["content-encoding"]?r(415,"UNSUPPORTED_ENCODING","Request body must use identity encoding."):new Promise(t=>{const s=[];let d=0,n=!1;const u=(e,d,u)=>{n||(n=!0,clearTimeout(N),o.removeListener("data",a),o.removeListener("end",c),o.removeListener("aborted",i),o.removeListener("error",i),o.removeListener("close",i),s.length=0,t(!e||r(e,d,u)))},i=()=>u(400,"INVALID_JSON","Request body is unavailable or incomplete."),a=e=>{const t=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8");d+=t.length,d>1048576?u(413,"REQUEST_TOO_LARGE","Request body exceeds 1 MiB"):s.push(t)},c=()=>{try{e.body=JSON.parse(Buffer.concat(s,d).toString("utf8"))}catch{return void u(400,"INVALID_JSON","Request body is not valid JSON.")}u()},N=setTimeout(()=>u(408,"REQUEST_TIMEOUT","Timed out reading request body."),3e4);N.unref(),o.on("data",a),o.on("end",c),o.on("aborted",i),o.on("error",i),o.on("close",i)}):r(400,"BODY_PARSER_MISSING","Provide a readable Node request stream or a parsed JSON body.")}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { UnsharedRequest, UnsharedResponse, UnsharedNextFunction } from './types';
|
|
2
|
-
import type { UnsharedClient } from './client';
|
|
1
|
+
import type { UnsharedRequest, UnsharedResponse, UnsharedNextFunction } from './types.mjs';
|
|
2
|
+
import type { UnsharedClient } from './client.mjs';
|
|
3
3
|
export interface MiddlewareOptions<TReq extends UnsharedRequest = UnsharedRequest> {
|
|
4
4
|
/** Override userId extractor. Falls back to req.body.user_id. */
|
|
5
5
|
userIdExtractor?: (req: TReq) => string | undefined;
|
|
@@ -38,7 +38,6 @@ export interface MiddlewareOptions<TReq extends UnsharedRequest = UnsharedReques
|
|
|
38
38
|
* @example
|
|
39
39
|
* ```typescript
|
|
40
40
|
* assertTrustProxy(app); // throws at startup if not set
|
|
41
|
-
* app.use(express.json());
|
|
42
41
|
* app.use(createUnsharedMiddleware(client, options));
|
|
43
42
|
* ```
|
|
44
43
|
*/
|
|
@@ -51,8 +50,8 @@ export declare function assertTrustProxy(app: any): void;
|
|
|
51
50
|
* Passes all other requests to next().
|
|
52
51
|
*
|
|
53
52
|
* **Prerequisites:**
|
|
54
|
-
* -
|
|
55
|
-
*
|
|
53
|
+
* - Existing default JSON parser order is supported by the browser's 100 KiB
|
|
54
|
+
* proxy limit. Unparsed SDK routes are also read automatically up to 1 MiB.
|
|
56
55
|
* - For cross-origin frontends, pass `corsOrigins` instead of configuring CORS
|
|
57
56
|
* separately — the middleware handles OPTIONS preflight automatically.
|
|
58
57
|
* - `user_id` is automatically scrubbed from `req.body` after it is read, so
|
|
@@ -67,10 +66,10 @@ export declare function assertTrustProxy(app: any): void;
|
|
|
67
66
|
* ```typescript
|
|
68
67
|
* import { createUnsharedMiddleware } from "unshared-clientjs-sdk";
|
|
69
68
|
*
|
|
70
|
-
* app.use(express.json()); // must come first
|
|
71
69
|
* app.use(createUnsharedMiddleware(client, {
|
|
72
70
|
* userIdExtractor: (req) => req.user?.id,
|
|
73
71
|
* }));
|
|
72
|
+
* app.use(express.json()); // application routes keep their own default limit
|
|
74
73
|
* ```
|
|
75
74
|
*/
|
|
76
75
|
export declare function createUnsharedMiddleware<TReq extends UnsharedRequest = UnsharedRequest>(client: UnsharedClient, options?: MiddlewareOptions<TReq>): (req: TReq, res: UnsharedResponse, next: UnsharedNextFunction) => Promise<void>;
|
package/dist/esm/middleware.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sendJson,sendEmpty,getRequestPath}from"./middleware/utils/http-helpers";export function assertTrustProxy(e){if(!e?.get?.("trust proxy"))throw new Error('[unshared-labs] Express "trust proxy" is not set.\n\n Fix: add this line before mounting any middleware:\n app.set("trust proxy", 1);\n\n Why: without it, req.ip returns the proxy/load-balancer IP instead of\n the real client IP, which degrades account-sharing detection accuracy.\n Set to 1 if behind a single reverse proxy (Nginx, ALB, CloudFront),\n or the number of trusted proxies in your chain.')}export function createUnsharedMiddleware(e,
|
|
1
|
+
import{sendJson,sendEmpty,getRequestPath}from"./middleware/utils/http-helpers.mjs";import{readJsonBody}from"./middleware/utils/read-json-body.mjs";export function assertTrustProxy(e){if(!e?.get?.("trust proxy"))throw new Error('[unshared-labs] Express "trust proxy" is not set.\n\n Fix: add this line before mounting any middleware:\n app.set("trust proxy", 1);\n\n Why: without it, req.ip returns the proxy/load-balancer IP instead of\n the real client IP, which degrades account-sharing detection accuracy.\n Set to 1 if behind a single reverse proxy (Nginx, ALB, CloudFront),\n or the number of trusted proxies in your chain.')}export function createUnsharedMiddleware(e,t){const{userIdExtractor:r,eventTypeExtractor:o,sessionIdExtractor:s,ipAddressExtractor:n,defaultEventType:i="browser_event",routePrefix:c="/unshared",corsOrigins:d}=t??{},a=`${c}/submit-fingerprint-event`,y=d?Array.isArray(d)?d:[d]:null;return async(t,c,d)=>{const p=getRequestPath(t.url);if(y&&p===a){const e=t.headers.origin??"",r=y.includes("*");if((r||y.includes(e))&&(c.setHeader("Access-Control-Allow-Origin",r?"*":e),c.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),c.setHeader("Access-Control-Allow-Headers","Content-Type, X-Idempotency-Key, X-Session-Id, X-Permanent-Device-Id")),"OPTIONS"===t.method)return void sendEmpty(c,204)}if("POST"===t.method&&p===a)try{if(!await readJsonBody(t,c))return;const d=t.body??{};if(!d||"object"!=typeof d||Array.isArray(d))return void sendJson(c,400,{success:!1,error:{code:"VALIDATION_ERROR",message:"Request body must be a JSON object"}});const a=d.context&&"object"==typeof d.context?d.context:{},y=a.identity&&"object"==typeof a.identity?a.identity:{},p=a.identifiers&&"object"==typeof a.identifiers?a.identifiers:{},u=a.event&&"object"==typeof a.event?a.event:{};let f,l,h,b;try{f=(r?r(t):void 0)??y.user_id}catch{f=y.user_id}try{l=(o?o(t):void 0)??u.type??i}catch{l=u.type??i}try{h=(s?s(t):void 0)??t.headers["x-session-id"]?.toString()??p.session_hash}catch{h=t.headers["x-session-id"]?.toString()??p.session_hash}const m=t.ip??t.socket?.remoteAddress??"";try{b=(n?n(t):void 0)??m}catch{b=m}const x=t.headers["x-permanent-device-id"]?.toString()??p.unshared_device_id,A=a.sdk&&"object"==typeof a.sdk?a.sdk.name:void 0,g="string"==typeof A&&A.startsWith("unshared-")&&d.fingerprint&&"object"==typeof d.fingerprint&&d.context&&"object"==typeof d.context&&!Array.isArray(d.context)&&d.context.identity&&"object"==typeof d.context.identity&&!Array.isArray(d.context.identity)&&d.context.identifiers&&"object"==typeof d.context.identifiers&&!Array.isArray(d.context.identifiers)&&d.context.event&&"object"==typeof d.context.event&&!Array.isArray(d.context.event),j=!Object.prototype.hasOwnProperty.call(d,"context")&&"string"==typeof d.hash&&"string"==typeof d.stable_hash&&"string"==typeof d.collected_at&&d.components&&"object"==typeof d.components&&!Array.isArray(d.components),v=g||j?{...d,context:{...a,identity:{...y,...f?{user_id:f}:{}},identifiers:{...p,...h?{session_hash:h}:{},...x?{unshared_device_id:x}:{}},event:{...u,type:l,...b?{ip_address:b}:{},user_agent:t.headers["user-agent"]?.toString()??""}}}:d,E=await e.submitFingerprint(v,{idempotencyKey:t.headers["x-idempotency-key"]?.toString()});if(!E.success)return void sendJson(c,200,{success:!1,error:E.error??{code:"UPSTREAM_ERROR",message:"Upstream request failed"}});sendJson(c,202,{success:!0,data:E.data})}catch(e){sendJson(c,200,{success:!1,error:{code:"MIDDLEWARE_ERROR",message:e instanceof Error?e.message:"Middleware error"}})}else d()}}
|