// Isonyma client snippet. Copy this file into your project (for example lib/isonyma.ts). // No dependencies. Node 20+, Next.js (route handlers, server actions, edge), Bun, Deno. // // Privacy: raw identifiers (email, IP, phone, user agent, device and card ids) never // leave your server. They are normalized and hashed here with your account's signal key // (the last part of ISONYMA_API_KEY); only hashes and coarse facts are sent. // // Fail-open: on timeout, network error or any non-2xx response it returns null and your // code continues exactly as before. It never throws. export type IsonymaEventType = "signup" | "credit_grant" | "llm_call"; /** Raw signals. Hashed locally by isonymaEvent; never sent as is. All optional. */ export interface IsonymaRawSignals { email?: string | null; ip?: string | null; userAgent?: string | null; /** Your device or browser fingerprint id, if you have one. */ deviceId?: string | null; /** Payment card fingerprint, for example Stripe's card.fingerprint. */ cardFingerprint?: string | null; phone?: string | null; /** Autonomous system number of the client IP, if your platform provides it. */ asn?: number | null; /** Two-letter country code of the client IP, if your platform provides it. */ country?: string | null; } export interface IsonymaEvent { type: IsonymaEventType; /** Your internal user or account id. Never an email or phone number. */ account_id: string; /** ISO 8601. Defaults to now. */ occurred_at?: string; /** Credits granted, or estimated cost of the LLM call, in USD. */ amount_usd?: number; signals?: IsonymaRawSignals; /** For llm_call: the request you send to the LLM. Only its Prompt DNA (two hashes) is * sent; the prompt text never leaves your server. */ llm?: IsonymaLlmRequest; test?: boolean; } /** The parts of an LLM request that Prompt DNA looks at. Works with OpenAI and Anthropic * request objects as they are. */ export interface IsonymaLlmRequest { /** A model name, or a Vercel AI SDK model object. */ model?: unknown; /** Chat messages; the last user message is the prompt. */ messages?: readonly unknown[] | null; /** Or the prompt itself, for completion-style calls and the AI SDK. */ prompt?: unknown; /** OpenAI Responses API: a string or a list of messages. */ input?: unknown; instructions?: unknown; system?: unknown; temperature?: number | null; top_p?: number | null; topP?: number | null; max_tokens?: number | null; max_completion_tokens?: number | null; max_output_tokens?: number | null; maxOutputTokens?: number | null; maxTokens?: number | null; /** Tool definitions: only their names are used. */ tools?: unknown; response_format?: unknown; } type IsonymaMessage = { role?: string; content?: unknown } | null; export interface IsonymaDecision { decision_id: string; recommendation: "allow" | "review" | "hold"; applied: boolean; mode: "shadow" | "enforce"; summary: string; reasons: { code: string; text: string }[]; usd_at_risk: number; } const ISONYMA_TIMEOUT_MS = 300; const ISONYMA_LABEL_TIMEOUT_MS = 3000; const ISONYMA_CLIENT = "ts-0.5"; export async function isonymaEvent(event: IsonymaEvent): Promise { try { const env = globalThis.process?.env ?? {}; const key = env.ISONYMA_API_KEY; if (!key) return null; const base = env.ISONYMA_API_URL ?? "https://api.isonyma.com"; const { signals: raw, llm, ...rest } = event; const signals = await isonymaHashSignals(key, raw ?? {}); if (llm) { try { Object.assign(signals, await isonymaPromptDna(key, llm)); } catch { // an unusual request shape: send the event without Prompt DNA } } const res = await fetch(`${base}/v0/events`, { method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body: JSON.stringify({ ...rest, signals }), signal: AbortSignal.timeout(ISONYMA_TIMEOUT_MS), }); if (!res.ok) return null; return (await res.json()) as IsonymaDecision; } catch { return null; // fail-open: Isonyma must never break your product } } /** * Tell Isonyma you banned an account for abuse or fraud ("banned"), or cleared a flagged one or * lifted a ban ("normal"). Bans are remembered: the same people are held when they come back. * Fail-open like isonymaEvent: returns false on any error, never throws. Off the user's hot path, * so it waits longer (3 s). For many accounts at once use isonymaLabels. */ export async function isonymaLabel(accountId: string, label: "banned" | "normal"): Promise { return isonymaLabels([{ accountId, label }]); } /** Up to 1,000 labels in one call, for bulk bans or imports. */ export async function isonymaLabels(items: { accountId: string; label: "banned" | "normal" }[]): Promise { try { const env = globalThis.process?.env ?? {}; const key = env.ISONYMA_API_KEY; if (!key || items.length === 0) return false; const base = env.ISONYMA_API_URL ?? "https://api.isonyma.com"; let ok = true; for (let i = 0; i < items.length; i += 1000) { const labels = items.slice(i, i + 1000).map((x) => ({ account_id: x.accountId, label: x.label })); const res = await fetch(`${base}/v0/labels`, { method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body: JSON.stringify({ labels }), signal: AbortSignal.timeout(ISONYMA_LABEL_TIMEOUT_MS), }); ok = ok && res.ok; } return ok; } catch { return false; } } export type IsonymaPlatform = "vercel" | "cloudflare" | "fly" | "proxy"; /** * Client IP, user agent and country from request headers. * Headers are only trusted when the platform that sets them is known from server-side * config, never from the request (a client can send any header). Platform: the argument, * else ISONYMA_PLATFORM, else detected from VERCEL or FLY_APP_NAME, else "proxy": one reverse * proxy in front of the app, which appends the client IP as the last x-forwarded-for entry. */ export function isonymaRequestSignals(headers: Headers, platform?: IsonymaPlatform): IsonymaRawSignals { const env = (globalThis as { process?: { env?: Record } }).process?.env ?? {}; const p: IsonymaPlatform = platform ?? (env.ISONYMA_PLATFORM as IsonymaPlatform | undefined) ?? (env.VERCEL ? "vercel" : env.FLY_APP_NAME ? "fly" : "proxy"); const last = (v: string | null) => v?.split(",").map((x) => x.trim()).filter(Boolean).pop() ?? null; const first = (v: string | null) => v?.split(",")[0]?.trim() || null; let ip: string | null; let country: string | null = null; if (p === "vercel") { ip = first(headers.get("x-vercel-forwarded-for")) ?? first(headers.get("x-forwarded-for")); country = headers.get("x-vercel-ip-country"); } else if (p === "cloudflare") { ip = headers.get("cf-connecting-ip"); country = headers.get("cf-ipcountry"); } else if (p === "fly") { ip = headers.get("fly-client-ip"); } else { ip = last(headers.get("x-forwarded-for")) ?? headers.get("x-real-ip"); } return { ip, userAgent: headers.get("user-agent"), country }; } // ---------- hashing (runs locally) ---------- const enc = new TextEncoder(); let keyCache: { hex: string; key: CryptoKey } | undefined; function toHex(buf: ArrayBuffer): string { return Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join(""); } async function signalKey(apiKey: string): Promise { const hex = apiKey.slice(apiKey.lastIndexOf("_") + 1); if (!/^[0-9a-f]{64}$/.test(hex)) throw new Error("ISONYMA_API_KEY has no signal key"); if (keyCache?.hex === hex) return keyCache.key; const bytes = new Uint8Array(hex.match(/../g)!.map((x) => parseInt(x, 16))); const key = await crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); keyCache = { hex, key }; return key; } async function keyed(key: CryptoKey, kind: string, value: string): Promise { const sig = await crypto.subtle.sign("HMAC", key, enc.encode(`${kind}\u0000${value}`)); return toHex(sig).slice(0, 32); } /** Hashes raw signals with the account's signal key. Exported for backfill scripts. */ export async function isonymaHashSignals(apiKey: string, raw: IsonymaRawSignals): Promise> { const key = await signalKey(apiKey); const out: Record = { client: ISONYMA_CLIENT }; const email = raw.email ? isonymaNormalizeEmail(raw.email) : null; if (email) { out.email_hash = await keyed(key, "email", email.normalized); if (email.stem) out.email_stem_hash = await keyed(key, "email_stem", email.stem); out.email_domain_sha256 = toHex(await crypto.subtle.digest("SHA-256", enc.encode(email.domain))); out.email_shape = email.shape; out.email_tagged = email.tagged; } const ip = raw.ip ? isonymaNormalizeIp(raw.ip) : null; if (ip && !ip.private) { out.ip_hash = await keyed(key, "ip", ip.address); out.ip_net_hash = await keyed(key, "ip_net", ip.network); out.ip_version = ip.version; } if (raw.userAgent) { const ua = isonymaUserAgent(raw.userAgent); out.user_agent_hash = await keyed(key, "user_agent", ua.normalized); out.ua_family = ua.family; out.ua_automation = ua.automation; } const device = isonymaReal(raw.deviceId); if (device) out.device_hash = await keyed(key, "device_id", device); const card = isonymaReal(raw.cardFingerprint); if (card) out.card_hash = await keyed(key, "card_fingerprint", card); const phone = raw.phone ? isonymaNormalizePhone(raw.phone) : null; if (phone) out.phone_hash = await keyed(key, "phone", phone); if (Number.isInteger(raw.asn) && raw.asn! > 0 && raw.asn! <= 4294967295) out.asn = raw.asn; if (raw.country && /^[A-Za-z]{2}$/.test(raw.country)) out.ip_country = raw.country.toUpperCase(); return out; } // ---------- normalization ---------- const DOTLESS = new Set(["gmail.com", "googlemail.com"]); const PLUS = new Set([ "gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com", "msn.com", "icloud.com", "me.com", "mac.com", "proton.me", "protonmail.com", "pm.me", "fastmail.com", "yandex.ru", "yandex.com", "zoho.com", ]); const MINUS = new Set(["yahoo.com", "ymail.com"]); const ALIASES: Record = { "googlemail.com": "gmail.com", "ya.ru": "yandex.ru" }; // ---------- Prompt DNA (runs locally) ---------- function promptText(req: IsonymaLlmRequest): string { if (typeof req.prompt === "string") return req.prompt; // Chat messages, AI SDK messages passed as prompt, or Responses input. const msgs = ([req.messages, req.prompt, req.input].find(Array.isArray) ?? []) as IsonymaMessage[]; if (!msgs.length && typeof req.input === "string") return req.input; // OpenAI Responses const user = [...msgs].reverse().find((m) => m && m.role === "user"); return contentText(user?.content); } function contentText(c: unknown): string { if (typeof c === "string") return c; if (Array.isArray(c)) { return c .map((p) => (typeof p === "string" ? p : p && typeof p === "object" && "text" in p ? String((p as { text: unknown }).text) : "")) .join(" "); } return ""; } /** A prompt reduced to its template: what a script keeps fixed when it fills in values. * Null for short prompts ("continue", "make it shorter"): everyone sends those. */ export function isonymaPromptTemplate(text: string): string | null { const t = text .toLowerCase() .replace(/https?:\/\/\S+/g, "") .replace(/[^\s@]+@[^\s@]+\.[a-z]{2,}/g, "") // Quoted values; an apostrophe inside a word (it's, don't) is not a quote. .replace(/"[^"\n]{0,500}"|“[^”\n]{0,500}”|«[^»\n]{0,500}»|(?") .replace(/\d+([.,]\d+)*/g, "0") .replace(/\s+/g, " ") .trim(); return t.length >= 40 && t.split(" ").length >= 6 ? t : null; } const fnv = (s: string, seed: number) => { let h = (0x811c9dc5 ^ seed) >>> 0; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 0; return h; }; /** Shapes of a template, for fuzzy Prompt DNA: what stays when a script puts free text in * a slot (its first and last 12 words) or is edited slightly (MinHash of its word * triples, 4 bands of 4, over the first 2,000 words so long prompts stay cheap). Only * templates of 24 words or more: shorter ones say too little. */ export function isonymaPromptShapes(template: string | null): string[] { const w = template ? template.split(" ") : []; if (w.length < 24) return []; const out = [`h:${w.slice(0, 12).join(" ")}`, `t:${w.slice(-12).join(" ")}`]; const shingles = new Set(); for (let i = 0; i + 3 <= Math.min(w.length, 2000); i++) shingles.add(w.slice(i, i + 3).join(" ")); const mins = Array.from({ length: 16 }, (_, k) => { let m = 0xffffffff; for (const sh of shingles) m = Math.min(m, fnv(sh, k * 0x9e3779b1)); return m; }); for (let b = 0; b < 4; b++) out.push(`m${b}:${mins.slice(b * 4, b * 4 + 4).join(",")}`); return out; } /** The request setup: model, parameters, tools, output format, system prompt. */ export function isonymaPromptHarness(req: IsonymaLlmRequest): string { const model = typeof req.model === "string" ? req.model : (req.model as { modelId?: string } | undefined)?.modelId ?? ""; type Tool = { name?: string; function?: { name?: string } } | null; // An array of tool definitions, or an AI SDK tool set keyed by name. const tools = (Array.isArray(req.tools) ? (req.tools as Tool[]).map((t) => (t && (t.function?.name ?? t.name)) || "") : req.tools && typeof req.tools === "object" ? Object.keys(req.tools) : []) .sort() .join(","); const msgs = (Array.isArray(req.messages) ? req.messages : []) as IsonymaMessage[]; const system = contentText(req.system) || contentText(req.instructions) || contentText(msgs.find((m) => m && m.role === "system")?.content); const num = (n: unknown) => (typeof n === "number" ? String(Math.round(n * 100) / 100) : ""); return [ model, num(req.temperature), num(req.top_p ?? req.topP), num(req.max_tokens ?? req.max_completion_tokens ?? req.max_output_tokens ?? req.maxOutputTokens ?? req.maxTokens), tools, (req.response_format as { type?: string } | null | undefined)?.type ?? "", system.replace(/\s+/g, " ").trim().toLowerCase(), ].join("|"); } /** Prompt DNA of one LLM request: keyed hashes of the prompt template and of the request * setup. Isonyma ties the two together itself. */ export interface IsonymaPromptDna { prompt_harness_hash: string; prompt_tpl_hash?: string; prompt_shape_hashes?: string[]; } export async function isonymaPromptDna(apiKey: string, req: IsonymaLlmRequest): Promise { const key = await signalKey(apiKey); const out: IsonymaPromptDna = { prompt_harness_hash: await keyed(key, "prompt_harness", isonymaPromptHarness(req)) }; const tpl = isonymaPromptTemplate(promptText(req)); if (tpl) out.prompt_tpl_hash = await keyed(key, "prompt_tpl", tpl); const shapes = isonymaPromptShapes(tpl); if (shapes.length) out.prompt_shape_hashes = await Promise.all(shapes.map((v) => keyed(key, "prompt_shape", v))); return out; } /** Hashes of your product's own prompts and request setups, for POST /v0/presets: they * are never evidence. Give prompts exactly as they are sent to the LLM. */ export async function isonymaPresetHashes( apiKey: string, presets: { prompts?: string[]; requests?: IsonymaLlmRequest[] }, ): Promise<{ prompt_tpl_hashes: string[]; prompt_harness_hashes: string[]; prompt_shape_hashes: string[] }> { const key = await signalKey(apiKey); const tpl: string[] = []; const shapes: string[] = []; for (const p of presets.prompts ?? []) { const t = isonymaPromptTemplate(p); if (t) tpl.push(await keyed(key, "prompt_tpl", t)); for (const v of isonymaPromptShapes(t)) shapes.push(await keyed(key, "prompt_shape", v)); } const harness: string[] = []; for (const r of presets.requests ?? []) harness.push(await keyed(key, "prompt_harness", isonymaPromptHarness(r))); return { prompt_tpl_hashes: tpl, prompt_harness_hashes: harness, prompt_shape_hashes: shapes }; } const PLACEHOLDER = /^(null|none|nil|undefined|unknown|n\/?a|\\n|-+|0+|default|not ?set|\[object object\])$/i; /** Trimmed value, or null for empty and placeholder values ("unknown", "null", "0"): * one constant shared by every account would link them all. */ export function isonymaReal(v: string | null | undefined): string | null { const t = v?.trim(); return t && !PLACEHOLDER.test(t) ? t : null; } export function isonymaNormalizeEmail(raw: string) { const value = raw.trim().toLowerCase(); if (!/^[^@\s]{1,64}@[a-z0-9.-]{1,253}\.(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/.test(value)) return null; const at = value.lastIndexOf("@"); let local = value.slice(0, at); let domain = value.slice(at + 1).replace(/\.$/, ""); domain = ALIASES[domain] ?? domain; let tagged = false; if (PLUS.has(domain) && local.includes("+")) [local, tagged] = [local.split("+")[0], true]; else if (MINUS.has(domain) && local.includes("-")) [local, tagged] = [local.split("-")[0], true]; if (DOTLESS.has(domain)) local = local.replace(/\./g, ""); if (!local) return null; const letters = local.replace(/[^a-z]/g, ""); // Name plus digits series (john.smith123): only with 4+ letters, so short school-style // ids (s123456) do not collide. const stem = letters.length >= 4 && /\d/.test(local) ? `${letters}@${domain}` : null; return { normalized: `${local}@${domain}`, domain, tagged, shape: shape(local), stem }; } function shape(local: string): string { const runs: [string, number][] = []; for (const ch of local) { const kind = /[a-z]/.test(ch) ? "L" : /\d/.test(ch) ? "D" : "S"; const last = runs[runs.length - 1]; if (last && last[0] === kind) last[1]++; else runs.push([kind, 1]); } return runs.slice(0, 20).map(([k, n]) => k + Math.min(n, 999)).join(""); } export function isonymaNormalizePhone(raw: string): string | null { // Pass E.164 (+countrycode...) when you can: numbers without a country code cannot be // matched with the same number written internationally. let digits = raw.replace(/\(0\)/g, "").replace(/\D/g, ""); if (raw.trim().startsWith("00")) digits = digits.slice(2); return digits.length >= 7 && digits.length <= 15 ? `+${digits}` : null; } function parseV4(s: string): number[] | null { const parts = s.split("."); if (parts.length !== 4) return null; const nums = parts.map((p) => (/^\d{1,3}$/.test(p) ? Number(p) : NaN)); return nums.every((n) => n >= 0 && n <= 255) ? nums : null; } function parseV6(s: string): number[] | null { let v = s.toLowerCase().split("%")[0]; if (v.includes(".")) { const cut = v.lastIndexOf(":"); const v4 = parseV4(v.slice(cut + 1)); if (!v4) return null; v = `${v.slice(0, cut + 1)}${((v4[0] << 8) | v4[1]).toString(16)}:${((v4[2] << 8) | v4[3]).toString(16)}`; } const halves = v.split("::"); if (halves.length > 2) return null; const toNums = (part: string) => (part ? part.split(":").map((x) => (/^[0-9a-f]{1,4}$/.test(x) ? parseInt(x, 16) : NaN)) : []); const head = toNums(halves[0]); const tail = halves.length === 2 ? toNums(halves[1]) : []; const fill = 8 - head.length - tail.length; if (halves.length === 1 ? fill !== 0 : fill < 1) return null; const all = [...head, ...Array(halves.length === 2 ? fill : 0).fill(0), ...tail]; return all.every((n) => n >= 0 && n <= 0xffff) ? all : null; } export function isonymaNormalizeIp(raw: string) { let s = raw.trim(); const bracketed = s.match(/^\[([^\]]+)\](?::\d+)?$/); // [2001:db8::1]:443 if (bracketed) s = bracketed[1]; else if (/^\d{1,3}(\.\d{1,3}){3}:\d+$/.test(s)) s = s.slice(0, s.lastIndexOf(":")); // 1.2.3.4:443 const v4 = parseV4(s); if (v4) { const [a, b] = v4; const priv = a === 10 || a === 127 || a === 0 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127) || a >= 224; return { address: v4.join("."), network: `${v4.slice(0, 3).join(".")}.0/24`, version: 4, private: priv }; } const v6 = parseV6(s); if (!v6) return null; const nat64 = v6[0] === 0x64 && v6[1] === 0xff9b && v6.slice(2, 6).every((x) => x === 0); if ((v6.slice(0, 5).every((x) => x === 0) && v6[5] === 0xffff) || nat64) { return isonymaNormalizeIp(`${v6[6] >> 8}.${v6[6] & 255}.${v6[7] >> 8}.${v6[7] & 255}`); } const hexes = v6.map((x) => x.toString(16)); const priv = v6.slice(0, 7).every((x) => x === 0) || (v6[0] & 0xfe00) === 0xfc00 || (v6[0] & 0xffc0) === 0xfe80 || (v6[0] & 0xff00) === 0xff00; return { address: hexes.join(":"), network: `${hexes.slice(0, 4).join(":")}::/64`, version: 6, private: priv }; } const AUTOMATION: [string, string][] = [ ["headlesschrome", "HeadlessChrome"], ["phantomjs", "PhantomJS"], ["puppeteer", "Puppeteer"], ["playwright", "Playwright"], ["selenium", "Selenium"], ["python-requests", "python-requests"], ["python-httpx", "python-httpx"], ["aiohttp", "aiohttp"], ["curl/", "curl"], ["wget/", "wget"], ["go-http-client", "Go-http-client"], ["okhttp", "okhttp"], ["axios/", "axios"], ["node-fetch", "node-fetch"], ["undici", "undici"], ["postmanruntime", "Postman"], ["insomnia", "Insomnia"], ["scrapy", "Scrapy"], ["java/", "Java"], ["libwww-perl", "libwww-perl"], ]; const BROWSERS: [string, string][] = [ ["edg/", "Edge"], ["opr/", "Opera"], ["firefox/", "Firefox"], ["chrome/", "Chrome"], ["safari/", "Safari"], ]; export function isonymaUserAgent(raw: string) { const normalized = raw.trim().split(/\s+/).join(" ").slice(0, 512); const low = normalized.toLowerCase(); for (const [needle, family] of AUTOMATION) if (low.includes(needle)) return { normalized, family, automation: true }; for (const [needle, family] of BROWSERS) if (low.includes(needle)) return { normalized, family, automation: false }; return { normalized, family: "other", automation: false }; }