@kya-os/checkpoint-shared 1.5.1 → 1.6.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.
- package/CHANGELOG.md +217 -0
- package/dist/beacon-nonce/index.d.mts +36 -0
- package/dist/beacon-nonce/index.d.mts.map +1 -0
- package/dist/beacon-nonce/index.d.ts +36 -0
- package/dist/beacon-nonce/index.d.ts.map +1 -0
- package/dist/beacon-nonce/index.js +305 -0
- package/dist/beacon-nonce/index.mjs +294 -0
- package/dist/beacon-nonce/index.mjs.map +1 -0
- package/dist/beacon-types/index.d.mts +40 -0
- package/dist/beacon-types/index.d.mts.map +1 -1
- package/dist/beacon-types/index.d.ts +40 -0
- package/dist/beacon-types/index.d.ts.map +1 -1
- package/dist/beacon-types/index.js +53 -5
- package/dist/beacon-types/index.mjs +49 -6
- package/dist/beacon-types/index.mjs.map +1 -1
- package/dist/browser-posture-BuChqmH5.d.mts +169 -0
- package/dist/browser-posture-BuChqmH5.d.mts.map +1 -0
- package/dist/browser-posture-DIaVLuW3.d.ts +169 -0
- package/dist/browser-posture-DIaVLuW3.d.ts.map +1 -0
- package/dist/browser-posture-cookie.d.mts +4 -2
- package/dist/browser-posture-cookie.d.mts.map +1 -0
- package/dist/browser-posture-cookie.d.ts +4 -2
- package/dist/browser-posture-cookie.d.ts.map +1 -0
- package/dist/browser-posture-cookie.mjs.map +1 -1
- package/dist/browser-posture-proof.d.mts +18 -0
- package/dist/browser-posture-proof.d.mts.map +1 -0
- package/dist/browser-posture-proof.d.ts +18 -0
- package/dist/browser-posture-proof.d.ts.map +1 -0
- package/dist/browser-posture-proof.js +66 -0
- package/dist/browser-posture-proof.mjs +63 -0
- package/dist/browser-posture-proof.mjs.map +1 -0
- package/dist/browser-posture-report.d.mts +59 -2
- package/dist/browser-posture-report.d.mts.map +1 -1
- package/dist/browser-posture-report.d.ts +59 -2
- package/dist/browser-posture-report.d.ts.map +1 -1
- package/dist/browser-posture-report.js +1 -1
- package/dist/browser-posture-report.mjs +1 -1
- package/dist/browser-posture-report.mjs.map +1 -1
- package/dist/browser-posture.d.mts +2 -85
- package/dist/browser-posture.d.ts +2 -85
- package/dist/browser-posture.js +207 -45
- package/dist/browser-posture.mjs +195 -45
- package/dist/browser-posture.mjs.map +1 -1
- package/dist/browser.d.mts +0 -8
- package/dist/browser.d.mts.map +1 -1
- package/dist/browser.d.ts +0 -8
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/browser.mjs.map +1 -1
- package/dist/clearance.d.mts +1 -1
- package/dist/clearance.d.ts +1 -1
- package/dist/clearance.js +2 -2
- package/dist/clearance.mjs +2 -2
- package/dist/{client-ip-HOfe6ucV.mjs → client-ip-B2Xeo-GK.mjs} +2 -2
- package/dist/{client-ip-HOfe6ucV.mjs.map → client-ip-B2Xeo-GK.mjs.map} +1 -1
- package/dist/{client-ip-1y2iXAYW.js → client-ip-CW6pRyLf.js} +1 -1
- package/dist/consent-handoff.d.mts +41 -0
- package/dist/consent-handoff.d.mts.map +1 -0
- package/dist/consent-handoff.d.ts +41 -0
- package/dist/consent-handoff.d.ts.map +1 -0
- package/dist/consent-handoff.js +1 -0
- package/dist/consent-handoff.mjs +2 -0
- package/dist/consent-handoff.mjs.map +1 -0
- package/dist/errors/index.d.mts +155 -0
- package/dist/errors/index.d.mts.map +1 -1
- package/dist/errors/index.d.ts +155 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +513 -9
- package/dist/errors/index.mjs +513 -10
- package/dist/errors/index.mjs.map +1 -1
- package/dist/{external-jr_S4iSS.d.ts → external-B7WI9FyQ.d.mts} +2 -2
- package/dist/{external-jr_S4iSS.d.mts.map → external-B7WI9FyQ.d.mts.map} +1 -1
- package/dist/{external-jr_S4iSS.d.mts → external-B7WI9FyQ.d.ts} +2 -2
- package/dist/{external-jr_S4iSS.d.ts.map → external-B7WI9FyQ.d.ts.map} +1 -1
- package/dist/gateway-client-ip.d.mts +1 -1
- package/dist/gateway-client-ip.d.ts +1 -1
- package/dist/gateway-client-ip.js +2 -2
- package/dist/gateway-client-ip.mjs +2 -2
- package/dist/index.d.mts +6375 -1532
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +6375 -1532
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5629 -697
- package/dist/index.mjs +5341 -683
- package/dist/index.mjs.map +1 -1
- package/dist/mcpi/approval-grant/index.d.mts +1 -1
- package/dist/mcpi/approval-grant/index.d.mts.map +1 -1
- package/dist/mcpi/approval-grant/index.d.ts +1 -1
- package/dist/mcpi/approval-grant/index.d.ts.map +1 -1
- package/dist/mcpi/approval-grant/index.js +58 -49
- package/dist/mcpi/approval-grant/index.mjs +58 -49
- package/dist/mcpi/approval-grant/index.mjs.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.mts +3 -2
- package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.ts +3 -2
- package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
- package/dist/posture-origins/index.d.mts +41 -0
- package/dist/posture-origins/index.d.mts.map +1 -0
- package/dist/posture-origins/index.d.ts +41 -0
- package/dist/posture-origins/index.d.ts.map +1 -0
- package/dist/posture-origins/index.js +441 -0
- package/dist/posture-origins/index.mjs +430 -0
- package/dist/posture-origins/index.mjs.map +1 -0
- package/dist/posture-origins-LFkX80oF.js +627 -0
- package/dist/posture-origins-Pn-ii-Pp.mjs +533 -0
- package/dist/posture-origins-Pn-ii-Pp.mjs.map +1 -0
- package/dist/{project-verification-key-CgSVX9_m.mjs → project-verification-key-66N4edKn.mjs} +2 -2
- package/dist/{project-verification-key-CgSVX9_m.mjs.map → project-verification-key-66N4edKn.mjs.map} +1 -1
- package/dist/{project-verification-key-C3L5rd8a.js → project-verification-key-BccT12tQ.js} +1 -1
- package/dist/rules.json +0 -1
- package/dist/{schemas-DxY-dk9y.mjs → schemas-7qodsG-Z.mjs} +49 -2
- package/dist/schemas-7qodsG-Z.mjs.map +1 -0
- package/dist/{schemas-BmjNLAE7.js → schemas-YhagYDx_.js} +59 -0
- package/dist/signals/index.d.mts +75 -55
- package/dist/signals/index.d.mts.map +1 -1
- package/dist/signals/index.d.ts +75 -55
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +246 -2
- package/dist/signals/index.mjs +236 -3
- package/dist/signals/index.mjs.map +1 -1
- package/fixtures/browser-integrity/captured-java-0.2.1-missing-score.json +10 -0
- package/fixtures/browser-integrity/null-score.json +11 -0
- package/fixtures/browser-integrity/numeric-score.json +11 -0
- package/fixtures/browser-posture-claims.json +168 -0
- package/fixtures/browser-posture-headers.json +6 -0
- package/fixtures/cli-registration.v2.json +115 -0
- package/fixtures/detection/reason-codes.json +1 -1
- package/fixtures/kya-http/README.md +34 -25
- package/fixtures/kya-http/consent-handoff.codes.json +34 -0
- package/fixtures/kya-http/protected-resource-metadata.full.json +14 -5
- package/fixtures/kya-http/protected-resource-metadata.invalid-issuer.json +51 -0
- package/fixtures/kya-http/protected-resource-metadata.no-issuer.json +32 -0
- package/fixtures/reviewer-grant-revocation.v1.json +285 -0
- package/fixtures/workbench/a2a-signed-request.v1.json +255 -0
- package/fixtures/workbench/artifact-bindings.v1.json +1003 -0
- package/fixtures/workbench/delegation-management.v1.json +507 -0
- package/fixtures/workbench/didcomm-task-source.v1.json +191 -0
- package/fixtures/workbench/graph-interfaces.v1.json +1887 -0
- package/fixtures/workbench/identity-provisioning.v1.json +643 -0
- package/fixtures/workbench/linear-installation.v1.json +484 -0
- package/fixtures/workbench/management-session.v1.json +716 -0
- package/fixtures/workbench/model-credentials.v1.json +630 -0
- package/fixtures/workbench/source-claim-pooled.v1.json +50 -0
- package/fixtures/workbench/task-grant.v1.json +695 -0
- package/fixtures/workbench/task-status-projection.v1.json +591 -0
- package/fixtures/workbench/workload-enrollment.v1.json +580 -0
- package/package.json +24 -5
- package/src/data/compiled/merged-rules.json +2 -9
- package/src/data/default-rules.json +0 -1
- package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +0 -5
- package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +0 -1
- package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +0 -5
- package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +0 -1
- package/dist/browser-posture.d.mts.map +0 -1
- package/dist/browser-posture.d.ts.map +0 -1
- package/dist/patterns-CkRVOdtV.js +0 -243
- package/dist/patterns-DzkGy_qk.mjs +0 -173
- package/dist/patterns-DzkGy_qk.mjs.map +0 -1
- package/dist/schemas-DxY-dk9y.mjs.map +0 -1
- package/fixtures/kya-http/protected-resource-metadata.global.json +0 -28
package/dist/browser.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser.mjs","names":[],"sources":["../src/utils/client-ip.ts","../src/browser.ts"],"sourcesContent":["/**\n * Runtime-agnostic client-IP normalization and trust resolution.\n *\n * Header presence is not proof of provenance. Callers must select the\n * deployment profile that describes which infrastructure has already\n * authenticated a value before using the result for security decisions.\n */\n\nexport type ClientIpSource =\n | 'explicit'\n | 'cf-connecting-ip'\n | 'x-vercel-forwarded-for'\n | 'x-forwarded-for'\n | 'x-real-ip'\n | 'framework'\n | 'socket'\n | 'none';\n\nexport interface ClientIpResolution {\n ip: string | null;\n source: ClientIpSource;\n trusted: boolean;\n}\n\nexport type ClientIpTrustPolicy =\n | { platform: 'vercel' }\n | { platform: 'cloudflare' }\n | { platform: 'trusted-proxy'; trustedHops: number }\n | { platform: 'direct' };\n\nexport type ClientIpHeaderValue = string | readonly string[] | undefined;\nexport type ClientIpHeaders = Headers | Record<string, ClientIpHeaderValue>;\n\nexport interface ResolveClientIpInput {\n headers: ClientIpHeaders;\n directAddress?: string | null;\n frameworkAddress?: string | null;\n explicitAddress?: string | null;\n /** True only after the caller has authenticated the explicit value. */\n explicitAddressTrusted?: boolean;\n policy: ClientIpTrustPolicy;\n}\n\nconst MAX_INPUT_LENGTH = 4096;\nconst MAX_TOKEN_LENGTH = 128;\nconst MAX_FORWARDED_HOPS = 32;\n\nfunction hasControlCharacter(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f) return true;\n }\n return false;\n}\n\nfunction parsePort(value: string): boolean {\n return /^(?:0|[1-9]\\d{0,4})$/.test(value) && Number(value) <= 65535;\n}\n\nfunction parseIpv4(value: string): number[] | null {\n const parts = value.split('.');\n if (parts.length !== 4) return null;\n\n const octets: number[] = [];\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part)) return null;\n const octet = Number(part);\n if (octet > 255) return null;\n octets.push(octet);\n }\n return octets;\n}\n\nfunction parseHexGroup(value: string): number | null {\n if (!/^[0-9a-fA-F]{1,4}$/.test(value)) return null;\n return Number.parseInt(value, 16);\n}\n\n/** Parses a bare IPv6 address into its 8 groups (`::` expanded). Exported for reuse by anything that needs to mask/truncate an address (see `anonymize-ip.ts`), not just resolve one. */\nexport function parseIpv6(value: string): number[] | null {\n if (!value || value.includes('%') || hasControlCharacter(value)) return null;\n\n let address = value;\n if (address.includes('.')) {\n const lastColon = address.lastIndexOf(':');\n if (lastColon < 0) return null;\n const ipv4 = parseIpv4(address.slice(lastColon + 1));\n if (!ipv4) return null;\n const first = (ipv4[0]! << 8) | ipv4[1]!;\n const second = (ipv4[2]! << 8) | ipv4[3]!;\n address = `${address.slice(0, lastColon + 1)}${first.toString(16)}:${second.toString(16)}`;\n }\n\n const doubleColon = address.indexOf('::');\n if (doubleColon !== address.lastIndexOf('::')) return null;\n\n const parseGroups = (part: string): number[] | null => {\n if (!part) return [];\n const groups = part.split(':');\n const parsed: number[] = [];\n for (const group of groups) {\n const number = parseHexGroup(group);\n if (number === null) return null;\n parsed.push(number);\n }\n return parsed;\n };\n\n if (doubleColon >= 0) {\n const head = parseGroups(address.slice(0, doubleColon));\n const tail = parseGroups(address.slice(doubleColon + 2));\n if (!head || !tail) return null;\n const missing = 8 - head.length - tail.length;\n if (missing < 1) return null;\n return [...head, ...Array<number>(missing).fill(0), ...tail];\n }\n\n const groups = parseGroups(address);\n return groups?.length === 8 ? groups : null;\n}\n\n/** RFC 5952 canonical `::` compression for 8 IPv6 groups. Exported alongside `parseIpv6`. */\nexport function compressIpv6(groups: number[]): string {\n const rendered = groups.map((group) => group.toString(16));\n let bestStart = -1;\n let bestLength = 1;\n let runStart = -1;\n\n for (let index = 0; index <= groups.length; index += 1) {\n if (index < groups.length && groups[index] === 0) {\n if (runStart < 0) runStart = index;\n continue;\n }\n if (runStart >= 0) {\n const runLength = index - runStart;\n if (runLength > bestLength) {\n bestStart = runStart;\n bestLength = runLength;\n }\n runStart = -1;\n }\n }\n\n if (bestStart < 0) return rendered.join(':');\n const before = rendered.slice(0, bestStart).join(':');\n const after = rendered.slice(bestStart + bestLength).join(':');\n if (!before && !after) return '::';\n if (!before) return `::${after}`;\n if (!after) return `${before}::`;\n return `${before}::${after}`;\n}\n\nfunction normalizeToken(rawToken: string): string | null {\n const token = rawToken.trim();\n if (!token || token.length > MAX_TOKEN_LENGTH || hasControlCharacter(token)) return null;\n\n let address = token;\n if (token.startsWith('[')) {\n const closing = token.indexOf(']');\n if (closing <= 1) return null;\n const suffix = token.slice(closing + 1);\n if (suffix && (!suffix.startsWith(':') || !parsePort(suffix.slice(1)))) return null;\n address = token.slice(1, closing);\n } else if ((token.match(/:/g) ?? []).length === 1 && token.includes('.')) {\n const colon = token.indexOf(':');\n if (!parsePort(token.slice(colon + 1))) return null;\n address = token.slice(0, colon);\n }\n\n const ipv4 = parseIpv4(address);\n if (ipv4) return ipv4.join('.');\n\n const ipv6 = parseIpv6(address);\n return ipv6 ? compressIpv6(ipv6) : null;\n}\n\nfunction boundedTokens(raw: string | null | undefined): string[] | null {\n if (raw == null || !raw || raw.length > MAX_INPUT_LENGTH || hasControlCharacter(raw)) return null;\n const tokens = raw.split(',');\n if (tokens.length > MAX_FORWARDED_HOPS) return null;\n return tokens;\n}\n\n/** Normalize the first valid address in a bounded header value. */\nexport function normalizeClientIp(raw: string | null | undefined): string | null {\n const tokens = boundedTokens(raw);\n if (!tokens) return null;\n for (const token of tokens) {\n const normalized = normalizeToken(token);\n if (normalized) return normalized;\n }\n return null;\n}\n\nfunction getHeader(headers: ClientIpHeaders, name: string): string | undefined {\n if ('get' in headers && typeof headers.get === 'function') {\n return headers.get(name) ?? undefined;\n }\n\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== wanted || value === undefined) continue;\n return Array.isArray(value) ? value.join(',') : value;\n }\n return undefined;\n}\n\nfunction result(\n ip: string | null,\n source: Exclude<ClientIpSource, 'none'>,\n trusted: boolean\n): ClientIpResolution | null {\n return ip ? { ip, source, trusted } : null;\n}\n\nfunction resolveAddress(\n raw: string | null | undefined,\n source: 'framework' | 'socket'\n): ClientIpResolution | null {\n return result(normalizeClientIp(raw), source, true);\n}\n\nfunction resolveExplicit(input: ResolveClientIpInput): ClientIpResolution | null {\n if (input.explicitAddressTrusted !== true) return null;\n return result(normalizeClientIp(input.explicitAddress), 'explicit', true);\n}\n\nfunction resolveVercel(input: ResolveClientIpInput): ClientIpResolution {\n const platform = result(\n normalizeClientIp(getHeader(input.headers, 'x-vercel-forwarded-for')),\n 'x-vercel-forwarded-for',\n true\n );\n if (platform) return platform;\n\n const overwrittenXff = result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n true\n );\n if (overwrittenXff) return overwrittenXff;\n\n const realIp = result(\n normalizeClientIp(getHeader(input.headers, 'x-real-ip')),\n 'x-real-ip',\n false\n );\n if (realIp) return realIp;\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? { ip: null, source: 'none', trusted: false }\n );\n}\n\nfunction resolveCloudflare(input: ResolveClientIpInput): ClientIpResolution {\n const cloudflare = result(\n normalizeClientIp(getHeader(input.headers, 'cf-connecting-ip')),\n 'cf-connecting-ip',\n true\n );\n if (cloudflare) return cloudflare;\n\n return (\n resolveAddress(input.directAddress, 'socket') ??\n resolveAddress(input.frameworkAddress, 'framework') ??\n result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n false\n ) ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\nfunction resolveTrustedProxy(input: ResolveClientIpInput, trustedHops: number): ClientIpResolution {\n const raw = getHeader(input.headers, 'x-forwarded-for');\n const tokens = boundedTokens(raw);\n if (tokens && Number.isInteger(trustedHops) && trustedHops > 0 && tokens.length > trustedHops) {\n const parsed = tokens.map(normalizeToken);\n const selectedIndex = tokens.length - trustedHops - 1;\n const selected = parsed[selectedIndex];\n // Parse every token before selecting one. Otherwise an invalid token could\n // silently move the trusted boundary toward an attacker-controlled value.\n if (selected && parsed.every((token) => token !== null)) {\n return { ip: selected, source: 'x-forwarded-for', trusted: true };\n }\n }\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\n/** Resolve a client IP using an explicit deployment trust profile. */\nexport function resolveClientIp(input: ResolveClientIpInput): ClientIpResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'vercel':\n return resolveVercel(input);\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'trusted-proxy':\n return resolveTrustedProxy(input, input.policy.trustedHops);\n case 'direct':\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n }\n}\n","/**\n * Browser-specific exports for Checkpoint\n *\n * Minimal bundle for browser/beacon usage without:\n * - Detection rules (server-side only)\n * - YAML parsing (build-time only)\n * - Zod schemas (replaced with simple validators)\n * - Server-side utilities\n *\n * Bundle target: <5KB minified\n */\n\n// Client-IP normalization is dependency-free and safe for Workers/browser\n// consumers. Keeping it on this entrypoint prevents adapters from importing\n// the server-heavy shared barrel just to resolve request provenance.\nexport * from './utils/client-ip';\n\n// ============================================================================\n// CORE TYPES (TypeScript interfaces only, zero runtime)\n// ============================================================================\n\nexport interface BrowserDetectionResult {\n category: AgentCategory;\n confidence: ConfidenceLevel;\n agent?: AgentInfo;\n}\n\n/**\n * @deprecated Use BrowserDetectionResult.\n */\nexport type { BrowserDetectionResult as DetectionResult };\n\nexport type AgentCategory = 'human' | 'bot' | 'agent';\nexport type ConfidenceLevel = 'low' | 'medium' | 'high' | 'very_high';\n\nexport interface AgentInfo {\n name: string;\n version?: string;\n url?: string;\n company?: string;\n}\n\n// ============================================================================\n// BEACON TYPES\n// ============================================================================\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\nexport interface BeaconEvent {\n type: BeaconEventType;\n data: BeaconCollectorData;\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n sessionId: string;\n timestamp: number;\n eventName?: string;\n [key: string]: unknown;\n}\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\nexport interface BeaconBatch {\n projectId: string;\n events: BeaconEvent[];\n sessionId: string;\n batchId: string;\n timestamp: number;\n /**\n * Carries `BeaconConfig.anonymizeIp` to the server. The server truncates\n * the persisted IP to /24 (IPv4) or /64 (IPv6) before storage when true.\n */\n anonymizeIp?: boolean;\n /** Nonce-bound ingest (build item 5): the value from the prior 202 response's `nonce`. See checkpoint-beacon's `BeaconBatch` for the full doc comment. */\n nonce?: string;\n /** Declares this client echoes nonces — see checkpoint-beacon's `BeaconBatch`. */\n nonceEcho?: boolean;\n}\n\nexport interface BatchEvent {\n id: string;\n event: BeaconEvent;\n timestamp: number;\n retryCount: number;\n hash: string;\n priority: 'low' | 'normal' | 'high' | 'critical';\n}\n\n// ============================================================================\n// CONFIG TYPES\n// ============================================================================\n\n/** Who the host site says the visitor is. Mirrors `beacon-types`' own copy — this bundle imports nothing by design, so the type is restated rather than shared. */\nexport interface BeaconIdentity {\n userId: string;\n}\n\nexport interface BeaconConfig {\n projectId: string; // Same as pixel's data-project-id\n environment?: 'development' | 'staging' | 'production' | string;\n tags?: Record<string, string | number | boolean>;\n identity?: BeaconIdentity;\n /** Where batches are POSTed. Defaults to the endpoint in NETWORK_CONTRACT.md. */\n endpoint?: string;\n enabled?: boolean;\n debug?: boolean;\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n\n // Privacy\n respectDoNotTrack?: boolean;\n anonymizeIp?: boolean;\n\n // Session\n sessionTimeout?: number;\n sessionCookieName?: string;\n\n // Transport\n batchSize?: number;\n flushInterval?: number;\n maxQueueSize?: number;\n retryAttempts?: number;\n retryDelay?: number;\n\n // Worker\n useWorker?: boolean;\n workerUrl?: string;\n workerConfig?: WorkerConfig;\n}\n\nexport interface TransportConfig {\n batchSize?: number;\n flushInterval?: number;\n maxRetries: number;\n retryDelayBase: number;\n offlineQueueSize: number;\n useCompression: boolean;\n compressionThreshold: number;\n networkAdaptation: boolean;\n dedupWindow: number;\n}\n\nexport interface WorkerConfig {\n enabled?: boolean;\n url?: string;\n heartbeatInterval?: number;\n maxUnhealthyCount?: number;\n maxRetries?: number;\n retryDelay?: number;\n restartDelay?: number;\n messageTimeout?: number;\n compressionThreshold?: number;\n allowFallback?: boolean;\n crossOriginIsolated?: boolean;\n maxRestartAttempts?: number;\n terminationTimeout?: number;\n taskTimeout?: number;\n fallbackDelay?: number;\n enableFallback?: boolean;\n}\n\n// ============================================================================\n// TRANSPORT TYPES\n// ============================================================================\n\nexport interface TransportOptions {\n immediate?: boolean;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n retry?: boolean;\n timeout?: number;\n}\n\nexport interface TransportResponse {\n success: boolean;\n timestamp: number;\n batchId?: string;\n error?: string;\n}\n\nexport type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';\n\nexport interface TransportMetrics {\n eventsSent: number;\n eventsFailed: number;\n eventsQueued: number;\n batchesSent: number;\n batchesFailed: number;\n bytesTransferred: number;\n compressionRatio?: number;\n averageLatency?: number;\n lastSuccessTimestamp?: number;\n lastErrorTimestamp?: number;\n}\n\nexport type ConnectionType =\n | 'bluetooth'\n | 'cellular'\n | 'ethernet'\n | 'none'\n | 'wifi'\n | 'wimax'\n | 'other'\n | 'unknown';\n\nexport interface NetworkInfo {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\n// ============================================================================\n// WORKER TYPES\n// ============================================================================\n\nexport type MessagePriority = 'low' | 'normal' | 'high' | 'critical';\n\nexport type WorkerErrorType =\n | 'initialization'\n | 'runtime'\n | 'communication'\n | 'timeout'\n | 'memory'\n | 'unknown';\n\nexport type WorkerAction =\n | 'process'\n | 'init'\n | 'terminate'\n | 'pause'\n | 'resume'\n | 'status'\n | 'health';\n\nexport type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n\nexport interface WorkerMessage {\n id: string;\n type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n action?: string;\n payload?: unknown;\n timestamp: number;\n compressed?: boolean;\n priority?: MessagePriority;\n correlationId?: string;\n}\n\nexport type WorkerState =\n | 'idle'\n | 'initializing'\n | 'ready'\n | 'processing'\n | 'error'\n | 'terminating'\n | 'terminated';\n\nexport type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\nexport interface WorkerMetrics {\n tasksProcessed: number;\n tasksFailed: number;\n averageProcessingTime: number;\n memoryUsage?: number;\n cpuUsage?: number;\n healthStatus: WorkerHealthStatus;\n lastHealthCheck: number;\n restartCount: number;\n errorRate: number;\n}\n\nexport interface WorkerError {\n type: string;\n message: string;\n stack?: string;\n timestamp: number;\n recoverable: boolean;\n}\n\nexport interface WorkerCapabilities {\n workerAPI: boolean;\n sharedArrayBuffer: boolean;\n transferableObjects: boolean;\n offscreenCanvas: boolean;\n webAssembly: boolean;\n atomics: boolean;\n bigInt: boolean;\n csp: {\n workerSrc: boolean;\n scriptSrc: boolean;\n blobUrls: boolean;\n inlineWorkers: boolean;\n };\n performance: {\n memory: boolean;\n measureUserAgentSpecificMemory: boolean;\n };\n}\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: unknown;\n priority: 'low' | 'normal' | 'high' | 'critical';\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n error?: WorkerError;\n maxRetries?: number;\n retries?: number;\n timeout?: number;\n}\n\nexport interface FallbackOptions {\n useRequestIdleCallback: boolean;\n idleTimeout: number;\n chunkSize: number;\n throttleMs: number;\n maxExecutionTime: number;\n}\n\nexport interface ResourceUsage {\n memoryUsage: number;\n cpuUsage: number;\n taskCount: number;\n activeWorkers: number;\n pendingTasks: number;\n completedTasks: number;\n failedTasks: number;\n averageTaskDuration: number;\n memory?: number;\n cpu?: number;\n tasks?: number;\n}\n\nexport interface WorkerPoolConfig {\n maxWorkers: number;\n minWorkers: number;\n workerIdleTimeout: number;\n taskQueueSize: number;\n resourceLimits: Record<string, unknown>;\n autoScale?: boolean;\n scaleUpThreshold?: number;\n scaleDownThreshold?: number;\n}\n\nexport type BeaconWorkerMessageType = 'init' | 'collect' | 'flush' | 'config' | 'status' | 'error';\n\nexport type ProtocolVersion = '1.0' | '1.1' | '2.0';\n\nexport interface BeaconWorkerMessage {\n type: BeaconWorkerMessageType;\n data?: unknown;\n payload?: unknown;\n messageId: string;\n timestamp: number;\n id?: string;\n}\n\n// ============================================================================\n// CIRCUIT BREAKER & RETRY\n// ============================================================================\n\nexport interface CircuitBreakerConfig {\n threshold: number;\n timeout: number;\n resetTimeout: number;\n}\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half-open';\n\nexport interface RetryStrategy {\n maxAttempts: number;\n baseDelay: number;\n maxDelay: number;\n factor: number;\n jitter: boolean;\n}\n\n// ============================================================================\n// OFFLINE QUEUE\n// ============================================================================\n\nexport interface OfflineQueueEntry {\n id: string;\n events: BeaconEvent[];\n timestamp: number;\n expiresAt: number;\n retryCount: number;\n size: number;\n}\n\n// ============================================================================\n// SIMPLE VALIDATORS (Lightweight replacements for Zod)\n// ============================================================================\n\n/**\n * Validates a beacon event\n */\nexport function validateBeaconEvent(event: unknown): event is BeaconEvent {\n if (!event || typeof event !== 'object') return false;\n const e = event as Record<string, unknown>;\n const metadata = e.metadata as Record<string, unknown> | undefined;\n return !!(\n e.type &&\n typeof e.type === 'string' &&\n e.data &&\n typeof e.data === 'object' &&\n metadata &&\n typeof metadata === 'object' &&\n metadata.sessionId &&\n metadata.timestamp\n );\n}\n\n/**\n * Validates beacon configuration\n */\nexport function validateBeaconConfig(config: unknown): config is BeaconConfig {\n if (!config || typeof config !== 'object') return false;\n const c = config as Record<string, unknown>;\n return !!(c.projectId && typeof c.projectId === 'string');\n}\n\n/**\n * Validates a beacon batch\n */\nexport function validateBeaconBatch(batch: unknown): batch is BeaconBatch {\n if (!batch || typeof batch !== 'object') return false;\n const b = batch as Record<string, unknown>;\n return !!(\n b.projectId &&\n typeof b.projectId === 'string' &&\n Array.isArray(b.events) &&\n b.events.every((e: unknown) => validateBeaconEvent(e)) &&\n b.sessionId &&\n typeof b.sessionId === 'string' &&\n b.batchId &&\n b.timestamp &&\n typeof b.timestamp === 'number'\n );\n}\n\n/** Rejects an identity naming nobody: downstream this becomes `detections.user_id`, where an empty string reads as \"identified\" while identifying no one. */\nfunction isBrowserBeaconIdentity(value: unknown): value is BeaconIdentity {\n return (\n typeof value === 'object' &&\n value !== null &&\n // Arrays are objects and would otherwise pass. `beacon-types`' own guard\n // rejects them via `isRecord`; these two are meant to agree, and a silent\n // divergence between two allowlists is exactly what this file's comments\n // promise is not happening.\n !Array.isArray(value) &&\n typeof (value as BeaconIdentity).userId === 'string' &&\n (value as BeaconIdentity).userId.length > 0\n );\n}\n\n/**\n * Parse beacon config with defaults\n */\nexport function parseBeaconConfig(input: unknown): BeaconConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n\n if (!config.projectId || typeof config.projectId !== 'string') {\n throw new Error('Project ID is required');\n }\n\n return {\n projectId: config.projectId as string,\n environment: config.environment as string | undefined,\n tags: config.tags as Record<string, string | number | boolean> | undefined,\n // Kept in step with the `beacon-types` copy of this allowlist by hand.\n // Both parsers drop any key they do not name, silently — which is how\n // `identity` first shipped inert. The check is restated rather than\n // imported because this bundle deliberately has no imports at all.\n identity: isBrowserBeaconIdentity(config.identity) ? config.identity : undefined,\n endpoint: config.endpoint as string | undefined,\n enabled: config.enabled !== false,\n debug: config.debug === true,\n logLevel: (config.logLevel as 'error' | 'warn' | 'info' | 'debug' | undefined) || 'error',\n respectDoNotTrack: config.respectDoNotTrack !== false,\n anonymizeIp: config.anonymizeIp === true,\n sessionTimeout: (config.sessionTimeout as number | undefined) || 1800000, // 30 minutes\n sessionCookieName: (config.sessionCookieName as string | undefined) || '_as_beacon_session',\n batchSize: (config.batchSize as number | undefined) || 10,\n flushInterval: (config.flushInterval as number | undefined) || 5000,\n maxQueueSize: (config.maxQueueSize as number | undefined) || 100,\n retryAttempts: (config.retryAttempts as number | undefined) || 3,\n retryDelay: (config.retryDelay as number | undefined) || 2000,\n useWorker: config.useWorker !== false,\n workerUrl: config.workerUrl as string | undefined,\n workerConfig: config.workerConfig as WorkerConfig | undefined,\n };\n}\n\n/**\n * Simple type guards\n */\nexport const Guards = {\n isBeaconEvent: validateBeaconEvent,\n isBeaconConfig: validateBeaconConfig,\n isBeaconBatch: validateBeaconBatch,\n\n isWorkerMessage(msg: unknown): msg is WorkerMessage {\n if (!msg || typeof msg !== 'object') return false;\n const m = msg as Record<string, unknown>;\n return !!(\n m.id &&\n m.type &&\n ['request', 'response', 'error', 'heartbeat', 'status'].includes(m.type as string) &&\n typeof m.timestamp === 'number'\n );\n },\n\n isWorkerError(err: unknown): err is WorkerError {\n if (!err || typeof err !== 'object') return false;\n const e = err as Record<string, unknown>;\n return !!(\n e.type &&\n e.message &&\n typeof e.timestamp === 'number' &&\n typeof e.recoverable === 'boolean'\n );\n },\n\n isWorkerCapabilities(cap: unknown): cap is WorkerCapabilities {\n if (!cap || typeof cap !== 'object') return false;\n const c = cap as Record<string, unknown>;\n return !!(\n typeof c.workerAPI === 'boolean' &&\n typeof c.sharedArrayBuffer === 'boolean' &&\n typeof c.transferableObjects === 'boolean' &&\n typeof c.offscreenCanvas === 'boolean'\n );\n },\n};\n\n// ============================================================================\n// PARSE FUNCTIONS (with defaults and validation)\n// ============================================================================\n\nexport function parseWorkerConfig(input: unknown): WorkerConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n enabled: config.enabled !== false,\n url: config.url as string | undefined,\n heartbeatInterval: (config.heartbeatInterval as number | undefined) || 5000,\n maxUnhealthyCount: (config.maxUnhealthyCount as number | undefined) || 3,\n maxRetries: (config.maxRetries as number | undefined) || 3,\n retryDelay: (config.retryDelay as number | undefined) || 1000,\n messageTimeout: (config.messageTimeout as number | undefined) || 30000,\n compressionThreshold: (config.compressionThreshold as number | undefined) || 1024,\n allowFallback: config.allowFallback !== false,\n crossOriginIsolated: config.crossOriginIsolated === true,\n };\n}\n\nexport function parseWorkerMessage(input: unknown): WorkerMessage {\n const msg = input as Record<string, unknown>;\n if (!msg || typeof msg !== 'object') {\n throw new Error('Invalid worker message');\n }\n return {\n id: (msg.id as string | undefined) || crypto.randomUUID(),\n type:\n (msg.type as 'request' | 'response' | 'error' | 'heartbeat' | 'status' | undefined) ||\n 'request',\n action: msg.action as string | undefined,\n payload: msg.payload,\n timestamp: (msg.timestamp as number | undefined) || Date.now(),\n compressed: msg.compressed === true,\n priority: (msg.priority as 'low' | 'normal' | 'high' | 'critical' | undefined) || 'normal',\n correlationId: msg.correlationId as string | undefined,\n };\n}\n\nexport function parseWorkerError(input: unknown): WorkerError {\n const err = input as Record<string, unknown>;\n if (!err || typeof err !== 'object') {\n return {\n type: 'unknown',\n message: String(input),\n timestamp: Date.now(),\n recoverable: false,\n };\n }\n return {\n type: (err.type as string | undefined) || 'unknown',\n message: (err.message as string | undefined) || 'Unknown error',\n stack: err.stack as string | undefined,\n timestamp: (err.timestamp as number | undefined) || Date.now(),\n recoverable: Boolean(err.recoverable),\n };\n}\n\nexport function parseWorkerCapabilities(input: unknown): WorkerCapabilities {\n const cap = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n workerAPI: cap.workerAPI !== false,\n sharedArrayBuffer: cap.sharedArrayBuffer === true,\n transferableObjects: cap.transferableObjects === true,\n offscreenCanvas: cap.offscreenCanvas === true,\n webAssembly: cap.webAssembly === true,\n atomics: cap.atomics === true,\n bigInt: cap.bigInt === true,\n csp: (cap.csp as\n | { workerSrc: boolean; scriptSrc: boolean; blobUrls: boolean; inlineWorkers: boolean }\n | undefined) || {\n workerSrc: false,\n scriptSrc: false,\n blobUrls: false,\n inlineWorkers: false,\n },\n performance: (cap.performance as\n | { memory: boolean; measureUserAgentSpecificMemory: boolean }\n | undefined) || {\n memory: false,\n measureUserAgentSpecificMemory: false,\n },\n };\n}\n\nexport function parseWorkerTask(input: unknown): WorkerTask {\n const task = input as Record<string, unknown>;\n if (!task || typeof task !== 'object') {\n throw new Error('Invalid worker task');\n }\n return {\n id: (task.id as string | undefined) || crypto.randomUUID(),\n type: (task.type as string | undefined) || 'process',\n data: task.data,\n priority: (task.priority as 'low' | 'normal' | 'high' | 'critical' | undefined) || 'normal',\n createdAt: (task.createdAt as number | undefined) || Date.now(),\n startedAt: task.startedAt as number | undefined,\n completedAt: task.completedAt as number | undefined,\n error: task.error as WorkerError | undefined,\n maxRetries: task.maxRetries as number | undefined,\n retries: task.retries as number | undefined,\n timeout: task.timeout as number | undefined,\n };\n}\n\nexport function parseFallbackOptions(input: unknown): FallbackOptions {\n const opts = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n useRequestIdleCallback: opts.useRequestIdleCallback !== false,\n idleTimeout: (opts.idleTimeout as number | undefined) || 10000,\n chunkSize: (opts.chunkSize as number | undefined) || 10,\n throttleMs: (opts.throttleMs as number | undefined) || 16,\n maxExecutionTime: (opts.maxExecutionTime as number | undefined) || 50,\n };\n}\n\nexport function parseRetryStrategy(input: unknown): RetryStrategy {\n const strategy = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n maxAttempts: (strategy.maxAttempts as number | undefined) || 3,\n baseDelay: (strategy.baseDelay as number | undefined) || 1000,\n maxDelay: (strategy.maxDelay as number | undefined) || 30000,\n factor: (strategy.factor as number | undefined) || 2,\n jitter: strategy.jitter !== false,\n };\n}\n\nexport function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n threshold: (config.threshold as number | undefined) || 5,\n timeout: (config.timeout as number | undefined) || 60000,\n resetTimeout: (config.resetTimeout as number | undefined) || 30000,\n };\n}\n\nexport function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry {\n const entry = input as Record<string, unknown>;\n if (!entry || typeof entry !== 'object') {\n throw new Error('Invalid offline queue entry');\n }\n return {\n id:\n (entry.id as string | undefined) ||\n `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,\n events: Array.isArray(entry.events) ? entry.events : [],\n timestamp: (entry.timestamp as number | undefined) || Date.now(),\n expiresAt: (entry.expiresAt as number | undefined) || Date.now() + 86400000, // 24 hours\n retryCount: (entry.retryCount as number | undefined) || 0,\n size: (entry.size as number | undefined) || 0,\n };\n}\n\nexport function parseResourceUsage(input: unknown): ResourceUsage {\n const usage = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n memoryUsage: (usage.memoryUsage as number | undefined) || 0,\n cpuUsage: (usage.cpuUsage as number | undefined) || 0,\n taskCount: (usage.taskCount as number | undefined) || 0,\n activeWorkers: (usage.activeWorkers as number | undefined) || 0,\n pendingTasks: (usage.pendingTasks as number | undefined) || 0,\n completedTasks: (usage.completedTasks as number | undefined) || 0,\n failedTasks: (usage.failedTasks as number | undefined) || 0,\n averageTaskDuration: (usage.averageTaskDuration as number | undefined) || 0,\n };\n}\n\nexport function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n maxWorkers: (config.maxWorkers as number | undefined) || 4,\n minWorkers: (config.minWorkers as number | undefined) || 1,\n workerIdleTimeout: (config.workerIdleTimeout as number | undefined) || 60000,\n taskQueueSize: (config.taskQueueSize as number | undefined) || 100,\n resourceLimits: (config.resourceLimits as Record<string, unknown> | undefined) || {},\n };\n}\n\nexport function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage {\n const msg = input as Record<string, unknown>;\n if (!msg || typeof msg !== 'object') {\n throw new Error('Invalid beacon worker message');\n }\n return {\n type: (msg.type as BeaconWorkerMessageType | undefined) || 'collect',\n data: msg.data,\n messageId: (msg.messageId as string | undefined) || crypto.randomUUID(),\n timestamp: (msg.timestamp as number | undefined) || Date.now(),\n };\n}\n\n// ============================================================================\n// MINIMAL CONSTANTS\n// ============================================================================\n\nexport const DEFAULT_CONFIG = {\n batchSize: 10,\n flushInterval: 5000,\n sessionTimeout: 1800000,\n sessionCookieName: '_as_beacon_session',\n retryAttempts: 3,\n retryDelay: 2000,\n} as const;\n\nexport const ERROR_TYPES = {\n NETWORK: 'network',\n VALIDATION: 'validation',\n TIMEOUT: 'timeout',\n UNKNOWN: 'unknown',\n} as const;\n\n// For future CDN rule loading\nexport const RULE_CACHE = {\n DEFAULT_DURATION: 3600000, // 1 hour\n MAX_DURATION: 86400000, // 24 hours\n MIN_DURATION: 60000, // 1 minute\n STORAGE_KEY: 'agentshield_rules',\n TIMESTAMP_KEY: 'agentshield_rules_timestamp',\n} as const;\n"],"mappings":"AA+CA,SAAS,EAAoB,EAAwB,CACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAAK,CACrC,IAAM,EAAO,EAAM,WAAW,CAAC,EAC/B,GAAI,GAAQ,IAAQ,IAAS,IAAM,MAAO,EAC5C,CACA,MAAO,EACT,CAEA,SAAS,EAAU,EAAwB,CACzC,MAAO,uBAAuB,KAAK,CAAK,GAAK,OAAO,CAAK,GAAK,KAChE,CAEA,SAAS,EAAU,EAAgC,CACjD,IAAM,EAAQ,EAAM,MAAM,GAAG,EAC7B,GAAI,EAAM,SAAW,EAAG,OAAO,KAE/B,IAAM,EAAmB,CAAC,EAC1B,IAAK,IAAM,KAAQ,EAAO,CACxB,GAAI,CAAC,YAAY,KAAK,CAAI,EAAG,OAAO,KACpC,IAAM,EAAQ,OAAO,CAAI,EACzB,GAAI,EAAQ,IAAK,OAAO,KACxB,EAAO,KAAK,CAAK,CACnB,CACA,OAAO,CACT,CAEA,SAAS,EAAc,EAA8B,CAEnD,MADK,qBAAqB,KAAK,CAAK,EAC7B,OAAO,SAAS,EAAO,EAAE,EADc,IAEhD,CAGA,SAAgB,EAAU,EAAgC,CACxD,GAAI,CAAC,GAAS,EAAM,SAAS,GAAG,GAAK,EAAoB,CAAK,EAAG,OAAO,KAExE,IAAI,EAAU,EACd,GAAI,EAAQ,SAAS,GAAG,EAAG,CACzB,IAAM,EAAY,EAAQ,YAAY,GAAG,EACzC,GAAI,EAAY,EAAG,OAAO,KAC1B,IAAM,EAAO,EAAU,EAAQ,MAAM,EAAY,CAAC,CAAC,EACnD,GAAI,CAAC,EAAM,OAAO,KAClB,IAAM,EAAS,EAAK,IAAO,EAA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GAAI,CAAC,GAAO,OAAO,GAAQ,SACzB,MAAU,MAAM,+BAA+B,EAEjD,MAAO,CACL,KAAO,EAAI,MAAgD,UAC3D,KAAM,EAAI,KACV,UAAY,EAAI,WAAoC,OAAO,WAAW,EACtE,UAAY,EAAI,WAAoC,KAAK,IAAI,CAC/D,CACF,CAMA,MAAa,EAAiB,CAC5B,UAAW,GACX,cAAe,IACf,eAAgB,KAChB,kBAAmB,qBACnB,cAAe,EACf,WAAY,GACd,EAEa,EAAc,CACzB,QAAS,UACT,WAAY,aACZ,QAAS,UACT,QAAS,SACX,EAGa,EAAa,CACxB,iBAAkB,KAClB,aAAc,MACd,aAAc,IACd,YAAa,oBACb,cAAe,6BACjB"}
|
|
1
|
+
{"version":3,"file":"browser.mjs","names":[],"sources":["../src/utils/client-ip.ts","../src/browser.ts"],"sourcesContent":["/**\n * Runtime-agnostic client-IP normalization and trust resolution.\n *\n * Header presence is not proof of provenance. Callers must select the\n * deployment profile that describes which infrastructure has already\n * authenticated a value before using the result for security decisions.\n */\n\nexport type ClientIpSource =\n | 'explicit'\n | 'cf-connecting-ip'\n | 'x-vercel-forwarded-for'\n | 'x-forwarded-for'\n | 'x-real-ip'\n | 'framework'\n | 'socket'\n | 'none';\n\nexport interface ClientIpResolution {\n ip: string | null;\n source: ClientIpSource;\n trusted: boolean;\n}\n\nexport type ClientIpTrustPolicy =\n | { platform: 'vercel' }\n | { platform: 'cloudflare' }\n | { platform: 'trusted-proxy'; trustedHops: number }\n | { platform: 'direct' };\n\nexport type ClientIpHeaderValue = string | readonly string[] | undefined;\nexport type ClientIpHeaders = Headers | Record<string, ClientIpHeaderValue>;\n\nexport interface ResolveClientIpInput {\n headers: ClientIpHeaders;\n directAddress?: string | null;\n frameworkAddress?: string | null;\n explicitAddress?: string | null;\n /** True only after the caller has authenticated the explicit value. */\n explicitAddressTrusted?: boolean;\n policy: ClientIpTrustPolicy;\n}\n\nconst MAX_INPUT_LENGTH = 4096;\nconst MAX_TOKEN_LENGTH = 128;\nconst MAX_FORWARDED_HOPS = 32;\n\nfunction hasControlCharacter(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f) return true;\n }\n return false;\n}\n\nfunction parsePort(value: string): boolean {\n return /^(?:0|[1-9]\\d{0,4})$/.test(value) && Number(value) <= 65535;\n}\n\nfunction parseIpv4(value: string): number[] | null {\n const parts = value.split('.');\n if (parts.length !== 4) return null;\n\n const octets: number[] = [];\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part)) return null;\n const octet = Number(part);\n if (octet > 255) return null;\n octets.push(octet);\n }\n return octets;\n}\n\nfunction parseHexGroup(value: string): number | null {\n if (!/^[0-9a-fA-F]{1,4}$/.test(value)) return null;\n return Number.parseInt(value, 16);\n}\n\n/** Parses a bare IPv6 address into its 8 groups (`::` expanded). Exported for reuse by anything that needs to mask/truncate an address (see `anonymize-ip.ts`), not just resolve one. */\nexport function parseIpv6(value: string): number[] | null {\n if (!value || value.includes('%') || hasControlCharacter(value)) return null;\n\n let address = value;\n if (address.includes('.')) {\n const lastColon = address.lastIndexOf(':');\n if (lastColon < 0) return null;\n const ipv4 = parseIpv4(address.slice(lastColon + 1));\n if (!ipv4) return null;\n const first = (ipv4[0]! << 8) | ipv4[1]!;\n const second = (ipv4[2]! << 8) | ipv4[3]!;\n address = `${address.slice(0, lastColon + 1)}${first.toString(16)}:${second.toString(16)}`;\n }\n\n const doubleColon = address.indexOf('::');\n if (doubleColon !== address.lastIndexOf('::')) return null;\n\n const parseGroups = (part: string): number[] | null => {\n if (!part) return [];\n const groups = part.split(':');\n const parsed: number[] = [];\n for (const group of groups) {\n const number = parseHexGroup(group);\n if (number === null) return null;\n parsed.push(number);\n }\n return parsed;\n };\n\n if (doubleColon >= 0) {\n const head = parseGroups(address.slice(0, doubleColon));\n const tail = parseGroups(address.slice(doubleColon + 2));\n if (!head || !tail) return null;\n const missing = 8 - head.length - tail.length;\n if (missing < 1) return null;\n return [...head, ...Array<number>(missing).fill(0), ...tail];\n }\n\n const groups = parseGroups(address);\n return groups?.length === 8 ? groups : null;\n}\n\n/** RFC 5952 canonical `::` compression for 8 IPv6 groups. Exported alongside `parseIpv6`. */\nexport function compressIpv6(groups: number[]): string {\n const rendered = groups.map((group) => group.toString(16));\n let bestStart = -1;\n let bestLength = 1;\n let runStart = -1;\n\n for (let index = 0; index <= groups.length; index += 1) {\n if (index < groups.length && groups[index] === 0) {\n if (runStart < 0) runStart = index;\n continue;\n }\n if (runStart >= 0) {\n const runLength = index - runStart;\n if (runLength > bestLength) {\n bestStart = runStart;\n bestLength = runLength;\n }\n runStart = -1;\n }\n }\n\n if (bestStart < 0) return rendered.join(':');\n const before = rendered.slice(0, bestStart).join(':');\n const after = rendered.slice(bestStart + bestLength).join(':');\n if (!before && !after) return '::';\n if (!before) return `::${after}`;\n if (!after) return `${before}::`;\n return `${before}::${after}`;\n}\n\nfunction normalizeToken(rawToken: string): string | null {\n const token = rawToken.trim();\n if (!token || token.length > MAX_TOKEN_LENGTH || hasControlCharacter(token)) return null;\n\n let address = token;\n if (token.startsWith('[')) {\n const closing = token.indexOf(']');\n if (closing <= 1) return null;\n const suffix = token.slice(closing + 1);\n if (suffix && (!suffix.startsWith(':') || !parsePort(suffix.slice(1)))) return null;\n address = token.slice(1, closing);\n } else if ((token.match(/:/g) ?? []).length === 1 && token.includes('.')) {\n const colon = token.indexOf(':');\n if (!parsePort(token.slice(colon + 1))) return null;\n address = token.slice(0, colon);\n }\n\n const ipv4 = parseIpv4(address);\n if (ipv4) return ipv4.join('.');\n\n const ipv6 = parseIpv6(address);\n return ipv6 ? compressIpv6(ipv6) : null;\n}\n\nfunction boundedTokens(raw: string | null | undefined): string[] | null {\n if (raw == null || !raw || raw.length > MAX_INPUT_LENGTH || hasControlCharacter(raw)) return null;\n const tokens = raw.split(',');\n if (tokens.length > MAX_FORWARDED_HOPS) return null;\n return tokens;\n}\n\n/** Normalize the first valid address in a bounded header value. */\nexport function normalizeClientIp(raw: string | null | undefined): string | null {\n const tokens = boundedTokens(raw);\n if (!tokens) return null;\n for (const token of tokens) {\n const normalized = normalizeToken(token);\n if (normalized) return normalized;\n }\n return null;\n}\n\nfunction getHeader(headers: ClientIpHeaders, name: string): string | undefined {\n if ('get' in headers && typeof headers.get === 'function') {\n return headers.get(name) ?? undefined;\n }\n\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== wanted || value === undefined) continue;\n return Array.isArray(value) ? value.join(',') : value;\n }\n return undefined;\n}\n\nfunction result(\n ip: string | null,\n source: Exclude<ClientIpSource, 'none'>,\n trusted: boolean\n): ClientIpResolution | null {\n return ip ? { ip, source, trusted } : null;\n}\n\nfunction resolveAddress(\n raw: string | null | undefined,\n source: 'framework' | 'socket'\n): ClientIpResolution | null {\n return result(normalizeClientIp(raw), source, true);\n}\n\nfunction resolveExplicit(input: ResolveClientIpInput): ClientIpResolution | null {\n if (input.explicitAddressTrusted !== true) return null;\n return result(normalizeClientIp(input.explicitAddress), 'explicit', true);\n}\n\nfunction resolveVercel(input: ResolveClientIpInput): ClientIpResolution {\n const platform = result(\n normalizeClientIp(getHeader(input.headers, 'x-vercel-forwarded-for')),\n 'x-vercel-forwarded-for',\n true\n );\n if (platform) return platform;\n\n const overwrittenXff = result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n true\n );\n if (overwrittenXff) return overwrittenXff;\n\n const realIp = result(\n normalizeClientIp(getHeader(input.headers, 'x-real-ip')),\n 'x-real-ip',\n false\n );\n if (realIp) return realIp;\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? { ip: null, source: 'none', trusted: false }\n );\n}\n\nfunction resolveCloudflare(input: ResolveClientIpInput): ClientIpResolution {\n const cloudflare = result(\n normalizeClientIp(getHeader(input.headers, 'cf-connecting-ip')),\n 'cf-connecting-ip',\n true\n );\n if (cloudflare) return cloudflare;\n\n return (\n resolveAddress(input.directAddress, 'socket') ??\n resolveAddress(input.frameworkAddress, 'framework') ??\n result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n false\n ) ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\nfunction resolveTrustedProxy(input: ResolveClientIpInput, trustedHops: number): ClientIpResolution {\n const raw = getHeader(input.headers, 'x-forwarded-for');\n const tokens = boundedTokens(raw);\n if (tokens && Number.isInteger(trustedHops) && trustedHops >= 0 && tokens.length > trustedHops) {\n const parsed = tokens.map(normalizeToken);\n const selectedIndex = tokens.length - trustedHops - 1;\n const selected = parsed[selectedIndex];\n // Parse every token before selecting one. Otherwise an invalid token could\n // silently move the trusted boundary toward an attacker-controlled value.\n if (selected && parsed.every((token) => token !== null)) {\n return { ip: selected, source: 'x-forwarded-for', trusted: true };\n }\n }\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\n/** Resolve a client IP using an explicit deployment trust profile. */\nexport function resolveClientIp(input: ResolveClientIpInput): ClientIpResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'vercel':\n return resolveVercel(input);\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'trusted-proxy':\n return resolveTrustedProxy(input, input.policy.trustedHops);\n case 'direct':\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n }\n}\n","/**\n * Browser-specific exports for Checkpoint\n *\n * Minimal bundle for browser/beacon usage without:\n * - Detection rules (server-side only)\n * - YAML parsing (build-time only)\n * - Zod schemas (replaced with simple validators)\n * - Server-side utilities\n *\n * Bundle target: <5KB minified\n */\n\n// Client-IP normalization is dependency-free and safe for Workers/browser\n// consumers. Keeping it on this entrypoint prevents adapters from importing\n// the server-heavy shared barrel just to resolve request provenance.\nexport * from './utils/client-ip';\n\n// ============================================================================\n// CORE TYPES (TypeScript interfaces only, zero runtime)\n// ============================================================================\n\nexport interface BrowserDetectionResult {\n category: AgentCategory;\n confidence: ConfidenceLevel;\n agent?: AgentInfo;\n}\n\n/**\n * @deprecated Use BrowserDetectionResult.\n */\nexport type { BrowserDetectionResult as DetectionResult };\n\nexport type AgentCategory = 'human' | 'bot' | 'agent';\nexport type ConfidenceLevel = 'low' | 'medium' | 'high' | 'very_high';\n\nexport interface AgentInfo {\n name: string;\n version?: string;\n url?: string;\n company?: string;\n}\n\n// ============================================================================\n// BEACON TYPES\n// ============================================================================\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\nexport interface BeaconEvent {\n type: BeaconEventType;\n data: BeaconCollectorData;\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n sessionId: string;\n timestamp: number;\n eventName?: string;\n [key: string]: unknown;\n}\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\nexport interface BeaconBatch {\n projectId: string;\n events: BeaconEvent[];\n sessionId: string;\n batchId: string;\n timestamp: number;\n /**\n * Carries `BeaconConfig.anonymizeIp` to the server. The server truncates\n * the persisted IP to /24 (IPv4) or /64 (IPv6) before storage when true.\n */\n anonymizeIp?: boolean;\n /** Nonce-bound ingest (build item 5): the value from the prior 202 response's `nonce`. See checkpoint-beacon's `BeaconBatch` for the full doc comment. */\n nonce?: string;\n /** Declares this client echoes nonces — see checkpoint-beacon's `BeaconBatch`. */\n nonceEcho?: boolean;\n}\n\nexport interface BatchEvent {\n id: string;\n event: BeaconEvent;\n timestamp: number;\n retryCount: number;\n hash: string;\n priority: 'low' | 'normal' | 'high' | 'critical';\n}\n\n// ============================================================================\n// CONFIG TYPES\n// ============================================================================\n\n/** Who the host site says the visitor is. Mirrors `beacon-types`' own copy — this bundle imports nothing by design, so the type is restated rather than shared. */\nexport interface BeaconIdentity {\n userId: string;\n}\n\nexport interface BeaconConfig {\n projectId: string; // Same as pixel's data-project-id\n environment?: 'development' | 'staging' | 'production' | string;\n tags?: Record<string, string | number | boolean>;\n identity?: BeaconIdentity;\n /** Where batches are POSTed. Defaults to the endpoint in NETWORK_CONTRACT.md. */\n endpoint?: string;\n enabled?: boolean;\n debug?: boolean;\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n\n // Privacy\n respectDoNotTrack?: boolean;\n anonymizeIp?: boolean;\n\n // Session\n sessionTimeout?: number;\n sessionCookieName?: string;\n\n // Transport\n batchSize?: number;\n flushInterval?: number;\n maxQueueSize?: number;\n retryAttempts?: number;\n retryDelay?: number;\n\n // Worker\n useWorker?: boolean;\n workerUrl?: string;\n workerConfig?: WorkerConfig;\n}\n\nexport interface TransportConfig {\n batchSize?: number;\n flushInterval?: number;\n maxRetries: number;\n retryDelayBase: number;\n offlineQueueSize: number;\n useCompression: boolean;\n compressionThreshold: number;\n networkAdaptation: boolean;\n dedupWindow: number;\n}\n\nexport interface WorkerConfig {\n enabled?: boolean;\n url?: string;\n heartbeatInterval?: number;\n maxUnhealthyCount?: number;\n maxRetries?: number;\n retryDelay?: number;\n restartDelay?: number;\n messageTimeout?: number;\n compressionThreshold?: number;\n allowFallback?: boolean;\n crossOriginIsolated?: boolean;\n maxRestartAttempts?: number;\n terminationTimeout?: number;\n taskTimeout?: number;\n fallbackDelay?: number;\n enableFallback?: boolean;\n}\n\n// ============================================================================\n// TRANSPORT TYPES\n// ============================================================================\n\nexport interface TransportOptions {\n immediate?: boolean;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n retry?: boolean;\n timeout?: number;\n}\n\nexport interface TransportResponse {\n success: boolean;\n timestamp: number;\n batchId?: string;\n error?: string;\n}\n\nexport type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';\n\nexport interface TransportMetrics {\n eventsSent: number;\n eventsFailed: number;\n eventsQueued: number;\n batchesSent: number;\n batchesFailed: number;\n bytesTransferred: number;\n compressionRatio?: number;\n averageLatency?: number;\n lastSuccessTimestamp?: number;\n lastErrorTimestamp?: number;\n}\n\nexport type ConnectionType =\n | 'bluetooth'\n | 'cellular'\n | 'ethernet'\n | 'none'\n | 'wifi'\n | 'wimax'\n | 'other'\n | 'unknown';\n\nexport interface NetworkInfo {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\n// ============================================================================\n// WORKER TYPES\n// ============================================================================\n\nexport type MessagePriority = 'low' | 'normal' | 'high' | 'critical';\n\nexport type WorkerErrorType =\n | 'initialization'\n | 'runtime'\n | 'communication'\n | 'timeout'\n | 'memory'\n | 'unknown';\n\nexport type WorkerAction =\n | 'process'\n | 'init'\n | 'terminate'\n | 'pause'\n | 'resume'\n | 'status'\n | 'health';\n\nexport type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n\nexport interface WorkerMessage {\n id: string;\n type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n action?: string;\n payload?: unknown;\n timestamp: number;\n compressed?: boolean;\n priority?: MessagePriority;\n correlationId?: string;\n}\n\nexport type WorkerState =\n | 'idle'\n | 'initializing'\n | 'ready'\n | 'processing'\n | 'error'\n | 'terminating'\n | 'terminated';\n\nexport type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\nexport interface WorkerMetrics {\n tasksProcessed: number;\n tasksFailed: number;\n averageProcessingTime: number;\n memoryUsage?: number;\n cpuUsage?: number;\n healthStatus: WorkerHealthStatus;\n lastHealthCheck: number;\n restartCount: number;\n errorRate: number;\n}\n\nexport interface WorkerError {\n type: string;\n message: string;\n stack?: string;\n timestamp: number;\n recoverable: boolean;\n}\n\nexport interface WorkerCapabilities {\n workerAPI: boolean;\n sharedArrayBuffer: boolean;\n transferableObjects: boolean;\n offscreenCanvas: boolean;\n webAssembly: boolean;\n atomics: boolean;\n bigInt: boolean;\n csp: {\n workerSrc: boolean;\n scriptSrc: boolean;\n blobUrls: boolean;\n inlineWorkers: boolean;\n };\n performance: {\n memory: boolean;\n measureUserAgentSpecificMemory: boolean;\n };\n}\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: unknown;\n priority: 'low' | 'normal' | 'high' | 'critical';\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n error?: WorkerError;\n maxRetries?: number;\n retries?: number;\n timeout?: number;\n}\n\nexport interface FallbackOptions {\n useRequestIdleCallback: boolean;\n idleTimeout: number;\n chunkSize: number;\n throttleMs: number;\n maxExecutionTime: number;\n}\n\nexport interface ResourceUsage {\n memoryUsage: number;\n cpuUsage: number;\n taskCount: number;\n activeWorkers: number;\n pendingTasks: number;\n completedTasks: number;\n failedTasks: number;\n averageTaskDuration: number;\n memory?: number;\n cpu?: number;\n tasks?: number;\n}\n\nexport interface WorkerPoolConfig {\n maxWorkers: number;\n minWorkers: number;\n workerIdleTimeout: number;\n taskQueueSize: number;\n resourceLimits: Record<string, unknown>;\n autoScale?: boolean;\n scaleUpThreshold?: number;\n scaleDownThreshold?: number;\n}\n\nexport type BeaconWorkerMessageType = 'init' | 'collect' | 'flush' | 'config' | 'status' | 'error';\n\nexport type ProtocolVersion = '1.0' | '1.1' | '2.0';\n\nexport interface BeaconWorkerMessage {\n type: BeaconWorkerMessageType;\n data?: unknown;\n payload?: unknown;\n messageId: string;\n timestamp: number;\n id?: string;\n}\n\n// ============================================================================\n// CIRCUIT BREAKER & RETRY\n// ============================================================================\n\nexport interface CircuitBreakerConfig {\n threshold: number;\n timeout: number;\n resetTimeout: number;\n}\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half-open';\n\nexport interface RetryStrategy {\n maxAttempts: number;\n baseDelay: number;\n maxDelay: number;\n factor: number;\n jitter: boolean;\n}\n\n// ============================================================================\n// OFFLINE QUEUE\n// ============================================================================\n\nexport interface OfflineQueueEntry {\n id: string;\n events: BeaconEvent[];\n timestamp: number;\n expiresAt: number;\n retryCount: number;\n size: number;\n}\n\n// ============================================================================\n// SIMPLE VALIDATORS (Lightweight replacements for Zod)\n// ============================================================================\n\n/**\n * Validates a beacon event\n */\nexport function validateBeaconEvent(event: unknown): event is BeaconEvent {\n if (!event || typeof event !== 'object') return false;\n const e = event as Record<string, unknown>;\n const metadata = e.metadata as Record<string, unknown> | undefined;\n return !!(\n e.type &&\n typeof e.type === 'string' &&\n e.data &&\n typeof e.data === 'object' &&\n metadata &&\n typeof metadata === 'object' &&\n metadata.sessionId &&\n metadata.timestamp\n );\n}\n\n/**\n * Validates beacon configuration\n */\nexport function validateBeaconConfig(config: unknown): config is BeaconConfig {\n if (!config || typeof config !== 'object') return false;\n const c = config as Record<string, unknown>;\n return !!(c.projectId && typeof c.projectId === 'string');\n}\n\n/**\n * Validates a beacon batch\n */\nexport function validateBeaconBatch(batch: unknown): batch is BeaconBatch {\n if (!batch || typeof batch !== 'object') return false;\n const b = batch as Record<string, unknown>;\n return !!(\n b.projectId &&\n typeof b.projectId === 'string' &&\n Array.isArray(b.events) &&\n b.events.every((e: unknown) => validateBeaconEvent(e)) &&\n b.sessionId &&\n typeof b.sessionId === 'string' &&\n b.batchId &&\n b.timestamp &&\n typeof b.timestamp === 'number'\n );\n}\n\n/** Rejects an identity naming nobody: downstream this becomes `detections.user_id`, where an empty string reads as \"identified\" while identifying no one. */\nfunction isBrowserBeaconIdentity(value: unknown): value is BeaconIdentity {\n return (\n typeof value === 'object' &&\n value !== null &&\n // Arrays are objects and would otherwise pass. `beacon-types`' own guard\n // rejects them via `isRecord`; these two are meant to agree, and a silent\n // divergence between two allowlists is exactly what this file's comments\n // promise is not happening.\n !Array.isArray(value) &&\n typeof (value as BeaconIdentity).userId === 'string' &&\n (value as BeaconIdentity).userId.length > 0\n );\n}\n\n/**\n * Parse beacon config with defaults\n */\nexport function parseBeaconConfig(input: unknown): BeaconConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n\n if (!config.projectId || typeof config.projectId !== 'string') {\n throw new Error('Project ID is required');\n }\n\n return {\n projectId: config.projectId as string,\n environment: config.environment as string | undefined,\n tags: config.tags as Record<string, string | number | boolean> | undefined,\n identity: isBrowserBeaconIdentity(config.identity) ? config.identity : undefined,\n endpoint: config.endpoint as string | undefined,\n enabled: config.enabled !== false,\n debug: config.debug === true,\n logLevel: (config.logLevel as 'error' | 'warn' | 'info' | 'debug' | undefined) || 'error',\n respectDoNotTrack: config.respectDoNotTrack !== false,\n anonymizeIp: config.anonymizeIp === true,\n sessionTimeout: (config.sessionTimeout as number | undefined) || undefined,\n sessionCookieName: (config.sessionCookieName as string | undefined) || '_as_beacon_session',\n batchSize: (config.batchSize as number | undefined) || 10,\n flushInterval: (config.flushInterval as number | undefined) || 5000,\n maxQueueSize: (config.maxQueueSize as number | undefined) || 100,\n retryAttempts: (config.retryAttempts as number | undefined) || 3,\n retryDelay: (config.retryDelay as number | undefined) || 2000,\n useWorker: config.useWorker !== false,\n workerUrl: config.workerUrl as string | undefined,\n workerConfig: config.workerConfig as WorkerConfig | undefined,\n };\n}\n\n/**\n * Simple type guards\n */\nexport const Guards = {\n isBeaconEvent: validateBeaconEvent,\n isBeaconConfig: validateBeaconConfig,\n isBeaconBatch: validateBeaconBatch,\n\n isWorkerMessage(msg: unknown): msg is WorkerMessage {\n if (!msg || typeof msg !== 'object') return false;\n const m = msg as Record<string, unknown>;\n return !!(\n m.id &&\n m.type &&\n ['request', 'response', 'error', 'heartbeat', 'status'].includes(m.type as string) &&\n typeof m.timestamp === 'number'\n );\n },\n\n isWorkerError(err: unknown): err is WorkerError {\n if (!err || typeof err !== 'object') return false;\n const e = err as Record<string, unknown>;\n return !!(\n e.type &&\n e.message &&\n typeof e.timestamp === 'number' &&\n typeof e.recoverable === 'boolean'\n );\n },\n\n isWorkerCapabilities(cap: unknown): cap is WorkerCapabilities {\n if (!cap || typeof cap !== 'object') return false;\n const c = cap as Record<string, unknown>;\n return !!(\n typeof c.workerAPI === 'boolean' &&\n typeof c.sharedArrayBuffer === 'boolean' &&\n typeof c.transferableObjects === 'boolean' &&\n typeof c.offscreenCanvas === 'boolean'\n );\n },\n};\n\n// ============================================================================\n// PARSE FUNCTIONS (with defaults and validation)\n// ============================================================================\n\nexport function parseWorkerConfig(input: unknown): WorkerConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n enabled: config.enabled !== false,\n url: config.url as string | undefined,\n heartbeatInterval: (config.heartbeatInterval as number | undefined) || 5000,\n maxUnhealthyCount: (config.maxUnhealthyCount as number | undefined) || 3,\n maxRetries: (config.maxRetries as number | undefined) || 3,\n retryDelay: (config.retryDelay as number | undefined) || 1000,\n messageTimeout: (config.messageTimeout as number | undefined) || 30000,\n compressionThreshold: (config.compressionThreshold as number | undefined) || 1024,\n allowFallback: config.allowFallback !== false,\n crossOriginIsolated: config.crossOriginIsolated === true,\n };\n}\n\nexport function parseWorkerMessage(input: unknown): WorkerMessage {\n const msg = input as Record<string, unknown>;\n if (!msg || typeof msg !== 'object') {\n throw new Error('Invalid worker message');\n }\n return {\n id: (msg.id as string | undefined) || crypto.randomUUID(),\n type:\n (msg.type as 'request' | 'response' | 'error' | 'heartbeat' | 'status' | undefined) ||\n 'request',\n action: msg.action as string | undefined,\n payload: msg.payload,\n timestamp: (msg.timestamp as number | undefined) || Date.now(),\n compressed: msg.compressed === true,\n priority: (msg.priority as 'low' | 'normal' | 'high' | 'critical' | undefined) || 'normal',\n correlationId: msg.correlationId as string | undefined,\n };\n}\n\nexport function parseWorkerError(input: unknown): WorkerError {\n const err = input as Record<string, unknown>;\n if (!err || typeof err !== 'object') {\n return {\n type: 'unknown',\n message: String(input),\n timestamp: Date.now(),\n recoverable: false,\n };\n }\n return {\n type: (err.type as string | undefined) || 'unknown',\n message: (err.message as string | undefined) || 'Unknown error',\n stack: err.stack as string | undefined,\n timestamp: (err.timestamp as number | undefined) || Date.now(),\n recoverable: Boolean(err.recoverable),\n };\n}\n\nexport function parseWorkerCapabilities(input: unknown): WorkerCapabilities {\n const cap = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n workerAPI: cap.workerAPI !== false,\n sharedArrayBuffer: cap.sharedArrayBuffer === true,\n transferableObjects: cap.transferableObjects === true,\n offscreenCanvas: cap.offscreenCanvas === true,\n webAssembly: cap.webAssembly === true,\n atomics: cap.atomics === true,\n bigInt: cap.bigInt === true,\n csp: (cap.csp as\n | { workerSrc: boolean; scriptSrc: boolean; blobUrls: boolean; inlineWorkers: boolean }\n | undefined) || {\n workerSrc: false,\n scriptSrc: false,\n blobUrls: false,\n inlineWorkers: false,\n },\n performance: (cap.performance as\n | { memory: boolean; measureUserAgentSpecificMemory: boolean }\n | undefined) || {\n memory: false,\n measureUserAgentSpecificMemory: false,\n },\n };\n}\n\nexport function parseWorkerTask(input: unknown): WorkerTask {\n const task = input as Record<string, unknown>;\n if (!task || typeof task !== 'object') {\n throw new Error('Invalid worker task');\n }\n return {\n id: (task.id as string | undefined) || crypto.randomUUID(),\n type: (task.type as string | undefined) || 'process',\n data: task.data,\n priority: (task.priority as 'low' | 'normal' | 'high' | 'critical' | undefined) || 'normal',\n createdAt: (task.createdAt as number | undefined) || Date.now(),\n startedAt: task.startedAt as number | undefined,\n completedAt: task.completedAt as number | undefined,\n error: task.error as WorkerError | undefined,\n maxRetries: task.maxRetries as number | undefined,\n retries: task.retries as number | undefined,\n timeout: task.timeout as number | undefined,\n };\n}\n\nexport function parseFallbackOptions(input: unknown): FallbackOptions {\n const opts = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n useRequestIdleCallback: opts.useRequestIdleCallback !== false,\n idleTimeout: (opts.idleTimeout as number | undefined) || 10000,\n chunkSize: (opts.chunkSize as number | undefined) || 10,\n throttleMs: (opts.throttleMs as number | undefined) || 16,\n maxExecutionTime: (opts.maxExecutionTime as number | undefined) || 50,\n };\n}\n\nexport function parseRetryStrategy(input: unknown): RetryStrategy {\n const strategy = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n maxAttempts: (strategy.maxAttempts as number | undefined) || 3,\n baseDelay: (strategy.baseDelay as number | undefined) || 1000,\n maxDelay: (strategy.maxDelay as number | undefined) || 30000,\n factor: (strategy.factor as number | undefined) || 2,\n jitter: strategy.jitter !== false,\n };\n}\n\nexport function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n threshold: (config.threshold as number | undefined) || 5,\n timeout: (config.timeout as number | undefined) || 60000,\n resetTimeout: (config.resetTimeout as number | undefined) || 30000,\n };\n}\n\nexport function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry {\n const entry = input as Record<string, unknown>;\n if (!entry || typeof entry !== 'object') {\n throw new Error('Invalid offline queue entry');\n }\n return {\n id:\n (entry.id as string | undefined) ||\n `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,\n events: Array.isArray(entry.events) ? entry.events : [],\n timestamp: (entry.timestamp as number | undefined) || Date.now(),\n expiresAt: (entry.expiresAt as number | undefined) || Date.now() + 86400000, // 24 hours\n retryCount: (entry.retryCount as number | undefined) || 0,\n size: (entry.size as number | undefined) || 0,\n };\n}\n\nexport function parseResourceUsage(input: unknown): ResourceUsage {\n const usage = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n memoryUsage: (usage.memoryUsage as number | undefined) || 0,\n cpuUsage: (usage.cpuUsage as number | undefined) || 0,\n taskCount: (usage.taskCount as number | undefined) || 0,\n activeWorkers: (usage.activeWorkers as number | undefined) || 0,\n pendingTasks: (usage.pendingTasks as number | undefined) || 0,\n completedTasks: (usage.completedTasks as number | undefined) || 0,\n failedTasks: (usage.failedTasks as number | undefined) || 0,\n averageTaskDuration: (usage.averageTaskDuration as number | undefined) || 0,\n };\n}\n\nexport function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n maxWorkers: (config.maxWorkers as number | undefined) || 4,\n minWorkers: (config.minWorkers as number | undefined) || 1,\n workerIdleTimeout: (config.workerIdleTimeout as number | undefined) || 60000,\n taskQueueSize: (config.taskQueueSize as number | undefined) || 100,\n resourceLimits: (config.resourceLimits as Record<string, unknown> | undefined) || {},\n };\n}\n\nexport function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage {\n const msg = input as Record<string, unknown>;\n if (!msg || typeof msg !== 'object') {\n throw new Error('Invalid beacon worker message');\n }\n return {\n type: (msg.type as BeaconWorkerMessageType | undefined) || 'collect',\n data: msg.data,\n messageId: (msg.messageId as string | undefined) || crypto.randomUUID(),\n timestamp: (msg.timestamp as number | undefined) || Date.now(),\n };\n}\n\n// ============================================================================\n// MINIMAL CONSTANTS\n// ============================================================================\n\nexport const DEFAULT_CONFIG = {\n batchSize: 10,\n flushInterval: 5000,\n sessionCookieName: '_as_beacon_session',\n retryAttempts: 3,\n retryDelay: 2000,\n} as const;\n\nexport const ERROR_TYPES = {\n NETWORK: 'network',\n VALIDATION: 'validation',\n TIMEOUT: 'timeout',\n UNKNOWN: 'unknown',\n} as const;\n"],"mappings":"AA+CA,SAAS,EAAoB,EAAwB,CACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAAK,CACrC,IAAM,EAAO,EAAM,WAAW,CAAC,EAC/B,GAAI,GAAQ,IAAQ,IAAS,IAAM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
package/dist/clearance.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as ZodObject, L as output, T as ZodNumber, V as $strip, j as ZodString, t as external_d_exports, x as ZodLiteral } from "./external-B7WI9FyQ.mjs";
|
|
2
2
|
import { JWK } from "jose";
|
|
3
3
|
//#region src/clearance.d.ts
|
|
4
4
|
export declare const CLEARANCE_TTL_SECONDS = 600;
|
package/dist/clearance.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as ZodObject, L as output, T as ZodNumber, V as $strip, j as ZodString, t as external_d_exports, x as ZodLiteral } from "./external-B7WI9FyQ.js";
|
|
2
2
|
import { JWK } from "jose";
|
|
3
3
|
//#region src/clearance.d.ts
|
|
4
4
|
export declare const CLEARANCE_TTL_SECONDS = 600;
|
package/dist/clearance.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_schemas = require('./schemas-
|
|
3
|
-
const require_project_verification_key = require('./project-verification-key-
|
|
2
|
+
const require_schemas = require('./schemas-YhagYDx_.js');
|
|
3
|
+
const require_project_verification_key = require('./project-verification-key-BccT12tQ.js');
|
|
4
4
|
let jose = require("jose");
|
|
5
5
|
|
|
6
6
|
//#region src/clearance.ts
|
package/dist/clearance.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as projectVerificationKey } from "./project-verification-key-
|
|
1
|
+
import { C as string, g as literal, v as number, y as object } from "./schemas-7qodsG-Z.mjs";
|
|
2
|
+
import { t as projectVerificationKey } from "./project-verification-key-66N4edKn.mjs";
|
|
3
3
|
import { SignJWT, importJWK, jwtVerify } from "jose";
|
|
4
4
|
|
|
5
5
|
//#region src/clearance.ts
|
|
@@ -179,7 +179,7 @@ function resolveCloudflare(input) {
|
|
|
179
179
|
}
|
|
180
180
|
function resolveTrustedProxy(input, trustedHops) {
|
|
181
181
|
const tokens = boundedTokens(getHeader(input.headers, "x-forwarded-for"));
|
|
182
|
-
if (tokens && Number.isInteger(trustedHops) && trustedHops
|
|
182
|
+
if (tokens && Number.isInteger(trustedHops) && trustedHops >= 0 && tokens.length > trustedHops) {
|
|
183
183
|
const parsed = tokens.map(normalizeToken);
|
|
184
184
|
const selected = parsed[tokens.length - trustedHops - 1];
|
|
185
185
|
if (selected && parsed.every((token) => token !== null)) return {
|
|
@@ -212,4 +212,4 @@ function resolveClientIp(input) {
|
|
|
212
212
|
|
|
213
213
|
//#endregion
|
|
214
214
|
export { resolveClientIp as i, normalizeClientIp as n, parseIpv6 as r, compressIpv6 as t };
|
|
215
|
-
//# sourceMappingURL=client-ip-
|
|
215
|
+
//# sourceMappingURL=client-ip-B2Xeo-GK.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-ip-HOfe6ucV.mjs","names":[],"sources":["../src/utils/client-ip.ts"],"sourcesContent":["/**\n * Runtime-agnostic client-IP normalization and trust resolution.\n *\n * Header presence is not proof of provenance. Callers must select the\n * deployment profile that describes which infrastructure has already\n * authenticated a value before using the result for security decisions.\n */\n\nexport type ClientIpSource =\n | 'explicit'\n | 'cf-connecting-ip'\n | 'x-vercel-forwarded-for'\n | 'x-forwarded-for'\n | 'x-real-ip'\n | 'framework'\n | 'socket'\n | 'none';\n\nexport interface ClientIpResolution {\n ip: string | null;\n source: ClientIpSource;\n trusted: boolean;\n}\n\nexport type ClientIpTrustPolicy =\n | { platform: 'vercel' }\n | { platform: 'cloudflare' }\n | { platform: 'trusted-proxy'; trustedHops: number }\n | { platform: 'direct' };\n\nexport type ClientIpHeaderValue = string | readonly string[] | undefined;\nexport type ClientIpHeaders = Headers | Record<string, ClientIpHeaderValue>;\n\nexport interface ResolveClientIpInput {\n headers: ClientIpHeaders;\n directAddress?: string | null;\n frameworkAddress?: string | null;\n explicitAddress?: string | null;\n /** True only after the caller has authenticated the explicit value. */\n explicitAddressTrusted?: boolean;\n policy: ClientIpTrustPolicy;\n}\n\nconst MAX_INPUT_LENGTH = 4096;\nconst MAX_TOKEN_LENGTH = 128;\nconst MAX_FORWARDED_HOPS = 32;\n\nfunction hasControlCharacter(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f) return true;\n }\n return false;\n}\n\nfunction parsePort(value: string): boolean {\n return /^(?:0|[1-9]\\d{0,4})$/.test(value) && Number(value) <= 65535;\n}\n\nfunction parseIpv4(value: string): number[] | null {\n const parts = value.split('.');\n if (parts.length !== 4) return null;\n\n const octets: number[] = [];\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part)) return null;\n const octet = Number(part);\n if (octet > 255) return null;\n octets.push(octet);\n }\n return octets;\n}\n\nfunction parseHexGroup(value: string): number | null {\n if (!/^[0-9a-fA-F]{1,4}$/.test(value)) return null;\n return Number.parseInt(value, 16);\n}\n\n/** Parses a bare IPv6 address into its 8 groups (`::` expanded). Exported for reuse by anything that needs to mask/truncate an address (see `anonymize-ip.ts`), not just resolve one. */\nexport function parseIpv6(value: string): number[] | null {\n if (!value || value.includes('%') || hasControlCharacter(value)) return null;\n\n let address = value;\n if (address.includes('.')) {\n const lastColon = address.lastIndexOf(':');\n if (lastColon < 0) return null;\n const ipv4 = parseIpv4(address.slice(lastColon + 1));\n if (!ipv4) return null;\n const first = (ipv4[0]! << 8) | ipv4[1]!;\n const second = (ipv4[2]! << 8) | ipv4[3]!;\n address = `${address.slice(0, lastColon + 1)}${first.toString(16)}:${second.toString(16)}`;\n }\n\n const doubleColon = address.indexOf('::');\n if (doubleColon !== address.lastIndexOf('::')) return null;\n\n const parseGroups = (part: string): number[] | null => {\n if (!part) return [];\n const groups = part.split(':');\n const parsed: number[] = [];\n for (const group of groups) {\n const number = parseHexGroup(group);\n if (number === null) return null;\n parsed.push(number);\n }\n return parsed;\n };\n\n if (doubleColon >= 0) {\n const head = parseGroups(address.slice(0, doubleColon));\n const tail = parseGroups(address.slice(doubleColon + 2));\n if (!head || !tail) return null;\n const missing = 8 - head.length - tail.length;\n if (missing < 1) return null;\n return [...head, ...Array<number>(missing).fill(0), ...tail];\n }\n\n const groups = parseGroups(address);\n return groups?.length === 8 ? groups : null;\n}\n\n/** RFC 5952 canonical `::` compression for 8 IPv6 groups. Exported alongside `parseIpv6`. */\nexport function compressIpv6(groups: number[]): string {\n const rendered = groups.map((group) => group.toString(16));\n let bestStart = -1;\n let bestLength = 1;\n let runStart = -1;\n\n for (let index = 0; index <= groups.length; index += 1) {\n if (index < groups.length && groups[index] === 0) {\n if (runStart < 0) runStart = index;\n continue;\n }\n if (runStart >= 0) {\n const runLength = index - runStart;\n if (runLength > bestLength) {\n bestStart = runStart;\n bestLength = runLength;\n }\n runStart = -1;\n }\n }\n\n if (bestStart < 0) return rendered.join(':');\n const before = rendered.slice(0, bestStart).join(':');\n const after = rendered.slice(bestStart + bestLength).join(':');\n if (!before && !after) return '::';\n if (!before) return `::${after}`;\n if (!after) return `${before}::`;\n return `${before}::${after}`;\n}\n\nfunction normalizeToken(rawToken: string): string | null {\n const token = rawToken.trim();\n if (!token || token.length > MAX_TOKEN_LENGTH || hasControlCharacter(token)) return null;\n\n let address = token;\n if (token.startsWith('[')) {\n const closing = token.indexOf(']');\n if (closing <= 1) return null;\n const suffix = token.slice(closing + 1);\n if (suffix && (!suffix.startsWith(':') || !parsePort(suffix.slice(1)))) return null;\n address = token.slice(1, closing);\n } else if ((token.match(/:/g) ?? []).length === 1 && token.includes('.')) {\n const colon = token.indexOf(':');\n if (!parsePort(token.slice(colon + 1))) return null;\n address = token.slice(0, colon);\n }\n\n const ipv4 = parseIpv4(address);\n if (ipv4) return ipv4.join('.');\n\n const ipv6 = parseIpv6(address);\n return ipv6 ? compressIpv6(ipv6) : null;\n}\n\nfunction boundedTokens(raw: string | null | undefined): string[] | null {\n if (raw == null || !raw || raw.length > MAX_INPUT_LENGTH || hasControlCharacter(raw)) return null;\n const tokens = raw.split(',');\n if (tokens.length > MAX_FORWARDED_HOPS) return null;\n return tokens;\n}\n\n/** Normalize the first valid address in a bounded header value. */\nexport function normalizeClientIp(raw: string | null | undefined): string | null {\n const tokens = boundedTokens(raw);\n if (!tokens) return null;\n for (const token of tokens) {\n const normalized = normalizeToken(token);\n if (normalized) return normalized;\n }\n return null;\n}\n\nfunction getHeader(headers: ClientIpHeaders, name: string): string | undefined {\n if ('get' in headers && typeof headers.get === 'function') {\n return headers.get(name) ?? undefined;\n }\n\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== wanted || value === undefined) continue;\n return Array.isArray(value) ? value.join(',') : value;\n }\n return undefined;\n}\n\nfunction result(\n ip: string | null,\n source: Exclude<ClientIpSource, 'none'>,\n trusted: boolean\n): ClientIpResolution | null {\n return ip ? { ip, source, trusted } : null;\n}\n\nfunction resolveAddress(\n raw: string | null | undefined,\n source: 'framework' | 'socket'\n): ClientIpResolution | null {\n return result(normalizeClientIp(raw), source, true);\n}\n\nfunction resolveExplicit(input: ResolveClientIpInput): ClientIpResolution | null {\n if (input.explicitAddressTrusted !== true) return null;\n return result(normalizeClientIp(input.explicitAddress), 'explicit', true);\n}\n\nfunction resolveVercel(input: ResolveClientIpInput): ClientIpResolution {\n const platform = result(\n normalizeClientIp(getHeader(input.headers, 'x-vercel-forwarded-for')),\n 'x-vercel-forwarded-for',\n true\n );\n if (platform) return platform;\n\n const overwrittenXff = result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n true\n );\n if (overwrittenXff) return overwrittenXff;\n\n const realIp = result(\n normalizeClientIp(getHeader(input.headers, 'x-real-ip')),\n 'x-real-ip',\n false\n );\n if (realIp) return realIp;\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? { ip: null, source: 'none', trusted: false }\n );\n}\n\nfunction resolveCloudflare(input: ResolveClientIpInput): ClientIpResolution {\n const cloudflare = result(\n normalizeClientIp(getHeader(input.headers, 'cf-connecting-ip')),\n 'cf-connecting-ip',\n true\n );\n if (cloudflare) return cloudflare;\n\n return (\n resolveAddress(input.directAddress, 'socket') ??\n resolveAddress(input.frameworkAddress, 'framework') ??\n result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n false\n ) ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\nfunction resolveTrustedProxy(input: ResolveClientIpInput, trustedHops: number): ClientIpResolution {\n const raw = getHeader(input.headers, 'x-forwarded-for');\n const tokens = boundedTokens(raw);\n if (tokens && Number.isInteger(trustedHops) && trustedHops > 0 && tokens.length > trustedHops) {\n const parsed = tokens.map(normalizeToken);\n const selectedIndex = tokens.length - trustedHops - 1;\n const selected = parsed[selectedIndex];\n // Parse every token before selecting one. Otherwise an invalid token could\n // silently move the trusted boundary toward an attacker-controlled value.\n if (selected && parsed.every((token) => token !== null)) {\n return { ip: selected, source: 'x-forwarded-for', trusted: true };\n }\n }\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\n/** Resolve a client IP using an explicit deployment trust profile. */\nexport function resolveClientIp(input: ResolveClientIpInput): ClientIpResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'vercel':\n return resolveVercel(input);\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'trusted-proxy':\n return resolveTrustedProxy(input, input.policy.trustedHops);\n case 'direct':\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n }\n}\n"],"mappings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AAK;CACtC,IAAI,UAAU,OAAO;CAErB,QAAQ,MAAM,OAAO,UAArB;EACE,KAAK,UACH,OAAO,cAAc,KAAK;EAC5B,KAAK,cACH,OAAO,kBAAkB,KAAK;EAChC,KAAK,iBACH,OAAO,oBAAoB,OAAO,MAAM,OAAO,WAAW;EAC5D,KAAK,UACH,OACE,eAAe,MAAM,kBAAkB,WAAW,KAClD,eAAe,MAAM,eAAe,QAAQ,KAAK;GAC/C,IAAI;GACJ,QAAQ;GACR,SAAS;EACX;CAEN;AACF"}
|
|
1
|
+
{"version":3,"file":"client-ip-B2Xeo-GK.mjs","names":[],"sources":["../src/utils/client-ip.ts"],"sourcesContent":["/**\n * Runtime-agnostic client-IP normalization and trust resolution.\n *\n * Header presence is not proof of provenance. Callers must select the\n * deployment profile that describes which infrastructure has already\n * authenticated a value before using the result for security decisions.\n */\n\nexport type ClientIpSource =\n | 'explicit'\n | 'cf-connecting-ip'\n | 'x-vercel-forwarded-for'\n | 'x-forwarded-for'\n | 'x-real-ip'\n | 'framework'\n | 'socket'\n | 'none';\n\nexport interface ClientIpResolution {\n ip: string | null;\n source: ClientIpSource;\n trusted: boolean;\n}\n\nexport type ClientIpTrustPolicy =\n | { platform: 'vercel' }\n | { platform: 'cloudflare' }\n | { platform: 'trusted-proxy'; trustedHops: number }\n | { platform: 'direct' };\n\nexport type ClientIpHeaderValue = string | readonly string[] | undefined;\nexport type ClientIpHeaders = Headers | Record<string, ClientIpHeaderValue>;\n\nexport interface ResolveClientIpInput {\n headers: ClientIpHeaders;\n directAddress?: string | null;\n frameworkAddress?: string | null;\n explicitAddress?: string | null;\n /** True only after the caller has authenticated the explicit value. */\n explicitAddressTrusted?: boolean;\n policy: ClientIpTrustPolicy;\n}\n\nconst MAX_INPUT_LENGTH = 4096;\nconst MAX_TOKEN_LENGTH = 128;\nconst MAX_FORWARDED_HOPS = 32;\n\nfunction hasControlCharacter(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f) return true;\n }\n return false;\n}\n\nfunction parsePort(value: string): boolean {\n return /^(?:0|[1-9]\\d{0,4})$/.test(value) && Number(value) <= 65535;\n}\n\nfunction parseIpv4(value: string): number[] | null {\n const parts = value.split('.');\n if (parts.length !== 4) return null;\n\n const octets: number[] = [];\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part)) return null;\n const octet = Number(part);\n if (octet > 255) return null;\n octets.push(octet);\n }\n return octets;\n}\n\nfunction parseHexGroup(value: string): number | null {\n if (!/^[0-9a-fA-F]{1,4}$/.test(value)) return null;\n return Number.parseInt(value, 16);\n}\n\n/** Parses a bare IPv6 address into its 8 groups (`::` expanded). Exported for reuse by anything that needs to mask/truncate an address (see `anonymize-ip.ts`), not just resolve one. */\nexport function parseIpv6(value: string): number[] | null {\n if (!value || value.includes('%') || hasControlCharacter(value)) return null;\n\n let address = value;\n if (address.includes('.')) {\n const lastColon = address.lastIndexOf(':');\n if (lastColon < 0) return null;\n const ipv4 = parseIpv4(address.slice(lastColon + 1));\n if (!ipv4) return null;\n const first = (ipv4[0]! << 8) | ipv4[1]!;\n const second = (ipv4[2]! << 8) | ipv4[3]!;\n address = `${address.slice(0, lastColon + 1)}${first.toString(16)}:${second.toString(16)}`;\n }\n\n const doubleColon = address.indexOf('::');\n if (doubleColon !== address.lastIndexOf('::')) return null;\n\n const parseGroups = (part: string): number[] | null => {\n if (!part) return [];\n const groups = part.split(':');\n const parsed: number[] = [];\n for (const group of groups) {\n const number = parseHexGroup(group);\n if (number === null) return null;\n parsed.push(number);\n }\n return parsed;\n };\n\n if (doubleColon >= 0) {\n const head = parseGroups(address.slice(0, doubleColon));\n const tail = parseGroups(address.slice(doubleColon + 2));\n if (!head || !tail) return null;\n const missing = 8 - head.length - tail.length;\n if (missing < 1) return null;\n return [...head, ...Array<number>(missing).fill(0), ...tail];\n }\n\n const groups = parseGroups(address);\n return groups?.length === 8 ? groups : null;\n}\n\n/** RFC 5952 canonical `::` compression for 8 IPv6 groups. Exported alongside `parseIpv6`. */\nexport function compressIpv6(groups: number[]): string {\n const rendered = groups.map((group) => group.toString(16));\n let bestStart = -1;\n let bestLength = 1;\n let runStart = -1;\n\n for (let index = 0; index <= groups.length; index += 1) {\n if (index < groups.length && groups[index] === 0) {\n if (runStart < 0) runStart = index;\n continue;\n }\n if (runStart >= 0) {\n const runLength = index - runStart;\n if (runLength > bestLength) {\n bestStart = runStart;\n bestLength = runLength;\n }\n runStart = -1;\n }\n }\n\n if (bestStart < 0) return rendered.join(':');\n const before = rendered.slice(0, bestStart).join(':');\n const after = rendered.slice(bestStart + bestLength).join(':');\n if (!before && !after) return '::';\n if (!before) return `::${after}`;\n if (!after) return `${before}::`;\n return `${before}::${after}`;\n}\n\nfunction normalizeToken(rawToken: string): string | null {\n const token = rawToken.trim();\n if (!token || token.length > MAX_TOKEN_LENGTH || hasControlCharacter(token)) return null;\n\n let address = token;\n if (token.startsWith('[')) {\n const closing = token.indexOf(']');\n if (closing <= 1) return null;\n const suffix = token.slice(closing + 1);\n if (suffix && (!suffix.startsWith(':') || !parsePort(suffix.slice(1)))) return null;\n address = token.slice(1, closing);\n } else if ((token.match(/:/g) ?? []).length === 1 && token.includes('.')) {\n const colon = token.indexOf(':');\n if (!parsePort(token.slice(colon + 1))) return null;\n address = token.slice(0, colon);\n }\n\n const ipv4 = parseIpv4(address);\n if (ipv4) return ipv4.join('.');\n\n const ipv6 = parseIpv6(address);\n return ipv6 ? compressIpv6(ipv6) : null;\n}\n\nfunction boundedTokens(raw: string | null | undefined): string[] | null {\n if (raw == null || !raw || raw.length > MAX_INPUT_LENGTH || hasControlCharacter(raw)) return null;\n const tokens = raw.split(',');\n if (tokens.length > MAX_FORWARDED_HOPS) return null;\n return tokens;\n}\n\n/** Normalize the first valid address in a bounded header value. */\nexport function normalizeClientIp(raw: string | null | undefined): string | null {\n const tokens = boundedTokens(raw);\n if (!tokens) return null;\n for (const token of tokens) {\n const normalized = normalizeToken(token);\n if (normalized) return normalized;\n }\n return null;\n}\n\nfunction getHeader(headers: ClientIpHeaders, name: string): string | undefined {\n if ('get' in headers && typeof headers.get === 'function') {\n return headers.get(name) ?? undefined;\n }\n\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== wanted || value === undefined) continue;\n return Array.isArray(value) ? value.join(',') : value;\n }\n return undefined;\n}\n\nfunction result(\n ip: string | null,\n source: Exclude<ClientIpSource, 'none'>,\n trusted: boolean\n): ClientIpResolution | null {\n return ip ? { ip, source, trusted } : null;\n}\n\nfunction resolveAddress(\n raw: string | null | undefined,\n source: 'framework' | 'socket'\n): ClientIpResolution | null {\n return result(normalizeClientIp(raw), source, true);\n}\n\nfunction resolveExplicit(input: ResolveClientIpInput): ClientIpResolution | null {\n if (input.explicitAddressTrusted !== true) return null;\n return result(normalizeClientIp(input.explicitAddress), 'explicit', true);\n}\n\nfunction resolveVercel(input: ResolveClientIpInput): ClientIpResolution {\n const platform = result(\n normalizeClientIp(getHeader(input.headers, 'x-vercel-forwarded-for')),\n 'x-vercel-forwarded-for',\n true\n );\n if (platform) return platform;\n\n const overwrittenXff = result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n true\n );\n if (overwrittenXff) return overwrittenXff;\n\n const realIp = result(\n normalizeClientIp(getHeader(input.headers, 'x-real-ip')),\n 'x-real-ip',\n false\n );\n if (realIp) return realIp;\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? { ip: null, source: 'none', trusted: false }\n );\n}\n\nfunction resolveCloudflare(input: ResolveClientIpInput): ClientIpResolution {\n const cloudflare = result(\n normalizeClientIp(getHeader(input.headers, 'cf-connecting-ip')),\n 'cf-connecting-ip',\n true\n );\n if (cloudflare) return cloudflare;\n\n return (\n resolveAddress(input.directAddress, 'socket') ??\n resolveAddress(input.frameworkAddress, 'framework') ??\n result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n false\n ) ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\nfunction resolveTrustedProxy(input: ResolveClientIpInput, trustedHops: number): ClientIpResolution {\n const raw = getHeader(input.headers, 'x-forwarded-for');\n const tokens = boundedTokens(raw);\n if (tokens && Number.isInteger(trustedHops) && trustedHops >= 0 && tokens.length > trustedHops) {\n const parsed = tokens.map(normalizeToken);\n const selectedIndex = tokens.length - trustedHops - 1;\n const selected = parsed[selectedIndex];\n // Parse every token before selecting one. Otherwise an invalid token could\n // silently move the trusted boundary toward an attacker-controlled value.\n if (selected && parsed.every((token) => token !== null)) {\n return { ip: selected, source: 'x-forwarded-for', trusted: true };\n }\n }\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\n/** Resolve a client IP using an explicit deployment trust profile. */\nexport function resolveClientIp(input: ResolveClientIpInput): ClientIpResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'vercel':\n return resolveVercel(input);\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'trusted-proxy':\n return resolveTrustedProxy(input, input.policy.trustedHops);\n case 'direct':\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n }\n}\n"],"mappings":";AA2CA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAE3B,SAAS,oBAAoB,OAAwB;CACnD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,OAAO,MAAM,WAAW,CAAC;EAC/B,IAAI,QAAQ,M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OACE,eAAe,MAAM,kBAAkB,WAAW,KAClD,eAAe,MAAM,eAAe,QAAQ,KAAK;GAC/C,IAAI;GACJ,QAAQ;GACR,SAAS;EACX;CAEN;AACF"}
|
|
@@ -179,7 +179,7 @@ function resolveCloudflare(input) {
|
|
|
179
179
|
}
|
|
180
180
|
function resolveTrustedProxy(input, trustedHops) {
|
|
181
181
|
const tokens = boundedTokens(getHeader(input.headers, "x-forwarded-for"));
|
|
182
|
-
if (tokens && Number.isInteger(trustedHops) && trustedHops
|
|
182
|
+
if (tokens && Number.isInteger(trustedHops) && trustedHops >= 0 && tokens.length > trustedHops) {
|
|
183
183
|
const parsed = tokens.map(normalizeToken);
|
|
184
184
|
const selected = parsed[tokens.length - trustedHops - 1];
|
|
185
185
|
if (selected && parsed.every((token) => token !== null)) return {
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/consent-handoff.d.ts
|
|
3
|
+
export declare const CONSENT_HANDOFF_SOURCES: readonly ["module", "probe"];
|
|
4
|
+
export type ConsentHandoffSource = (typeof CONSENT_HANDOFF_SOURCES)[number];
|
|
5
|
+
export declare const CONSENT_HANDOFF_REPORT_OUTCOMES: readonly ["registered", "registration_failed", "not_configured"];
|
|
6
|
+
export type ConsentHandoffReportOutcome = (typeof CONSENT_HANDOFF_REPORT_OUTCOMES)[number];
|
|
7
|
+
export declare const CONSENT_HANDOFF_MODULE_REASONS: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config"];
|
|
8
|
+
export type ConsentHandoffModuleReason = (typeof CONSENT_HANDOFF_MODULE_REASONS)[number];
|
|
9
|
+
export declare const CONSENT_HANDOFF_PROBE_CODES: readonly ["challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
10
|
+
export type ConsentHandoffProbeCode = (typeof CONSENT_HANDOFF_PROBE_CODES)[number];
|
|
11
|
+
export declare const CONSENT_HANDOFF_CODES: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config", "challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
12
|
+
export type ConsentHandoffCode = (typeof CONSENT_HANDOFF_CODES)[number];
|
|
13
|
+
export declare const CONSENT_HANDOFF_HEALTH_OUTCOMES: readonly ["ok", "failed", "not_configured"];
|
|
14
|
+
export type ConsentHandoffHealthOutcome = (typeof CONSENT_HANDOFF_HEALTH_OUTCOMES)[number];
|
|
15
|
+
export declare const ConsentHandoffHostSchema: z.ZodString;
|
|
16
|
+
export declare const ConsentHandoffReportSchema: z.ZodObject<{
|
|
17
|
+
outcome: z.ZodEnum<{
|
|
18
|
+
registered: "registered";
|
|
19
|
+
registration_failed: "registration_failed";
|
|
20
|
+
not_configured: "not_configured";
|
|
21
|
+
}>;
|
|
22
|
+
reason: z.ZodOptional<z.ZodEnum<{
|
|
23
|
+
http_401: "http_401";
|
|
24
|
+
http_403: "http_403";
|
|
25
|
+
http_404: "http_404";
|
|
26
|
+
http_4xx: "http_4xx";
|
|
27
|
+
http_5xx: "http_5xx";
|
|
28
|
+
http_other: "http_other";
|
|
29
|
+
timeout: "timeout";
|
|
30
|
+
network_error: "network_error";
|
|
31
|
+
invalid_response: "invalid_response";
|
|
32
|
+
missing_proof: "missing_proof";
|
|
33
|
+
placeholder_proof: "placeholder_proof";
|
|
34
|
+
invalid_config: "invalid_config";
|
|
35
|
+
}>>;
|
|
36
|
+
httpStatus: z.ZodCatch<z.ZodOptional<z.ZodNumber>>;
|
|
37
|
+
host: z.ZodCatch<z.ZodOptional<z.ZodString>>;
|
|
38
|
+
}, z.core.$strip>;
|
|
39
|
+
export type ConsentHandoffReport = z.infer<typeof ConsentHandoffReportSchema>;
|
|
40
|
+
//#endregion
|
|
41
|
+
//# sourceMappingURL=consent-handoff.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consent-handoff.d.mts","names":[],"sources":["../src/consent-handoff.ts"],"mappings":";;qBAgBa;YACD,+BAA+B;qBAG9B;YAKD,sCAAsC;qBAGrC;YAcD,qCAAqC;qBAGpC;YAOD,kCAAkC;qBAGjC;YAID,6BAA6B;qBAG5B;YACD,sCAAsC;qBAMrC,0BAAwB,EAAA;qBAQxB,4BAA0B,EAAA;;;;;;;;;;;;;;;;;;;;;;GAKrC,EAAA,KAAA;YACU,uBAAuB,EAAE,aAAa"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/consent-handoff.d.ts
|
|
3
|
+
export declare const CONSENT_HANDOFF_SOURCES: readonly ["module", "probe"];
|
|
4
|
+
export type ConsentHandoffSource = (typeof CONSENT_HANDOFF_SOURCES)[number];
|
|
5
|
+
export declare const CONSENT_HANDOFF_REPORT_OUTCOMES: readonly ["registered", "registration_failed", "not_configured"];
|
|
6
|
+
export type ConsentHandoffReportOutcome = (typeof CONSENT_HANDOFF_REPORT_OUTCOMES)[number];
|
|
7
|
+
export declare const CONSENT_HANDOFF_MODULE_REASONS: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config"];
|
|
8
|
+
export type ConsentHandoffModuleReason = (typeof CONSENT_HANDOFF_MODULE_REASONS)[number];
|
|
9
|
+
export declare const CONSENT_HANDOFF_PROBE_CODES: readonly ["challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
10
|
+
export type ConsentHandoffProbeCode = (typeof CONSENT_HANDOFF_PROBE_CODES)[number];
|
|
11
|
+
export declare const CONSENT_HANDOFF_CODES: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config", "challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
12
|
+
export type ConsentHandoffCode = (typeof CONSENT_HANDOFF_CODES)[number];
|
|
13
|
+
export declare const CONSENT_HANDOFF_HEALTH_OUTCOMES: readonly ["ok", "failed", "not_configured"];
|
|
14
|
+
export type ConsentHandoffHealthOutcome = (typeof CONSENT_HANDOFF_HEALTH_OUTCOMES)[number];
|
|
15
|
+
export declare const ConsentHandoffHostSchema: z.ZodString;
|
|
16
|
+
export declare const ConsentHandoffReportSchema: z.ZodObject<{
|
|
17
|
+
outcome: z.ZodEnum<{
|
|
18
|
+
registered: "registered";
|
|
19
|
+
registration_failed: "registration_failed";
|
|
20
|
+
not_configured: "not_configured";
|
|
21
|
+
}>;
|
|
22
|
+
reason: z.ZodOptional<z.ZodEnum<{
|
|
23
|
+
http_401: "http_401";
|
|
24
|
+
http_403: "http_403";
|
|
25
|
+
http_404: "http_404";
|
|
26
|
+
http_4xx: "http_4xx";
|
|
27
|
+
http_5xx: "http_5xx";
|
|
28
|
+
http_other: "http_other";
|
|
29
|
+
timeout: "timeout";
|
|
30
|
+
network_error: "network_error";
|
|
31
|
+
invalid_response: "invalid_response";
|
|
32
|
+
missing_proof: "missing_proof";
|
|
33
|
+
placeholder_proof: "placeholder_proof";
|
|
34
|
+
invalid_config: "invalid_config";
|
|
35
|
+
}>>;
|
|
36
|
+
httpStatus: z.ZodCatch<z.ZodOptional<z.ZodNumber>>;
|
|
37
|
+
host: z.ZodCatch<z.ZodOptional<z.ZodString>>;
|
|
38
|
+
}, z.core.$strip>;
|
|
39
|
+
export type ConsentHandoffReport = z.infer<typeof ConsentHandoffReportSchema>;
|
|
40
|
+
//#endregion
|
|
41
|
+
//# sourceMappingURL=consent-handoff.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consent-handoff.d.ts","names":[],"sources":["../src/consent-handoff.ts"],"mappings":";;qBAgBa;YACD,+BAA+B;qBAG9B;YAKD,sCAAsC;qBAGrC;YAcD,qCAAqC;qBAGpC;YAOD,kCAAkC;qBAGjC;YAID,6BAA6B;qBAG5B;YACD,sCAAsC;qBAMrC,0BAAwB,EAAA;qBAQxB,4BAA0B,EAAA;;;;;;;;;;;;;;;;;;;;;;GAKrC,EAAA,KAAA;YACU,uBAAuB,EAAE,aAAa"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("zod");const t=[`module`,`probe`],n=[`registered`,`registration_failed`,`not_configured`],r=[`http_401`,`http_403`,`http_404`,`http_4xx`,`http_5xx`,`http_other`,`timeout`,`network_error`,`invalid_response`,`missing_proof`,`placeholder_proof`,`invalid_config`],i=[`challenge_missing`,`challenge_proof_unsigned`,`challenge_proof_invalid`,`pickup_not_202`,`consent_page_unreachable`],a=[...r,...i],o=[`ok`,`failed`,`not_configured`],s=e.z.string().max(261).regex(/^(?:[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*|\[[0-9A-Fa-f:.]+\])(?::\d{1,5})?$/),c=e.z.object({outcome:e.z.enum(n),reason:e.z.enum(r).optional(),httpStatus:e.z.number().int().min(100).max(599).optional().catch(void 0),host:s.optional().catch(void 0)});exports.CONSENT_HANDOFF_CODES=a,exports.CONSENT_HANDOFF_HEALTH_OUTCOMES=o,exports.CONSENT_HANDOFF_MODULE_REASONS=r,exports.CONSENT_HANDOFF_PROBE_CODES=i,exports.CONSENT_HANDOFF_REPORT_OUTCOMES=n,exports.CONSENT_HANDOFF_SOURCES=t,exports.ConsentHandoffHostSchema=s,exports.ConsentHandoffReportSchema=c;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{z as e}from"zod";const t=[`module`,`probe`],n=[`registered`,`registration_failed`,`not_configured`],r=[`http_401`,`http_403`,`http_404`,`http_4xx`,`http_5xx`,`http_other`,`timeout`,`network_error`,`invalid_response`,`missing_proof`,`placeholder_proof`,`invalid_config`],i=[`challenge_missing`,`challenge_proof_unsigned`,`challenge_proof_invalid`,`pickup_not_202`,`consent_page_unreachable`],a=[...r,...i],o=[`ok`,`failed`,`not_configured`],s=e.string().max(261).regex(/^(?:[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*|\[[0-9A-Fa-f:.]+\])(?::\d{1,5})?$/),c=e.object({outcome:e.enum(n),reason:e.enum(r).optional(),httpStatus:e.number().int().min(100).max(599).optional().catch(void 0),host:s.optional().catch(void 0)});export{a as CONSENT_HANDOFF_CODES,o as CONSENT_HANDOFF_HEALTH_OUTCOMES,r as CONSENT_HANDOFF_MODULE_REASONS,i as CONSENT_HANDOFF_PROBE_CODES,n as CONSENT_HANDOFF_REPORT_OUTCOMES,t as CONSENT_HANDOFF_SOURCES,s as ConsentHandoffHostSchema,c as ConsentHandoffReportSchema};
|
|
2
|
+
//# sourceMappingURL=consent-handoff.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consent-handoff.mjs","names":[],"sources":["../src/consent-handoff.ts"],"sourcesContent":["import { z } from 'zod';\n\n/**\n * Consent-handoff health vocabulary: whether an agent that hits a delegation\n * challenge gets a consent link that can actually be redeemed.\n *\n * Two sources report into one health record per project:\n * - `module`: the PEP itself (the .NET module today), on its log-detection\n * report, right after it tries to register the challenge anchor.\n * - `probe`: the scheduled external check that plays an agent against the site.\n *\n * The module vocabulary is pinned by\n * `fixtures/kya-http/consent-handoff.codes.json`, which the .NET registrar also\n * asserts against.\n */\n\nexport const CONSENT_HANDOFF_SOURCES = ['module', 'probe'] as const;\nexport type ConsentHandoffSource = (typeof CONSENT_HANDOFF_SOURCES)[number];\n\n/** `consentHandoff.outcome` as a PEP reports it. */\nexport const CONSENT_HANDOFF_REPORT_OUTCOMES = [\n 'registered',\n 'registration_failed',\n 'not_configured',\n] as const;\nexport type ConsentHandoffReportOutcome = (typeof CONSENT_HANDOFF_REPORT_OUTCOMES)[number];\n\n/** Why a PEP's anchor registration failed. Every `http_*` code carries `httpStatus`. */\nexport const CONSENT_HANDOFF_MODULE_REASONS = [\n 'http_401',\n 'http_403',\n 'http_404',\n 'http_4xx',\n 'http_5xx',\n 'http_other',\n 'timeout',\n 'network_error',\n 'invalid_response',\n 'missing_proof',\n 'placeholder_proof',\n 'invalid_config',\n] as const;\nexport type ConsentHandoffModuleReason = (typeof CONSENT_HANDOFF_MODULE_REASONS)[number];\n\n/** Which stage of the handoff the external probe saw fail. */\nexport const CONSENT_HANDOFF_PROBE_CODES = [\n 'challenge_missing',\n 'challenge_proof_unsigned',\n 'challenge_proof_invalid',\n 'pickup_not_202',\n 'consent_page_unreachable',\n] as const;\nexport type ConsentHandoffProbeCode = (typeof CONSENT_HANDOFF_PROBE_CODES)[number];\n\n/** Every failure code either source can record. */\nexport const CONSENT_HANDOFF_CODES = [\n ...CONSENT_HANDOFF_MODULE_REASONS,\n ...CONSENT_HANDOFF_PROBE_CODES,\n] as const;\nexport type ConsentHandoffCode = (typeof CONSENT_HANDOFF_CODES)[number];\n\n/** A health observation: the handoff worked, failed, or is not set up on purpose. */\nexport const CONSENT_HANDOFF_HEALTH_OUTCOMES = ['ok', 'failed', 'not_configured'] as const;\nexport type ConsentHandoffHealthOutcome = (typeof CONSENT_HANDOFF_HEALTH_OUTCOMES)[number];\n\n// host[:port] only: never a path, query or userinfo.\nconst AUTHORITY_PATTERN = /^(?:[A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*|\\[[0-9A-Fa-f:.]+\\])(?::\\d{1,5})?$/;\n\n/** A strict `host[:port]`. The probe route requires it; reports only prefer it. */\nexport const ConsentHandoffHostSchema = z.string().max(261).regex(AUTHORITY_PATTERN);\n\n/**\n * The `consentHandoff` block of a log-detection report. A detail that doesn't\n * validate is dropped on its own, so the outcome and reason still count: .NET's\n * `Uri.Authority` can give a host this pattern refuses (an underscore, a Unicode\n * label, a trailing dot), and losing the host must never lose the 401 with it.\n */\nexport const ConsentHandoffReportSchema = z.object({\n outcome: z.enum(CONSENT_HANDOFF_REPORT_OUTCOMES),\n reason: z.enum(CONSENT_HANDOFF_MODULE_REASONS).optional(),\n httpStatus: z.number().int().min(100).max(599).optional().catch(undefined),\n host: ConsentHandoffHostSchema.optional().catch(undefined),\n});\nexport type ConsentHandoffReport = z.infer<typeof ConsentHandoffReportSchema>;\n"],"mappings":"wBAgBA,MAAa,EAA0B,CAAC,SAAU,OAAO,EAI5C,EAAkC,CAC7C,aACA,sBACA,gBACF,EAIa,EAAiC,CAC5C,WACA,WACA,WACA,WACA,WACA,aACA,UACA,gBACA,mBACA,gBACA,oBACA,gBACF,EAIa,EAA8B,CACzC,oBACA,2BACA,0BACA,iBACA,0BACF,EAIa,EAAwB,CACnC,GAAG,EACH,GAAG,CACL,EAIa,EAAkC,CAAC,KAAM,SAAU,gBAAgB,EAOnE,EAA2B,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,MAAM,yEAAiB,EAQtE,EAA6B,EAAE,OAAO,CACjD,QAAS,EAAE,KAAK,CAA+B,EAC/C,OAAQ,EAAE,KAAK,CAA8B,CAAC,CAAC,SAAS,EACxD,WAAY,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,EACzE,KAAM,EAAyB,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,CAC3D,CAAC"}
|