Browser geolocation and risk signals

Kade Web SDK

Collect location, device fingerprints, and browser integrity markers, then evaluate geofence and fraud policy through one browser SDK.

~144 KB minified ~47 KB gzipped AES-GCM encrypted requests GPS or IP location flow

Overview

The SDK exposes a global KadeSDK constructor. It encrypts ping and server fingerprint payloads, manages location collection, and supports one-off or continuous checks.

Every ping

Fingerprint data and static browser markers are included on every ping, alongside active markers and location data when available.

Predictable lifecycle

Calling init() during application startup is recommended. Public async methods also initialize automatically when needed.

Browser requirements. Use a modern secure-context browser with the Geolocation and Web Crypto APIs. IndexedDB is used for persisted identifiers when available and the SDK degrades without it. Location permission behavior varies by browser and operating system.

What the SDK collects

Each ping sends the following to Kade, on behalf of and as instructed by the operator that integrates the SDK:

Wi-Fi network names or BSSIDs, contacts, keystrokes and the content of the page are not collected. Kade processes this data as a processor under the operator's data processing agreement and does not sell or share it with other operators.

The operator is responsible for giving players notice of this collection and, where the law of the player's jurisdiction requires it for precise location or device data, for obtaining consent before calling ping() or startContinuousPing(). The browser's own location permission prompt is not a substitute for that notice. Where consent is refused, call the SDK with skipLocation so only the IP-based estimate is used, or do not call it.

Install

Choose the npm package for module-based applications, or load the browser bundle directly from the CDN.

Option 1: npm

Configure GitHub Packages in the project's .npmrc. Use a GitHub personal access token with read:packages permission; do not commit the token.

@kade-technologies:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_PACKAGES_TOKEN}
npm install @kade-technologies/web-sdk@1.1.0
import KadeSDK, {
  type PingOptions,
} from '@kade-technologies/web-sdk';

const options: PingOptions = { userId: 'player-123' };
const sdk = new KadeSDK({ apiToken: 'your-api-token' });
await sdk.ping(options);

Option 2: CDN

Add the CDN bundle before your application code. It creates window.KadeSDK.

<script src="https://sdk.kade.io/1.1.0/kade-sdk.js"></script>

Current production bundle size: ~144 KB minified / ~47 KB gzipped.

CDN projects can use npm types without bundling npm runtime. Install the package as a development dependency and use import type, as described in TypeScript. Type-only imports are erased during compilation.

Migration

The Web SDK public API rename (completed in 0.6.1) is in effect in SDK 1.1.0. Integrations use sdk.kade.io and KadeSDK.

The bundle exposes only window.KadeSDK. Geofence domain terminology, storage keys, response payloads, and wire error-code strings remain unchanged.

Quick start

Initialize once, request location from a user gesture when your experience needs an explicit permission prompt, then send a ping.

const sdk = new KadeSDK({
  apiToken: 'your-api-token',
  regionId: 123
});

sdk.onError((error, context) => {
  console.error(`Kade SDK error in ${context}`, error);
});

// Recommended at startup; ping() also initializes automatically.
// Top-level await needs a module script; otherwise wrap in an async function.
await sdk.init();

// Call from a click or tap handler if permission may need to be prompted.
document.querySelector('#verify-location').addEventListener('click', async () => {
  await sdk.requestLocationPermission();

  const result = await sdk.ping({
    userId: 'player-123',
    source: 'login',
    email: 'player@example.com'
  });

  if (result.blocked) {
    console.log('Blocked:', result.code, result.message);
  } else {
    console.log('Inside:', result.inside);
    console.log('Area:', result.area?.name);
  }
});
Location opt-out applies per call. Each ping(), startContinuousPing(), and primeLocation() call decides whether geolocation is requested from its own skipLocation option. A later call without skipLocation can request location again on the same instance.

Core API

These methods form the documented host-facing surface used by browser integrations.

