@shieldlabs-ai/node 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/constants.ts","../src/errors.ts","../src/normalize.ts","../src/version.ts","../src/runtime.ts","../src/webhooks.ts","../src/http.ts","../src/validation.ts","../src/history.ts","../src/management.ts","../src/risk.ts","../src/index.ts"],"names":["backend","DEFAULT_TIMEOUT_MS","DEFAULT_MAX_RETRIES","band"],"mappings":";;;;;AAGO,IAAM,QAAA,GAAW;AAMjB,IAAM,OAAA,GAAU,OAAO,MAAA,CAAO;AAAA,EACnC,GAAA,EAAK,KAAA;AAAA,EACL,mBAAA,EAAqB,qBAAA;AAAA,EACrB,WAAA,EAAa,aAAA;AAAA,EACb,kBAAA,EAAoB,oBAAA;AAAA,EACpB,uBAAA,EAAyB,yBAAA;AAAA,EACzB,0BAAA,EAA4B,4BAAA;AAAA,EAC5B,kBAAA,EAAoB,oBAAA;AAAA,EACpB,gBAAA,EAAkB,kBAAA;AAAA,EAClB,oBAAA,EAAsB,sBAAA;AAAA,EACtB,eAAA,EAAiB,iBAAA;AAAA,EACjB,iBAAA,EAAmB,mBAAA;AAAA,EACnB,GAAA,EAAK,KAAA;AAAA,EACL,aAAA,EAAe,eAAA;AAAA,EACf,KAAA,EAAO,OAAA;AAAA,EACP,aAAA,EAAe,eAAA;AAAA,EACf,MAAA,EAAQ,QAAA;AAAA,EACR,iBAAA,EAAmB,mBAAA;AAAA,EACnB,YAAA,EAAc;AAChB,CAAU;AAMH,IAAM,UAAA,GAAa,OAAO,MAAA,CAAO;AAAA,EACtC,OAAA,EAAS,OAAO,MAAA,CAAO,EAAE,KAAK,CAAA,EAAG,GAAA,EAAK,IAAI,CAAA;AAAA,EAC1C,UAAA,EAAY,OAAO,MAAA,CAAO,EAAE,KAAK,EAAA,EAAI,GAAA,EAAK,IAAI,CAAA;AAAA,EAC9C,SA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MAAA,EAAiC;AAC5E,EAAA,OAAO,mBAAA,CAAoB,OAAA,EAAS,MAAA,EAAQ,MAAM,CAAA;AACpD","file":"index.js","sourcesContent":["import type { DetectionFlags, LookupType, RiskBand } from './types.js';\n\n/** The all-zero UUID. As a device ID it means \"no usable device signals\". */\nexport const NIL_UUID = '00000000-0000-0000-0000-000000000000';\n\n/**\n * Known risk signal slugs (`IdentificationSignal.name`). Signal names are an open set: new slugs\n * can appear at any time, so compare against these constants and never treat them as exhaustive.\n */\nexport const SIGNALS = Object.freeze({\n TOR: 'tor',\n JAVASCRIPT_DISABLED: 'javascript_disabled',\n OS_MISMATCH: 'os_mismatch',\n ANTIDETECT_BROWSER: 'antidetect_browser',\n PROXY_ROUTED_ANTIDETECT: 'proxy_routed_antidetect',\n PORT_SCAN_ROUTED_VIA_PROXY: 'port_scan_routed_via_proxy',\n BROWSER_AUTOMATION: 'browser_automation',\n STUN_NOT_CHECKED: 'stun_not_checked',\n STUN_LATE_CORRECTION: 'stun_late_correction',\n OS_NOT_DETECTED: 'os_not_detected',\n BROWSER_VPN_PROXY: 'browser_vpn_proxy',\n VPN: 'vpn',\n PRIVACY_RELAY: 'privacy_relay',\n PROXY: 'proxy',\n DATACENTER_IP: 'datacenter_ip',\n ABUSER: 'abuser',\n TIMEZONE_MISMATCH: 'timezone_mismatch',\n RATE_LIMITED: 'rate_limited',\n} as const);\n\n/** A known signal slug. */\nexport type KnownSignal = (typeof SIGNALS)[keyof typeof SIGNALS];\n\n/** Score ranges of the three risk bands (inclusive). */\nexport const RISK_BANDS = Object.freeze({\n trusted: Object.freeze({ min: 0, max: 29 }),\n suspicious: Object.freeze({ min: 30, max: 59 }),\n dangerous: Object.freeze({ min: 60, max: 100 }),\n} as const);\n\nexport const RISK_BAND_NAMES: readonly RiskBand[] = ['trusted', 'suspicious', 'dangerous'];\n\nexport const LOOKUP_TYPES: readonly LookupType[] = [\n 'ip',\n 'user_hid',\n 'visitor_id',\n 'request_id',\n 'device_id',\n 'session_id',\n 'cookie_id',\n];\n\nexport type FlagKey = keyof DetectionFlags;\n\n/** The 19 detection flag keys, in the order the webhook payload lists them. */\nexport const FLAG_KEYS: readonly FlagKey[] = [\n 'vpn',\n 'privacy_relay',\n 'browser_vpn_proxy',\n 'tor',\n 'proxy',\n 'datacenter_ip',\n 'abuser',\n 'os_mismatch',\n 'os_not_detected',\n 'timezone_mismatch',\n 'anti_detect_browser',\n 'browser_automation',\n 'ip_mismatch',\n 'incognito',\n 'search_bot',\n 'suspicious_paid_click',\n 'javascript_disabled',\n 'stun_not_checked',\n 'check_incomplete',\n];\n\n/** Webhook schema version this SDK was built for. */\nexport const KNOWN_SCHEMA_VERSION = '2026-06-01';\n\nexport const DEFAULT_HISTORY_BASE_URL = 'https://account.shieldlabs.ai';\nexport const DEFAULT_MANAGEMENT_BASE_URL = 'https://api.shieldlabs.ai';\n","/**\n * Error hierarchy of the SDK.\n *\n * ShieldLabsError\n * ApiError (the server answered with an error status or an unusable body)\n * BadRequestError (400), AuthenticationError (401, 403), QuotaExceededError (402),\n * NotFoundError (404), RateLimitError (429), ServerError (5xx)\n * ConnectionError (network failure), TimeoutError (per-attempt timeout)\n * SignatureVerificationError, WebhookParseError\n * ValidationError (invalid arguments, detected before any HTTP request)\n */\n\n/** Minimal view of response headers (a `Headers` object satisfies it). */\nexport interface HeadersLike {\n get(name: string): string | null;\n}\n\n/** Base class of every error thrown by this SDK. */\nexport class ShieldLabsError extends Error {\n override name = 'ShieldLabsError';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options?.cause === undefined ? undefined : { cause: options.cause });\n }\n}\n\nexport interface ApiErrorOptions {\n status: number;\n /** Parsed response body: a JSON value when the body parses as JSON, the raw text otherwise, null when empty. */\n body?: unknown;\n headers?: HeadersLike | undefined;\n cause?: unknown;\n}\n\nconst EMPTY_HEADERS: HeadersLike = { get: () => null };\n\n/** The server answered with an error status (or a success status with an unusable body). */\nexport class ApiError extends ShieldLabsError {\n override name = 'ApiError';\n /** HTTP status code. */\n readonly status: number;\n /** Parsed response body: JSON value, raw text, or null when the body was empty. */\n readonly body: unknown;\n /** Response headers. */\n readonly headers: HeadersLike;\n\n constructor(message: string, options: ApiErrorOptions) {\n super(message, { cause: options.cause });\n this.status = options.status;\n this.body = options.body === undefined ? null : options.body;\n this.headers = options.headers ?? EMPTY_HEADERS;\n }\n}\n\n/** HTTP 400. */\nexport class BadRequestError extends ApiError {\n override name = 'BadRequestError';\n}\n\n/** HTTP 401 or 403: the key, secret or domain is wrong, or the domain is disabled. */\nexport class AuthenticationError extends ApiError {\n override name = 'AuthenticationError';\n}\n\n/**\n * HTTP 402. Neither the History API nor the Management API returns it today: an account over its\n * included volume keeps working and its profile shows a negative remaining count.\n */\nexport class QuotaExceededError extends ApiError {\n override name = 'QuotaExceededError';\n}\n\n/** HTTP 404: usually a wrong base URL or path. */\nexport class NotFoundError extends ApiError {\n override name = 'NotFoundError';\n}\n\n/** HTTP 429. */\nexport class RateLimitError extends ApiError {\n override name = 'RateLimitError';\n /** Seconds to wait, from the Retry-After header, when the server sent one. */\n readonly retryAfter: number | undefined;\n\n constructor(message: string, options: ApiErrorOptions & { retryAfter?: number | undefined }) {\n super(message, options);\n this.retryAfter = options.retryAfter;\n }\n}\n\n/** HTTP 5xx, including gateway errors from edge proxies. */\nexport class ServerError extends ApiError {\n override name = 'ServerError';\n}\n\n/** The request never produced an HTTP response (DNS, TLS, connection reset, and so on). */\nexport class ConnectionError extends ShieldLabsError {\n override name = 'ConnectionError';\n}\n\n/** A request attempt took longer than the configured timeout. */\nexport class TimeoutError extends ShieldLabsError {\n override name = 'TimeoutError';\n}\n\n/** The X-Shield-Signature header is missing, malformed or does not match the body. */\nexport class SignatureVerificationError extends ShieldLabsError {\n override name = 'SignatureVerificationError';\n}\n\n/** The webhook body is authentic but is not a usable ShieldLabs event. */\nexport class WebhookParseError extends ShieldLabsError {\n override name = 'WebhookParseError';\n}\n\n/** An argument is invalid. Thrown before any HTTP request is sent. */\nexport class ValidationError extends ShieldLabsError {\n override name = 'ValidationError';\n}\n","/**\n * Normalization of History API rows and webhook `data` objects into one `Identification` shape.\n *\n * This module follows the shared normalization rules used by every ShieldLabs server SDK,\n * including their edge cases (truthiness of flag values, whitespace trimming rules and\n * timestamp handling), so that all SDKs produce identical results for identical input.\n * The only intentional differences are type guarantees: a value of the wrong JSON type becomes\n * \"\" (strings), 0 (weights) or NaN (scores) instead of being passed through.\n */\nimport { FLAG_KEYS, type FlagKey } from './constants.js';\nimport type {\n DetectionFlags,\n DomainProfile,\n Identification,\n IdentificationSignal,\n IpInfo,\n TrafficSource,\n} from './types.js';\n\nexport type JsonObject = Record<string, unknown>;\n\nexport function isPlainObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasOwn(obj: JsonObject, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/** Own property value, or undefined when the key is absent. */\nfunction own(obj: JsonObject, key: string): unknown {\n return hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n/** A string property, or \"\" when it is absent or not a string. */\nfunction stringField(obj: JsonObject, key: string): string {\n const value = own(obj, key);\n return typeof value === 'string' ? value : '';\n}\n\n/** Truthiness as defined by the shared rules: empty strings, arrays and objects, 0 and null are false. */\nexport function isTruthy(value: unknown): boolean {\n if (value === undefined || value === null) return false;\n if (typeof value === 'boolean') return value;\n if (typeof value === 'number') return value !== 0;\n if (typeof value === 'string') return value.length > 0;\n if (Array.isArray(value)) return value.length > 0;\n if (typeof value === 'object') return Object.keys(value).length > 0;\n return true;\n}\n\n// Unicode whitespace as defined by the shared rules. Differs from String.prototype.trim():\n// it includes U+001C to U+001F and U+0085, and excludes U+FEFF.\nconst WHITESPACE = new Set<number>([\n 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x85, 0xa0, 0x1680, 0x2000, 0x2001,\n 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f,\n 0x205f, 0x3000,\n]);\n\n/** Trims whitespace (as defined above) from both ends. */\nexport function stripWhitespace(text: string): string {\n let start = 0;\n let end = text.length;\n while (start < end && WHITESPACE.has(text.charCodeAt(start))) start++;\n while (end > start && WHITESPACE.has(text.charCodeAt(end - 1))) end--;\n return text.slice(start, end);\n}\n\nfunction stripUnderscores(text: string): string {\n let start = 0;\n let end = text.length;\n while (start < end && text[start] === '_') start++;\n while (end > start && text[end - 1] === '_') end--;\n return text.slice(start, end);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Signal slugs\n// ---------------------------------------------------------------------------------------------\n\nconst EXACT_SLUGS = new Map<string, string>([\n ['Is tor', 'tor'],\n ['Is VPN', 'vpn'],\n ['Is privacy relay', 'privacy_relay'],\n ['Is proxy', 'proxy'],\n ['Is datacenter', 'datacenter_ip'],\n ['Is abuser', 'abuser'],\n ['Stun is not checked', 'stun_not_checked'],\n ['Stun passed (late arrival, corrected)', 'stun_late_correction'],\n ['UA OS is not detected', 'os_not_detected'],\n ['Network OS is not detected', 'os_not_detected'],\n ['Browser timezone ≠ IP-timezone', 'timezone_mismatch'],\n ['Browser VPN/Proxy', 'browser_vpn_proxy'],\n ['Browser Automation', 'browser_automation'],\n ['Port scan routed via proxy (antidetect browser pattern)', 'proxy_routed_antidetect'],\n ['User has been banned 1H, to many requests', 'rate_limited'],\n]);\n\nconst PREFIX_SLUGS: ReadonlyArray<readonly [prefix: string, slug: string]> = [\n ['Antidetect browser', 'antidetect_browser'],\n ['Os_mismatch', 'os_mismatch'],\n ['OS mismatch2', 'os_mismatch2'],\n ['TCP handshake', 'tcp_handshake_v2'],\n ['Latency test', 'ws_tcp_latency'],\n ['JavaScript disabled', 'javascript_disabled'],\n];\n\nconst STICKY_PREFIX = 'Sticky verdict: ';\nconst LETTER_OR_DIGIT = /^[\\p{L}\\p{Nd}]$/u;\n\n/**\n * Slug for a description without an explicit mapping: the text before the first \"(\",\n * lowercased, with spaces, \"-\" and \"/\" collapsed to \"_\", \"≠\" written as \"_neq_\" and any other\n * punctuation dropped.\n */\nexport function fallbackSlug(description: string): string {\n let text = stripWhitespace(description);\n const paren = text.indexOf('(');\n if (paren >= 0) text = stripWhitespace(text.slice(0, paren));\n let out = '';\n let previousWasSeparator = false;\n for (const ch of text) {\n if (ch === ' ' || ch === '-' || ch === '/') {\n if (!previousWasSeparator && out.length > 0) {\n out += '_';\n previousWasSeparator = true;\n }\n } else if (ch === '≠') {\n out += '_neq_';\n previousWasSeparator = false;\n } else if (LETTER_OR_DIGIT.test(ch)) {\n out += ch.toLowerCase();\n previousWasSeparator = false;\n }\n }\n const slug = stripUnderscores(out);\n return slug === '' ? 'unknown' : slug;\n}\n\n/** Signal slug for a History `score_details` description (the webhook `signals[].name`). */\nexport function signalSlug(description: string): string {\n const exact = EXACT_SLUGS.get(description);\n if (exact !== undefined) return exact;\n for (const [prefix, slug] of PREFIX_SLUGS) {\n if (description.startsWith(prefix)) return slug;\n }\n if (description.startsWith(STICKY_PREFIX)) {\n const colon = description.indexOf(':');\n const rest =\n colon >= 0 && colon + 1 < description.length\n ? stripWhitespace(description.slice(colon + 1))\n : description;\n return fallbackSlug(rest);\n }\n return fallbackSlug(description);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Timestamps\n// ---------------------------------------------------------------------------------------------\n\n// History rows: \"YYYY-MM-DD HH:MM:SS[.fff]\" in UTC. A zone designator is accepted and ignored.\nconst HISTORY_TIME =\n /^(\\d{4})-(\\d{2})-(\\d{2})[ T](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,9}))?(?:Z|[+-]\\d{2}:?\\d{2})?$/;\n// Webhooks and the Management API: RFC 3339 with up to 9 fractional digits. A single trailing\n// newline is tolerated.\nconst RFC3339 =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,9}))?(Z|[+-]\\d{2}:\\d{2})\\n?$/;\n\nfunction isLeapYear(year: number): boolean {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\nfunction daysInMonth(year: number, month: number): number {\n if (month === 2) return isLeapYear(year) ? 29 : 28;\n return [4, 6, 9, 11].includes(month) ? 30 : 31;\n}\n\nfunction pad(value: number, width: number): string {\n return String(value).padStart(width, '0');\n}\n\n/**\n * Formats matched date parts as \"YYYY-MM-DDTHH:MM:SS.mmmZ\" after applying the offset. The\n * fraction is truncated to milliseconds (never rounded). Returns null for impossible dates.\n */\nfunction formatUtc(match: RegExpMatchArray, offsetMinutes: number): string | null {\n const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) =>\n Number(match[i]),\n ) as [number, number, number, number, number, number];\n if (\n year < 1 ||\n month < 1 ||\n month > 12 ||\n day < 1 ||\n day > daysInMonth(year, month) ||\n hour > 23 ||\n minute > 59 ||\n second > 59\n ) {\n return null;\n }\n const local = new Date(0);\n local.setUTCFullYear(year, month - 1, day);\n local.setUTCHours(hour, minute, second, 0);\n const utc = new Date(local.getTime() - offsetMinutes * 60_000);\n const utcYear = utc.getUTCFullYear();\n if (utcYear < 1 || utcYear > 9999) return null;\n const millis = (match[7] ?? '0').slice(0, 3).padEnd(3, '0');\n return (\n `${pad(utcYear, 4)}-${pad(utc.getUTCMonth() + 1, 2)}-${pad(utc.getUTCDate(), 2)}` +\n `T${pad(utc.getUTCHours(), 2)}:${pad(utc.getUTCMinutes(), 2)}:${pad(utc.getUTCSeconds(), 2)}` +\n `.${millis}Z`\n );\n}\n\n/** History `created_at` (\"YYYY-MM-DD HH:MM:SS[.fff]\", UTC) to RFC 3339 with milliseconds. */\nexport function parseHistoryTime(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const text = stripWhitespace(value);\n if (text === '') return null;\n const match = text.match(HISTORY_TIME);\n return match ? formatUtc(match, 0) : null;\n}\n\n/** RFC 3339 timestamp (up to 9 fractional digits, any offset) to UTC with milliseconds. */\nexport function parseRfc3339(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const match = value.match(RFC3339);\n if (!match) return null;\n const zone = match[8] ?? 'Z';\n let offsetMinutes = 0;\n if (zone !== 'Z') {\n const sign = zone.startsWith('+') ? 1 : -1;\n offsetMinutes = sign * (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(4, 6)));\n }\n return formatUtc(match, offsetMinutes);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Identification\n// ---------------------------------------------------------------------------------------------\n\ntype HistoryFlagKey = Exclude<FlagKey, 'browser_vpn_proxy' | 'ip_mismatch'>;\n\nconst HISTORY_FLAG_COLUMNS: Readonly<Record<HistoryFlagKey, string>> = {\n vpn: 'is_vpn',\n privacy_relay: 'is_privacy_relay',\n tor: 'is_tor',\n proxy: 'is_proxy',\n datacenter_ip: 'is_datacenter',\n abuser: 'is_abuser',\n os_mismatch: 'is_os_mismatch',\n os_not_detected: 'is_os_not_detected',\n timezone_mismatch: 'is_timezone_mismatch',\n anti_detect_browser: 'is_antidetect',\n browser_automation: 'is_browser_automation',\n incognito: 'is_incognito',\n search_bot: 'is_search_bot',\n suspicious_paid_click: 'is_suspicious_paid_click',\n javascript_disabled: 'is_js_disabled',\n stun_not_checked: 'is_stun_not_checked',\n check_incomplete: 'check_incomplete',\n};\n\n/** IP sentinel handling: trimmed, and \"0.0.0.0\" means no IP (\"\"). */\nfunction normalizeIp(value: unknown): string {\n if (typeof value !== 'string') return '';\n const ip = stripWhitespace(value);\n return ip === '0.0.0.0' ? '' : ip;\n}\n\n/** \"\" and null become null; other User HID values (including sentinels) are kept. */\nfunction normalizeUserHid(value: unknown): string | null {\n if (value === undefined || value === null || value === '') return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return null;\n}\n\n/** Score as sent; absent means 0, a non-numeric value becomes NaN (never a valid score). */\nfunction normalizeScore(obj: JsonObject, key: string): number {\n if (!hasOwn(obj, key)) return 0;\n const value = obj[key];\n return typeof value === 'number' ? value : Number.NaN;\n}\n\n/** Parses the JSON-encoded `score_details` string. \"\" or invalid JSON gives an empty list. */\nfunction parseScoreDetails(value: unknown): unknown[] {\n const text = isTruthy(value) ? value : '[]';\n if (typeof text !== 'string') return [];\n try {\n const parsed: unknown = JSON.parse(text);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n}\n\nfunction ipInfo(value: unknown): IpInfo {\n const obj = isPlainObject(value) ? value : {};\n return { ip: normalizeIp(own(obj, 'ip')), country: stringField(obj, 'country') };\n}\n\nconst TRAFFIC_KEYS: ReadonlyArray<keyof TrafficSource> = [\n 'channel',\n 'referrer_domain',\n 'landing_url',\n 'click_id_type',\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_content',\n 'utm_term',\n];\n\n/** Builds an Identification from one History API row. */\nexport function fromHistoryRow(row: JsonObject): Identification {\n const leakSource = stripWhitespace(stringField(row, 'webrtc_leak_source'));\n let localIp: string;\n let localCountry: string;\n if (leakSource !== '' && leakSource !== 'none') {\n localIp = normalizeIp(own(row, 'webrtc_leak_ip'));\n localCountry = stringField(row, 'webrtc_leak_country');\n } else {\n localIp = normalizeIp(own(row, 'web_rtc_ip'));\n localCountry = stringField(row, 'web_rtc_country');\n }\n const publicIp = normalizeIp(own(row, 'ip'));\n\n const signals: IdentificationSignal[] = [];\n let ipLeakDetail = false;\n for (const entry of parseScoreDetails(own(row, 'score_details'))) {\n if (!isPlainObject(entry)) continue;\n const description = stringField(entry, 'Description');\n if (description.startsWith('IP ≠ leakIP')) ipLeakDetail = true;\n const value = own(entry, 'Value');\n if (typeof value !== 'number' || !Number.isInteger(value) || value === 0) continue;\n signals.push({ name: signalSlug(description), weight: value, description });\n }\n\n const searchBot = isTruthy(own(row, 'is_search_bot'));\n const flags = {} as DetectionFlags;\n for (const key of FLAG_KEYS) {\n if (key === 'browser_vpn_proxy') {\n flags[key] = own(row, 'connection_type') === 'browser_vpn_proxy';\n } else if (key === 'ip_mismatch') {\n flags[key] =\n !searchBot && (ipLeakDetail || (publicIp !== '' && localIp !== '' && publicIp !== localIp));\n } else {\n flags[key] = isTruthy(own(row, HISTORY_FLAG_COLUMNS[key]));\n }\n }\n\n const siteDomain = own(row, 'site_domain');\n let domain: string;\n if (isTruthy(siteDomain)) {\n domain = typeof siteDomain === 'string' ? siteDomain : '';\n } else {\n domain = stringField(row, 'domain');\n }\n\n return {\n request_id: stringField(row, 'request_id'),\n visitor_id: stringField(row, 'visitor_id'),\n device_id: stringField(row, 'device_id'),\n session_id: stringField(row, 'session_id'),\n cookie_id: stringField(row, 'cookie_id'),\n user_hid: normalizeUserHid(own(row, 'user_hid')),\n domain,\n public_ip: { ip: publicIp, country: stringField(row, 'country') },\n local_ip: { ip: localIp, country: localCountry },\n connection_type: stringField(row, 'connection_type'),\n os: stringField(row, 'os'),\n browser: stringField(row, 'browser'),\n device_type: stringField(row, 'device_type'),\n traffic_source: {\n channel: stringField(row, 'traffic_channel'),\n referrer_domain: stringField(row, 'referrer_domain'),\n landing_url: stringField(row, 'entry_url'),\n click_id_type: stringField(row, 'click_id_type'),\n utm_source: stringField(row, 'utm_source'),\n utm_medium: stringField(row, 'utm_medium'),\n utm_campaign: stringField(row, 'utm_campaign'),\n utm_content: stringField(row, 'utm_content'),\n utm_term: stringField(row, 'utm_term'),\n },\n risk_score: normalizeScore(row, 'score'),\n signals,\n detection_flags: flags,\n observed_at: parseHistoryTime(own(row, 'created_at')),\n source: 'history',\n raw: row,\n };\n}\n\n/** Builds an Identification from the `data` object of an `identification.scored` webhook. */\nexport function fromWebhookData(data: JsonObject): Identification {\n const rawFlags = own(data, 'detection_flags');\n const flagSource = isPlainObject(rawFlags) ? rawFlags : {};\n const flags = {} as DetectionFlags;\n for (const key of FLAG_KEYS) flags[key] = isTruthy(own(flagSource, key));\n\n const rawTraffic = own(data, 'traffic_source');\n const trafficSource = isPlainObject(rawTraffic) ? rawTraffic : {};\n const traffic = {} as TrafficSource;\n for (const key of TRAFFIC_KEYS) traffic[key] = stringField(trafficSource, key);\n\n const rawSignals = own(data, 'signals');\n const signals: IdentificationSignal[] = Array.isArray(rawSignals)\n ? rawSignals.filter(isPlainObject).map((signal) => {\n const weight = own(signal, 'weight');\n return {\n name: stringField(signal, 'name'),\n weight: typeof weight === 'number' ? weight : 0,\n description: null,\n };\n })\n : [];\n\n return {\n request_id: stringField(data, 'request_id'),\n visitor_id: stringField(data, 'visitor_id'),\n device_id: stringField(data, 'device_id'),\n session_id: stringField(data, 'session_id'),\n cookie_id: stringField(data, 'cookie_id'),\n user_hid: normalizeUserHid(own(data, 'user_hid')),\n domain: stringField(data, 'domain'),\n public_ip: ipInfo(own(data, 'public_ip')),\n local_ip: ipInfo(own(data, 'local_ip')),\n connection_type: stringField(data, 'connection_type'),\n os: stringField(data, 'os'),\n browser: stringField(data, 'browser'),\n device_type: stringField(data, 'device_type'),\n traffic_source: traffic,\n risk_score: normalizeScore(data, 'risk_score'),\n signals,\n detection_flags: flags,\n observed_at: parseRfc3339(own(data, 'observed_at')),\n source: 'webhook',\n raw: data,\n };\n}\n\n/** Builds a DomainProfile from a Management API profile response (PascalCase keys). */\nexport function profileFromResponse(body: JsonObject): DomainProfile {\n const weight = own(body, 'Weight');\n return {\n domain: stringField(body, 'Domain'),\n remaining_identifications: typeof weight === 'number' && Number.isFinite(weight) ? weight : 0,\n public_key_masked: stringField(body, 'PublicKey'),\n secret_key_masked: stringField(body, 'Secret'),\n created_at: parseRfc3339(own(body, 'CreatedAt')),\n raw: body,\n };\n}\n","/** Version of this SDK. Sent in the User-Agent header of every request. */\nexport const VERSION = '1.0.0';\n","import { VERSION } from './version.js';\n\ninterface RuntimeGlobals {\n Bun?: { version?: unknown };\n Deno?: { version?: { deno?: unknown } };\n EdgeRuntime?: unknown;\n navigator?: { userAgent?: unknown };\n process?: { versions?: { node?: unknown } };\n}\n\nexport function detectRuntime(): string | null {\n const g = globalThis as unknown as RuntimeGlobals;\n if (typeof g.Bun?.version === 'string') return `bun/${g.Bun.version}`;\n if (typeof g.Deno?.version?.deno === 'string') return `deno/${g.Deno.version.deno}`;\n if (typeof g.EdgeRuntime === 'string') return 'edge-runtime';\n if (g.navigator?.userAgent === 'Cloudflare-Workers') return 'workerd';\n if (typeof g.process?.versions?.node === 'string') return `node/${g.process.versions.node}`;\n return null;\n}\n\nlet cachedUserAgent: string | undefined;\n\n/** \"shieldlabs-node/<version>\" followed by the runtime, for example \"node/20.11.1\". */\nexport function userAgent(): string {\n if (cachedUserAgent === undefined) {\n const runtime = detectRuntime();\n cachedUserAgent = runtime\n ? `shieldlabs-node/${VERSION} ${runtime}`\n : `shieldlabs-node/${VERSION}`;\n }\n return cachedUserAgent;\n}\n\n/** The reason an aborted signal carries, or a generic AbortError. */\nexport function abortReason(signal: AbortSignal): unknown {\n if (signal.reason !== undefined) return signal.reason;\n const error = new Error('The operation was aborted.');\n error.name = 'AbortError';\n return error;\n}\n\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortReason(signal);\n}\n\n/** Longest delay of one timer: runtimes fire a timer with a longer delay almost at once. */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/** Waits `ms` milliseconds; rejects with the abort reason as soon as `signal` aborts. */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(abortReason(signal as AbortSignal));\n };\n // A wait longer than one timer allows runs as a chain of timers.\n const wait = (left: number): void => {\n timer = setTimeout(\n () => {\n if (left > MAX_TIMER_DELAY_MS) {\n wait(left - MAX_TIMER_DELAY_MS);\n return;\n }\n signal?.removeEventListener('abort', onAbort);\n resolve();\n },\n Math.min(left, MAX_TIMER_DELAY_MS),\n );\n };\n wait(ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nconst warned = new Set<string>();\nconst MAX_WARNINGS = 32;\n\n/** Prints a warning once per process for each key. Never include secrets in `message`. */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key) || warned.size >= MAX_WARNINGS) return;\n warned.add(key);\n console.warn(`[shieldlabs] ${message}`);\n}\n\n/**\n * Warns once when a client is created in a web page (a global window with a document), where its\n * key is visible to every visitor. Servers, workers and edge runtimes stay silent.\n */\nexport function warnIfBrowserPage(client: string, key: string): void {\n const g = globalThis as { window?: unknown; document?: unknown };\n if (g.window !== undefined && g.document !== undefined) {\n warnOnce(\n `browser-page:${client}`,\n `${client} was created in a web page, where its ${key} is visible to every visitor. Use @shieldlabs-ai/node on your server only; in the page, use the browser SDK (@shieldlabs-ai/js).`,\n );\n }\n}\n\n/** Test hook: forget which warnings were printed. */\nexport function resetWarnings(): void {\n warned.clear();\n}\n","import { KNOWN_SCHEMA_VERSION } from './constants.js';\nimport {\n ShieldLabsError,\n SignatureVerificationError,\n ValidationError,\n WebhookParseError,\n} from './errors.js';\nimport { fromWebhookData, isPlainObject } from './normalize.js';\nimport { warnOnce } from './runtime.js';\nimport type {\n SignatureHeader,\n UnknownEventType,\n WebhookEvent,\n WebhookPayload,\n WebhookSecret,\n} from './types.js';\n\n/** Webhook signature verification and typed event parsing. */\nexport interface Webhooks {\n /**\n * True when `signatureHeader` (X-Shield-Signature) is a valid signature of `payload` for any\n * of the given secrets. Returns false for a malformed header, an empty secret or a payload that\n * is not raw bytes or a string. Needs node:crypto: in edge runtimes use `verifySignatureAsync`.\n */\n verifySignature(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): boolean;\n /**\n * Verifies the signature, then parses the body into a typed event.\n * Throws SignatureVerificationError or WebhookParseError.\n * Needs node:crypto: in edge runtimes use `constructEventAsync`.\n */\n constructEvent(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): WebhookEvent;\n /** Same as `verifySignature`, using WebCrypto where node:crypto is not available. */\n verifySignatureAsync(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): Promise<boolean>;\n /** Same as `constructEvent`, using WebCrypto where node:crypto is not available. */\n constructEventAsync(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): Promise<WebhookEvent>;\n}\n\n/** HMAC-SHA256 over `message` with the UTF-8 bytes of `key`. */\nexport type HmacSync = (key: string, message: Uint8Array) => Uint8Array;\nexport type HmacAsync = (key: string, message: Uint8Array) => Promise<Uint8Array>;\n\nexport interface CryptoBackend {\n /** Synchronous HMAC, or null where node:crypto is not loaded. */\n hmacSync: HmacSync | null;\n hmacAsync: HmacAsync;\n /** Constant-time comparison of two digests. */\n equal?: (a: Uint8Array, b: Uint8Array) => boolean;\n}\n\nconst SIGNATURE_PREFIX = 'sha256=';\nconst HEX_DIGEST = /^[0-9a-fA-F]{64}$/;\nconst MISMATCH =\n 'The webhook signature does not match the payload. Check the endpoint signing secret (including its whsec_ prefix) and verify the raw body bytes, not re-serialized JSON.';\n\nconst encoder = new TextEncoder();\n\n/** Lowercase hex digest from an X-Shield-Signature header value, or null when malformed. */\nexport function parseSignatureHeader(header: unknown): string | null {\n let value = header;\n if (Array.isArray(value)) {\n if (value.length !== 1) return null;\n value = value[0];\n }\n if (typeof value !== 'string') return null;\n const trimmed = value.trim();\n if (!trimmed.startsWith(SIGNATURE_PREFIX)) return null;\n const digest = trimmed.slice(SIGNATURE_PREFIX.length);\n return HEX_DIGEST.test(digest) ? digest.toLowerCase() : null;\n}\n\n/** The non-empty secrets of one secret or a list of secrets. */\nexport function secretList(secret: unknown): string[] {\n const list: unknown[] = Array.isArray(secret) ? secret : [secret];\n return list.filter((item): item is string => typeof item === 'string' && item !== '');\n}\n\nfunction isArrayBuffer(value: unknown): value is ArrayBuffer {\n return (\n value instanceof ArrayBuffer || Object.prototype.toString.call(value) === '[object ArrayBuffer]'\n );\n}\n\n/** The payload as bytes, or null when it is neither a string nor binary data. */\nexport function payloadBytes(payload: unknown): Uint8Array | null {\n if (typeof payload === 'string') return encoder.encode(payload);\n if (payload instanceof Uint8Array) return payload;\n if (ArrayBuffer.isView(payload)) {\n return new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);\n }\n if (isArrayBuffer(payload)) return new Uint8Array(payload);\n return null;\n}\n\nexport function hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n\n/** Compares two byte arrays without an early exit. */\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n\ntype Prepared =\n | { ok: true; bytes: Uint8Array; expected: Uint8Array; secrets: string[] }\n | { ok: false; reason: string };\n\nfunction prepare(payload: unknown, header: unknown, secret: unknown): Prepared {\n const bytes = payloadBytes(payload);\n if (bytes === null) {\n return {\n ok: false,\n reason:\n 'The payload must be the raw request body (a string, Uint8Array or ArrayBuffer). A parsed object cannot be verified because re-serializing changes the bytes.',\n };\n }\n const digest = parseSignatureHeader(header);\n if (digest === null) {\n return {\n ok: false,\n reason:\n 'The X-Shield-Signature header is missing or malformed (expected sha256=<64 hex characters>).',\n };\n }\n const secrets = secretList(secret);\n if (secrets.length === 0) {\n return { ok: false, reason: 'No webhook signing secret was provided.' };\n }\n return { ok: true, bytes, expected: hexToBytes(digest), secrets };\n}\n\nconst decoder = new TextDecoder('utf-8');\n\nfunction preview(text: string): string {\n return text.length > 40 ? `${text.slice(0, 37)}...` : text;\n}\n\n/** Parses verified webhook bytes into a typed event. */\nexport function parseEvent(bytes: Uint8Array): WebhookEvent {\n const text = decoder.decode(bytes);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new WebhookParseError('The webhook body is not valid JSON.', { cause: error });\n }\n if (!isPlainObject(parsed)) {\n throw new WebhookParseError('The webhook body is not a JSON object.');\n }\n const eventType = parsed.event_type;\n if (typeof eventType !== 'string' || eventType === '') {\n throw new WebhookParseError('The webhook body has no event_type.');\n }\n const schemaVersion = typeof parsed.schema_version === 'string' ? parsed.schema_version : '';\n const createdAt = typeof parsed.created_at === 'string' ? parsed.created_at : '';\n if (schemaVersion !== KNOWN_SCHEMA_VERSION) {\n warnOnce(\n `schema-version:${schemaVersion}`,\n `Received a webhook with schema_version \"${preview(schemaVersion)}\" while this SDK version targets \"${KNOWN_SCHEMA_VERSION}\". The event was parsed; update @shieldlabs-ai/node for typed support of newer fields.`,\n );\n }\n if (eventType === 'identification.scored') {\n if (!isPlainObject(parsed.data)) {\n throw new WebhookParseError('The identification.scored event has no data object.');\n }\n return {\n event_type: 'identification.scored',\n schema_version: schemaVersion,\n created_at: createdAt,\n data: fromWebhookData(parsed.data),\n raw: parsed,\n };\n }\n if (eventType === 'webhook.ping') {\n return {\n event_type: 'webhook.ping',\n schema_version: schemaVersion,\n created_at: createdAt,\n raw: parsed,\n };\n }\n return {\n event_type: eventType as UnknownEventType,\n schema_version: schemaVersion,\n created_at: createdAt,\n raw: parsed,\n };\n}\n\nexport function syncUnavailable(fn: string, alternative: string): ShieldLabsError {\n return new ShieldLabsError(\n `${fn}() is synchronous and needs node:crypto, which the edge build of @shieldlabs-ai/node does not load. Use await ${alternative}() instead.`,\n );\n}\n\n/** Builds the `webhooks` helpers on top of a crypto backend. */\nexport function createWebhooks(backend: CryptoBackend): Webhooks {\n const equal = backend.equal ?? constantTimeEqual;\n\n function verifySync(\n payload: unknown,\n header: unknown,\n secret: unknown,\n hmac: HmacSync,\n ): Prepared {\n const prepared = prepare(payload, header, secret);\n if (!prepared.ok) return prepared;\n for (const key of prepared.secrets) {\n if (equal(hmac(key, prepared.bytes), prepared.expected)) return prepared;\n }\n return { ok: false, reason: MISMATCH };\n }\n\n async function verifyAsync(\n payload: unknown,\n header: unknown,\n secret: unknown,\n ): Promise<Prepared> {\n const prepared = prepare(payload, header, secret);\n if (!prepared.ok) return prepared;\n for (const key of prepared.secrets) {\n if (equal(await backend.hmacAsync(key, prepared.bytes), prepared.expected)) return prepared;\n }\n return { ok: false, reason: MISMATCH };\n }\n\n function requireSync(fn: string, alternative: string): HmacSync {\n if (backend.hmacSync === null) throw syncUnavailable(fn, alternative);\n return backend.hmacSync;\n }\n\n return Object.freeze({\n verifySignature(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): boolean {\n const hmac = requireSync('webhooks.verifySignature', 'webhooks.verifySignatureAsync');\n return verifySync(payload, signatureHeader, secret, hmac).ok;\n },\n constructEvent(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): WebhookEvent {\n const hmac = requireSync('webhooks.constructEvent', 'webhooks.constructEventAsync');\n const result = verifySync(payload, signatureHeader, secret, hmac);\n if (!result.ok) throw new SignatureVerificationError(result.reason);\n return parseEvent(result.bytes);\n },\n async verifySignatureAsync(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): Promise<boolean> {\n return (await verifyAsync(payload, signatureHeader, secret)).ok;\n },\n async constructEventAsync(\n payload: WebhookPayload,\n signatureHeader: SignatureHeader,\n secret: WebhookSecret,\n ): Promise<WebhookEvent> {\n const result = await verifyAsync(payload, signatureHeader, secret);\n if (!result.ok) throw new SignatureVerificationError(result.reason);\n return parseEvent(result.bytes);\n },\n });\n}\n\nfunction validateUserHidInput(userId: unknown, secret: unknown): void {\n if (typeof userId !== 'string' || userId === '') {\n throw new ValidationError('userId must be a non-empty string.');\n }\n if (typeof secret !== 'string' || secret === '') {\n throw new ValidationError('secret must be a non-empty string.');\n }\n}\n\n/** HMAC-SHA256(key = secret, message = userId) as 64 lowercase hex characters. */\nexport function computeUserHid(backend: CryptoBackend, userId: string, secret: string): string {\n if (backend.hmacSync === null) throw syncUnavailable('userHid', 'userHidAsync');\n validateUserHidInput(userId, secret);\n return bytesToHex(backend.hmacSync(secret, encoder.encode(userId)));\n}\n\nexport async function computeUserHidAsync(\n backend: CryptoBackend,\n userId: string,\n secret: string,\n): Promise<string> {\n validateUserHidInput(userId, secret);\n return bytesToHex(await backend.hmacAsync(secret, encoder.encode(userId)));\n}\n","import {\n ApiError,\n AuthenticationError,\n BadRequestError,\n ConnectionError,\n NotFoundError,\n QuotaExceededError,\n RateLimitError,\n ServerError,\n ShieldLabsError,\n TimeoutError,\n ValidationError,\n type ApiErrorOptions,\n type HeadersLike,\n} from './errors.js';\nimport { isPlainObject } from './normalize.js';\nimport { abortReason, sleep, throwIfAborted, userAgent, warnOnce } from './runtime.js';\nimport type { FetchLike, FetchResponseLike } from './types.js';\n\nexport const BACKOFF_BASE_MS = 500;\nexport const BACKOFF_CAP_MS = 8_000;\nexport const RETRY_AFTER_CAP_MS = 10_000;\n/**\n * Shortest wait after a History 429 (the limit resets every second): after any 429 inside the wait\n * of `identifications.get`, and before retrying an ordinary request whose 429 had no Retry-After.\n * An ordinary request with Retry-After waits as long as it says, capped at RETRY_AFTER_CAP_MS.\n */\nexport const RATE_LIMIT_FLOOR_MS = 1_000;\nconst MAX_DETAIL_LENGTH = 200;\n\nexport type ApiName = 'History API' | 'Management API';\n\nexport interface TransportOptions {\n apiName: ApiName;\n /** Normalized base URL without a trailing slash. */\n baseUrl: string;\n /** Credential headers sent with every request. */\n headers: Record<string, string>;\n /** Credentials that must never appear in an error message or cause. */\n secrets: readonly string[];\n /** Per-attempt timeout in milliseconds. */\n timeout: number;\n maxRetries: number;\n /** False for the Management API: a 429 there starts a 10-minute block, so it is never retried. */\n retryRateLimited: boolean;\n fetch: FetchLike | undefined;\n}\n\nexport interface RequestOptions {\n query?: Record<string, string> | undefined;\n signal?: AbortSignal | undefined;\n /** Overrides the transport's maxRetries for this call. */\n maxRetries?: number | undefined;\n /** Caps the attempt timeout of this call in milliseconds; the client timeout still applies. */\n timeout?: number | undefined;\n}\n\nexport interface JsonResponse {\n body: unknown;\n status: number;\n headers: HeadersLike;\n}\n\n/** Loopback hosts, as the URL parser normalizes them. */\nexport function isLoopbackHost(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname.endsWith('.localhost') ||\n hostname === '[::1]' ||\n /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(hostname)\n );\n}\n\n/**\n * Normalizes a base URL: https origin plus an optional path prefix, no trailing slash. Plain http\n * is accepted for loopback hosts, and for other hosts only with `allowInsecureHttp`.\n * With `stripApiSuffix`, a trailing \"/api\" is removed so paths never become \"/api/api/...\".\n */\nexport function normalizeBaseUrl(\n input: unknown,\n name: string,\n stripApiSuffix: boolean,\n allowInsecureHttp = false,\n): string {\n if (typeof input !== 'string' || input.trim() === '') {\n throw new ValidationError(`${name} must be a non-empty URL.`);\n }\n let url: URL;\n try {\n url = new URL(input.trim());\n } catch {\n throw new ValidationError(`${name} is not a valid URL.`);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new ValidationError(`${name} must be an https URL.`);\n }\n if (url.username !== '' || url.password !== '') {\n throw new ValidationError(`${name} must not contain credentials.`);\n }\n if (url.search !== '' || url.hash !== '') {\n throw new ValidationError(`${name} must not contain a query string or a fragment.`);\n }\n if (url.protocol === 'http:' && !isLoopbackHost(url.hostname)) {\n if (!allowInsecureHttp) {\n throw new ValidationError(\n `${name} must be an https URL: with plain http the key would travel unencrypted. Plain http is accepted for localhost, 127.0.0.1 and [::1]; for a test server on another host, pass allowInsecureHttp: true.`,\n );\n }\n warnOnce(\n `insecure-base-url:${url.origin}`,\n `${name} uses plain http, so credentials travel unencrypted. Use https outside local testing.`,\n );\n }\n let path = url.pathname.replace(/\\/+$/, '');\n if (stripApiSuffix && /\\/api$/i.test(path)) path = path.slice(0, -4).replace(/\\/+$/, '');\n return `${url.origin}${path}`;\n}\n\n/** Parses a Retry-After header (delta seconds or an HTTP date) into seconds. */\nexport function parseRetryAfter(\n value: string | null | undefined,\n nowMs = Date.now(),\n): number | undefined {\n if (value === null || value === undefined) return undefined;\n const text = value.trim();\n if (/^\\d+(?:\\.\\d+)?$/.test(text)) return Number(text);\n // HTTP dates always name the weekday and month (\"Wed, 30 Sep 2026 12:00:30 GMT\").\n if (!/[a-z]{3}/i.test(text)) return undefined;\n const date = Date.parse(text);\n if (Number.isNaN(date)) return undefined;\n return Math.max(0, Math.ceil((date - nowMs) / 1000));\n}\n\nfunction truncate(text: string): string {\n return text.length > MAX_DETAIL_LENGTH ? `${text.slice(0, MAX_DETAIL_LENGTH - 3)}...` : text;\n}\n\nfunction errorDetail(body: unknown, parsedJson: boolean, text: string): string | undefined {\n if (parsedJson) {\n if (isPlainObject(body) && typeof body.error === 'string' && body.error !== '') {\n return truncate(body.error);\n }\n if (typeof body === 'string' && body !== '') return truncate(body);\n return undefined;\n }\n const trimmed = text.trim();\n if (trimmed === '' || trimmed.startsWith('<')) return undefined;\n return truncate(trimmed);\n}\n\nfunction hintFor(apiName: ApiName, status: number): string {\n if (status === 401 || status === 403) {\n return apiName === 'History API'\n ? ' Check that apiKey is the Private API Key (sec_...) of this domain.'\n : ' Check the Secret Key and that domain matches the registered domain exactly.';\n }\n if (status === 404) return ' Check the base URL.';\n if (status === 429 && apiName === 'Management API') {\n return ' The Management API allows about 15 requests per minute per IP, then blocks the IP for 10 minutes.';\n }\n return '';\n}\n\n/** Maps an error response to the matching error class. Never throws. */\nexport function createApiError(\n apiName: ApiName,\n status: number,\n text: string,\n headers: HeadersLike,\n): ApiError {\n let body: unknown = null;\n let parsedJson = false;\n if (text !== '') {\n try {\n body = JSON.parse(text);\n parsedJson = true;\n } catch {\n body = text;\n }\n }\n const detail = errorDetail(body, parsedJson, text);\n const message = `${apiName} request failed with HTTP ${status}${detail ? ` (${detail})` : ''}.${hintFor(apiName, status)}`;\n const options: ApiErrorOptions = { status, body, headers };\n if (status === 400) return new BadRequestError(message, options);\n if (status === 401 || status === 403) return new AuthenticationError(message, options);\n if (status === 402) return new QuotaExceededError(message, options);\n if (status === 404) return new NotFoundError(message, options);\n if (status === 429) {\n let retryAfter: number | undefined;\n try {\n retryAfter = parseRetryAfter(headers.get('retry-after'));\n } catch {\n retryAfter = undefined;\n }\n return new RateLimitError(message, { ...options, retryAfter });\n }\n if (status >= 500 && status <= 599) return new ServerError(message, options);\n return new ApiError(message, options);\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error && error.message ? error.message : String(error);\n}\n\n/**\n * The network cause behind a failed fetch, for example \" (connect ECONNREFUSED 192.0.2.1:443)\":\n * runtimes wrap it in a generic \"fetch failed\" error.\n */\nfunction causeDetail(error: unknown): string {\n const cause = error instanceof Error ? error.cause : undefined;\n if (typeof cause !== 'object' || cause === null) return '';\n const { code, message } = cause as { code?: unknown; message?: unknown };\n const codeText = typeof code === 'string' ? code : '';\n const text = typeof message === 'string' ? message.trim() : '';\n if (text !== '' && codeText !== '' && !text.includes(codeText)) {\n return ` (${codeText}: ${truncate(text)})`;\n }\n if (text !== '') return ` (${truncate(text)})`;\n return codeText === '' ? '' : ` (${codeText})`;\n}\n\n/** Text an error and its causes can print: messages, stacks and their own string properties. */\nfunction printableTexts(error: unknown): string[] {\n const texts: string[] = [];\n let current: unknown = error;\n for (let depth = 0; depth < 5 && current !== undefined && current !== null; depth++) {\n if (typeof current !== 'object') {\n if (typeof current === 'string') texts.push(current);\n break;\n }\n const { message, stack } = current as { message?: unknown; stack?: unknown };\n if (typeof message === 'string') texts.push(message);\n if (typeof stack === 'string') texts.push(stack);\n try {\n texts.push(JSON.stringify(current) ?? '');\n } catch {\n // Circular or otherwise unserializable: the message and stack above still count.\n }\n current = (current as { cause?: unknown }).cause;\n }\n return texts;\n}\n\nfunction mentionsSecret(texts: readonly string[], secrets: readonly string[]): boolean {\n return secrets.some((secret) => secret !== '' && texts.some((text) => text.includes(secret)));\n}\n\n/** Resolves when `promise` settles, or rejects as soon as `signal` aborts (even if `promise` never settles). */\nfunction raceWithAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n if (signal.aborted) {\n reject(abortReason(signal));\n return;\n }\n const onAbort = (): void => reject(abortReason(signal));\n signal.addEventListener('abort', onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener('abort', onAbort);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n\nfunction globalFetch(): FetchLike {\n const candidate = (globalThis as { fetch?: unknown }).fetch;\n if (typeof candidate !== 'function') {\n throw new ValidationError(\n 'No fetch implementation is available. Use Node.js 18 or later, or pass the fetch option.',\n );\n }\n const fetchFn = candidate as FetchLike;\n return (url, init) => fetchFn.call(globalThis, url, init);\n}\n\n/** Sends GET requests with timeouts, retries and error mapping. Safe for concurrent use. */\nexport class Transport {\n readonly #options: TransportOptions;\n\n constructor(options: TransportOptions) {\n this.#options = options;\n }\n\n /** The client's per-attempt timeout in milliseconds. */\n get timeout(): number {\n return this.#options.timeout;\n }\n\n async getJson(path: string, options: RequestOptions = {}): Promise<JsonResponse> {\n const maxRetries = options.maxRetries ?? this.#options.maxRetries;\n let url = `${this.#options.baseUrl}${path}`;\n if (options.query) url += `?${new URLSearchParams(options.query).toString()}`;\n for (let attempt = 0; ; attempt++) {\n throwIfAborted(options.signal);\n try {\n return await this.#attempt(url, options.signal, options.timeout);\n } catch (error) {\n if (attempt >= maxRetries || !this.#isRetryable(error)) throw error;\n await sleep(this.#retryDelay(error, attempt), options.signal);\n }\n }\n }\n\n #isRetryable(error: unknown): boolean {\n if (error instanceof ConnectionError || error instanceof TimeoutError) return true;\n if (error instanceof RateLimitError) return this.#options.retryRateLimited;\n return error instanceof ServerError;\n }\n\n #retryDelay(error: unknown, attempt: number): number {\n if (error instanceof ApiError) {\n const retryAfter =\n error instanceof RateLimitError\n ? error.retryAfter\n : parseRetryAfter(error.headers.get('retry-after'));\n if (retryAfter !== undefined) return Math.min(retryAfter * 1000, RETRY_AFTER_CAP_MS);\n }\n const nominal = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);\n const delay = nominal / 2 + Math.random() * (nominal / 2);\n return error instanceof RateLimitError ? Math.max(delay, RATE_LIMIT_FLOOR_MS) : delay;\n }\n\n #connectionError(error: unknown): ConnectionError {\n const { apiName, secrets } = this.#options;\n const message = `${apiName} request failed: ${messageOf(error)}${causeDetail(error)}`;\n if (mentionsSecret([message, ...printableTexts(error)], secrets)) {\n // For example a runtime error that echoes a header value: keep it out of logs entirely.\n return new ConnectionError(\n `${apiName} request failed before a response was received. The underlying error was withheld because it contained a credential.`,\n );\n }\n return new ConnectionError(message, { cause: error });\n }\n\n async #attempt(\n url: string,\n signal: AbortSignal | undefined,\n timeoutCap: number | undefined,\n ): Promise<JsonResponse> {\n const { apiName } = this.#options;\n const timeout = Math.min(this.#options.timeout, timeoutCap ?? Number.POSITIVE_INFINITY);\n const fetchImpl = this.#options.fetch ?? globalFetch();\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeout);\n const onAbort = (): void => controller.abort();\n signal?.addEventListener('abort', onAbort, { once: true });\n\n let response: FetchResponseLike;\n let text: string;\n try {\n const init = {\n method: 'GET' as const,\n headers: {\n Accept: 'application/json',\n 'User-Agent': userAgent(),\n ...this.#options.headers,\n },\n signal: controller.signal,\n };\n response = await raceWithAbort(\n Promise.resolve().then(() => fetchImpl(url, init)),\n controller.signal,\n );\n text = await raceWithAbort(\n Promise.resolve().then(() => response.text()),\n controller.signal,\n );\n } catch (error) {\n if (signal?.aborted) throw abortReason(signal);\n if (timedOut) {\n throw new TimeoutError(`${apiName} request timed out after ${timeout} ms.`, {\n cause: error,\n });\n }\n if (error instanceof ShieldLabsError) throw error;\n throw this.#connectionError(error);\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n }\n\n const { status, headers } = response;\n if (status >= 200 && status < 300) {\n try {\n return { body: JSON.parse(text) as unknown, status, headers };\n } catch (error) {\n throw new ApiError(\n `${apiName} returned a response that is not valid JSON (HTTP ${status}).`,\n {\n status,\n body: text,\n headers,\n cause: error,\n },\n );\n }\n }\n throw createApiError(apiName, status, text, headers);\n }\n}\n","import { LOOKUP_TYPES } from './constants.js';\nimport { ValidationError } from './errors.js';\nimport type { LookupType } from './types.js';\n\nconst UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\nconst IPV4_OCTET = '(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)';\nconst IPV4 = new RegExp(`^${IPV4_OCTET}(?:\\\\.${IPV4_OCTET}){3}$`);\n\nexport interface Lookup {\n type: LookupType;\n value: string;\n /** The value escaped as one URL path segment. */\n segment: string;\n}\n\nfunction describe(value: unknown): string {\n const text = typeof value === 'string' ? JSON.stringify(value) : String(value);\n return text.length > 40 ? `${text.slice(0, 37)}...` : text;\n}\n\n// Escapes that canonical path escaping leaves as plain characters: $ & + , : ; = @\nconst PLAIN_IN_PATH = /%(?:24|26|2B|2C|3A|3B|3D|40)/g;\n// Characters encodeURIComponent leaves as they are but canonical path escaping escapes.\nconst ESCAPED_IN_PATH = /[!'()*]/g;\n\n/**\n * Escapes a User HID as one URL path segment in canonical form: A-Z, a-z, 0-9, \"-\", \".\", \"_\",\n * \"~\" and $ & + , : ; = @ stay as they are, every other character becomes uppercase %XX of its\n * UTF-8 bytes. The History API decodes the value only when the path is escaped exactly this way\n * and otherwise compares the escaped text, which finds nothing.\n */\nexport function encodePathSegment(value: string): string {\n let escaped: string;\n try {\n escaped = encodeURIComponent(value);\n } catch {\n throw new ValidationError(\n 'user_hid must be valid Unicode text (it has an unpaired surrogate).',\n );\n }\n return escaped\n .replace(PLAIN_IN_PATH, (match) => decodeURIComponent(match))\n .replace(ESCAPED_IN_PATH, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n}\n\n/**\n * Validates a History lookup before anything is sent. The server does not validate: an unknown\n * type returns unfiltered rows and a malformed UUID or IP returns a 500.\n */\nexport function validateLookup(type: unknown, value: unknown): Lookup {\n if (typeof type !== 'string' || !LOOKUP_TYPES.includes(type as LookupType)) {\n throw new ValidationError(\n `Unknown lookup type ${describe(type)}. Use one of: ${LOOKUP_TYPES.join(', ')}.`,\n );\n }\n const lookupType = type as LookupType;\n if (typeof value !== 'string') {\n throw new ValidationError(`The ${lookupType} value must be a string.`);\n }\n if (lookupType === 'user_hid') {\n if (value === '') throw new ValidationError('user_hid must be a non-empty string.');\n if (value === '.' || value === '..') {\n throw new ValidationError(\n 'user_hid cannot be \".\" or \"..\": a URL path segment cannot carry it.',\n );\n }\n if (value.includes('/')) {\n throw new ValidationError(\n 'user_hid cannot contain \"/\": the History API cannot search a value with a slash. Use URL-safe User HIDs, such as the 64 hex characters of userHid().',\n );\n }\n return { type: lookupType, value, segment: encodePathSegment(value) };\n }\n if (lookupType === 'ip') {\n if (value.includes(':')) {\n throw new ValidationError(\n 'IPv6 addresses cannot be searched: the History API stores IPv4 addresses only.',\n );\n }\n if (!IPV4.test(value)) {\n throw new ValidationError('ip must be a dotted IPv4 address such as 203.0.113.24.');\n }\n return { type: lookupType, value, segment: value };\n }\n if (!UUID.test(value)) {\n throw new ValidationError(`${lookupType} must be a UUID (8-4-4-4-12 hexadecimal digits).`);\n }\n const uuid = value.toLowerCase();\n return { type: lookupType, value: uuid, segment: uuid };\n}\n\n/** A request ID must be a UUID; it is sent lowercase. */\nexport function validateRequestId(requestId: unknown): string {\n if (typeof requestId !== 'string' || !UUID.test(requestId)) {\n throw new ValidationError('requestId must be a UUID (8-4-4-4-12 hexadecimal digits).');\n }\n return requestId.toLowerCase();\n}\n\n/** A boolean option. */\nexport function validateBoolean(value: unknown, name: string): boolean {\n if (typeof value !== 'boolean') throw new ValidationError(`${name} must be a boolean.`);\n return value;\n}\n\n/** Integer page size from 1 to 100 (the server silently turns other values into 20). */\nexport function validatePageSize(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 100) {\n throw new ValidationError(`${name} must be an integer from 1 to 100.`);\n }\n return value;\n}\n\n/** Integer greater than or equal to 0. */\nexport function validateNonNegativeInteger(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new ValidationError(`${name} must be an integer greater than or equal to 0.`);\n }\n return value;\n}\n\n/** Finite number of milliseconds, greater than 0 (or greater than or equal to 0 when allowZero). */\nexport function validateMilliseconds(value: unknown, name: string, allowZero = false): number {\n if (\n typeof value !== 'number' ||\n !Number.isFinite(value) ||\n value < 0 ||\n (!allowZero && value === 0)\n ) {\n const bound = allowZero ? 'greater than or equal to 0' : 'greater than 0';\n throw new ValidationError(`${name} must be a number of milliseconds ${bound}.`);\n }\n return value;\n}\n\nconst HEADER_SAFE = /^[\\x21-\\x7E]+$/;\n\n/**\n * Throws when `text` cannot be sent as an HTTP header value. The check runs before any request,\n * because the errors of the HTTP layer can echo the rejected value; the message never includes it.\n */\nexport function requireHeaderSafe(text: string, name: string): void {\n if (!HEADER_SAFE.test(text)) {\n throw new ValidationError(\n `${name} contains characters that cannot be sent in an HTTP header (only visible ASCII characters are allowed).`,\n );\n }\n}\n\n/** True when every character is ASCII. */\nexport function isAscii(text: string): boolean {\n for (let index = 0; index < text.length; index++) {\n if (text.charCodeAt(index) > 0x7f) return false;\n }\n return true;\n}\n\n/** A non-empty string of visible ASCII characters (after trimming), returned trimmed. */\nexport function validateCredential(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new ValidationError(`${name} is required and must be a non-empty string.`);\n }\n const credential = value.trim();\n requireHeaderSafe(credential, name);\n return credential;\n}\n","import { DEFAULT_HISTORY_BASE_URL } from './constants.js';\nimport {\n ApiError,\n ConnectionError,\n RateLimitError,\n ServerError,\n type ShieldLabsError,\n TimeoutError,\n ValidationError,\n} from './errors.js';\nimport { RATE_LIMIT_FLOOR_MS, RETRY_AFTER_CAP_MS, Transport, normalizeBaseUrl } from './http.js';\nimport { fromHistoryRow, isPlainObject } from './normalize.js';\nimport { sleep, throwIfAborted, warnIfBrowserPage, warnOnce } from './runtime.js';\nimport type { FetchLike, HistoryPage, Identification, LookupType } from './types.js';\nimport {\n validateBoolean,\n validateCredential,\n validateLookup,\n validateMilliseconds,\n validateNonNegativeInteger,\n validatePageSize,\n validateRequestId,\n type Lookup,\n} from './validation.js';\n\n/** Options of the History API client. */\nexport interface ShieldLabsOptions {\n /** Private API Key of the domain (sec_...). Keep it on your server. */\n apiKey: string;\n /** Origin of the History API. Default https://account.shieldlabs.ai. A trailing /api is removed. */\n baseUrl?: string | undefined;\n /** Timeout of one HTTP attempt in milliseconds. Default 10 000. */\n timeout?: number | undefined;\n /** Retries for connection errors, timeouts, 429 and 5xx. Default 2. */\n maxRetries?: number | undefined;\n /** Custom fetch implementation. Default: the global fetch. */\n fetch?: FetchLike | undefined;\n /**\n * Accept a plain http `baseUrl` on a host other than localhost, 127.0.0.1 or [::1], for a test\n * server. The key then travels unencrypted. Default false.\n */\n allowInsecureHttp?: boolean | undefined;\n}\n\n/** Options of `history.search`. */\nexport interface SearchOptions {\n /** Page size from 1 to 100. Default 20. */\n limit?: number | undefined;\n /** Number of rows to skip. Default 0. */\n offset?: number | undefined;\n signal?: AbortSignal | undefined;\n}\n\n/** Options of `history.iterate`. */\nexport interface IterateOptions {\n /** Rows per request from 1 to 100. Default 100. */\n pageSize?: number | undefined;\n /** Stop after this many identifications. Default: no limit. */\n maxItems?: number | undefined;\n signal?: AbortSignal | undefined;\n}\n\n/** Options of `identifications.get`. */\nexport interface GetIdentificationOptions {\n /** Poll until the identification appears (true) or read once (false). Default true. */\n wait?: boolean | undefined;\n /**\n * Total time budget of the wait in milliseconds, counted from the call. Default 10 000. The\n * last poll runs at this deadline. Each poll is one HTTP attempt whose timeout is the client\n * timeout, shortened to the time left but never below 1 second, so the last poll can end up\n * to 1 second after the deadline. Pass `signal` (for example `AbortSignal.timeout(11_000)`)\n * for a hard limit that also cancels a request in flight.\n */\n timeout?: number | undefined;\n /**\n * Base wait between polls in milliseconds. The waits are 1, 2, 4 and 6 times this value, then 8\n * times it for every later wait, each capped at 2 000 or at this value when it is longer.\n * Default 250, which gives waits of 250, 500, 1 000, 1 500 and then 2 000; 1 000 gives 1 000\n * and then 2 000; 3 000 gives 3 000 every time.\n */\n pollInterval?: number | undefined;\n signal?: AbortSignal | undefined;\n}\n\nconst API_KEY_FORMAT = /^sec_[a-z0-9]{8}-[a-z0-9]{8}-[a-z0-9]{8}$/;\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_RETRIES = 2;\nconst DEFAULT_LIMIT = 20;\nconst DEFAULT_PAGE_SIZE = 100;\nconst DEFAULT_WAIT_TIMEOUT_MS = 10_000;\nconst DEFAULT_POLL_INTERVAL_MS = 250;\n/** Cap of every wait between polls, unless `pollInterval` is longer: then that is the cap. */\nconst POLL_WAIT_CAP_MS = 2_000;\n/** Multiples of `pollInterval` for the waits after the first four polls. */\nconst POLL_WAIT_FACTORS = [1, 2, 4, 6] as const;\n/** Multiple of `pollInterval` for every later wait. */\nconst LAST_POLL_WAIT_FACTOR = 8;\n/** Shortest attempt timeout of a poll, even when less time is left before the deadline. */\nconst MIN_POLL_ATTEMPT_MS = 1_000;\n\n/**\n * The scheduled wait after poll number `index` (0 for the first poll): `pollInterval` times 1, 2,\n * 4 and 6, then 8 times it for every later wait, each capped at max(2 s, `pollInterval`). The\n * default 250 ms gives 250, 500, 1 000, 1 500 and then 2 000 ms; 1 s gives 1 s and then 2 s;\n * 3 s gives 3 s every time.\n */\nexport function pollWait(index: number, pollInterval: number): number {\n const factor = POLL_WAIT_FACTORS[index] ?? LAST_POLL_WAIT_FACTOR;\n return Math.min(Math.max(POLL_WAIT_CAP_MS, pollInterval), pollInterval * factor);\n}\n\nfunction parsePage(body: unknown, status: number, headers: ApiError['headers']): HistoryPage {\n if (!isPlainObject(body) || !Array.isArray(body.data)) {\n throw new ApiError('History API returned an unexpected response body.', {\n status,\n body,\n headers,\n });\n }\n const data = body.data.filter(isPlainObject).map(fromHistoryRow);\n const total =\n typeof body.total === 'number' && Number.isFinite(body.total) ? body.total : data.length;\n return { data, total };\n}\n\n/**\n * One validated History request. `maxRetries` overrides the client setting and `attemptTimeout`\n * caps the client timeout when given.\n */\nasync function fetchPage(\n transport: Transport,\n lookup: Lookup,\n limit: number,\n offset: number,\n signal: AbortSignal | undefined,\n maxRetries?: number,\n attemptTimeout?: number,\n): Promise<HistoryPage> {\n const path = `/api/v1/history/${lookup.type}/${lookup.segment}`;\n const response = await transport.getJson(path, {\n query: { limit: String(limit), offset: String(offset) },\n signal,\n maxRetries,\n timeout: attemptTimeout,\n });\n return parsePage(response.body, response.status, response.headers);\n}\n\n/** Errors a later poll can get past: 429, 5xx, connection failures and attempt timeouts. */\nfunction isTransientPollError(error: unknown): error is ShieldLabsError {\n return (\n error instanceof RateLimitError ||\n error instanceof ServerError ||\n error instanceof ConnectionError ||\n error instanceof TimeoutError\n );\n}\n\n/** Reads identifications from the History API. */\nexport class HistoryResource {\n readonly #transport: Transport;\n\n constructor(transport: Transport) {\n this.#transport = transport;\n }\n\n /**\n * One page of identifications for one identifier, newest first.\n * `GET /api/v1/history/{type}/{value}`.\n */\n async search(type: LookupType, value: string, options: SearchOptions = {}): Promise<HistoryPage> {\n const lookup = validateLookup(type, value);\n const limit = validatePageSize(options.limit ?? DEFAULT_LIMIT, 'limit');\n const offset = validateNonNegativeInteger(options.offset ?? 0, 'offset');\n return fetchPage(this.#transport, lookup, limit, offset, options.signal);\n }\n\n /**\n * Every identification for one identifier, newest first, fetched page by page. Rows repeated\n * across pages (new rows can shift offsets) are skipped by request ID. Stops at `total`, at an\n * empty page or after `maxItems`.\n */\n iterate(\n type: LookupType,\n value: string,\n options: IterateOptions = {},\n ): AsyncGenerator<Identification, void, undefined> {\n const lookup = validateLookup(type, value);\n const pageSize = validatePageSize(options.pageSize ?? DEFAULT_PAGE_SIZE, 'pageSize');\n const maxItems =\n options.maxItems === undefined\n ? undefined\n : validateNonNegativeInteger(options.maxItems, 'maxItems');\n return this.#iterate(lookup, pageSize, maxItems, options.signal);\n }\n\n async *#iterate(\n lookup: Lookup,\n pageSize: number,\n maxItems: number | undefined,\n signal: AbortSignal | undefined,\n ): AsyncGenerator<Identification, void, undefined> {\n const seen = new Set<string>();\n let offset = 0;\n let yielded = 0;\n for (;;) {\n if (maxItems !== undefined && yielded >= maxItems) return;\n const page = await fetchPage(this.#transport, lookup, pageSize, offset, signal);\n if (page.data.length === 0) return;\n for (const identification of page.data) {\n const key = identification.request_id;\n if (key !== '') {\n if (seen.has(key)) continue;\n seen.add(key);\n }\n yield identification;\n yielded++;\n if (maxItems !== undefined && yielded >= maxItems) return;\n }\n offset += page.data.length;\n if (offset >= page.total) return;\n }\n }\n}\n\n/** Reads single identifications by request ID. */\nexport class IdentificationsResource {\n readonly #transport: Transport;\n\n constructor(transport: Transport) {\n this.#transport = transport;\n }\n\n /**\n * The identification with this request ID, or null when none is found.\n *\n * Scoring is asynchronous: the row appears about 1 to 3 seconds after the browser call and can\n * be refined for up to about 10 seconds while follow-up checks finish; this returns the first\n * version it sees. With `wait` (the default), `timeout` is the total budget of the call:\n *\n * - The first poll runs at once. The waits between polls are `pollInterval` times 1, 2, 4 and 6,\n * then 8 times it for every later wait, each capped at max(2 s, `pollInterval`): 250 ms,\n * 500 ms, 1 s, 1.5 s and then every 2 s by default, and every 3 s for a `pollInterval` of\n * 3 s. A wait that would pass the deadline is cut short, so the last poll runs at the\n * deadline.\n * - Each poll is one HTTP attempt without retries, with the timeout\n * min(client timeout, max(time left, 1 s)).\n * - 429, 5xx, connection errors and timeouts do not end the wait. After a 429 the next wait is\n * the longest of the scheduled wait, 1 s and the Retry-After capped at 10 s (a missing\n * Retry-After, 0 or a past date counts as 0), cut short at the deadline like any other wait.\n * When the capped Retry-After is longer than the time left, that RateLimitError is thrown at\n * once.\n * - At the deadline, the error of the last poll is thrown if it failed; otherwise the result\n * is null.\n * - 400, 401, 403 and 404 (and any other error that another poll cannot fix) are thrown at once.\n */\n async get(\n requestId: string,\n options: GetIdentificationOptions = {},\n ): Promise<Identification | null> {\n const id = validateRequestId(requestId);\n const wait = validateBoolean(options.wait ?? true, 'wait');\n const timeout = validateMilliseconds(\n options.timeout ?? DEFAULT_WAIT_TIMEOUT_MS,\n 'timeout',\n true,\n );\n const pollInterval = validateMilliseconds(\n options.pollInterval ?? DEFAULT_POLL_INTERVAL_MS,\n 'pollInterval',\n );\n const { signal } = options;\n throwIfAborted(signal);\n const lookup: Lookup = { type: 'request_id', value: id, segment: id };\n\n if (!wait) {\n const page = await fetchPage(this.#transport, lookup, 1, 0, signal);\n return page.data[0] ?? null;\n }\n return this.#poll(lookup, Date.now() + timeout, pollInterval, signal);\n }\n\n async #poll(\n lookup: Lookup,\n deadline: number,\n pollInterval: number,\n signal: AbortSignal | undefined,\n ): Promise<Identification | null> {\n let atDeadline = false;\n for (let index = 0; ; index++) {\n const attemptTimeout = Math.min(\n this.#transport.timeout,\n Math.max(deadline - Date.now(), MIN_POLL_ATTEMPT_MS),\n );\n let failure: ShieldLabsError | undefined;\n try {\n const page = await fetchPage(this.#transport, lookup, 1, 0, signal, 0, attemptTimeout);\n const found = page.data[0];\n if (found) return found;\n } catch (error) {\n throwIfAborted(signal);\n if (!isTransientPollError(error)) throw error;\n failure = error;\n }\n\n const remaining = deadline - Date.now();\n if (atDeadline || remaining <= 0) {\n if (failure !== undefined) throw failure;\n return null;\n }\n\n let delay = pollWait(index, pollInterval);\n if (failure instanceof RateLimitError) {\n // No Retry-After counts as 0, like \"Retry-After: 0\" or a past date: the 1 s floor applies.\n const retryAfter = Math.min((failure.retryAfter ?? 0) * 1000, RETRY_AFTER_CAP_MS);\n // Retry-After asks for more time than is left: no later poll fits before the deadline.\n if (retryAfter > remaining) throw failure;\n delay = Math.max(delay, RATE_LIMIT_FLOOR_MS, retryAfter);\n }\n if (delay >= remaining) {\n delay = remaining;\n atDeadline = true;\n }\n await sleep(delay, signal);\n }\n }\n}\n\n/**\n * Client for the History API (`https://account.shieldlabs.ai`), authenticated with the Private\n * API Key of one domain. Stateless apart from its configuration, so one instance can be shared\n * by concurrent requests.\n */\nexport class ShieldLabs {\n /** Single identifications by request ID, with wait-for-verdict polling. */\n readonly identifications: IdentificationsResource;\n /** History lookups by identifier. */\n readonly history: HistoryResource;\n\n constructor(options: ShieldLabsOptions) {\n if (!isPlainObject(options)) {\n throw new ValidationError('new ShieldLabs() needs an options object with apiKey.');\n }\n const apiKey = validateCredential(options.apiKey, 'apiKey');\n warnIfBrowserPage('ShieldLabs', 'Private API Key');\n if (!API_KEY_FORMAT.test(apiKey)) {\n warnOnce(\n 'api-key-format',\n 'apiKey does not look like a Private API Key (sec_xxxxxxxx-xxxxxxxx-xxxxxxxx). The History API needs the Private API Key, not the Public Key or the Secret Key.',\n );\n }\n const baseUrl = normalizeBaseUrl(\n options.baseUrl ?? DEFAULT_HISTORY_BASE_URL,\n 'baseUrl',\n true,\n validateBoolean(options.allowInsecureHttp ?? false, 'allowInsecureHttp'),\n );\n const timeout = validateMilliseconds(options.timeout ?? DEFAULT_TIMEOUT_MS, 'timeout');\n const maxRetries = validateNonNegativeInteger(\n options.maxRetries ?? DEFAULT_MAX_RETRIES,\n 'maxRetries',\n );\n if (options.fetch !== undefined && typeof options.fetch !== 'function') {\n throw new ValidationError('fetch must be a function.');\n }\n const transport = new Transport({\n apiName: 'History API',\n baseUrl,\n headers: { Authorization: `Bearer ${apiKey}` },\n secrets: [apiKey],\n timeout,\n maxRetries,\n retryRateLimited: true,\n fetch: options.fetch,\n });\n this.history = new HistoryResource(transport);\n this.identifications = new IdentificationsResource(transport);\n }\n}\n","import { DEFAULT_MANAGEMENT_BASE_URL } from './constants.js';\nimport { ApiError, ValidationError } from './errors.js';\nimport { Transport, normalizeBaseUrl } from './http.js';\nimport { isPlainObject, profileFromResponse } from './normalize.js';\nimport { warnIfBrowserPage } from './runtime.js';\nimport type { DomainProfile, FetchLike } from './types.js';\nimport {\n isAscii,\n requireHeaderSafe,\n validateBoolean,\n validateCredential,\n validateMilliseconds,\n validateNonNegativeInteger,\n} from './validation.js';\n\n/** Options of the Management API client. */\nexport interface ShieldLabsManagementOptions {\n /** Secret Key of the domain. Keep it on your server. */\n secretKey: string;\n /** The registered domain, for example \"example.com\". Normalized before it is sent. */\n domain: string;\n /** Origin of the Management API. Default https://api.shieldlabs.ai. */\n baseUrl?: string | undefined;\n /** Timeout of one HTTP attempt in milliseconds. Default 10 000. */\n timeout?: number | undefined;\n /** Retries for connection errors, timeouts and 5xx (never for 429). Default 2. */\n maxRetries?: number | undefined;\n /** Custom fetch implementation. Default: the global fetch. */\n fetch?: FetchLike | undefined;\n /**\n * Accept a plain http `baseUrl` on a host other than localhost, 127.0.0.1 or [::1], for a test\n * server. The Secret Key then travels unencrypted. Default false.\n */\n allowInsecureHttp?: boolean | undefined;\n}\n\n/** Options of `getProfile`. */\nexport interface GetProfileOptions {\n signal?: AbortSignal | undefined;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_RETRIES = 2;\n\n/**\n * Normalizes a domain the way registered domains are stored: trimmed, lowercase, without scheme,\n * path, trailing slash or a leading \"www.\". The server matches the registered domain exactly.\n */\nexport function normalizeDomain(input: string): string {\n let domain = input.trim().toLowerCase();\n domain = domain.replace(/^[a-z][a-z0-9+.-]*:\\/\\//, '');\n domain = domain.split(/[/?#]/, 1)[0] ?? '';\n return domain.replace(/^www\\./, '');\n}\n\n/**\n * Client for the Management API (`https://api.shieldlabs.ai`), authenticated with the Secret Key\n * and the registered domain. The API allows about 15 requests per minute per IP and then blocks\n * the IP for 10 minutes, so this client never retries a 429: call it sparingly and cache results.\n * Safe for concurrent use.\n */\nexport class ShieldLabsManagement {\n /** The normalized domain sent in X-Shield-Domain. */\n readonly domain: string;\n readonly #transport: Transport;\n\n constructor(options: ShieldLabsManagementOptions) {\n if (!isPlainObject(options)) {\n throw new ValidationError(\n 'new ShieldLabsManagement() needs an options object with secretKey and domain.',\n );\n }\n const secretKey = validateCredential(options.secretKey, 'secretKey');\n warnIfBrowserPage('ShieldLabsManagement', 'Secret Key');\n if (typeof options.domain !== 'string') {\n throw new ValidationError('domain is required and must be a string such as \"example.com\".');\n }\n const domain = normalizeDomain(options.domain);\n if (domain === '') {\n throw new ValidationError('domain is required and must be a string such as \"example.com\".');\n }\n if (!isAscii(domain)) {\n throw new ValidationError('domain must be ASCII: pass the punycode form (xn--...).');\n }\n requireHeaderSafe(domain, 'domain');\n const baseUrl = normalizeBaseUrl(\n options.baseUrl ?? DEFAULT_MANAGEMENT_BASE_URL,\n 'baseUrl',\n false,\n validateBoolean(options.allowInsecureHttp ?? false, 'allowInsecureHttp'),\n );\n const timeout = validateMilliseconds(options.timeout ?? DEFAULT_TIMEOUT_MS, 'timeout');\n const maxRetries = validateNonNegativeInteger(\n options.maxRetries ?? DEFAULT_MAX_RETRIES,\n 'maxRetries',\n );\n if (options.fetch !== undefined && typeof options.fetch !== 'function') {\n throw new ValidationError('fetch must be a function.');\n }\n this.domain = domain;\n this.#transport = new Transport({\n apiName: 'Management API',\n baseUrl,\n headers: { 'X-Shield-Domain': domain, Authorization: `Bearer ${secretKey}` },\n secrets: [secretKey],\n timeout,\n maxRetries,\n retryRateLimited: false,\n fetch: options.fetch,\n });\n }\n\n /** The domain profile: remaining identifications and masked keys. `GET /v1/profile`. */\n async getProfile(options: GetProfileOptions = {}): Promise<DomainProfile> {\n const response = await this.#transport.getJson('/v1/profile', { signal: options.signal });\n if (!isPlainObject(response.body)) {\n throw new ApiError('Management API returned an unexpected response body.', {\n status: response.status,\n body: response.body,\n headers: response.headers,\n });\n }\n return profileFromResponse(response.body);\n }\n}\n","import { FLAG_KEYS, NIL_UUID, RISK_BAND_NAMES, type FlagKey } from './constants.js';\nimport { ValidationError } from './errors.js';\nimport type { DetectionFlags, Identification, RiskBand } from './types.js';\n\n/**\n * Risk band for a Risk Score: trusted 0-29, suspicious 30-59, dangerous 60-100.\n * A score above 100 (the 999 marker) is not a score: it returns \"rate_limited\".\n */\nexport function riskBand(score: number): RiskBand | 'rate_limited' {\n if (typeof score !== 'number' || Number.isNaN(score)) {\n throw new ValidationError('riskBand() needs a numeric Risk Score.');\n }\n if (score > 100) return 'rate_limited';\n if (score >= 60) return 'dangerous';\n if (score >= 30) return 'suspicious';\n return 'trusted';\n}\n\n/** True for the rate-limit marker (a Risk Score above 100, sent as 999). */\nexport function isRateLimited(score: number): boolean {\n return typeof score === 'number' && score > 100;\n}\n\n/** Why an identification did not pass `evaluateIdentification`. */\nexport type EvaluationReason =\n | 'missing'\n | 'replayed'\n | 'stale'\n | 'rate_limited'\n | 'no_device_signals'\n | 'blocked_flag'\n | 'blocked_band';\n\n/** Result of `evaluateIdentification`. */\nexport interface Evaluation {\n /** True when every check passed. */\n ok: boolean;\n /** The first check that failed, or null when `ok` is true. */\n reason: EvaluationReason | null;\n /** Band of the Risk Score (\"rate_limited\" for the 999 marker), or null when the identification is missing. */\n band: RiskBand | 'rate_limited' | null;\n /** The detection flag that failed the check, when `reason` is \"blocked_flag\". */\n flag?: keyof DetectionFlags;\n}\n\n/** Options of `evaluateIdentification`. The defaults are a starting point to tune. */\nexport interface EvaluateOptions {\n /**\n * Maximum age of the identification in milliseconds, measured from `observed_at`. Default\n * 300 000 (5 minutes). `Infinity` skips the freshness check.\n */\n maxAge?: number | undefined;\n /** Current time (Date or epoch milliseconds). Default: now. */\n now?: Date | number | undefined;\n /** Bands that fail the check. Default [\"dangerous\"]. */\n blockBands?: readonly RiskBand[] | undefined;\n /** Detection flags that fail the check. Default [\"browser_automation\", \"javascript_disabled\"]. */\n blockFlags?: readonly (keyof DetectionFlags)[] | undefined;\n /**\n * Returns true when this request ID was already used for a protected action. The SDK keeps\n * no state: claim the request ID in your own store first (an atomic insert-if-absent) and\n * return the result here. Must return a boolean synchronously.\n */\n isReplay?: ((requestId: string) => boolean) | undefined;\n}\n\nconst DEFAULT_MAX_AGE_MS = 300_000;\nconst DEFAULT_BLOCK_BANDS: readonly RiskBand[] = ['dangerous'];\nconst DEFAULT_BLOCK_FLAGS: readonly FlagKey[] = ['browser_automation', 'javascript_disabled'];\n\nfunction resolveNow(now: Date | number | undefined): number {\n if (now === undefined) return Date.now();\n const value = now instanceof Date ? now.getTime() : now;\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ValidationError('now must be a valid Date or a number of epoch milliseconds.');\n }\n return value;\n}\n\nfunction isThenable(value: unknown): boolean {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\n/**\n * Applies a reusable guard policy to an identification. Checks run in this order and the first\n * failure wins: missing identification, replayed request ID (`isReplay`), older than `maxAge`,\n * rate-limit marker, all-zero device ID, a flag in `blockFlags`, a band in `blockBands`.\n */\nexport function evaluateIdentification(\n identification: Identification | null | undefined,\n options: EvaluateOptions = {},\n): Evaluation {\n const maxAge = options.maxAge ?? DEFAULT_MAX_AGE_MS;\n if (typeof maxAge !== 'number' || Number.isNaN(maxAge) || maxAge < 0) {\n throw new ValidationError(\n 'maxAge must be a number of milliseconds greater than or equal to 0, or Infinity to skip the freshness check.',\n );\n }\n const nowMs = resolveNow(options.now);\n const blockBands = options.blockBands ?? DEFAULT_BLOCK_BANDS;\n for (const band of blockBands) {\n if (!RISK_BAND_NAMES.includes(band)) {\n throw new ValidationError(\n `Unknown risk band in blockBands. Use one of: ${RISK_BAND_NAMES.join(', ')}.`,\n );\n }\n }\n const blockFlags = options.blockFlags ?? DEFAULT_BLOCK_FLAGS;\n for (const flag of blockFlags) {\n if (!FLAG_KEYS.includes(flag)) {\n throw new ValidationError(\n `Unknown detection flag in blockFlags. Use one of: ${FLAG_KEYS.join(', ')}.`,\n );\n }\n }\n\n if (identification === null || identification === undefined) {\n return { ok: false, reason: 'missing', band: null };\n }\n\n const band = riskBand(identification.risk_score);\n\n if (options.isReplay) {\n const replayed: unknown = options.isReplay(identification.request_id);\n if (isThenable(replayed)) {\n throw new ValidationError(\n 'isReplay must return a boolean synchronously. Claim the request ID in your store first (an atomic insert-if-absent), then pass the result, for example isReplay: () => !claimed.',\n );\n }\n if (replayed) return { ok: false, reason: 'replayed', band };\n }\n\n if (maxAge !== Number.POSITIVE_INFINITY) {\n const observedMs =\n identification.observed_at === null ? Number.NaN : Date.parse(identification.observed_at);\n if (Number.isNaN(observedMs) || nowMs - observedMs > maxAge) {\n return { ok: false, reason: 'stale', band };\n }\n }\n\n if (isRateLimited(identification.risk_score)) {\n return { ok: false, reason: 'rate_limited', band };\n }\n\n if (!identification.device_id || identification.device_id === NIL_UUID) {\n return { ok: false, reason: 'no_device_signals', band };\n }\n\n for (const flag of blockFlags) {\n if (identification.detection_flags[flag]) {\n return { ok: false, reason: 'blocked_flag', band, flag };\n }\n }\n\n if (band !== 'rate_limited' && blockBands.includes(band)) {\n return { ok: false, reason: 'blocked_band', band };\n }\n\n return { ok: true, reason: null, band };\n}\n","/**\n * @shieldlabs-ai/node for Node.js and Bun.\n *\n * Read identifications from the History API, read the domain profile from the Management API,\n * verify signed webhooks and apply risk helpers. Edge runtimes resolve `edge.ts` instead, which\n * exposes the same API without loading node:crypto.\n */\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport {\n computeUserHid,\n computeUserHidAsync,\n createWebhooks,\n type CryptoBackend,\n type Webhooks,\n} from './webhooks.js';\n\nconst hmacSync = (key: string, message: Uint8Array): Uint8Array =>\n createHmac('sha256', key).update(message).digest();\n\nconst backend: CryptoBackend = {\n hmacSync,\n hmacAsync: (key, message) => Promise.resolve().then(() => hmacSync(key, message)),\n equal: (a, b) => a.length === b.length && timingSafeEqual(a, b),\n};\n\n/** Webhook signature verification (X-Shield-Signature) and typed event parsing. */\nexport const webhooks: Webhooks = createWebhooks(backend);\n\n/**\n * A stable, irreversible User HID for one of your accounts: HMAC-SHA256 of `userId` keyed with\n * `secret`, as 64 lowercase hex characters. Compute it on your server and pass it to the browser\n * agent instead of a raw email address or account ID. Throws ValidationError on empty input.\n * Needs node:crypto: in edge runtimes use `userHidAsync`.\n */\nexport function userHid(userId: string, secret: string): string {\n return computeUserHid(backend, userId, secret);\n}\n\n/** Same as `userHid`, as a promise (works in every runtime). */\nexport function userHidAsync(userId: string, secret: string): Promise<string> {\n return computeUserHidAsync(backend, userId, secret);\n}\n\nexport * from './common.js';\n"]}
package/package.json CHANGED
@@ -1,6 +1,140 @@
1
1
  {
2
2
  "name": "@shieldlabs-ai/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "ShieldLabs server SDK for Node.js and edge runtimes: History API and Management API clients, webhook signature verification, typed identifications and risk helpers.",
5
+ "license": "MIT",
6
+ "author": "ShieldLabs Inc. <contact@shieldlabs.ai>",
7
+ "homepage": "https://docs.shieldlabs.ai",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ShieldLabs-ai/shieldlabs-node.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/ShieldLabs-ai/shieldlabs-node/issues",
14
+ "email": "contact@shieldlabs.ai"
15
+ },
16
+ "keywords": [
17
+ "shieldlabs",
18
+ "device-intelligence",
19
+ "risk-score",
20
+ "fraud-prevention",
21
+ "bot-detection",
22
+ "webhooks",
23
+ "server-sdk"
24
+ ],
25
+ "type": "module",
26
+ "main": "./dist/index.cjs",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "bun": {
32
+ "import": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "require": {
37
+ "types": "./dist/index.d.cts",
38
+ "default": "./dist/index.cjs"
39
+ }
40
+ },
41
+ "deno": {
42
+ "import": {
43
+ "types": "./dist/index.d.ts",
44
+ "default": "./dist/edge.js"
45
+ },
46
+ "require": {
47
+ "types": "./dist/index.d.cts",
48
+ "default": "./dist/edge.cjs"
49
+ }
50
+ },
51
+ "workerd": {
52
+ "import": {
53
+ "types": "./dist/index.d.ts",
54
+ "default": "./dist/edge.js"
55
+ },
56
+ "require": {
57
+ "types": "./dist/index.d.cts",
58
+ "default": "./dist/edge.cjs"
59
+ }
60
+ },
61
+ "worker": {
62
+ "import": {
63
+ "types": "./dist/index.d.ts",
64
+ "default": "./dist/edge.js"
65
+ },
66
+ "require": {
67
+ "types": "./dist/index.d.cts",
68
+ "default": "./dist/edge.cjs"
69
+ }
70
+ },
71
+ "edge-light": {
72
+ "import": {
73
+ "types": "./dist/index.d.ts",
74
+ "default": "./dist/edge.js"
75
+ },
76
+ "require": {
77
+ "types": "./dist/index.d.cts",
78
+ "default": "./dist/edge.cjs"
79
+ }
80
+ },
81
+ "browser": {
82
+ "import": {
83
+ "types": "./dist/index.d.ts",
84
+ "default": "./dist/edge.js"
85
+ },
86
+ "require": {
87
+ "types": "./dist/index.d.cts",
88
+ "default": "./dist/edge.cjs"
89
+ }
90
+ },
91
+ "import": {
92
+ "types": "./dist/index.d.ts",
93
+ "default": "./dist/index.js"
94
+ },
95
+ "require": {
96
+ "types": "./dist/index.d.cts",
97
+ "default": "./dist/index.cjs"
98
+ },
99
+ "default": "./dist/index.js"
100
+ },
101
+ "./package.json": "./package.json"
102
+ },
103
+ "files": [
104
+ "dist",
105
+ "README.md",
106
+ "CHANGELOG.md",
107
+ "LICENSE"
108
+ ],
109
+ "sideEffects": false,
110
+ "engines": {
111
+ "node": ">=18"
112
+ },
113
+ "scripts": {
114
+ "build": "tsup",
115
+ "typecheck": "tsc --noEmit",
116
+ "lint": "eslint . && prettier --check .",
117
+ "format": "prettier --write .",
118
+ "test": "vitest run",
119
+ "test:package": "node scripts/check-package.mjs",
120
+ "test:runtime": "node test/runtime/smoke.mjs && node --conditions=worker test/runtime/smoke.mjs",
121
+ "test:example": "node scripts/smoke-example.mjs",
122
+ "prepack": "npm run build"
123
+ },
124
+ "publishConfig": {
125
+ "access": "public"
126
+ },
127
+ "devDependencies": {
128
+ "@eslint/js": "^9.39.5",
129
+ "@types/node": "^20.19.43",
130
+ "@vitest/coverage-v8": "^4.1.11",
131
+ "eslint": "^9.39.5",
132
+ "globals": "^16.5.0",
133
+ "prettier": "^3.9.9",
134
+ "tsup": "^8.5.1",
135
+ "typescript": "^5.9.3",
136
+ "typescript-eslint": "^8.71.0",
137
+ "vite": "^6.4.3",
138
+ "vitest": "^4.1.11"
139
+ }
140
+ }