unshared-clientjs-sdk 3.0.0-rc.15 → 3.0.1-rc.16
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 +13 -1
- package/dist/client.d.ts +3 -1
- package/dist/client.js +1 -1
- package/dist/esm/client.d.mts +3 -1
- package/dist/esm/client.mjs +1 -1
- package/dist/esm/index.d.mts +1 -0
- package/dist/esm/middleware/dispatch-processing.mjs +1 -1
- package/dist/esm/middleware/index.d.mts +7 -0
- package/dist/esm/middleware/index.mjs +1 -1
- package/dist/esm/middleware/injection/fingerprint-script.mjs +1 -1
- package/dist/esm/middleware/routes/verify.mjs +1 -1
- package/dist/esm/middleware/utils/flagged-response.d.mts +5 -1
- package/dist/esm/middleware/utils/flagged-response.mjs +1 -1
- package/dist/esm/middleware/verdict-cache.d.mts +7 -2
- package/dist/esm/middleware/verdict-cache.mjs +1 -1
- package/dist/esm/shared-types.d.mts +4 -0
- package/dist/esm/web/protection-handler.mjs +1 -1
- package/dist/esm/web/types.d.mts +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/middleware/dispatch-processing.js +1 -1
- package/dist/middleware/index.d.ts +7 -0
- package/dist/middleware/index.js +1 -1
- package/dist/middleware/injection/fingerprint-script.js +1 -1
- package/dist/middleware/routes/verify.js +1 -1
- package/dist/middleware/utils/flagged-response.d.ts +5 -1
- package/dist/middleware/utils/flagged-response.js +1 -1
- package/dist/middleware/verdict-cache.d.ts +7 -2
- package/dist/middleware/verdict-cache.js +1 -1
- package/dist/shared-types.d.ts +4 -0
- package/dist/web/protection-handler.js +1 -1
- package/dist/web/types.d.ts +2 -0
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ Node.js SDK for Unshared v3 ingestion, risk checks, email verification, and appl
|
|
|
8
8
|
npm install unshared-clientjs-sdk@^3
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
Requires Node.js 20 or newer.
|
|
11
|
+
Requires Node.js 20 or newer for v3 compatibility. For production, use the latest patched Node.js 24 LTS release (or a newer supported LTS). Node.js 20 is end-of-life and no longer receives community security fixes; see the [Node.js release schedule](https://nodejs.org/en/about/previous-releases).
|
|
12
12
|
|
|
13
13
|
```typescript
|
|
14
14
|
import { UnsharedClient } from 'unshared-clientjs-sdk';
|
|
@@ -94,6 +94,16 @@ await client.checkUser({
|
|
|
94
94
|
|
|
95
95
|
`checkUser` is read-only and can retry. On transport or HTTP failure it deliberately returns a clean verdict with `failedOpen` metadata so an outage does not accidentally block users.
|
|
96
96
|
|
|
97
|
+
### Per-user enforcement
|
|
98
|
+
|
|
99
|
+
V3 checks can return `enforcement_type: 'no_enforcement' | 'soft_block' | 'hard_block'` alongside the existing boolean. The SDK sends `X-Unshared-Enforcement-Version: 1` automatically; older backend responses remain valid (`true` retains soft behavior). The legacy `processUserEvent(...).analysis` also carries the optional field.
|
|
100
|
+
|
|
101
|
+
Keep your existing `unsharedBoundToUser` integration and enable `flaggedMode: 'gate'` (or `blockFlagged: true`) on protected pages **and data routes**. Soft blocks keep the verification flow. Hard blocks return HTTP 403 for HTML and data before the protected handler runs, even in overlay mode; successful OTP does not bypass them. `account_flagged` responses and `unshared:flagged` event details include the optional enforcement type. Monitoring/custom-handler integrations retain control of their response.
|
|
102
|
+
|
|
103
|
+
Set `hardBlockPage` to trusted standalone HTML to present your own contact-support modal on hard-blocked navigations. The SDK still returns HTTP 403 with `Cache-Control: no-store`, withholds the protected handler, and leaves JSON errors unchanged. Keep this document free of protected content and verification controls. This option customizes server HTML only; custom frontend flagged handlers should navigate to a protected page or show their own contact modal when `enforcement_type` is `hard_block`.
|
|
104
|
+
|
|
105
|
+
Use `cacheMissStrategy: 'block'` to check the first uncached request. Existing fail-open, cache expiry, and stale-while-revalidate behavior remains; this feature is not durable fail-closed authorization. Known cached hard decisions survive failed refreshes. See the [Aced.io upgrade guide](../../../clients/exponent/docs/aced-v3-hard-block-integration.md) for route coverage and rollout requirements, and the [backend contract](../../../docs/backend-hard-block-v3-prompt.md) for capability negotiation.
|
|
106
|
+
|
|
97
107
|
### Email Verification
|
|
98
108
|
|
|
99
109
|
Trigger returns a challenge ID that Verify must send back:
|
|
@@ -221,6 +231,7 @@ Resolvers receive your Node/Express request (`TReq`). The `@internal`
|
|
|
221
231
|
| `deviceId` | Header/cookie fallback | Resolver, then `X-Device-Id`, then `__unshared_stable_hash`, then legacy `__unshared_fp_id`. Missing values are omitted, not fabricated or replaced with the full hash. Client-provided identifiers are correlation signals, not authentication. |
|
|
222
232
|
| `onFlagged` | Unset (pass through) | Receives `{ userId, emailAddress, verdict, req, res, next }` for flagged, unverified users. Own the response or call `next()`; exceptions pass through. Ignored by gate/overlay. |
|
|
223
233
|
| `blockFlagged` | `false` | Shorthand for gate mode when `flaggedMode` is unset. Requires installed `unshared-frontend-sdk` and the default prefix. |
|
|
234
|
+
| `hardBlockPage` | Built-in access-denied page | Trusted standalone HTML for hard-blocked navigations. Requires enabled enforcement; preserves HTTP 403 and API behavior. |
|
|
224
235
|
| `flaggedMode` | Unset | `'gate'` withholds app content: HTML GET navigations receive a 200 verification-only page, other requests a 403 `account_flagged`. `'overlay'` delivers HTML with a cosmetic blur/modal but returns 403 for data requests. Wins over `blockFlagged`, ignores `onFlagged`; overlay implies `autoInterstitial`. Both require the browser SDK and default prefix. |
|
|
225
236
|
| `autoInterstitial` | `false` (implied by overlay) | Boots a proxy browser SDK to show the published modal on intercepted 403s/deferred status flagging and reload on completion. UX only; pair with server enforcement. Requires browser SDK and default prefix. |
|
|
226
237
|
| `interstitialFlowType` | `'email_verification'` | Flow requested by the automatic inline modal, including overlay. Does not override the standalone gate page's default flow. |
|
|
@@ -393,6 +404,7 @@ Web differences here.
|
|
|
393
404
|
| `deviceId` | Header/cookie fallback | Request resolver, `X-Device-Id`, canonical `__unshared_stable_hash`, then legacy `__unshared_fp_id`. Missing values omitted; these are not authentication credentials. |
|
|
394
405
|
| `fingerprintSdkBundle` | `''` | Manually supply browser SDK UMD text, typically a bundler raw import. Required for fresh inline collection and all renderer modes; installing the package alone does not load it. Missing `/fp.js` returns 503 `no-store`. |
|
|
395
406
|
| `blockFlagged` | `false` | Gate shorthand unless `flaggedMode` is set. Requires bundle and default prefix. |
|
|
407
|
+
| `hardBlockPage` | Built-in access-denied page | Trusted standalone contact-support HTML for hard-blocked navigations; preserves HTTP 403 and API errors. |
|
|
396
408
|
| `flaggedMode` | Unset | `'gate'` withholds HTML/data; `'overlay'` delivers HTML but withholds data with 403 and implies automatic modal. Wins over `blockFlagged`; both ignore `onFlagged`. Bundle/default prefix required; flow routing must be supplied separately (below). |
|
|
397
409
|
| `autoInterstitial` | `false` (implied by overlay) | Automatic modal UX, not access control. Requires bundle, default prefix and your flow-route wiring. |
|
|
398
410
|
| `interstitialFlowType` | `'email_verification'` | Automatic inline/overlay flow type, not the standalone gate's default flow. Must be published. |
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CheckUserRequest, CheckUserResult as V3CheckUserResult, FingerprintWireFormat, IngestResult, JSONObject, VerifyEmailRequest, VerifyEmailResult } from './shared-types';
|
|
1
|
+
import type { EnforcementType, CheckUserRequest, CheckUserResult as V3CheckUserResult, FingerprintWireFormat, IngestResult, JSONObject, VerifyEmailRequest, VerifyEmailResult } from './shared-types';
|
|
2
2
|
export interface UnsharedClientConfig {
|
|
3
3
|
/**
|
|
4
4
|
* Secret API key. Must be kept server-side.
|
|
@@ -127,10 +127,12 @@ export interface ProcessUserEventResult {
|
|
|
127
127
|
analysis: {
|
|
128
128
|
status: 'success' | 'error';
|
|
129
129
|
is_user_flagged: boolean;
|
|
130
|
+
enforcement_type?: EnforcementType;
|
|
130
131
|
status_details?: string;
|
|
131
132
|
};
|
|
132
133
|
}
|
|
133
134
|
export interface CheckUserResult {
|
|
135
|
+
enforcement_type?: EnforcementType;
|
|
134
136
|
is_user_flagged: boolean;
|
|
135
137
|
/** Present on authoritative v3 responses; omitted by local fail-open defaults. */
|
|
136
138
|
decision_id?: string;
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"t",{value:!0}),exports.UnsharedClient=void 0;const webcrypto_1=require("./webcrypto"),DEFAULT_BASE_URL="https://api.unshared.ai",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3,MAX_REQUEST_BYTES=1<<20,MAX_ENCRYPTED_REQUEST_BYTES=Math.floor(1572864),SDK_VERSION="3.0.0",UUID_V4_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function isSecureOrLoopbackUrl(e){try{const s=new URL(e);return"https:"===s.protocol||"localhost"===s.hostname||"[::1]"===s.hostname||/^127\./.test(s.hostname)}catch{return!1}}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)}function asJSONObject(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function isJSONObject(e,s=new WeakSet){if(null===e||"object"!=typeof e||Array.isArray(e)||s.has(e))return!1;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return!1;s.add(e);for(const t of Object.values(e))if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&!("number"==typeof t&&Number.isFinite(t)||Array.isArray(t)&&isJSONValue(t,s)||isJSONObject(t,s)))return!1;return s.delete(e),!0}function isJSONValue(e,s){if(null===e||"string"==typeof e||"boolean"==typeof e)return!0;if("number"==typeof e)return Number.isFinite(e);if(Array.isArray(e)){if(s.has(e))return!1;s.add(e);let t=Object.keys(e).length===e.length;for(let r=0;t&&r<e.length;r++)t=Object.prototype.hasOwnProperty.call(e,r)&&isJSONValue(e[r],s);return s.delete(e),t}return isJSONObject(e,s)}function hasExactKeys(e,s){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&(Object.keys(e).length===s.length&&s.every(s=>Object.prototype.hasOwnProperty.call(e,s)))}function isValidDateTime(e){if("string"!=typeof e)return!1;const s=/^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.exec(e);if(!s||Number.isNaN(Date.parse(e)))return!1;const t=Number(s[1]),r=Number(s[2]),i=Number(s[3]);return r>=1&&r<=12&&i>=1&&i<=[31,t%4!=0||t%100==0&&t%400!=0?28:29,31,30,31,30,31,31,30,31,30,31][r-1]}function isIngestResult(e){return hasExactKeys(e,["event_id","collected_at","endpoint_version"])&&"string"==typeof e.event_id&&UUID_V4_PATTERN.test(e.event_id)&&isValidDateTime(e.collected_at)&&"v3"===e.endpoint_version}function isCheckUserResult(e){if(!hasExactKeys(e,["is_user_flagged","decision_id","decision_code"]))return!1;const s=new Set(["FLAGGED_RISK_MATCH","NO_ENFORCING_RISK","NO_IDENTITY_MATCH","IDENTITY_UNCERTAIN","CHECK_UNAVAILABLE"]);return"boolean"==typeof e.is_user_flagged&&"string"==typeof e.decision_id&&UUID_V4_PATTERN.test(e.decision_id)&&"string"==typeof e.decision_code&&s.has(e.decision_code)&&e.is_user_flagged===("FLAGGED_RISK_MATCH"===e.decision_code)}function isTriggerEmailResult(e){return hasExactKeys(e,["verification_id","next_allowed_at","retry_after_seconds"])&&"string"==typeof e.verification_id&&UUID_V4_PATTERN.test(e.verification_id)&&isValidDateTime(e.next_allowed_at)&&Number.isInteger(e.retry_after_seconds)&&e.retry_after_seconds>=0}function isVerifyEmailResult(e){return hasExactKeys(e,["verified","verification_scope"])?!0===e.verified&&"email"===e.verification_scope:hasExactKeys(e,["verified","verification_scope","reason"])&&!1===e.verified&&"email"===e.verification_scope&&"invalid_code"===e.reason}function compactIdentifiers(e){const s={};for(const[t,r]of Object.entries(e))"string"==typeof r&&""!==r.trim()&&(s[t]=r.trim());return s}async function parseErrorBody(e,s=!1){const t=await e.text();try{const r=JSON.parse(t);if(s)return hasExactKeys(r,["success","error"])&&!1===r.success&&hasExactKeys(r.error,["code","message"])&&"string"==typeof r.error.code&&"string"==typeof r.error.message?{code:r.error.code,message:r.error.message}:{code:"PARSE_ERROR",message:"Invalid v3 error envelope"};const i=r;return"string"==typeof i?.error?.code?{code:i.error.code,message:"string"==typeof i.error.message?i.error.message:"Unknown error",details:i.error.details}:{code:"UNKNOWN_ERROR",message:t||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:t||e.statusText}}}class UnsharedClient{constructor(e){if(this.i=new Map,!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");if(e.baseUrl&&!isSecureOrLoopbackUrl(e.baseUrl))throw new Error("baseUrl must be a valid HTTPS URL except for loopback development URLs");this.o=e.apiKey,this.u=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this._=e.timeout??1e4,this.l=e.maxRetries??3,this.p=e.fetch}async R(e,s,t){const r=t?.maxRequestBytes??1048576;if(s.body&&(new TextEncoder).encode(s.body).byteLength>r)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds "+(1048576===r?"1 MiB":"1.5 MiB")}};const i=(t?.maxRetries??this.l)+1,a=t?.timeoutMs??this._;let n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let r=1;r<=i;r++){r>1&&await sleep(retryDelay(r-1));const i=new AbortController,o=setTimeout(()=>i.abort(),a);try{const r=this.p??globalThis.fetch,a=await r(e,{method:s.method,headers:{"X-API-Key":this.o,...s.headers},body:s.body,signal:i.signal});if(a.ok){let e,s;try{e=await a.text()}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}};continue}if(""===e.trim())return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Empty v3 response body"}};try{s=JSON.parse(e)}catch{return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Unparseable 2xx response body"}}}return(t?.strictEnvelope?hasExactKeys(s,["success","data"])&&!0===s.success:!0===s?.success&&Object.prototype.hasOwnProperty.call(s,"data"))?void 0!==t?.expectedStatus&&a.status!==t.expectedStatus?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:`Unexpected success status ${a.status}`}}:t?.validateData&&!t.validateData(s.data)?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response data"}}:{success:!0,status:a.status,data:s.data}:{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response envelope"}}}const o=await parseErrorBody(a,t?.strictEnvelope);if(a.status>=400&&a.status<500){if(429===a.status){const e=a.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(o.retryAfter=s)}if(null==o.retryAfter){const e=o.details?.retry_after_seconds;"number"!=typeof e||isNaN(e)||(o.retryAfter=e)}}return{success:!1,status:a.status,error:o}}if(n={success:!1,status:a.status,error:o},t?.retryHttpError&&!t.retryHttpError(a.status,o))return n}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}finally{clearTimeout(o)}}return n}async m(e,s,t){if(!isJSONObject(s))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};let r,i;try{r=JSON.stringify(s)}catch(e){return{success:!1,status:400,error:{code:"INVALID_JSON",message:e instanceof Error?e.message:String(e)}}}if((new TextEncoder).encode(r).byteLength>1048576)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds 1 MiB"}};try{this.h??(this.h=(0,webcrypto_1.sha256Bytes)(this.o).then(webcrypto_1.importAesGcmKey)),i=JSON.stringify({encrypted_data:await(0,webcrypto_1.encryptDataWeb)(r,await this.h)})}catch(e){return{success:!1,status:0,error:{code:"CLIENT_ENCRYPTION_ERROR",message:e instanceof Error?e.message:String(e)}}}return this.R(`${this.u}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...t?.idempotencyKey?{"X-Idempotency-Key":t.idempotencyKey}:{}},body:i},{timeoutMs:t?.timeoutMs,maxRetries:0,maxRequestBytes:MAX_ENCRYPTED_REQUEST_BYTES,expectedStatus:202,strictEnvelope:!0,validateData:e=>isIngestResult(e)})}async submitFingerprint(e,s){return this.m("/v3/submit-fingerprint-event",e,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()})}async submitFingerprintEvent(e,s){const t=compactIdentifiers({unshared_device_id:s?.permanentDeviceId,device_id:s?.deviceId,stable_hash:s?.stableHash??e.fingerprint_id,full_hash:s?.fullHash??e.full_hash,session_hash:s?.sessionHash}),r={fingerprint:asJSONObject(e),context:{sdk:{name:"unshared-clientjs-sdk",version:"3.0.0",runtime:"node"},identity:{...s?.userId?{user_id:s.userId}:{},...s?.emailAddress?{email_address:s.emailAddress}:{}},identifiers:t,event:{...s?.eventType?{event_type:s.eventType}:{},...s?.ipAddress?{ip_address:s.ipAddress}:{},...s?.userAgent?{user_agent:s.userAgent}:{}}}},i=await this.m("/v3/submit-fingerprint-event",r,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()});return i.success?i.data?{success:!0,status:i.status,data:{...i.data,hash:e.full_hash,stable_hash:e.fingerprint_id,version:e.version??"unknown"}}:{success:!1,status:i.status,error:{code:"PARSE_ERROR",message:"Invalid v3 ingestion result"}}:{success:!1,status:i.status,error:i.error}}async processUserEvent(e,s){if(null===e||"object"!=typeof e||Array.isArray(e))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};const t=new Set(["eventType","userId","ipAddress","deviceId","sessionHash","userAgent","emailAddress","fingerprintId","permanentDeviceId","subscriptionStatus","eventDetails"]);if(!Object.keys(e).every(e=>t.has(e))||"string"!=typeof e.eventType||"string"!=typeof e.userId||"string"!=typeof e.emailAddress||"string"!=typeof e.deviceId||"string"!=typeof e.sessionHash)return this.m("/v3/process-user-event",e,{timeoutMs:s?.timeoutMs});const r=e,i=compactIdentifiers({unshared_device_id:r.permanentDeviceId,device_id:r.deviceId,stable_hash:r.fingerprintId,session_hash:r.sessionHash}),a={event_type:r.eventType,identity:{user_id:r.userId,email_address:r.emailAddress},identifiers:i,context:{ip_address:r.ipAddress,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{}},...r.eventDetails?{event_details:asJSONObject(r.eventDetails)}:{}},n=await this.m("/v3/process-user-event",a,{timeoutMs:s?.timeoutMs});if(!n.success)return{success:!1,status:n.status,error:n.error};const o=await this.checkUser({user_id:r.userId,email_address:r.emailAddress,identifiers:i},{timeoutMs:s?.timeoutMs,maxRetries:s?.maxRetries});return o.success?{success:!0,status:o.status,data:{event:{event_type:r.eventType,user_id:r.userId,email_address:r.emailAddress,ip_address:r.ipAddress,device_id:r.deviceId,...r.permanentDeviceId?{permanent_device_id:r.permanentDeviceId}:{},session_hash:r.sessionHash,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{},...r.eventDetails?{event_details:JSON.stringify(r.eventDetails)}:{}},analysis:{status:o.failedOpen?"error":"success",is_user_flagged:o.data.is_user_flagged,...o.data.decision_code?{status_details:o.data.decision_code}:{}}},...o.failedOpen?{failedOpen:o.failedOpen}:{}}:{success:!1,status:o.status,error:o.error}}async checkUser(e,s={}){const t="string"==typeof s?{deviceId:s}:s,r="string"==typeof e?{email_address:e,identifiers:compactIdentifiers({unshared_device_id:t.permanentDeviceId,device_id:t.deviceId,stable_hash:t.fingerprintId,full_hash:t.fullHash,session_hash:t.sessionHash})}:e;if("string"!=typeof r.email_address||""===r.email_address.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"email_address must be a non-empty string"}};if(0===Object.keys(r.identifiers).length)return{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:0,reason:"no_device_id"}};const i=await this.R(`${this.u}/v3/check-user`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},{timeoutMs:t.timeoutMs,maxRetries:t.maxRetries,expectedStatus:200,strictEnvelope:!0,validateData:isCheckUserResult,retryHttpError:(e,s)=>"RATE_LIMIT_UNAVAILABLE"===s.code||"AUDIT_UNAVAILABLE"===s.code});return i.success?"CHECK_UNAVAILABLE"===i.data?.decision_code?{...i,failedOpen:{status:i.status}}:i:{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:i.status}}}async triggerEmailVerification(e,s,t){if("string"!=typeof e||""===e.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"emailAddress must be a non-empty string"}};const r={email_address:e,identifiers:compactIdentifiers({unshared_device_id:t?.permanentDeviceId,device_id:s,stable_hash:t?.fingerprintId,full_hash:t?.fullHash,session_hash:t?.sessionHash})};if(0===Object.keys(r.identifiers).length)return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"At least one non-empty identifier is required"}};const i=await this.R(`${this.u}/v3/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isTriggerEmailResult});return i.success?(this.i.set(e.trim().toLowerCase(),i.data.verification_id),{...i,data:{...i.data,message:"Verification code sent"}}):!i.success&&(0===i.status||i.status>=500)?{success:!1,status:i.status,error:{code:"DELIVERY_FAILED",message:i.error?.message??"Delivery failed"}}:{success:!1,status:i.status,error:i.error??{code:"PARSE_ERROR",message:"Missing v3 verification response"}}}async verify(e,s,t,r){const i=r?.verificationId??this.i.get(e.trim().toLowerCase());if(!i)return{success:!1,status:400,error:{code:"MISSING_VERIFICATION_ID",message:"Trigger email verification before verifying the code"}};if(!UUID_V4_PATTERN.test(i)||!/^\d{6}$/.test(t))return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verificationId must be a UUIDv4 and code must be exactly 6 digits"}};const a={verification_id:i,code:t},n=await this.R(`${this.u}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult});return!n.success&&(0===n.status||n.status>=500)?{success:!1,status:n.status,error:{code:"DELIVERY_FAILED",message:n.error?.message??"Delivery failed"}}:n.success?!0!==n.data?.verified?{success:!1,status:n.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:n.data?.reason?{reason:n.data.reason}:void 0}}:(this.i.delete(e.trim().toLowerCase()),n):n}async verifyEmail(e){return e&&UUID_V4_PATTERN.test(e.verification_id)&&/^\d{6}$/.test(e.code)?this.R(`${this.u}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult}):{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verification_id must be a UUIDv4 and code must be exactly 6 digits"}}}async getInterstitialFlow(e){const s=new URLSearchParams;return s.set("flow_type",e?.flowType||"email_verification"),s.set("platform",e?.platform||"web"),this.R(`${this.u}/v2/interstitial-flow?${s}`,{method:"GET"})}}exports.UnsharedClient=UnsharedClient;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"t",{value:!0}),exports.UnsharedClient=void 0;const webcrypto_1=require("./webcrypto"),DEFAULT_BASE_URL="https://api.unshared.ai",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3,MAX_REQUEST_BYTES=1<<20,MAX_ENCRYPTED_REQUEST_BYTES=Math.floor(1572864),SDK_VERSION="3.0.0",UUID_V4_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function isSecureOrLoopbackUrl(e){try{const s=new URL(e);return"https:"===s.protocol||"localhost"===s.hostname||"[::1]"===s.hostname||/^127\./.test(s.hostname)}catch{return!1}}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)}function asJSONObject(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function isJSONObject(e,s=new WeakSet){if(null===e||"object"!=typeof e||Array.isArray(e)||s.has(e))return!1;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return!1;s.add(e);for(const t of Object.values(e))if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&!("number"==typeof t&&Number.isFinite(t)||Array.isArray(t)&&isJSONValue(t,s)||isJSONObject(t,s)))return!1;return s.delete(e),!0}function isJSONValue(e,s){if(null===e||"string"==typeof e||"boolean"==typeof e)return!0;if("number"==typeof e)return Number.isFinite(e);if(Array.isArray(e)){if(s.has(e))return!1;s.add(e);let t=Object.keys(e).length===e.length;for(let r=0;t&&r<e.length;r++)t=Object.prototype.hasOwnProperty.call(e,r)&&isJSONValue(e[r],s);return s.delete(e),t}return isJSONObject(e,s)}function hasExactKeys(e,s){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&(Object.keys(e).length===s.length&&s.every(s=>Object.prototype.hasOwnProperty.call(e,s)))}function isValidDateTime(e){if("string"!=typeof e)return!1;const s=/^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.exec(e);if(!s||Number.isNaN(Date.parse(e)))return!1;const t=Number(s[1]),r=Number(s[2]),i=Number(s[3]);return r>=1&&r<=12&&i>=1&&i<=[31,t%4!=0||t%100==0&&t%400!=0?28:29,31,30,31,30,31,31,30,31,30,31][r-1]}function isIngestResult(e){return hasExactKeys(e,["event_id","collected_at","endpoint_version"])&&"string"==typeof e.event_id&&UUID_V4_PATTERN.test(e.event_id)&&isValidDateTime(e.collected_at)&&"v3"===e.endpoint_version}function isCheckUserResult(e){const s=["is_user_flagged","decision_id","decision_code"];if(!hasExactKeys(e,s)&&!hasExactKeys(e,[...s,"enforcement_type"]))return!1;if("enforcement_type"in e&&(!["no_enforcement","soft_block","hard_block"].includes(e.enforcement_type)||e.is_user_flagged!==("no_enforcement"!==e.enforcement_type)))return!1;const t=new Set(["FLAGGED_RISK_MATCH","NO_ENFORCING_RISK","NO_IDENTITY_MATCH","IDENTITY_UNCERTAIN","CHECK_UNAVAILABLE"]);return"boolean"==typeof e.is_user_flagged&&"string"==typeof e.decision_id&&UUID_V4_PATTERN.test(e.decision_id)&&"string"==typeof e.decision_code&&t.has(e.decision_code)&&e.is_user_flagged===("FLAGGED_RISK_MATCH"===e.decision_code)}function isTriggerEmailResult(e){return hasExactKeys(e,["verification_id","next_allowed_at","retry_after_seconds"])&&"string"==typeof e.verification_id&&UUID_V4_PATTERN.test(e.verification_id)&&isValidDateTime(e.next_allowed_at)&&Number.isInteger(e.retry_after_seconds)&&e.retry_after_seconds>=0}function isVerifyEmailResult(e){return hasExactKeys(e,["verified","verification_scope"])?!0===e.verified&&"email"===e.verification_scope:hasExactKeys(e,["verified","verification_scope","reason"])&&!1===e.verified&&"email"===e.verification_scope&&"invalid_code"===e.reason}function compactIdentifiers(e){const s={};for(const[t,r]of Object.entries(e))"string"==typeof r&&""!==r.trim()&&(s[t]=r.trim());return s}async function parseErrorBody(e,s=!1){const t=await e.text();try{const r=JSON.parse(t);if(s)return hasExactKeys(r,["success","error"])&&!1===r.success&&hasExactKeys(r.error,["code","message"])&&"string"==typeof r.error.code&&"string"==typeof r.error.message?{code:r.error.code,message:r.error.message}:{code:"PARSE_ERROR",message:"Invalid v3 error envelope"};const i=r;return"string"==typeof i?.error?.code?{code:i.error.code,message:"string"==typeof i.error.message?i.error.message:"Unknown error",details:i.error.details}:{code:"UNKNOWN_ERROR",message:t||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:t||e.statusText}}}class UnsharedClient{constructor(e){if(this.i=new Map,!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");if(e.baseUrl&&!isSecureOrLoopbackUrl(e.baseUrl))throw new Error("baseUrl must be a valid HTTPS URL except for loopback development URLs");this.o=e.apiKey,this.u=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this._=e.timeout??1e4,this.l=e.maxRetries??3,this.p=e.fetch}async m(e,s,t){const r=t?.maxRequestBytes??1048576;if(s.body&&(new TextEncoder).encode(s.body).byteLength>r)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds "+(1048576===r?"1 MiB":"1.5 MiB")}};const i=(t?.maxRetries??this.l)+1,a=t?.timeoutMs??this._;let n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let r=1;r<=i;r++){r>1&&await sleep(retryDelay(r-1));const i=new AbortController,o=setTimeout(()=>i.abort(),a);try{const r=this.p??globalThis.fetch,a=await r(e,{method:s.method,headers:{"X-API-Key":this.o,...s.headers},body:s.body,signal:i.signal});if(a.ok){let e,s;try{e=await a.text()}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}};continue}if(""===e.trim())return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Empty v3 response body"}};try{s=JSON.parse(e)}catch{return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Unparseable 2xx response body"}}}return(t?.strictEnvelope?hasExactKeys(s,["success","data"])&&!0===s.success:!0===s?.success&&Object.prototype.hasOwnProperty.call(s,"data"))?void 0!==t?.expectedStatus&&a.status!==t.expectedStatus?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:`Unexpected success status ${a.status}`}}:t?.validateData&&!t.validateData(s.data)?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response data"}}:{success:!0,status:a.status,data:s.data}:{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response envelope"}}}const o=await parseErrorBody(a,t?.strictEnvelope);if(a.status>=400&&a.status<500){if(429===a.status){const e=a.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(o.retryAfter=s)}if(null==o.retryAfter){const e=o.details?.retry_after_seconds;"number"!=typeof e||isNaN(e)||(o.retryAfter=e)}}return{success:!1,status:a.status,error:o}}if(n={success:!1,status:a.status,error:o},t?.retryHttpError&&!t.retryHttpError(a.status,o))return n}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}finally{clearTimeout(o)}}return n}async R(e,s,t){if(!isJSONObject(s))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};let r,i;try{r=JSON.stringify(s)}catch(e){return{success:!1,status:400,error:{code:"INVALID_JSON",message:e instanceof Error?e.message:String(e)}}}if((new TextEncoder).encode(r).byteLength>1048576)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds 1 MiB"}};try{this.h??(this.h=(0,webcrypto_1.sha256Bytes)(this.o).then(webcrypto_1.importAesGcmKey)),i=JSON.stringify({encrypted_data:await(0,webcrypto_1.encryptDataWeb)(r,await this.h)})}catch(e){return{success:!1,status:0,error:{code:"CLIENT_ENCRYPTION_ERROR",message:e instanceof Error?e.message:String(e)}}}return this.m(`${this.u}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...t?.idempotencyKey?{"X-Idempotency-Key":t.idempotencyKey}:{}},body:i},{timeoutMs:t?.timeoutMs,maxRetries:0,maxRequestBytes:MAX_ENCRYPTED_REQUEST_BYTES,expectedStatus:202,strictEnvelope:!0,validateData:e=>isIngestResult(e)})}async submitFingerprint(e,s){return this.R("/v3/submit-fingerprint-event",e,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()})}async submitFingerprintEvent(e,s){const t=compactIdentifiers({unshared_device_id:s?.permanentDeviceId,device_id:s?.deviceId,stable_hash:s?.stableHash??e.fingerprint_id,full_hash:s?.fullHash??e.full_hash,session_hash:s?.sessionHash}),r={fingerprint:asJSONObject(e),context:{sdk:{name:"unshared-clientjs-sdk",version:"3.0.0",runtime:"node"},identity:{...s?.userId?{user_id:s.userId}:{},...s?.emailAddress?{email_address:s.emailAddress}:{}},identifiers:t,event:{...s?.eventType?{event_type:s.eventType}:{},...s?.ipAddress?{ip_address:s.ipAddress}:{},...s?.userAgent?{user_agent:s.userAgent}:{}}}},i=await this.R("/v3/submit-fingerprint-event",r,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()});return i.success?i.data?{success:!0,status:i.status,data:{...i.data,hash:e.full_hash,stable_hash:e.fingerprint_id,version:e.version??"unknown"}}:{success:!1,status:i.status,error:{code:"PARSE_ERROR",message:"Invalid v3 ingestion result"}}:{success:!1,status:i.status,error:i.error}}async processUserEvent(e,s){if(null===e||"object"!=typeof e||Array.isArray(e))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};const t=new Set(["eventType","userId","ipAddress","deviceId","sessionHash","userAgent","emailAddress","fingerprintId","permanentDeviceId","subscriptionStatus","eventDetails"]);if(!Object.keys(e).every(e=>t.has(e))||"string"!=typeof e.eventType||"string"!=typeof e.userId||"string"!=typeof e.emailAddress||"string"!=typeof e.deviceId||"string"!=typeof e.sessionHash)return this.R("/v3/process-user-event",e,{timeoutMs:s?.timeoutMs});const r=e,i=compactIdentifiers({unshared_device_id:r.permanentDeviceId,device_id:r.deviceId,stable_hash:r.fingerprintId,session_hash:r.sessionHash}),a={event_type:r.eventType,identity:{user_id:r.userId,email_address:r.emailAddress},identifiers:i,context:{ip_address:r.ipAddress,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{}},...r.eventDetails?{event_details:asJSONObject(r.eventDetails)}:{}},n=await this.R("/v3/process-user-event",a,{timeoutMs:s?.timeoutMs});if(!n.success)return{success:!1,status:n.status,error:n.error};const o=await this.checkUser({user_id:r.userId,email_address:r.emailAddress,identifiers:i},{timeoutMs:s?.timeoutMs,maxRetries:s?.maxRetries});return o.success?{success:!0,status:o.status,data:{event:{event_type:r.eventType,user_id:r.userId,email_address:r.emailAddress,ip_address:r.ipAddress,device_id:r.deviceId,...r.permanentDeviceId?{permanent_device_id:r.permanentDeviceId}:{},session_hash:r.sessionHash,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{},...r.eventDetails?{event_details:JSON.stringify(r.eventDetails)}:{}},analysis:{status:o.failedOpen?"error":"success",is_user_flagged:o.data.is_user_flagged,...o.data.enforcement_type?{enforcement_type:o.data.enforcement_type}:{},...o.data.decision_code?{status_details:o.data.decision_code}:{}}},...o.failedOpen?{failedOpen:o.failedOpen}:{}}:{success:!1,status:o.status,error:o.error}}async checkUser(e,s={}){const t="string"==typeof s?{deviceId:s}:s,r="string"==typeof e?{email_address:e,identifiers:compactIdentifiers({unshared_device_id:t.permanentDeviceId,device_id:t.deviceId,stable_hash:t.fingerprintId,full_hash:t.fullHash,session_hash:t.sessionHash})}:e;if("string"!=typeof r.email_address||""===r.email_address.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"email_address must be a non-empty string"}};if(0===Object.keys(r.identifiers).length)return{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:0,reason:"no_device_id"}};const i=await this.m(`${this.u}/v3/check-user`,{method:"POST",headers:{"Content-Type":"application/json","X-Unshared-Enforcement-Version":"1"},body:JSON.stringify(r)},{timeoutMs:t.timeoutMs,maxRetries:t.maxRetries,expectedStatus:200,strictEnvelope:!0,validateData:isCheckUserResult,retryHttpError:(e,s)=>"RATE_LIMIT_UNAVAILABLE"===s.code||"AUDIT_UNAVAILABLE"===s.code});return i.success?"CHECK_UNAVAILABLE"===i.data?.decision_code?{...i,failedOpen:{status:i.status}}:i:{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:i.status}}}async triggerEmailVerification(e,s,t){if("string"!=typeof e||""===e.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"emailAddress must be a non-empty string"}};const r={email_address:e,identifiers:compactIdentifiers({unshared_device_id:t?.permanentDeviceId,device_id:s,stable_hash:t?.fingerprintId,full_hash:t?.fullHash,session_hash:t?.sessionHash})};if(0===Object.keys(r.identifiers).length)return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"At least one non-empty identifier is required"}};const i=await this.m(`${this.u}/v3/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isTriggerEmailResult});return i.success?(this.i.set(e.trim().toLowerCase(),i.data.verification_id),{...i,data:{...i.data,message:"Verification code sent"}}):!i.success&&(0===i.status||i.status>=500)?{success:!1,status:i.status,error:{code:"DELIVERY_FAILED",message:i.error?.message??"Delivery failed"}}:{success:!1,status:i.status,error:i.error??{code:"PARSE_ERROR",message:"Missing v3 verification response"}}}async verify(e,s,t,r){const i=r?.verificationId??this.i.get(e.trim().toLowerCase());if(!i)return{success:!1,status:400,error:{code:"MISSING_VERIFICATION_ID",message:"Trigger email verification before verifying the code"}};if(!UUID_V4_PATTERN.test(i)||!/^\d{6}$/.test(t))return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verificationId must be a UUIDv4 and code must be exactly 6 digits"}};const a={verification_id:i,code:t},n=await this.m(`${this.u}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult});return!n.success&&(0===n.status||n.status>=500)?{success:!1,status:n.status,error:{code:"DELIVERY_FAILED",message:n.error?.message??"Delivery failed"}}:n.success?!0!==n.data?.verified?{success:!1,status:n.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:n.data?.reason?{reason:n.data.reason}:void 0}}:(this.i.delete(e.trim().toLowerCase()),n):n}async verifyEmail(e){return e&&UUID_V4_PATTERN.test(e.verification_id)&&/^\d{6}$/.test(e.code)?this.m(`${this.u}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult}):{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verification_id must be a UUIDv4 and code must be exactly 6 digits"}}}async getInterstitialFlow(e){const s=new URLSearchParams;return s.set("flow_type",e?.flowType||"email_verification"),s.set("platform",e?.platform||"web"),this.m(`${this.u}/v2/interstitial-flow?${s}`,{method:"GET"})}}exports.UnsharedClient=UnsharedClient;
|
package/dist/esm/client.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CheckUserRequest, CheckUserResult as V3CheckUserResult, FingerprintWireFormat, IngestResult, JSONObject, VerifyEmailRequest, VerifyEmailResult } from './shared-types.mjs';
|
|
1
|
+
import type { EnforcementType, CheckUserRequest, CheckUserResult as V3CheckUserResult, FingerprintWireFormat, IngestResult, JSONObject, VerifyEmailRequest, VerifyEmailResult } from './shared-types.mjs';
|
|
2
2
|
export interface UnsharedClientConfig {
|
|
3
3
|
/**
|
|
4
4
|
* Secret API key. Must be kept server-side.
|
|
@@ -127,10 +127,12 @@ export interface ProcessUserEventResult {
|
|
|
127
127
|
analysis: {
|
|
128
128
|
status: 'success' | 'error';
|
|
129
129
|
is_user_flagged: boolean;
|
|
130
|
+
enforcement_type?: EnforcementType;
|
|
130
131
|
status_details?: string;
|
|
131
132
|
};
|
|
132
133
|
}
|
|
133
134
|
export interface CheckUserResult {
|
|
135
|
+
enforcement_type?: EnforcementType;
|
|
134
136
|
is_user_flagged: boolean;
|
|
135
137
|
/** Present on authoritative v3 responses; omitted by local fail-open defaults. */
|
|
136
138
|
decision_id?: string;
|
package/dist/esm/client.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{encryptDataWeb,importAesGcmKey,sha256Bytes}from"./webcrypto.mjs";const DEFAULT_BASE_URL="https://api.unshared.ai",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3,MAX_REQUEST_BYTES=1<<20,MAX_ENCRYPTED_REQUEST_BYTES=Math.floor(1572864),SDK_VERSION="3.0.0",UUID_V4_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function isSecureOrLoopbackUrl(e){try{const s=new URL(e);return"https:"===s.protocol||"localhost"===s.hostname||"[::1]"===s.hostname||/^127\./.test(s.hostname)}catch{return!1}}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)}function asJSONObject(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function isJSONObject(e,s=new WeakSet){if(null===e||"object"!=typeof e||Array.isArray(e)||s.has(e))return!1;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return!1;s.add(e);for(const t of Object.values(e))if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&!("number"==typeof t&&Number.isFinite(t)||Array.isArray(t)&&isJSONValue(t,s)||isJSONObject(t,s)))return!1;return s.delete(e),!0}function isJSONValue(e,s){if(null===e||"string"==typeof e||"boolean"==typeof e)return!0;if("number"==typeof e)return Number.isFinite(e);if(Array.isArray(e)){if(s.has(e))return!1;s.add(e);let t=Object.keys(e).length===e.length;for(let r=0;t&&r<e.length;r++)t=Object.prototype.hasOwnProperty.call(e,r)&&isJSONValue(e[r],s);return s.delete(e),t}return isJSONObject(e,s)}function hasExactKeys(e,s){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&(Object.keys(e).length===s.length&&s.every(s=>Object.prototype.hasOwnProperty.call(e,s)))}function isValidDateTime(e){if("string"!=typeof e)return!1;const s=/^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.exec(e);if(!s||Number.isNaN(Date.parse(e)))return!1;const t=Number(s[1]),r=Number(s[2]),i=Number(s[3]);return r>=1&&r<=12&&i>=1&&i<=[31,t%4!=0||t%100==0&&t%400!=0?28:29,31,30,31,30,31,31,30,31,30,31][r-1]}function isIngestResult(e){return hasExactKeys(e,["event_id","collected_at","endpoint_version"])&&"string"==typeof e.event_id&&UUID_V4_PATTERN.test(e.event_id)&&isValidDateTime(e.collected_at)&&"v3"===e.endpoint_version}function isCheckUserResult(e){if(!hasExactKeys(e,["is_user_flagged","decision_id","decision_code"]))return!1;const s=new Set(["FLAGGED_RISK_MATCH","NO_ENFORCING_RISK","NO_IDENTITY_MATCH","IDENTITY_UNCERTAIN","CHECK_UNAVAILABLE"]);return"boolean"==typeof e.is_user_flagged&&"string"==typeof e.decision_id&&UUID_V4_PATTERN.test(e.decision_id)&&"string"==typeof e.decision_code&&s.has(e.decision_code)&&e.is_user_flagged===("FLAGGED_RISK_MATCH"===e.decision_code)}function isTriggerEmailResult(e){return hasExactKeys(e,["verification_id","next_allowed_at","retry_after_seconds"])&&"string"==typeof e.verification_id&&UUID_V4_PATTERN.test(e.verification_id)&&isValidDateTime(e.next_allowed_at)&&Number.isInteger(e.retry_after_seconds)&&e.retry_after_seconds>=0}function isVerifyEmailResult(e){return hasExactKeys(e,["verified","verification_scope"])?!0===e.verified&&"email"===e.verification_scope:hasExactKeys(e,["verified","verification_scope","reason"])&&!1===e.verified&&"email"===e.verification_scope&&"invalid_code"===e.reason}function compactIdentifiers(e){const s={};for(const[t,r]of Object.entries(e))"string"==typeof r&&""!==r.trim()&&(s[t]=r.trim());return s}async function parseErrorBody(e,s=!1){const t=await e.text();try{const r=JSON.parse(t);if(s)return hasExactKeys(r,["success","error"])&&!1===r.success&&hasExactKeys(r.error,["code","message"])&&"string"==typeof r.error.code&&"string"==typeof r.error.message?{code:r.error.code,message:r.error.message}:{code:"PARSE_ERROR",message:"Invalid v3 error envelope"};const i=r;return"string"==typeof i?.error?.code?{code:i.error.code,message:"string"==typeof i.error.message?i.error.message:"Unknown error",details:i.error.details}:{code:"UNKNOWN_ERROR",message:t||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:t||e.statusText}}}export class UnsharedClient{constructor(e){if(this.t=new Map,!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");if(e.baseUrl&&!isSecureOrLoopbackUrl(e.baseUrl))throw new Error("baseUrl must be a valid HTTPS URL except for loopback development URLs");this.i=e.apiKey,this.o=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this.u=e.timeout??1e4,this._=e.maxRetries??3,this.l=e.fetch}async p(e,s,t){const r=t?.maxRequestBytes??1048576;if(s.body&&(new TextEncoder).encode(s.body).byteLength>r)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds "+(1048576===r?"1 MiB":"1.5 MiB")}};const i=(t?.maxRetries??this._)+1,a=t?.timeoutMs??this.u;let n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let r=1;r<=i;r++){r>1&&await sleep(retryDelay(r-1));const i=new AbortController,o=setTimeout(()=>i.abort(),a);try{const r=this.l??globalThis.fetch,a=await r(e,{method:s.method,headers:{"X-API-Key":this.i,...s.headers},body:s.body,signal:i.signal});if(a.ok){let e,s;try{e=await a.text()}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}};continue}if(""===e.trim())return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Empty v3 response body"}};try{s=JSON.parse(e)}catch{return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Unparseable 2xx response body"}}}return(t?.strictEnvelope?hasExactKeys(s,["success","data"])&&!0===s.success:!0===s?.success&&Object.prototype.hasOwnProperty.call(s,"data"))?void 0!==t?.expectedStatus&&a.status!==t.expectedStatus?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:`Unexpected success status ${a.status}`}}:t?.validateData&&!t.validateData(s.data)?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response data"}}:{success:!0,status:a.status,data:s.data}:{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response envelope"}}}const o=await parseErrorBody(a,t?.strictEnvelope);if(a.status>=400&&a.status<500){if(429===a.status){const e=a.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(o.retryAfter=s)}if(null==o.retryAfter){const e=o.details?.retry_after_seconds;"number"!=typeof e||isNaN(e)||(o.retryAfter=e)}}return{success:!1,status:a.status,error:o}}if(n={success:!1,status:a.status,error:o},t?.retryHttpError&&!t.retryHttpError(a.status,o))return n}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}finally{clearTimeout(o)}}return n}async m(e,s,t){if(!isJSONObject(s))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};let r,i;try{r=JSON.stringify(s)}catch(e){return{success:!1,status:400,error:{code:"INVALID_JSON",message:e instanceof Error?e.message:String(e)}}}if((new TextEncoder).encode(r).byteLength>1048576)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds 1 MiB"}};try{this.R??(this.R=sha256Bytes(this.i).then(importAesGcmKey)),i=JSON.stringify({encrypted_data:await encryptDataWeb(r,await this.R)})}catch(e){return{success:!1,status:0,error:{code:"CLIENT_ENCRYPTION_ERROR",message:e instanceof Error?e.message:String(e)}}}return this.p(`${this.o}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...t?.idempotencyKey?{"X-Idempotency-Key":t.idempotencyKey}:{}},body:i},{timeoutMs:t?.timeoutMs,maxRetries:0,maxRequestBytes:MAX_ENCRYPTED_REQUEST_BYTES,expectedStatus:202,strictEnvelope:!0,validateData:e=>isIngestResult(e)})}async submitFingerprint(e,s){return this.m("/v3/submit-fingerprint-event",e,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()})}async submitFingerprintEvent(e,s){const t=compactIdentifiers({unshared_device_id:s?.permanentDeviceId,device_id:s?.deviceId,stable_hash:s?.stableHash??e.fingerprint_id,full_hash:s?.fullHash??e.full_hash,session_hash:s?.sessionHash}),r={fingerprint:asJSONObject(e),context:{sdk:{name:"unshared-clientjs-sdk",version:"3.0.0",runtime:"node"},identity:{...s?.userId?{user_id:s.userId}:{},...s?.emailAddress?{email_address:s.emailAddress}:{}},identifiers:t,event:{...s?.eventType?{event_type:s.eventType}:{},...s?.ipAddress?{ip_address:s.ipAddress}:{},...s?.userAgent?{user_agent:s.userAgent}:{}}}},i=await this.m("/v3/submit-fingerprint-event",r,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()});return i.success?i.data?{success:!0,status:i.status,data:{...i.data,hash:e.full_hash,stable_hash:e.fingerprint_id,version:e.version??"unknown"}}:{success:!1,status:i.status,error:{code:"PARSE_ERROR",message:"Invalid v3 ingestion result"}}:{success:!1,status:i.status,error:i.error}}async processUserEvent(e,s){if(null===e||"object"!=typeof e||Array.isArray(e))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};const t=new Set(["eventType","userId","ipAddress","deviceId","sessionHash","userAgent","emailAddress","fingerprintId","permanentDeviceId","subscriptionStatus","eventDetails"]);if(!Object.keys(e).every(e=>t.has(e))||"string"!=typeof e.eventType||"string"!=typeof e.userId||"string"!=typeof e.emailAddress||"string"!=typeof e.deviceId||"string"!=typeof e.sessionHash)return this.m("/v3/process-user-event",e,{timeoutMs:s?.timeoutMs});const r=e,i=compactIdentifiers({unshared_device_id:r.permanentDeviceId,device_id:r.deviceId,stable_hash:r.fingerprintId,session_hash:r.sessionHash}),a={event_type:r.eventType,identity:{user_id:r.userId,email_address:r.emailAddress},identifiers:i,context:{ip_address:r.ipAddress,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{}},...r.eventDetails?{event_details:asJSONObject(r.eventDetails)}:{}},n=await this.m("/v3/process-user-event",a,{timeoutMs:s?.timeoutMs});if(!n.success)return{success:!1,status:n.status,error:n.error};const o=await this.checkUser({user_id:r.userId,email_address:r.emailAddress,identifiers:i},{timeoutMs:s?.timeoutMs,maxRetries:s?.maxRetries});return o.success?{success:!0,status:o.status,data:{event:{event_type:r.eventType,user_id:r.userId,email_address:r.emailAddress,ip_address:r.ipAddress,device_id:r.deviceId,...r.permanentDeviceId?{permanent_device_id:r.permanentDeviceId}:{},session_hash:r.sessionHash,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{},...r.eventDetails?{event_details:JSON.stringify(r.eventDetails)}:{}},analysis:{status:o.failedOpen?"error":"success",is_user_flagged:o.data.is_user_flagged,...o.data.decision_code?{status_details:o.data.decision_code}:{}}},...o.failedOpen?{failedOpen:o.failedOpen}:{}}:{success:!1,status:o.status,error:o.error}}async checkUser(e,s={}){const t="string"==typeof s?{deviceId:s}:s,r="string"==typeof e?{email_address:e,identifiers:compactIdentifiers({unshared_device_id:t.permanentDeviceId,device_id:t.deviceId,stable_hash:t.fingerprintId,full_hash:t.fullHash,session_hash:t.sessionHash})}:e;if("string"!=typeof r.email_address||""===r.email_address.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"email_address must be a non-empty string"}};if(0===Object.keys(r.identifiers).length)return{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:0,reason:"no_device_id"}};const i=await this.p(`${this.o}/v3/check-user`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},{timeoutMs:t.timeoutMs,maxRetries:t.maxRetries,expectedStatus:200,strictEnvelope:!0,validateData:isCheckUserResult,retryHttpError:(e,s)=>"RATE_LIMIT_UNAVAILABLE"===s.code||"AUDIT_UNAVAILABLE"===s.code});return i.success?"CHECK_UNAVAILABLE"===i.data?.decision_code?{...i,failedOpen:{status:i.status}}:i:{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:i.status}}}async triggerEmailVerification(e,s,t){if("string"!=typeof e||""===e.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"emailAddress must be a non-empty string"}};const r={email_address:e,identifiers:compactIdentifiers({unshared_device_id:t?.permanentDeviceId,device_id:s,stable_hash:t?.fingerprintId,full_hash:t?.fullHash,session_hash:t?.sessionHash})};if(0===Object.keys(r.identifiers).length)return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"At least one non-empty identifier is required"}};const i=await this.p(`${this.o}/v3/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isTriggerEmailResult});return i.success?(this.t.set(e.trim().toLowerCase(),i.data.verification_id),{...i,data:{...i.data,message:"Verification code sent"}}):!i.success&&(0===i.status||i.status>=500)?{success:!1,status:i.status,error:{code:"DELIVERY_FAILED",message:i.error?.message??"Delivery failed"}}:{success:!1,status:i.status,error:i.error??{code:"PARSE_ERROR",message:"Missing v3 verification response"}}}async verify(e,s,t,r){const i=r?.verificationId??this.t.get(e.trim().toLowerCase());if(!i)return{success:!1,status:400,error:{code:"MISSING_VERIFICATION_ID",message:"Trigger email verification before verifying the code"}};if(!UUID_V4_PATTERN.test(i)||!/^\d{6}$/.test(t))return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verificationId must be a UUIDv4 and code must be exactly 6 digits"}};const a={verification_id:i,code:t},n=await this.p(`${this.o}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult});return!n.success&&(0===n.status||n.status>=500)?{success:!1,status:n.status,error:{code:"DELIVERY_FAILED",message:n.error?.message??"Delivery failed"}}:n.success?!0!==n.data?.verified?{success:!1,status:n.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:n.data?.reason?{reason:n.data.reason}:void 0}}:(this.t.delete(e.trim().toLowerCase()),n):n}async verifyEmail(e){return e&&UUID_V4_PATTERN.test(e.verification_id)&&/^\d{6}$/.test(e.code)?this.p(`${this.o}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult}):{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verification_id must be a UUIDv4 and code must be exactly 6 digits"}}}async getInterstitialFlow(e){const s=new URLSearchParams;return s.set("flow_type",e?.flowType||"email_verification"),s.set("platform",e?.platform||"web"),this.p(`${this.o}/v2/interstitial-flow?${s}`,{method:"GET"})}}
|
|
1
|
+
import{encryptDataWeb,importAesGcmKey,sha256Bytes}from"./webcrypto.mjs";const DEFAULT_BASE_URL="https://api.unshared.ai",DEFAULT_TIMEOUT_MS=1e4,DEFAULT_MAX_RETRIES=3,MAX_DELAY_MS=3e4,BASE_DELAY_MS=1e3,MAX_REQUEST_BYTES=1<<20,MAX_ENCRYPTED_REQUEST_BYTES=Math.floor(1572864),SDK_VERSION="3.0.0",UUID_V4_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function isSecureOrLoopbackUrl(e){try{const s=new URL(e);return"https:"===s.protocol||"localhost"===s.hostname||"[::1]"===s.hostname||/^127\./.test(s.hostname)}catch{return!1}}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)}function asJSONObject(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function isJSONObject(e,s=new WeakSet){if(null===e||"object"!=typeof e||Array.isArray(e)||s.has(e))return!1;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return!1;s.add(e);for(const t of Object.values(e))if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&!("number"==typeof t&&Number.isFinite(t)||Array.isArray(t)&&isJSONValue(t,s)||isJSONObject(t,s)))return!1;return s.delete(e),!0}function isJSONValue(e,s){if(null===e||"string"==typeof e||"boolean"==typeof e)return!0;if("number"==typeof e)return Number.isFinite(e);if(Array.isArray(e)){if(s.has(e))return!1;s.add(e);let t=Object.keys(e).length===e.length;for(let r=0;t&&r<e.length;r++)t=Object.prototype.hasOwnProperty.call(e,r)&&isJSONValue(e[r],s);return s.delete(e),t}return isJSONObject(e,s)}function hasExactKeys(e,s){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&(Object.keys(e).length===s.length&&s.every(s=>Object.prototype.hasOwnProperty.call(e,s)))}function isValidDateTime(e){if("string"!=typeof e)return!1;const s=/^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.exec(e);if(!s||Number.isNaN(Date.parse(e)))return!1;const t=Number(s[1]),r=Number(s[2]),i=Number(s[3]);return r>=1&&r<=12&&i>=1&&i<=[31,t%4!=0||t%100==0&&t%400!=0?28:29,31,30,31,30,31,31,30,31,30,31][r-1]}function isIngestResult(e){return hasExactKeys(e,["event_id","collected_at","endpoint_version"])&&"string"==typeof e.event_id&&UUID_V4_PATTERN.test(e.event_id)&&isValidDateTime(e.collected_at)&&"v3"===e.endpoint_version}function isCheckUserResult(e){const s=["is_user_flagged","decision_id","decision_code"];if(!hasExactKeys(e,s)&&!hasExactKeys(e,[...s,"enforcement_type"]))return!1;if("enforcement_type"in e&&(!["no_enforcement","soft_block","hard_block"].includes(e.enforcement_type)||e.is_user_flagged!==("no_enforcement"!==e.enforcement_type)))return!1;const t=new Set(["FLAGGED_RISK_MATCH","NO_ENFORCING_RISK","NO_IDENTITY_MATCH","IDENTITY_UNCERTAIN","CHECK_UNAVAILABLE"]);return"boolean"==typeof e.is_user_flagged&&"string"==typeof e.decision_id&&UUID_V4_PATTERN.test(e.decision_id)&&"string"==typeof e.decision_code&&t.has(e.decision_code)&&e.is_user_flagged===("FLAGGED_RISK_MATCH"===e.decision_code)}function isTriggerEmailResult(e){return hasExactKeys(e,["verification_id","next_allowed_at","retry_after_seconds"])&&"string"==typeof e.verification_id&&UUID_V4_PATTERN.test(e.verification_id)&&isValidDateTime(e.next_allowed_at)&&Number.isInteger(e.retry_after_seconds)&&e.retry_after_seconds>=0}function isVerifyEmailResult(e){return hasExactKeys(e,["verified","verification_scope"])?!0===e.verified&&"email"===e.verification_scope:hasExactKeys(e,["verified","verification_scope","reason"])&&!1===e.verified&&"email"===e.verification_scope&&"invalid_code"===e.reason}function compactIdentifiers(e){const s={};for(const[t,r]of Object.entries(e))"string"==typeof r&&""!==r.trim()&&(s[t]=r.trim());return s}async function parseErrorBody(e,s=!1){const t=await e.text();try{const r=JSON.parse(t);if(s)return hasExactKeys(r,["success","error"])&&!1===r.success&&hasExactKeys(r.error,["code","message"])&&"string"==typeof r.error.code&&"string"==typeof r.error.message?{code:r.error.code,message:r.error.message}:{code:"PARSE_ERROR",message:"Invalid v3 error envelope"};const i=r;return"string"==typeof i?.error?.code?{code:i.error.code,message:"string"==typeof i.error.message?i.error.message:"Unknown error",details:i.error.details}:{code:"UNKNOWN_ERROR",message:t||e.statusText}}catch{return{code:"UNKNOWN_ERROR",message:t||e.statusText}}}export class UnsharedClient{constructor(e){if(this.t=new Map,!e.apiKey||""===e.apiKey.trim())throw new Error("apiKey is required");if(e.baseUrl&&!isSecureOrLoopbackUrl(e.baseUrl))throw new Error("baseUrl must be a valid HTTPS URL except for loopback development URLs");this.i=e.apiKey,this.o=e.baseUrl?e.baseUrl.replace(/\/$/,""):DEFAULT_BASE_URL,this.u=e.timeout??1e4,this._=e.maxRetries??3,this.l=e.fetch}async p(e,s,t){const r=t?.maxRequestBytes??1048576;if(s.body&&(new TextEncoder).encode(s.body).byteLength>r)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds "+(1048576===r?"1 MiB":"1.5 MiB")}};const i=(t?.maxRetries??this._)+1,a=t?.timeoutMs??this.u;let n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:"Request failed"}};for(let r=1;r<=i;r++){r>1&&await sleep(retryDelay(r-1));const i=new AbortController,o=setTimeout(()=>i.abort(),a);try{const r=this.l??globalThis.fetch,a=await r(e,{method:s.method,headers:{"X-API-Key":this.i,...s.headers},body:s.body,signal:i.signal});if(a.ok){let e,s;try{e=await a.text()}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}};continue}if(""===e.trim())return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Empty v3 response body"}};try{s=JSON.parse(e)}catch{return{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Unparseable 2xx response body"}}}return(t?.strictEnvelope?hasExactKeys(s,["success","data"])&&!0===s.success:!0===s?.success&&Object.prototype.hasOwnProperty.call(s,"data"))?void 0!==t?.expectedStatus&&a.status!==t.expectedStatus?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:`Unexpected success status ${a.status}`}}:t?.validateData&&!t.validateData(s.data)?{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response data"}}:{success:!0,status:a.status,data:s.data}:{success:!1,status:a.status,error:{code:"PARSE_ERROR",message:"Invalid v3 response envelope"}}}const o=await parseErrorBody(a,t?.strictEnvelope);if(a.status>=400&&a.status<500){if(429===a.status){const e=a.headers.get("Retry-After");if(null!=e){const s=parseInt(e,10);isNaN(s)||(o.retryAfter=s)}if(null==o.retryAfter){const e=o.details?.retry_after_seconds;"number"!=typeof e||isNaN(e)||(o.retryAfter=e)}}return{success:!1,status:a.status,error:o}}if(n={success:!1,status:a.status,error:o},t?.retryHttpError&&!t.retryHttpError(a.status,o))return n}catch(e){n={success:!1,status:0,error:{code:"NETWORK_ERROR",message:e instanceof Error?e.message:String(e)}}}finally{clearTimeout(o)}}return n}async m(e,s,t){if(!isJSONObject(s))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};let r,i;try{r=JSON.stringify(s)}catch(e){return{success:!1,status:400,error:{code:"INVALID_JSON",message:e instanceof Error?e.message:String(e)}}}if((new TextEncoder).encode(r).byteLength>1048576)return{success:!1,status:413,error:{code:"REQUEST_TOO_LARGE",message:"Request body exceeds 1 MiB"}};try{this.R??(this.R=sha256Bytes(this.i).then(importAesGcmKey)),i=JSON.stringify({encrypted_data:await encryptDataWeb(r,await this.R)})}catch(e){return{success:!1,status:0,error:{code:"CLIENT_ENCRYPTION_ERROR",message:e instanceof Error?e.message:String(e)}}}return this.p(`${this.o}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...t?.idempotencyKey?{"X-Idempotency-Key":t.idempotencyKey}:{}},body:i},{timeoutMs:t?.timeoutMs,maxRetries:0,maxRequestBytes:MAX_ENCRYPTED_REQUEST_BYTES,expectedStatus:202,strictEnvelope:!0,validateData:e=>isIngestResult(e)})}async submitFingerprint(e,s){return this.m("/v3/submit-fingerprint-event",e,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()})}async submitFingerprintEvent(e,s){const t=compactIdentifiers({unshared_device_id:s?.permanentDeviceId,device_id:s?.deviceId,stable_hash:s?.stableHash??e.fingerprint_id,full_hash:s?.fullHash??e.full_hash,session_hash:s?.sessionHash}),r={fingerprint:asJSONObject(e),context:{sdk:{name:"unshared-clientjs-sdk",version:"3.0.0",runtime:"node"},identity:{...s?.userId?{user_id:s.userId}:{},...s?.emailAddress?{email_address:s.emailAddress}:{}},identifiers:t,event:{...s?.eventType?{event_type:s.eventType}:{},...s?.ipAddress?{ip_address:s.ipAddress}:{},...s?.userAgent?{user_agent:s.userAgent}:{}}}},i=await this.m("/v3/submit-fingerprint-event",r,{idempotencyKey:s?.idempotencyKey??globalThis.crypto.randomUUID()});return i.success?i.data?{success:!0,status:i.status,data:{...i.data,hash:e.full_hash,stable_hash:e.fingerprint_id,version:e.version??"unknown"}}:{success:!1,status:i.status,error:{code:"PARSE_ERROR",message:"Invalid v3 ingestion result"}}:{success:!1,status:i.status,error:i.error}}async processUserEvent(e,s){if(null===e||"object"!=typeof e||Array.isArray(e))return{success:!1,status:400,error:{code:"INVALID_JSON",message:"Request body must be a JSON object"}};const t=new Set(["eventType","userId","ipAddress","deviceId","sessionHash","userAgent","emailAddress","fingerprintId","permanentDeviceId","subscriptionStatus","eventDetails"]);if(!Object.keys(e).every(e=>t.has(e))||"string"!=typeof e.eventType||"string"!=typeof e.userId||"string"!=typeof e.emailAddress||"string"!=typeof e.deviceId||"string"!=typeof e.sessionHash)return this.m("/v3/process-user-event",e,{timeoutMs:s?.timeoutMs});const r=e,i=compactIdentifiers({unshared_device_id:r.permanentDeviceId,device_id:r.deviceId,stable_hash:r.fingerprintId,session_hash:r.sessionHash}),a={event_type:r.eventType,identity:{user_id:r.userId,email_address:r.emailAddress},identifiers:i,context:{ip_address:r.ipAddress,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{}},...r.eventDetails?{event_details:asJSONObject(r.eventDetails)}:{}},n=await this.m("/v3/process-user-event",a,{timeoutMs:s?.timeoutMs});if(!n.success)return{success:!1,status:n.status,error:n.error};const o=await this.checkUser({user_id:r.userId,email_address:r.emailAddress,identifiers:i},{timeoutMs:s?.timeoutMs,maxRetries:s?.maxRetries});return o.success?{success:!0,status:o.status,data:{event:{event_type:r.eventType,user_id:r.userId,email_address:r.emailAddress,ip_address:r.ipAddress,device_id:r.deviceId,...r.permanentDeviceId?{permanent_device_id:r.permanentDeviceId}:{},session_hash:r.sessionHash,user_agent:r.userAgent,...r.subscriptionStatus?{subscription_status:r.subscriptionStatus}:{},...r.eventDetails?{event_details:JSON.stringify(r.eventDetails)}:{}},analysis:{status:o.failedOpen?"error":"success",is_user_flagged:o.data.is_user_flagged,...o.data.enforcement_type?{enforcement_type:o.data.enforcement_type}:{},...o.data.decision_code?{status_details:o.data.decision_code}:{}}},...o.failedOpen?{failedOpen:o.failedOpen}:{}}:{success:!1,status:o.status,error:o.error}}async checkUser(e,s={}){const t="string"==typeof s?{deviceId:s}:s,r="string"==typeof e?{email_address:e,identifiers:compactIdentifiers({unshared_device_id:t.permanentDeviceId,device_id:t.deviceId,stable_hash:t.fingerprintId,full_hash:t.fullHash,session_hash:t.sessionHash})}:e;if("string"!=typeof r.email_address||""===r.email_address.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"email_address must be a non-empty string"}};if(0===Object.keys(r.identifiers).length)return{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:0,reason:"no_device_id"}};const i=await this.p(`${this.o}/v3/check-user`,{method:"POST",headers:{"Content-Type":"application/json","X-Unshared-Enforcement-Version":"1"},body:JSON.stringify(r)},{timeoutMs:t.timeoutMs,maxRetries:t.maxRetries,expectedStatus:200,strictEnvelope:!0,validateData:isCheckUserResult,retryHttpError:(e,s)=>"RATE_LIMIT_UNAVAILABLE"===s.code||"AUDIT_UNAVAILABLE"===s.code});return i.success?"CHECK_UNAVAILABLE"===i.data?.decision_code?{...i,failedOpen:{status:i.status}}:i:{success:!0,status:200,data:{is_user_flagged:!1},failedOpen:{status:i.status}}}async triggerEmailVerification(e,s,t){if("string"!=typeof e||""===e.trim())return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"emailAddress must be a non-empty string"}};const r={email_address:e,identifiers:compactIdentifiers({unshared_device_id:t?.permanentDeviceId,device_id:s,stable_hash:t?.fingerprintId,full_hash:t?.fullHash,session_hash:t?.sessionHash})};if(0===Object.keys(r.identifiers).length)return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"At least one non-empty identifier is required"}};const i=await this.p(`${this.o}/v3/trigger-email-verification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isTriggerEmailResult});return i.success?(this.t.set(e.trim().toLowerCase(),i.data.verification_id),{...i,data:{...i.data,message:"Verification code sent"}}):!i.success&&(0===i.status||i.status>=500)?{success:!1,status:i.status,error:{code:"DELIVERY_FAILED",message:i.error?.message??"Delivery failed"}}:{success:!1,status:i.status,error:i.error??{code:"PARSE_ERROR",message:"Missing v3 verification response"}}}async verify(e,s,t,r){const i=r?.verificationId??this.t.get(e.trim().toLowerCase());if(!i)return{success:!1,status:400,error:{code:"MISSING_VERIFICATION_ID",message:"Trigger email verification before verifying the code"}};if(!UUID_V4_PATTERN.test(i)||!/^\d{6}$/.test(t))return{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verificationId must be a UUIDv4 and code must be exactly 6 digits"}};const a={verification_id:i,code:t},n=await this.p(`${this.o}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult});return!n.success&&(0===n.status||n.status>=500)?{success:!1,status:n.status,error:{code:"DELIVERY_FAILED",message:n.error?.message??"Delivery failed"}}:n.success?!0!==n.data?.verified?{success:!1,status:n.status,error:{code:"VERIFICATION_FAILED",message:"Code is incorrect or expired",details:n.data?.reason?{reason:n.data.reason}:void 0}}:(this.t.delete(e.trim().toLowerCase()),n):n}async verifyEmail(e){return e&&UUID_V4_PATTERN.test(e.verification_id)&&/^\d{6}$/.test(e.code)?this.p(`${this.o}/v3/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},{maxRetries:0,expectedStatus:200,strictEnvelope:!0,validateData:isVerifyEmailResult}):{success:!1,status:400,error:{code:"VALIDATION_ERROR",message:"verification_id must be a UUIDv4 and code must be exactly 6 digits"}}}async getInterstitialFlow(e){const s=new URLSearchParams;return s.set("flow_type",e?.flowType||"email_verification"),s.set("platform",e?.platform||"web"),this.p(`${this.o}/v2/interstitial-flow?${s}`,{method:"GET"})}}
|
package/dist/esm/index.d.mts
CHANGED
|
@@ -6,3 +6,4 @@ export type { ProtectionConfig, Verdict } from './middleware/index.mjs';
|
|
|
6
6
|
export type { UnsharedClientConfig, ApiResult, UnsharedError, SubmitFingerprintOptions, SubmitFingerprintResult, ProcessUserEventParams, ProcessUserEventResult, CheckUserResult, TriggerEmailVerificationResult, VerifyResult, } from './client.mjs';
|
|
7
7
|
export type { UnsharedRequest, UnsharedResponse, UnsharedNextFunction } from './types.mjs';
|
|
8
8
|
export { sendJson } from './middleware/utils/http-helpers.mjs';
|
|
9
|
+
export type { EnforcementType } from './shared-types.mjs';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const DISPATCH_TIMEOUT_MS=2e3;export const SUBMIT_FP_TIMEOUT_MS=3e3;export async function runCheckUser(e,s,
|
|
1
|
+
export const DISPATCH_TIMEOUT_MS=2e3;export const SUBMIT_FP_TIMEOUT_MS=3e3;export async function runCheckUser(e,t,s,r,i){try{const r=e.cache.get(s)?.decisionVersion??0,n=await e.client.checkUser(t,{timeoutMs:i,maxRetries:0});if(n.success&&n.data&&!n.failedOpen){const t=e.cache.get(s)?.decisionVersion;if(t&&t!==r)return;return e.cache.update(s,{isFlagged:n.data.is_user_flagged,enforcementType:n.data.enforcement_type,isVerified:!1}),void e.backoff.noteSuccess()}if(n.failedOpen)return void e.backoff.noteFailure();n.error?.retryAfter?e.backoff.pause(1e3*n.error.retryAfter):e.backoff.noteFailure()}catch(t){e.backoff.noteFailure();try{e.onError&&e.onError(t,{operation:"processUserEvent",userId:s,emailAddress:r})}catch{}}}export async function runProcessUserEvent(e,t,s){try{const r=Object.fromEntries(Object.entries({device_id:t.deviceId,stable_hash:t.fingerprintId,full_hash:t.fullHash,unshared_device_id:t.permanentDeviceId,session_hash:t.sessionHash}).filter(e=>!!e[1]&&"unknown"!==e[1])),i=await e.client.processUserEvent({event_type:t.eventType,identity:{user_id:t.userId,email_address:t.emailAddress},identifiers:r,context:{ip_address:t.ipAddress,user_agent:t.userAgent}},{timeoutMs:s,maxRetries:0});if(i.failedOpen)return void e.backoff.noteFailure();i.success?await runCheckUser(e,{user_id:t.userId,email_address:t.emailAddress,identifiers:r},t.userId,t.emailAddress,s):i.error?.retryAfter?e.backoff.pause(1e3*i.error.retryAfter):e.backoff.noteFailure()}catch(s){e.backoff.noteFailure();try{e.onError&&e.onError(s,{operation:"processUserEvent",userId:t.userId,emailAddress:t.emailAddress})}catch{}}}
|
|
@@ -112,6 +112,13 @@ export interface ProtectionConfig<TReq extends UnsharedRequest = UnsharedRequest
|
|
|
112
112
|
* `unshared-frontend-sdk` installed + the default `routePrefix`. @default undefined
|
|
113
113
|
*/
|
|
114
114
|
flaggedMode?: 'gate' | 'overlay';
|
|
115
|
+
/**
|
|
116
|
+
* Trusted, standalone HTML for hard-blocked navigations (HTTP 403).
|
|
117
|
+
* Use a contact-support modal with no protected content or verification flow.
|
|
118
|
+
* Applies only when enforcement is enabled; JSON responses are unchanged.
|
|
119
|
+
* @default Built-in access-denied page
|
|
120
|
+
*/
|
|
121
|
+
hardBlockPage?: string;
|
|
115
122
|
/**
|
|
116
123
|
* Auto-render the interstitial modal on SPA/JSON `403 account_flagged` paths
|
|
117
124
|
* (and the deferred `/status` poll) with no app code. When `true`, the injected
|
|
@@ -1 +1 @@
|
|
|
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}`)}
|
|
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,HARD_BLOCK_PAGE}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:n,routePrefix:i="/__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:_,onFailOpen:I,blockFlagged:v=!1,flaggedMode:C,hardBlockPage:S=HARD_BLOCK_PAGE,autoInterstitial:y=!1,interstitialFlowType:k="email_verification"}=t,A=C??(v?"gate":void 0),T=y||"overlay"===A,E=e=>{if(I)try{I(e)}catch{}else"async_miss"!==e.reason&&warnFailOpenThrottled(e)},x=new VerdictCache(o,a),F=new RateLimitBackoff,U=new Map,j=new DispatchDedupe,P=Date.now().toString(36),O=generateFingerprintScript(i,P,{autoInterstitial:T,interstitialFlowType:k,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 w=createFingerprintBundleSource({disabled:t.disableS3Fingerprint}),D=void 0!==A||T,b="gate"===A?"flaggedMode 'gate' (blockFlagged)":"overlay"===A?"flaggedMode 'overlay'":"autoInterstitial";if(D&&!M)throw new Error(`[Unshared] ${b} requires unshared-frontend-sdk to be installed (its UMD bundle renders the interstitial).`);if(D&&"/__unshared"!==i)throw new Error(`[Unshared] ${b} requires the default routePrefix ("/__unshared"); the browser SDK proxy routes are fixed to that prefix.`);const R="gate"===A?generateGatePage(i,P):"",H=handleSubmitFingerprint({client:e,verdictCache:x,rateLimitBackoff:F,dispatchDedupe:j,resolveUserId:r,resolveEmailAddress:n,resolveSessionId:f,resolveDeviceId:h,disableBotFilter:u,onError:_}),$=handleVerifyTrigger({client:e,verdictCache:x,resolveEmailAddress:n,resolveDeviceId:h,resolveSessionId:f,onError:_}),B=handleVerify({client:e,verdictCache:x,resolveUserId:r,resolveEmailAddress:n,resolveDeviceId:h,resolveSessionId:f,onError:_}),N=handleGetInterstitialFlow({client:e}),L=s?Array.isArray(s)?s:[s]:null,V=`${i}/fp.js`,G=`${i}/fingerprint.js`,q=`${i}/submit-fp`,X=`${i}/verify-trigger`,K=`${i}/verify`,J=`${i}/status`,W=`${i}/interstitial-flow`,z=function(t,s,o){const a=getRequestPath(t.url),I=t.url||a;if(a.startsWith(i+"/")){if(function(e,t){if(!L)return;const r=e.headers.origin??"";L.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, X-Unshared-Enforcement-Type")):L.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, X-Unshared-Enforcement-Type"),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===V)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===G)return void w.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===X||a===K))return void readJsonBody(t,s).then(e=>{if(e)return a===q?H(t,s):a===X?$(t,s):B(t,s)}).catch(o);if("GET"===t.method&&a===W)return void N(t,s);if("GET"===t.method&&a===J){let i;s.setHeader("Cache-Control","no-store");try{i=r(t)}catch{}if(!i)return void sendJson(s,200,{status:"anonymous"});const o=resolveEmail(t,n);return void(async()=>{let r=x.get(i);if((!r||x.isStale(i))&&o&&!F.isPaused()&&!x.isRefreshing(i)){x.markRefreshing(i);try{const n=extractDeviceIdOrUndefined(t,h),s=extractFingerprintId(t),a=extractFullHash(t),d=extractPermanentDeviceId(t),c=extractSessionId(t,f);await fetchAndCacheVerdict(e,x,i,o,n,s,a,d,c,p,(e,t)=>E({operation:"checkUser",reason:e,status:t,userId:i,emailAddress:o})),r=x.get(i)}catch(e){_&&_(e,{operation:"checkUser",userId:i,emailAddress:o}),E({operation:"checkUser",reason:"exception",userId:i,emailAddress:o})}finally{x.clearRefreshing(i)}}r&&("hard_block"===r.enforcementType||r.isFlagged&&!r.isVerified)&&(void 0!==A||g)&&o?sendJson(s,200,{status:"flagged",email:maskEmail(o),...r.enforcementType?{enforcement_type:r.enforcementType}:{}}):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!==A))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"),n=r?Number(r):NaN,i=Number.isFinite(n)&&Date.now()-n<=SENTINEL_STICKINESS_TTL_MS;v=e&&i?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,O,d),void o()}const C=resolveEmail(t,n);if(setUserIdCookie(t,s,v),C&&setEmailCookie(t,s,C),!shouldIncludePath(a,l))return interceptForInjection(t,s,O,d),void o();if(!C)return interceptForInjection(t,s,O,d),void o();const y=extractSessionId(t,f),k=extractDeviceIdOrUndefined(t,h),T=extractFingerprintId(t),P=extractFullHash(t),D=extractPermanentDeviceId(t),b=t.headers["user-agent"]??"",z=extractClientIp(t);if(!A&&!u&&isBot(b))return void o();const Q=x.get(v);if(!Q){if("async"===m)return x.isRefreshing(v)||(x.markRefreshing(v),fetchAndCacheVerdict(e,x,v,C,k,T,P,D,y,p,(e,t)=>E({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:C})).catch(()=>E({operation:"checkUser",reason:"exception",userId:v,emailAddress:C})).finally(()=>x.clearRefreshing(v))),E({operation:"checkUser",reason:"async_miss",userId:v,emailAddress:C}),Y(),interceptForInjection(t,s,O,d),void o();let r=U.get(v);return r||(r=fetchAndCacheVerdict(e,x,v,C,k,T,P,D,y,p,(e,t)=>E({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:C})).finally(()=>U.delete(v)),U.set(v,r)),void r.then(e=>{e.isFlagged||Y(),applyVerdict(e,v,C,t,s,o,O,g,A,R,d,S)}).catch(()=>{E({operation:"checkUser",reason:"exception",userId:v,emailAddress:C}),Y(),interceptForInjection(t,s,O,d),o()})}function Y(){!u&&isBot(b)||y&&"unknown"!==y&&(F.isPaused()||dispatchUserEvent(e,x,F,j,{userId:v,emailAddress:C,sessionId:y,deviceId:k,fingerprintId:T,fullHash:P,permanentDeviceId:D,userAgent:b,ipAddress:z,eventType:I},_))}x.isStale(v)&&!x.isRefreshing(v)&&(x.markRefreshing(v),fetchAndCacheVerdict(e,x,v,C,k,T,P,D,y,p,(e,t)=>E({operation:"checkUser",reason:e,status:t,userId:v,emailAddress:C})).catch(()=>E({operation:"checkUser",reason:"exception",userId:v,emailAddress:C})).finally(()=>x.clearRefreshing(v))),Q.isFlagged||Y(),applyVerdict(Q,v,C,t,s,o,O,g,A,R,d,S)};return z.destroy=()=>{x.destroy(),w.stop()},z}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 n=e.body?.email;return"string"==typeof n&&n?n:void 0}function applyVerdict(e,t,r,n,i,s,o,a,d,c,l,u){const p="hard_block"===e.enforcementType,m=p||e.isFlagged&&!e.isVerified;if(d&&p)return i.setHeader("Cache-Control","no-store"),void(isHtmlNavigation(n.method,n.headers.accept)?(i.setHeader("Content-Type","text/html; charset=utf-8"),i.statusCode=403,i.end(u)):sendJson(i,403,flaggedResponse(r,e.enforcementType)));if("gate"===d&&m)isHtmlNavigation(n.method,n.headers.accept)?(i.statusCode=200,i.setHeader("Content-Type","text/html; charset=utf-8"),i.setHeader("Cache-Control","no-store"),i.end(c)):sendJson(i,403,flaggedResponse(r,e.enforcementType));else if("overlay"===d&&m)isHtmlNavigation(n.method,n.headers.accept)?(interceptForInjection(n,i,o,l),s()):sendJson(i,403,flaggedResponse(r,e.enforcementType));else if(interceptForInjection(n,i,o,l),m&&a)try{a({userId:t,emailAddress:r,verdict:e,req:n,res:i,next:s})}catch{s()}else s()}function interceptForInjection(e,t,r,n){delete e.headers["if-none-match"],delete e.headers["if-modified-since"],interceptResponse(t,(e,t)=>{if(!isHtmlContentType(t))return null;const n=e.toString("utf8"),i=n.lastIndexOf("</body>");return-1===i?n+r:n.slice(0,i)+r+n.slice(i)},{preventCaching:!0,streamingIdleMs:n})}function dispatchUserEvent(e,t,r,n,i,s){n.mark(i.userId,i.eventType),runProcessUserEvent({client:e,cache:t,backoff:r,onError:s},{eventType:i.eventType,userId:i.userId,emailAddress:i.emailAddress,ipAddress:i.ipAddress,deviceId:i.deviceId,fingerprintId:i.fingerprintId,fullHash:i.fullHash,permanentDeviceId:i.permanentDeviceId,sessionHash:i.sessionId,userAgent:i.userAgent},DISPATCH_TIMEOUT_MS)}async function fetchAndCacheVerdict(e,t,r,n,i,s,o,a,d,c=CHECK_USER_TIMEOUT_MS,l){const u={timeoutMs:c,maxRetries:0};i&&"unknown"!==i&&(u.deviceId=i),s&&"unknown"!==s&&(u.fingerprintId=s),o&&"unknown"!==o&&(u.fullHash=o),a&&(u.permanentDeviceId=a),d&&"unknown"!==d&&(u.sessionHash=d);const p=t.get(r)?.decisionVersion??0;let m;const f=await Promise.race([e.checkUser(n,u),new Promise(e=>{m=setTimeout(()=>e(null),c)})]);if(clearTimeout(m),!f)return l?.("timeout"),cacheFailOpenVerdict(t,r,n,d);if(f.failedOpen)return l?.(f.failedOpen.reason??"http_error",f.failedOpen.status),cacheFailOpenVerdict(t,r,n,d);const h=t.get(r);return h?.decisionVersion&&h.decisionVersion!==p?h:(t.set(r,{isFlagged:f.data?.is_user_flagged??!1,enforcementType:f.data?.enforcement_type,isVerified:!1,emailAddress:n,sessionId:d}),t.get(r))}function cacheFailOpenVerdict(e,t,r,n){const i=e.get(t);return e.set(t,{isFlagged:i?.isFlagged??!1,enforcementType:i?.enforcementType,isVerified:i?.isVerified??!1,emailAddress:r,sessionId:n},5e3,!1),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 n=Array.isArray(r)?[...r]:[String(r)];n.push(t),e.setHeader("Set-Cookie",n)}else e.setHeader("Set-Cookie",t)}function setUserIdCookie(e,t,r){const n=isSecureRequest(e)?"; Secure":"";appendSetCookie(t,`__unshared_uid=${encodeURIComponent(r)}; Path=/; SameSite=Lax; Max-Age=31536000${n}`),appendSetCookie(t,`__unshared_uid_at=${Date.now()}; Path=/; SameSite=Lax; Max-Age=31536000${n}`)}function setEmailCookie(e,t,r){const n=isSecureRequest(e)?"; Secure":"";appendSetCookie(t,`__unshared_email=${encodeURIComponent(r)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=31536000${n}`)}
|
|
@@ -1 +1 @@
|
|
|
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
|
+
export function generateFingerprintScript(e,n,t){const r=n?`?v=${escapeJavaScript(n)}`:"",i=t?.autoInterstitial?`\nvar _isdk=new UnsharedBrowser.UnsharedBrowser({baseUrl:""});\nvar _isdkShow=function(e){var d=(e&&e.detail)||shared.flagged||{};try{_isdk.showInterstitial({enforcementType:d.enforcement_type,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 if(body.enforcement_type)d.enforcement_type=body.enforcement_type;\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 +1 @@
|
|
|
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"),
|
|
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"),n=i?Array.isArray(i)?[...i]:[String(i)]:[];n.push(s),e.setHeader("Set-Cookie",n)}export function handleVerifyTrigger(e){return async(s,i)=>{try{const n=resolveEmail(s,s.body??{},e.resolveEmailAddress);if(!n)return void sendJson(i,400,{success:!1,error:{code:"VALIDATION_ERROR",message:"Email is required"}});const r=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(n,r&&"unknown"!==r?r:"",{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 n=(s.body??{}).code,r=parseCookie(s,VERIFICATION_COOKIE);if(!r||!n)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:r,code:n});if(o.success&&o.data?.verified){let n,r,a=!1;try{r=e.resolveUserId?.(s)}catch{}const t=resolveEmail(s,{},e.resolveEmailAddress),d=extractDeviceIdOrUndefined(s,e.resolveDeviceId),c=parseCookie(s,"__unshared_stable_hash")||parseCookie(s,"__unshared_fp_id")||void 0,u=parseCookie(s,"__unshared_full_hash")||parseCookie(s,"__unshared_fingerprint_id")||void 0,_=extractPermanentDeviceId(s),f=resolveSessionHash(s,e.resolveSessionId);if(r&&t){const s={...d&&"unknown"!==d?{device_id:d}:{},...c&&"unknown"!==c?{stable_hash:c}:{},...u&&"unknown"!==u?{full_hash:u}:{},..._?{unshared_device_id:_}:{},...f?{session_hash:f}:{}},i=e.verdictCache.get(r)?.decisionVersion??0,o=await e.client.checkUser({user_id:r,email_address:t,identifiers:s},{maxRetries:0});o.success&&o.data&&!o.failedOpen&&(e.verdictCache.get(r)?.decisionVersion??0)===i&&(e.verdictCache.update(r,{...o.data.enforcement_type?{isFlagged:o.data.is_user_flagged}:{},enforcementType:o.data.enforcement_type,isVerified:!o.data.is_user_flagged}),a=!o.data.is_user_flagged),n=e.verdictCache.get(r)?.enforcementType}const l=isSecureRequest(s)?"; Secure":"";appendCookie(i,`${VERIFICATION_COOKIE}=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0${l}`),n&&i.setHeader("X-Unshared-Enforcement-Type",n),a&&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 n=parseCookie(e,"__unshared_email");if(n)return n;const r=s.email;return"string"==typeof r&&r?r:void 0}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EnforcementType } from '../../shared-types.mjs';
|
|
1
2
|
export declare const ACCOUNT_FLAGGED_ERROR: "account_flagged";
|
|
2
3
|
/**
|
|
3
4
|
* Standardized response body for a flagged, unverified user. The injected
|
|
@@ -8,7 +9,10 @@ export declare const ACCOUNT_FLAGGED_ERROR: "account_flagged";
|
|
|
8
9
|
* any same-origin script via `e.detail.email`. The SDK's own modal resolves the
|
|
9
10
|
* real identity server-side, so it never needs the full address here.
|
|
10
11
|
*/
|
|
11
|
-
export declare function flaggedResponse(email: string): {
|
|
12
|
+
export declare function flaggedResponse(email: string, enforcementType?: EnforcementType): {
|
|
13
|
+
readonly enforcement_type?: EnforcementType | undefined;
|
|
12
14
|
readonly error: "account_flagged";
|
|
13
15
|
readonly email: string;
|
|
14
16
|
};
|
|
17
|
+
/** No protected markup, scripts, verification controls, or external dependencies. */
|
|
18
|
+
export declare const HARD_BLOCK_PAGE = "<!doctype html><html lang=\"en\"><head>\n<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<meta name=\"robots\" content=\"noindex,nofollow\"><title>Access denied</title>\n<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0b0b0c;color:#e5e7eb;font-family:system-ui,sans-serif}main{max-width:32rem;padding:2rem;text-align:center}</style>\n</head><body><main><h1>Access denied</h1><p>Your account cannot access this content. Contact support for assistance.</p></main></body></html>";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{maskEmail}from"./mask-email.mjs";export const ACCOUNT_FLAGGED_ERROR="account_flagged";export function flaggedResponse(
|
|
1
|
+
import{maskEmail}from"./mask-email.mjs";export const ACCOUNT_FLAGGED_ERROR="account_flagged";export function flaggedResponse(e,t){return{error:"account_flagged",email:maskEmail(e),...t?{enforcement_type:t}:{}}}export const HARD_BLOCK_PAGE='<!doctype html><html lang="en"><head>\n<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">\n<meta name="robots" content="noindex,nofollow"><title>Access denied</title>\n<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0b0b0c;color:#e5e7eb;font-family:system-ui,sans-serif}main{max-width:32rem;padding:2rem;text-align:center}</style>\n</head><body><main><h1>Access denied</h1><p>Your account cannot access this content. Contact support for assistance.</p></main></body></html>';
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
+
import type { EnforcementType } from '../shared-types.mjs';
|
|
1
2
|
export interface Verdict {
|
|
3
|
+
enforcementType?: EnforcementType;
|
|
4
|
+
/** @internal Changes only when an authoritative decision is written. */
|
|
5
|
+
decisionVersion?: number;
|
|
2
6
|
isFlagged: boolean;
|
|
3
7
|
isVerified: boolean;
|
|
4
8
|
emailAddress: string;
|
|
@@ -8,6 +12,7 @@ export interface Verdict {
|
|
|
8
12
|
}
|
|
9
13
|
export declare class VerdictCache {
|
|
10
14
|
private readonly _entries;
|
|
15
|
+
private _decisionVersion;
|
|
11
16
|
private readonly _activeRefreshes;
|
|
12
17
|
private readonly _defaultTtlMs;
|
|
13
18
|
private readonly _maxSize;
|
|
@@ -15,12 +20,12 @@ export declare class VerdictCache {
|
|
|
15
20
|
constructor(defaultTTL?: number, maxSize?: number);
|
|
16
21
|
private _ensureSweepTimer;
|
|
17
22
|
get(userId: string): Verdict | undefined;
|
|
18
|
-
set(userId: string, verdict: Omit<Verdict, 'cachedAt' | 'ttl'>, ttl?: number): void;
|
|
23
|
+
set(userId: string, verdict: Omit<Verdict, 'cachedAt' | 'ttl' | 'decisionVersion'>, ttl?: number, authoritative?: boolean): void;
|
|
19
24
|
/**
|
|
20
25
|
* Update an existing cache entry (e.g. from webhook).
|
|
21
26
|
* If the user is not in cache, creates a new entry.
|
|
22
27
|
*/
|
|
23
|
-
update(userId: string, partial: Partial<Pick<Verdict, 'isFlagged' | 'isVerified'>>): void;
|
|
28
|
+
update(userId: string, partial: Partial<Pick<Verdict, 'isFlagged' | 'isVerified' | 'enforcementType'>>): void;
|
|
24
29
|
delete(userId: string): void;
|
|
25
30
|
/**
|
|
26
31
|
* Returns true if the entry exists but is past its TTL.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const DEFAULT_TTL_MS=6e4,DEFAULT_MAX_SIZE=1e4,SWEEP_INTERVAL_MS=3e5;export class VerdictCache{constructor(t=6e4,s=1e4){this.t=new Map,this.i=new Set,this.
|
|
1
|
+
const DEFAULT_TTL_MS=6e4,DEFAULT_MAX_SIZE=1e4,SWEEP_INTERVAL_MS=3e5;export class VerdictCache{constructor(t=6e4,s=1e4){this.t=new Map,this.i=0,this.h=new Set,this.o=null,this.l=t,this.u=s}_(){if(!this.o)try{this.o=setInterval(()=>this.p(),3e5),this.o&&"function"==typeof this.o.unref&&this.o.unref()}catch{this.o=null}}get(t){return this.t.get(t)}set(t,s,i,e=!0){this._();const h=e?++this.i:this.t.get(t)?.decisionVersion??0;!this.t.has(t)&&this.t.size>=this.u?this.T():this.t.has(t)&&this.t.delete(t),this.t.set(t,{...s,decisionVersion:h,cachedAt:Date.now(),ttl:i??this.l})}update(t,s){this._();const i=this.t.get(t);i?(i.decisionVersion=++this.i,i.cachedAt=Date.now(),void 0!==s.isFlagged&&(i.isFlagged=s.isFlagged),void 0!==s.isVerified&&(i.isVerified=s.isVerified),"enforcementType"in s&&(i.enforcementType=s.enforcementType),this.t.delete(t),this.t.set(t,i)):(this.t.size>=this.u&&this.T(),this.t.set(t,{enforcementType:s.enforcementType,decisionVersion:++this.i,isFlagged:s.isFlagged??!1,isVerified:s.isVerified??!1,emailAddress:"",sessionId:"",cachedAt:Date.now(),ttl:this.l}))}delete(t){this.t.delete(t),this.h.delete(t)}isStale(t){const s=this.t.get(t);return!!s&&Date.now()-s.cachedAt>s.ttl}isRefreshing(t){return this.h.has(t)}markRefreshing(t){this.h.add(t)}clearRefreshing(t){this.h.delete(t)}get size(){return this.t.size}clear(){this.t.clear(),this.h.clear()}destroy(){this.o&&(clearInterval(this.o),this.o=null),this.clear()}p(){const t=Date.now();for(const[s,i]of this.t)t-i.cachedAt>2*i.ttl&&(this.t.delete(s),this.h.delete(s))}T(){const t=this.t.keys().next().value;void 0!==t&&(this.t.delete(t),this.h.delete(t))}}
|
|
@@ -96,7 +96,11 @@ export type CheckDecisionCode =
|
|
|
96
96
|
| 'IDENTITY_UNCERTAIN'
|
|
97
97
|
| 'CHECK_UNAVAILABLE';
|
|
98
98
|
|
|
99
|
+
export type EnforcementType = 'no_enforcement' | 'soft_block' | 'hard_block';
|
|
100
|
+
|
|
99
101
|
export interface CheckUserResult {
|
|
102
|
+
/** Negotiated by X-Unshared-Enforcement-Version: 1; absent on older backends. */
|
|
103
|
+
enforcement_type?: EnforcementType;
|
|
100
104
|
is_user_flagged: boolean;
|
|
101
105
|
decision_id: string;
|
|
102
106
|
decision_code: CheckDecisionCode;
|