new KadeSDK(config: KadeConfig) Creates an instance. apiToken is required.
onError(handler: (error: Error, context: string) => void): this Registers an SDK error observer and returns the instance for chaining. Promise rejections should still be handled by the caller.
init(): Promise<void> Prepares active/static markers, fingerprinting, persisted client identity, and encryption. Recommended for predictable startup; async SDK methods auto-initialize if it has not been called.
getFingerprint(userId?: string): Promise<FingerprintResult | FingerprintServerResponse> With no ID, returns the local FingerprintResult. With a userId, sends an encrypted fingerprint request and returns an enriched FingerprintServerResponse.
ping(options?: PingOptions): Promise<PingResponse> Sends one encrypted geofence check. Fingerprint and static markers are included on every ping.
startContinuousPing(options?: PingOptions, callback?: (response: PingResponse, error?: Error) => void): Promise<void> Starts adaptive polling. The SDK uses the server-provided interval for subsequent checks and reuses the supplied options. The loop stops when a response is blocked or returns HTTP 451 or 403. The one exception is LOCATION_PERMISSION_MISSING, which keeps retrying unless stopOnPermissionBlock is true.
stopContinuousPing(): void Stops continuous checks and associated location watchers.
destroy(): void Stops monitoring and clears SDK resources, caches, and initialization state. The handler registered with onError is kept.
primeLocation(): Promise<GeoLocation> Explicitly prompts when needed and obtains the initial high-accuracy fix. Call from a user gesture.
requestLocationPermission(): Promise<GeoLocation> Alias of primeLocation() for permission-oriented flows.
estimateLocation(options?: { userId?: string }): Promise<LocationEstimateResult> Uses network probes to estimate country, province, city, and an approximate point with a 90%-containment radius — without triggering a location prompt. It resolves to null fields when no estimate is available and does not throw for internal failures.
evaluateEmail(options: EvaluateEmailOptions): Promise<void> Submits a registration email for operator-side evaluation. It is fire-and-forget: the endpoint returns an empty response and SDK errors are swallowed so registration is not interrupted.
getDeviceId(): Promise<DeviceIdResult | null> Returns the device ID Kade assigned to this browser in your workspace, for A/B tests and analytics. Cached per tab session; concurrent calls share one request. Resolves null when no ID is available, never throws, and never prompts for location. See Device ID.

Location permissions

Browsers are most reliable when permission is requested in direct response to a user click or tap.

const allowButton = document.querySelector('#allow-location');

allowButton.addEventListener('click', async () => {
  try {
    const location = await sdk.primeLocation();
    console.log(location.latitude, location.longitude, location.accuracy);
  } catch (error) {
    console.error('Location was unavailable', error);
  }
});

Browser location

Omit skipLocation. The SDK uses its location buffer and watcher after the initial fix. Permission denial is represented in the ping flow and may produce a block response.

IP fallback only

Pass skipLocation: true to avoid browser geolocation. The server can use request-network location signals when available; accuracy and availability are environment dependent.

Network-only estimate

const estimate = await sdk.estimateLocation({ userId: 'player-123' });

if (estimate.province || estimate.country) {
  console.log(estimate.province?.code, estimate.country?.code);
  // City and point estimate (null when the model doesn't commit,
  // or on servers that predate them):
  console.log(estimate.city?.name, estimate.city?.metroArea);
  console.log(estimate.location?.lat, estimate.location?.lon,
              estimate.location?.radiusKm);
} else {
  // No answer: feature disabled, insufficient beacons, or degraded scoring.
}

Email evaluation

Submit registration identity data for server-side fraud evaluation. The verdict is available to operators through backoffice or webhooks, never returned to the browser.

await sdk.evaluateEmail({
  email: 'new.user@example.com',
  firstName: 'New',
  lastName: 'User',
  userId: 'player-123'
});
This method posts to /public/email-check using the same compression, encryption, and optional request signing as ping(). If the crypto path is unavailable the SDK falls back to sending the plain JSON body, which the server still accepts.

Your own fields: metadata

Send your traffic channel as trafficSource, under the label you use yourself (for example Instagram, Referred, Organic). Anything else you know about the registration that has no option of its own — ad click IDs, campaign tags, your own fields — goes in metadata, under names you choose. Kade stores it with the check and uses the click IDs to link registrations that arrived through the same ad click.

const url = new URL(window.location.href);

await sdk.evaluateEmail({
  email,
  firstName,
  lastName,
  userId: 'player-123',
  trafficSource: 'Instagram',
  metadata: {
    facebookClickId: url.searchParams.get('fbclid') ?? undefined,
    googleClickId: url.searchParams.get('gclid') ?? undefined,
    redtrackClickId: rtClickId,
    utmCampaign: url.searchParams.get('utm_campaign') ?? undefined,
  },
});

Kade recognises these names for the identifiers it uses:

Key (use this name)Also recognisedWhat it is
facebookClickIdfbclid, fbClickIdMeta (Facebook / Instagram) ad click ID: the fbclid parameter of the landing URL.
googleClickIdgclid, gClickIdGoogle Ads click ID: the gclid parameter of the landing URL.
redtrackClickIdrtclickid, rtkclickidRedTrack click ID.
microsoftClickIdmsclkidMicrosoft Advertising click ID: the msclkid parameter of the landing URL.
tiktokClickIdttclidTikTok ad click ID: the ttclid parameter of the landing URL.
utmCampaignutm_campaign, campaignThe campaign tag (utm_campaign).

Keys are matched ignoring case and _ . -; when several names for the same ID are sent, the name in the first column wins. Any other key is stored as sent, so you can add fields without waiting for an SDK release. Values must be flat (string, number or boolean); anything else is dropped, never an error. The server keeps at most 50 keys (letters, digits, _, ., -; up to 64 characters) and strings up to 512 characters. Send click IDs as strings, never as numbers: a numeric ID longer than about 15 digits loses its last digits when it is turned into JSON, before it reaches Kade.

Read the click IDs from the landing URL when the visitor arrives and keep them (for example in sessionStorage) until the registration is submitted: the sign-up page's own URL usually no longer carries them. Web SDK 1.1.0 and later send metadata; earlier versions drop it.

Form monitor

Records how the registration form was filled — never what was typed — and sends it with the next evaluateEmail() as formTelemetry. Per field: focus order and dwell, key, delete and paste counts, typing cadence, browser autofill and page-driven fills. Fields of type=password are never observed; no value, key identity or clipboard text is ever read into the record.

// Start it when the registration page loads (before the user types):
const sdk = new KadeSDK({ apiToken: 'YOUR_TOKEN', formMonitor: { autoStart: true } });
// or explicitly:
sdk.startFormMonitor();

// Your address picker filled the street field itself? Say so, so it is
// not read as pasted or autofilled:
sdk.markFieldFilledProgrammatically(streetInput); // element, or its autocomplete / name / id

// On submit, the record goes with the check automatically:
await sdk.evaluateEmail({ email, firstName, lastName });

sdk.stopFormMonitor();
startFormMonitor(options?: FormMonitorOptions): void strategy: 'delegate' (default — capture-phase listeners on the root, sees every field that exists now or later, including framework re-mounts), 'attach' (a MutationObserver attaches listeners per field; pass root for a shadow root delegation cannot see) or 'poll' (a periodic scan, pollIntervalMs, default 1000). exclude(el) leaves extra fields alone; persist: false turns off the sessionStorage mirror that lets a reload or multi-step form keep the record.
stopFormMonitor(): void Stops observing. The record collected so far still goes with the next check; destroy() drops it.
markFieldFilledProgrammatically(target: Element | string): void Marks a field as filled by the page (address picker, prefill).
getFormTelemetry(): FormTelemetry | null The record as it would be sent now — for checking an integration. null until a field has been touched.
Pass includeFormTelemetry: false to evaluateEmail() to leave the record out of one check. None of these methods throws into your page.

Device ID

getDeviceId() returns the device ID Kade assigned to this browser in your workspace: a stable key for A/B-test bucketing and analytics. It is cheap to call on every page load.

const device = await sdk.getDeviceId();

if (device) {
  // { deviceId: 'dev_…', match: 'known' | 'matched' | 'new',
  //   firstSeenAt: '2026-10-01T12:00:00.000Z', cached: false }
  assignVariant(device.deviceId); // your A/B bucketing
} else {
  // No ID: feature not enabled, origin not allowed, rate-limited,
  // timed out, or an older server. Carry on without one.
}

match says how Kade resolved the device: known (this browser's device key was already linked), matched (a new key matched a device Kade already knew, for example after cleared site data) or new. cached is true when the answer came from this tab's session cache instead of a request.

The ID can change. When Kade later finds that two IDs are the same device, or that one ID is really two devices, it tells your backend with the DEVICE_MERGED and DEVICE_SPLIT webhooks (see the webhook documentation). The cache lives in sessionStorage, so a new tab or visit asks again and gets the current ID.

The call posts to /public/device with the same compression, encryption, and optional request signing as ping(), and gives up after 2.5 seconds. Unlike evaluateEmail() it never falls back to a plain body: if encryption is unavailable it resolves null without a request. It never throws; unexpected failures (5xx, network errors) are also reported to your onError handler.

Address autocomplete

sdk.address fills a registration form's address from the Kade Address API: the user types, picks a row, and you get the address as form fields. It uses the same apiToken, payload encryption and signingSecret as pings, and the same host (https://api.kade.io/address), so your page needs no extra configuration and no Content Security Policy change.

Before you start, Kade enables it for your workspace. Send us the exact origins of the pages that use it (for example https://www.example.com); calls from any other origin are refused. For the KYC callback (below) you also get a server secret, which belongs on your backend only. Coverage today: Canada.

1. Suggest as the user types

const sdk = new KadeSDK({
  apiToken: 'your-api-token',
  signingSecret: 'your-workspace-signing-secret'
});

const input = document.querySelector('#address');
let timer;

// Optional: start the session when the field first gets focus, to show
// "Is this your address?" rows before anything is typed. Without this,
// the first suggest() starts the session itself.
input.addEventListener('focus', async () => {
  const { gpsSuggestions } = await sdk.address.startSession();
  if (!input.value && gpsSuggestions.length) render(gpsSuggestions, 'gps');
}, { once: true });

input.addEventListener('input', () => {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    const r = await sdk.address.suggest(input.value);
    if (r.stale) return;               // a newer keystroke already answered
    if (r.error) return showManualEntry();
    render(r.items, 'suggest');        // each row's display is ready to show
  }, 120);                             // debounce 100–150 ms
});

Every method resolves; none throws. A failed call comes back with an error field (or null from select() and getAddress()) and is also reported to onError. On any error, let the user type the address by hand.

2. Open the row the user picks

Each suggestion has a type:

typeWhat it isWhen it is picked
addressOne address.Call select() (step 3).
buildingA building with units (unitCount).List its units with units(row.id) and let the user pick one.
streetA street in a town (addressCount), offered while no house number is typed.List its addresses with street(row.id), in house-number order.

Treat any other type as address.

// A building: its units in natural order (101, 102, … PH1), up to 1000 at once.
const page = await sdk.address.units(row.id, { size: 1000 });
// page.units: [{ id, unit: '1201', display }], page.total, page.next
// Filter the list as the user types the unit, or ask the server:
//   sdk.address.units(row.id, { query: '12' })
// More than one page: sdk.address.units(row.id, { after: page.next })

// A street: its addresses, each with its house number.
const st = await sdk.address.street(row.id);
// st.addresses: [{ id, number: '12B', display, … }]
// st.complete === false: there are more; filter with the typed number:
//   sdk.address.street(row.id, { query: '12' })

3. Fill the form

select() records the pick and returns the address as form fields. Pass where the row was picked (via) and its position in the list you showed (rank, 0 = first).

const fields = await sdk.address.select({ id: row.id, via: 'suggest', rank: index });
// via: 'suggest' | 'units' | 'street' | 'gps'
if (!fields) return showManualEntry();

form.unit.value       = fields.unit ?? '';
form.number.value     = fields.number ?? '';
form.street.value     = fields.street ?? '';
form.city.value       = fields.city ?? '';
form.province.value   = fields.province ?? '';    // 'ON'
form.postalCode.value = fields.postalCode ?? '';  // 'M5V 2T6'
FieldTypeMeaning
unit, number, street, citystring | nullThe address split for your form; number keeps its suffix (12B).
provincestring | nullProvince or territory code, e.g. ON.
postalCodestring | nullPostal code.
postalCodeInferredbooleanThe postal code was inferred from neighbouring addresses; consider letting the user confirm it.
displaystringThe whole address on one line.
location{ lat, lon } | nullThe address's coordinates.
addressId, locationIdstring, string | nullKade's identifiers for the address and its building.

getAddress(id) returns the same fields without recording a pick, e.g. to preview a row.

Special cases

A unit we don't have

When the typed unit isn't in Kade's data, suggest() returns its building with unitNotFound: true and typedUnit. Keep that unit in the form's unit field and pass it on: select({ id, rank, typedUnit }).

The user types it by hand

Call sdk.address.selectManual() when the user gives up on the suggestions and fills the fields themselves. It's how Kade measures addresses the search didn't find.

Location

The SDK sends the newest location fix it already holds, if fresh, so nearby addresses rank first. It never prompts for permission. startSession({ location }) sets one explicitly; { location: null } sends none.

Sessions

A session starts on first use and is renewed automatically once when it expires. Call sdk.address.reset() when the form is reset or a new registration starts.

4. Report the KYC result (your backend)

Send sdk.address.getSessionId() with the registration form. When your KYC check finishes, your backend reports the result. This call is server to server: it needs the server secret, which must never reach the browser.

curl -X POST https://api.kade.io/address/v1/kyc-callback \
  -H 'Content-Type: application/json' \
  -H "x-api-key: $KADE_API_TOKEN" \
  -H "x-server-secret: $KADE_ADDRESS_SERVER_SECRET" \
  -d '{"session_id": "0c112d…", "result": "pass"}'
# result: pass | fail | review | abandoned. Response: 204.

Error codes

errorMeaning
networkThe request didn't complete (offline, or no answer within 5 seconds).
no_sessionA session couldn't be started; the next call tries again.
origin_not_allowed, unknown_api_keyThe page's origin or the API token isn't enabled for the Address API. Contact Kade with the origin.
signature_*Signing failed or doesn't match: check signingSecret and the device clock.
session_capToo many searches in one session; reset() starts a new one.
blockedRefused by the firewall, e.g. too many requests from one IP address.
http_<status>Any other failure, e.g. http_503.

Codes may be added over time: handle any unknown code like the others, by falling back to manual entry.

Configuration

Common configuration

OptionTypeBehavior
apiTokenstringRequired API token sent as x-api-key.
serverUrlstring?Defaults to https://api.kade.io.
regionIdnumber?Default region for pings; a ping-level value overrides it.
signingSecretstring?Enables HMAC-SHA256 on encrypted ping, server fingerprint, email evaluation and sdk.address requests.
locationStrategy'race' | 'sequential'?Location retrieval strategy; defaults to race.
stopOnPermissionBlockboolean?Stops continuous pinging on a location-permission block when true; defaults to false. Other blocked responses always stop the loop.
addressServerUrlstring?Address API used by sdk.address; defaults to serverUrl + /address.

PingOptions

interface PingOptions {
  userId?: string;
  silent?: boolean;
  skipLocation?: boolean;
  source?: string;
  regionId?: number;
  email?: string;
  firstName?: string;
  lastName?: string;
}

Advanced location tuning

Advanced options include locationMaxAge, locationMaxStalenessRadius, locationMaxAgeCeilingMs, locationMaxAgeAssumedSpeedMps, locationRecoveryAfterMs, locationRecoveryMinIntervalMs, locationRecoveryFailureCooldownMs, locationRecoveryMaxAccuracy, and locationFixSendCapMs. Their defaults coordinate caching, movement assumptions, and recovery throttling and should normally remain unchanged. Adjust them only with Kade integration guidance.

Response handling

ping() resolves to PingResponse. A matched area is represented by PingArea { id, name }.

interface PingArea {
  id: number;
  name: string;
}

interface PingResponse {
  inside: boolean;
  status: number;
  message?: string;
  code?: KadeResponseCode;
  interval: number;
  distanceToBorder?: number;   // absent from block responses
  regionId?: number | null;    // null when no region matched
  area?: PingArea | null;      // null when no area matched
  blocked?: boolean;
  clientId?: string;
}
const response = await sdk.ping({ userId: 'player-123' });

if (response.blocked) {
  handleBlocked(response.code, response.message);
} else if (response.inside) {
  console.log(`Matched ${response.area?.name ?? 'configured area'}`);
} else {
  console.log(`Outside by ${response.distanceToBorder} metres`);
}

Known block response codes

CodeMeaning
BLOCKEDGeneric security or compliance rejection.
BLACKLISTEDThe client is blacklisted.
DEV_TOOLS_DETECTEDDeveloper tools or debugger evidence caused the block.
VPN_DETECTEDVPN, proxy, hosting, or related network evidence caused it.
DEVELOPER_MODE_DETECTEDDevice developer mode or attached-debugger evidence caused it; mainly relevant to the shared mobile contract.
EMULATOR_DETECTEDAn emulator or simulator contributed to the block.
LOCATION_PERMISSION_MISSINGLocation permission was unavailable for verification.

The server can return other reason codes as well, such as OUT_OF_REGION or SUSPENDED, and the response type permits future string codes. Handle unknown codes as blocked when blocked === true.

Request signing

When signingSecret is configured, the SDK applies HMAC-SHA256 only to encrypted ping(), server fingerprint, evaluateEmail() and sdk.address requests.

const sdk = new KadeSDK({
  apiToken: 'your-api-token',
  signingSecret: 'your-workspace-signing-secret'
});

Message and header format

The signed message is timestamp.nonce.JSON.stringify(encryptedPayload). The returned signature header has this format:

X-Signature: t=1708012345678,n=a1b2c3d4e5f6...,s=64_character_hex_hmac
X-Request-Time: 1708012345678

The timestamp and random nonce are generated by the signing function. Signing failures are best-effort and do not change the encryption applied to these payloads.

Client-side secrets are visible to the browser user. Treat request signing as payload-integrity support, not as a way to hide a permanent credential in public JavaScript. Follow your Kade workspace's provisioning and rotation policy.

TypeScript

The npm package includes its declarations. npm runtime users receive them automatically; CDN users can install the same package only for compile-time types.

npm install --save-dev @kade-technologies/web-sdk@1.1.0
import type {
  FingerprintResult,
  PingOptions,
  PingResponse,
} from '@kade-technologies/web-sdk';

const options: PingOptions = { userId: 'player-123' };
const result: PingResponse = await sdk.ping(options);
const fingerprint: FingerprintResult = await sdk.getFingerprint();
import type is removed from emitted JavaScript. It does not load or bundle a second SDK runtime, so the CDN remains the only runtime source.

Key exported types

KadeConfig, PingOptions, PingResponse, PingArea, FingerprintResult, FingerprintServerResponse, EvaluateEmailOptions, GeoLocation, LocationEstimateResult, DeviceIdResult, and for sdk.address: AddressApi, AddressSuggestion, AddressSuggestResult, AddressUnitsResult, AddressStreetResult, AddressChoice and AddressDetails.

Playground

Exercise the bundle loaded by this page. Credentials entered here are used only by the in-page SDK instance.

Waiting for an action.

Best practices

Initialize once

Create one SDK instance and call init() at a predictable startup point. Handle both rejected promises and onError notifications.

Explain location use

Ask from a clear user gesture and provide context before the browser prompt. Handle denial without trapping the user.

Choose a location mode

Pass skipLocation per call when a check must not use browser location; a later call without it can request location again.

Clean up

Stop continuous checks when the flow ends and call destroy() when disposing the integration.

Need help with your integration?

Talk to the Kade team about implementation, configuration, or moving your location checks into production.

Contact Kade