@kya-os/checkpoint-beacon
v1.5.0
Published
Checkpoint client-side beacon for AI agent detection and analytics (formerly @kya-os/agentshield-beacon)
Readme
@kya-os/checkpoint-beacon
Client-side beacon for AI agent detection. It collects browser, performance, interaction, and fingerprint signals from a page and sends them to Checkpoint, where classification happens; the beacon itself never returns a verdict.
The full, verified guide is the Beacon page on the docs site, and the Beacon reference covers the API, sessions, data collection, delivery, and network and CSP detail. This README is the short version.
Features
- 🚀 Lightweight - Collection waits for browser idle time; the classic script build is budgeted at 32 KB gzipped
- 📊 Rich signals - Browser environment, navigation and paint timing, interaction counts, and curated fingerprint entropy on every event
- 🔄 Optional Web Worker - Delivery moves off the main thread automatically when the browser supports it; disable with
useWorker: false - 🔌 Framework Agnostic - Works with React, Vue, Angular, or vanilla JS
- 📦 Immediate delivery - Every send goes out on its own, gzip above 1 KB, retries with backoff
- 🔒 Privacy controls - Honors Do Not Track by default, strips URL fragments by default, optional query scrubbing and IP truncation
- 💾 Offline Support - Queue events in IndexedDB when offline, send when back online (in memory only while Do Not Track is on)
- 🎯 TypeScript Support - Full type definitions included
Installation
# npm
npm install @kya-os/checkpoint-beacon
# pnpm
pnpm add @kya-os/checkpoint-beacon
# yarn
yarn add @kya-os/checkpoint-beaconQuick Start
import { CheckpointBeacon } from '@kya-os/checkpoint-beacon';
// Initialize the beacon (same projectId as pixel!)
const beacon = new CheckpointBeacon({
projectId: 'acme-corp', // Same as data-project-id in pixel
});
// Construction sends the arrival page view; call collect() again only on a
// client-side route change.
// Track custom events
beacon.trackEvent('button_click', {
buttonId: 'signup-cta',
page: '/home',
});
// Clean up when done
beacon.destroy();CDN Usage
<script src="https://cdn.jsdelivr.net/npm/@kya-os/checkpoint-beacon/dist/beacon.min.js"></script>
<script>
const beacon = new CheckpointBeacon({
projectId: 'acme-corp', // Same as pixel
});
// Construction sends the arrival page view.
</script>window.CheckpointBeacon in this classic-<script> build is the
CheckpointBeacon class itself (constructible directly, as above), not a
namespace object with a .CheckpointBeacon property. Nothing shipped
depended on the older namespace-object shape, but note the change if you
were reading window.CheckpointBeacon for any reason other than
constructing it.
The lazy signals chunk (beacon-lazy-signals.min.js) is resolved as a
sibling of this file, so it loads from the same CDN directory with no extra
configuration. The script build strips console output, so debug and
logLevel only produce logs in the npm build.
Configuration
const beacon = new CheckpointBeacon({
// Required
projectId: 'acme-corp', // Same as pixel's data-project-id
// Optional
environment: 'production', // Tag your environment
tags: {
// Custom segmentation
version: '2.0.0',
region: 'us-east',
},
identity: { userId: 'user_123' }, // When the page already knows the visitor; otherwise call identify()
batchSize: 10, // @deprecated no-op, kept only so old configs still compile
flushInterval: 5000, // @deprecated no-op, the beacon dispatches on evidence, not a timer
evidenceGrowthFactor: 2, // send again once evidence has doubled since the last send
postureRefreshFraction: 0.5, // an interaction past this fraction of the posture TTL refreshes it
triggers: { unload: true }, // any of arrival, signals, interaction, untrusted, posture, unload can be turned off
proactiveRefreshMinIntervalMs: 30000, // low-frequency posture-refresh backstop, jittered against proactiveRefreshMaxIntervalMs (default)
proactiveRefreshMaxIntervalMs: 60000, // upper bound of that jitter window (default)
proactiveRefreshOnVisibilityResume: true, // force a refresh on visibility resume only if posture is stale (default)
proactiveRefreshOnOnline: true, // force a refresh when the browser regains connectivity (default)
maxQueueSize: 500, // Optional cap on queued batches; unset, only the storage budgets apply (default)
retryAttempts: 3, // Attempts per batch, including the first (default)
retryDelay: 2000, // Base retry delay in ms, doubling per attempt (default)
respectDoNotTrack: true, // Honor the browser DNT signal (default)
stripUrlFragment: true, // Strip #fragment from url/referrer (default)
scrubQueryParams: ['utm_source'], // Also redact these query params, even when allowlisted (default: none; every value but the utm ones is redacted anyway)
dropQueryParams: false, // Drop the whole query string from url/referrer (default)
anonymizeIp: true, // the server stores only a /24 (IPv4) or /48 (IPv6) prefix (default); false keeps the full address
// sessionTimeout: 2 * 60 * 60000, // Explicit idle gap in ms, up to six hours; the default is 1 hour on phones, 6 hours elsewhere
useWorker: true, // Worker processing is on by default; needs a same-origin worker script
// workerUrl: '/static/beacon.worker.js', // Required with a bundler; see Web Worker below
endpoint: 'https://kya.vouched.id/api/v1/beacon', // Where events go (default)
// High-volume installs: point at the durable ingest Worker instead. It
// acknowledges at the edge after durable admission (no origin round trip
// on the request path), issues the session nonce itself and serves posture
// from a per-session store; see "Durable ingest Worker" below.
// endpoint: 'https://checkpoint-beacon-ingest.kya-os.workers.dev/api/v1/beacon',
debug: false, // Debug logging (npm build only)
logLevel: 'error', // 'error' | 'warn' | 'info' | 'debug' (default 'error')
});A Do Not Track visitor (respectDoNotTrack: true, the default, with the browser's DNT signal on) never receives the _as_beacon_session cookie, and one they already hold is expired: the session id still exists in memory for the life of the page, and the only write to document.cookie is that expiry.
A session ends on events, with one timer as a fallback. The _as_beacon_session cookie (a UUID) and its sibling _as_beacon_session_meta (<campaignHash>.<userHash>, two 8-hex hashes, either may be empty) share a sliding expiry advanced by visitor input, navigation, and explicit collection or custom events. Automatic posture refresh, recovery, unload, and header reads do not extend the idle gap. That gap is one hour on phones and six hours elsewhere. sessionTimeout (milliseconds) overrides both, up to six hours. A new session starts when the idle gap passes, when identify() names a different user than the one recorded for the session, when identify() is called with no argument after a user was recorded, and when a page loads with campaign parameters (utm_source, utm_medium, utm_campaign, utm_term, utm_content, gclid, fbclid, msclkid) that differ from the stored ones (the new session keeps the user already recorded). A load with none of them, and the referrer, never start a session. Identifying an anonymous session records the user on it without splitting it. Both cookies follow the same rule as every other write here: a Do Not Track visitor, or one whose consent is withheld, never receives either.
The beacon also shares the pixel's persistent device id. Unless that same Do Not Track rule applies, each send reads the first-party identity cookie (checkpoint_user, then the legacy agentshield_user), mints a UUID when it holds none, rewrites both cookies for 365 days, and sends the id as deviceId beside sessionId only after reading it back from the cookie it wrote, so a browser that drops the write sends none. A stored id is sent only when it is a UUID the server accepts (versions 1 to 8, or the nil or max UUID). When two copies of one identity cookie hold different values, the beacon sends no id and writes nothing, and does not fall back to the other cookie. In worker mode the worker holds the id the page last handed it and replays queued batches under it, and the page clears it in the worker when Do Not Track is switched on. The cookie is host-wide on a registrable domain and secure on https, exactly as the pixel writes it, so a page running both keeps one id. Other fields the pixel stored in that cookie (userId and so on) are preserved.
requireConsent, grantConsent() and the loader's data-require-consent are accepted and ignored, so existing installs and typed configs keep working (the first use on a page logs one console.warn saying so): the beacon withholds nothing on consent. The hosted loader keeps one exception: on a Shopify storefront it waits for Shopify's Customer Privacy API to allow analytics, and expires the identity cookies when it does not. Everywhere else only Do Not Track (respectDoNotTrack) stops collection; storage the browser blocks only removes what would be stored (no device id is sent, the session id lives in memory). CheckpointBeacon.clearIdentity() still expires both identity cookies on request.
Every option, with its default, is documented on the
BeaconConfig type and rendered as the
options table on the docs site.
url and referrer are redacted client-side, before either field is collected. By default they keep
the scheme, host and path, redact path segments that look like an email address, a phone number or a
secret token, keep every query parameter name, replace every query value with "[redacted]" except
utm_source, utm_medium, utm_campaign, utm_term and utm_content (also redacted when they look
like an email address, a phone number or a token), and drop the fragment and any credentials. See
NETWORK_CONTRACT.md for the full data-inventory writeup.
Web Worker
Worker mode is on by default in supported browsers. The beacon creates a classic worker from
workerUrl, otherwise from beacon.worker.js next to the <script> tag that loaded
beacon.min.js, otherwise from /beacon.worker.js at the site root. Classic workers must be
same-origin, so with a bundler (no script tag) host dist/beacon.worker.js (exported as
@kya-os/checkpoint-beacon/worker) on your own origin and pass workerUrl. The same applies to the
lazy signals chunk: host dist/beacon-lazy-signals.min.js (exported as
@kya-os/checkpoint-beacon/lazy-signals) and pass lazySignalsUrl, or those 21 signals are never
collected. If the worker cannot start, the beacon falls back to the main thread silently.
For bundled or proxied installations, configure both companion assets explicitly:
const beacon = new CheckpointBeacon({
projectId: 'YOUR_PROJECT_ID',
workerUrl: '/static/beacon.worker.js',
lazySignalsUrl: '/static/beacon-lazy-signals.min.js',
});
beacon.collect('pageview');Serve both assets from the same package version as your beacon. workerUrl also controls the
canvas and WebGL render worker when Worker and OffscreenCanvas are available, including
when your main script is renamed or bundled into an application. Render collection uses a
separate worker from the processing and batching worker controlled by useWorker. Audio and
permissions collection remain on the main thread. Browsers without worker-rendering support,
or with a worker blocked by CSP or a loading error, retain the main-thread fallback.
Changing workerUrl through updateConfig applies to subsequent render collections.
Set useWorker: false to disable the processing worker explicitly. Page metadata, interaction
listeners, audio, and other page-dependent browser APIs still run on the main thread.
Integrity check on the lazy signals chunk
beacon.min.js embeds the SHA-384 hash of beacon-lazy-signals.min.js from the same build. The
beacon loads the chunk with that hash as its integrity and with crossorigin="anonymous", so a
chunk that differs by a single byte from the one it shipped with never runs. The beacon then
behaves as it does when the chunk fails to load: collection continues with fewer signals. An
explicit lazySignalsUrl is checked against the same hash, so copy beacon-lazy-signals.min.js
from the same package version as beacon.min.js. The worker file has no integrity check, because a
Worker constructor has no integrity option, and classic workers must be same-origin, so with
useWorker on, pass a same-origin workerUrl. Otherwise the worker cannot start and the beacon
uses the main thread.
A same-origin chunk, and the default install next to beacon.min.js, need nothing extra. A chunk on
another origin needs the host to send Access-Control-Allow-Origin (a specific origin or *) on
beacon-lazy-signals.min.js. Without it the browser refuses the chunk.
Framework Integration
React
The constructor reads window and navigator, so construct the beacon in browser-only code (an
effect, a mounted hook, or a plain browser script), never at module top level in code that also
runs on the server.
import { useEffect } from 'react';
import { CheckpointBeacon } from '@kya-os/checkpoint-beacon';
function App() {
useEffect(() => {
const beacon = new CheckpointBeacon({
projectId: process.env.REACT_APP_CHECKPOINT_PROJECT_ID,
environment: process.env.NODE_ENV,
});
const onPageHide = () => beacon.trackPageUnload();
window.addEventListener('pagehide', onPageHide);
return () => {
window.removeEventListener('pagehide', onPageHide);
beacon.destroy();
};
}, []);
return <div>Your App</div>;
}Vue
<script setup>
import { onMounted, onUnmounted } from 'vue';
import { CheckpointBeacon } from '@kya-os/checkpoint-beacon';
let beacon;
onMounted(() => {
beacon = new CheckpointBeacon({
projectId: import.meta.env.VITE_CHECKPOINT_PROJECT_ID,
environment: import.meta.env.MODE,
});
});
onUnmounted(() => {
beacon?.destroy();
});
</script>Next.js
App Router (Recommended)
// app/providers/beacon-provider.tsx
'use client';
import { useEffect } from 'react';
import { CheckpointBeacon } from '@kya-os/checkpoint-beacon';
let beacon: CheckpointBeacon | null = null;
export default function BeaconProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
if (!beacon) {
beacon = new CheckpointBeacon({
projectId: process.env.NEXT_PUBLIC_CHECKPOINT_PROJECT_ID!,
// Workers are opt-in and default to off; enable explicitly if needed:
// useWorker: true
});
}
return () => {
if (beacon) {
beacon.destroy();
}
};
}, []);
return <>{children}</>;
}
// app/layout.tsx
import BeaconProvider from './providers/beacon-provider';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<BeaconProvider>{children}</BeaconProvider>
</body>
</html>
);
}Pages Router
// pages/_app.js
import { useEffect } from 'react';
import { CheckpointBeacon } from '@kya-os/checkpoint-beacon';
let beacon;
export default function App({ Component, pageProps }) {
useEffect(() => {
if (!beacon) {
beacon = new CheckpointBeacon({
projectId: process.env.NEXT_PUBLIC_CHECKPOINT_PROJECT_ID,
// Workers are on by default when supported; pass useWorker: false to disable.
});
}
return () => {
if (beacon) {
beacon.destroy();
}
};
}, []);
return <Component {...pageProps} />;
}Next.js: Serve the worker and lazy chunk from your public assets directory and configure their URLs in development and production. Without an accessible worker asset, processing falls back to the main thread.
API Reference
Core Methods
new CheckpointBeacon(config)
Creates a beacon. It sends one pageview at construction (the arrival event), then dispatches
again only at an evidence transition, the first counted interaction, evidence doubling, the first
untrusted input, a counted interaction after the posture token goes stale, or the page being hidden
or unloaded. There is no timer: it never polls. Throws Project ID is required for Checkpoint
Beacon when projectId is missing or empty; every other option has a default. There is no
start() method.
beacon.collect(eventType?)
Run a collection round and send one event immediately. eventType defaults to 'pageview'; the
valid types are listed under Event Types. Under Do Not Track it resolves without
doing anything.
beacon.trackEvent(name, metadata?)
Send a custom event. Your metadata is spread into the event envelope, then eventName,
sessionId, timestamp, and identity are set on top of it. The name and metadata travel with
the event and pass validation, but the ingest endpoint currently persists only the event type, the
session id, and the identified user id, so custom metadata does not appear in the dashboard today.
beacon.prepareForAction({ action, maxPostureAgeMs?, maxWaitMs? })
Refresh posture evidence and wait for a posture token. Returns a Promise<void> that resolves at
the first of these: the beacon holds a usable token (an unexpired token counts, even one older than
maxPostureAgeMs), maxWaitMs has elapsed (default 3,000), or posture is withheld or switched off
(ingest withheld a token for a terminal reason such as domain-unset or origin-mismatch, Do Not
Track is on, or the beacon was destroyed). It never rejects.
The refresh it starts is a no-op if posture is already fresh (age under maxPostureAgeMs, default
30s), a refresh is already in flight, one settled too recently, or the beacon is already retrying a
pending posture. Calling it on every keystroke or pointer move still costs at most one request.
On a first visit, a page's first token is readable only after the first beacon request returns. A
call to your API made before then carries no token and is reported absent. Await this method
before that call. Once a token exists the await resolves at once, so later calls pay nothing.
maxWaitMs is limited to 0 through 10,000: a value outside that range is clamped, and a value that
is not a finite number uses the 3,000 default:
generateButton.addEventListener('focus', () => {
checkpoint.prepareForAction({ action: 'image_generate', maxPostureAgeMs: 30_000 });
});
async function onGenerateClick() {
await checkpoint.prepareForAction({ action: 'image_generate', maxPostureAgeMs: 30_000 });
await callImageGenerate();
}A call that does not await still works and sends whatever token is on hand. Where a call must never be
held, such as a latency-bound action, call prepareForAction at the moment of intent and do not await it.
beacon.trackPageUnload()
Record a pageunload event. It skips the idle wait, goes out immediately and uncompressed through
navigator.sendBeacon (or fetch with keepalive), then drains the offline queue. The beacon
already listens for visibilitychange and pagehide on its own, and skips a send when nothing has
changed since the last one, so calling this from your own pagehide handler is optional and safe
either way; you get one send, not two.
beacon.identify(identity?)
Attach a client-set identity ({ userId } and friends) to every event from now on.
Call with no argument to clear it again, for example on sign-out, so a shared device does not keep attributing the next visitor's activity to the person who left.
Naming a different user than the one already recorded for the session, or clearing it, starts a new session; naming a user on an anonymous session does not.
beacon.getPostureHeaders()
getPostureHeaders(): Record<string, string>The headers to attach to requests to your own backend, including one on another host, so it can read
the posture verdict; the beacon's cookies are host-only and do not travel there. A synchronous, pure
read: no network, no storage writes. It returns KYA-Posture-Session for the active browser session,
or an empty object after the session's idle deadline. It adds KYA-Posture only when an unexpired
token is available for that project and session. A session change immediately stops use of the old token. The latest token is the
newest: a receipt that arrives late does not replace a newer unexpired token for the same binding
(the newer issue time wins, and a later clean token does not replace an agent-driven one while that
one is unexpired, the same rule the posture cookie uses). When Do Not Track blocks collection,
the beacon clears the token and its reload cache. Destroying the last beacon clears its
in-memory token. On HTTPS, a new instance restores an unexpired token from session storage only
for the same project, origin, and session. Background renewal replaces the 120-second credential
without extending the session's idle deadline. A first visit still needs the first server response
before a signed token is available; missing posture remains unknown.
await fetch('https://api.example.com/generate', {
method: 'POST',
headers: { ...beacon.getPostureHeaders() },
});For a cross-origin request, add both header names to the API's Access-Control-Allow-Headers.
beacon.getSessionId()
The session id the beacon stamps on every event it sends (metadata.sessionId), so you can correlate what you show the visitor with the rows that land server-side.
A genuine read: polling it does not count as activity, so it neither extends the session past its idle gap nor touches the cookies.
This is the client-side id. The server assigns its own consolidated session id and returns it as sessionId on every accepted POST /api/v1/beacon receipt ({ success, accepted, sessionId, posture?, integrity?, nonce }). That value is the key for GET /api/v1/projects/{projectId}/sessions/{sessionId}, so a backend that stores it at collection time can fetch the visit later.
beacon.handoffUrl(url)
Returns a promise of url carrying a checkpoint_handoff query parameter, so a visitor who follows a link from one of your origins to another keeps one session. url may be relative; it resolves against the current page.
link.href = await beacon.handoffUrl('https://shop.example.com/cart');It posts { projectId, sessionId, nonce, deviceId, userHash } to <endpoint>/handoff, where userHash is the hash of the user the beacon is identified as (left out when anonymous), and nonce is the ingest nonce the server last handed back for this session (proof the session was observed) and deviceId is the persisted device id, left out when none is persisted. The token that comes back is opaque and stored on the server; it expires after 15 minutes and works once. Each session id can be adopted at most twice, one issuing device can hand off to at most three distinct devices in the 30 days after its first handoff, and one verified network and user agent can hand off to at most 20 distinct devices per hour, not counting redeemers on the same network and user agent as the issuer, so a link shared publicly can merge a few visitors, not an audience. A repeat use by the same redeemer within 15 minutes of the redemption returns the same session; any other later use starts a fresh session. It resolves the original url, unchanged and without a request, when Do Not Track applies, or the session has no stored nonce yet. It also resolves it unchanged, after the request, when the mint fails for any reason (network error, non-2xx including a refused nonce, malformed body). It never rejects.
The beacon on the destination page reads the parameter at load, sends it as handoffToken on the first batch only (with ~ and the hash of the user it is identified as appended when it is), and removes it from the address bar once the server answers adopted or rejected. It adopts the answer only if the session id is unchanged since that batch was sent, so an identify() to another user or a reset in between keeps the new session. A Do Not Track visitor has it stripped at load and never redeems it. A destination identified as a different user than the issuer is answered rejected, keeps its own session and leaves the token unspent; an anonymous destination records the issuer's user on the adopted session. The parameter never appears in the url or referrer the beacon reports. If no answer arrives, the parameter stays and the next load tries again. A handoff.status of unavailable means Checkpoint could not reach its handoff state in time: the parameter stays in the address bar and the next batch sends the token again. After three attempts that all answer unavailable, the beacon drops the token and removes the parameter.
The beacon sends its public key on every batch that has one, marks a batch without one with keyless (1 while the key is pending, 2 when none will come), and ignores announceKey in an ingest response.
beacon.updateConfig(updates)
Merge configuration at runtime. Changing useWorker, enableWebWorker, workerUrl, or
workerConfig restarts the worker; flipping respectDoNotTrack stops or resumes collection
mid-session. flushInterval and batchSize are accepted and ignored (deprecated no-ops).
endpoint, sessionTimeout, sessionCookieName, and lazySignalsUrl are read once at
construction and do not change here. anonymizeIp and the URL redaction options (stripUrlFragment,
scrubQueryParams, dropQueryParams) apply from the next send; changing anonymizeIp restarts the worker.
beacon.addCollector(collector)
Register an extra ICollector (exported from the package) for a signal the default set does not
carry. A second instance of an already registered class is refused; when two collectors write the
same key, the first writer wins.
beacon.destroy()
Remove the visibilitychange/pagehide listeners and the counted-interaction callback, dispose
every collector (removing its listeners), terminate the worker, and drain the offline queue.
With more than one beacon on the page (below), destroy() releases only the beacon you call it on.
More than one beacon on a page
Beacons that share a projectId share one running beacon. The second new CheckpointBeacon(...)
attaches to the first and returns a handle to it: one arrival pageview, one worker, one set of
dispatch timers, one DPoP key. Every method on the handle calls the shared beacon.
- The match is on
projectIdexactly as given.acme-corpand the project's UUID are different keys, so two beacons built with those two ids run separately. Use one id everywhere; the UUID is recommended. - The first beacon's
endpoint,lazySignalsUrl,useWorker,enableWebWorker,workerUrl,workerConfig, andtriggerswin. Each distinct conflicting value logs onewarn(npm build, whenlogLevelallows it).sessionTimeoutandsessionCookieNamealso keep the first beacon's values, without a warning. onReceiptruns for every beacon, for every receipt.- Privacy settings follow the most restrictive live handle. Each handle, the first beacon included,
contributes its own parsed value for
respectDoNotTrack,anonymizeIp,stripUrlFragment, anddropQueryParams, and its own list forscrubQueryParams. A setting a handle leaves unset (or sets toundefinedornull) contributes the default:respectDoNotTracktrue,stripUrlFragmenttrue,anonymizeIptrue,dropQueryParamsfalse, and noscrubQueryParamsnames. The shared beacon usestrueif any live handle contributestrue, and the deduplicated union of every live handle'sscrubQueryParams. It recomputes that whenever a handle callsupdateConfigor is destroyed. A handle can loosen only its own contribution: passingfalseor fewer names changes nothing while another live handle still holds the setting tight. When the first beacon callsupdateConfig({ anonymizeIp: false }), a restriction a handle set stays, and destroying that handle lifts it. Two default beacons keep fragments stripped for the survivor when the first is destroyed. A first beacon that setsstripUrlFragment: falsestays stripped while any other live handle leaves it unset, and is loosened only when that handle sets it tofalseitself or is destroyed. A later beacon that omitsrespectDoNotTrack, or passesundefinedornull, asks for the default,true. These keys log no conflictwarn. A destroyed handle'supdateConfigis ignored. Changing the effectiveanonymizeIprestarts the worker. - Everything else applies as an
updateConfigcall would, andupdateConfigon a handle follows the same rules. destroy()is reference-counted: the shared beacon stops when the last holder has released it. Destroying twice counts once. Afterdestroy(), that beacon's own methods do nothing:collect(),trackEvent()andprepareForAction()resolve with nothing sent,trackPageUnload(),addCollector()andidentify()do nothing, andupdateConfig()is ignored.getSessionId(),getPostureHeaders()andgetRequestProofHeader()still answer. A destroyed first beacon stops sending and itsonReceiptstops firing, while the shared beacon keeps running for the handles still alive. A response still in flight when the last holder is destroyed is ignored: no posture cookie, no receipt, no token fromgetPostureHeaders(), no nonce and no sent marker.- The handle's prototype is
CheckpointBeacon.prototype, soinstanceof CheckpointBeaconis true. - Only releases that carry this behavior attach to each other; an older copy on the page runs alone.
Event Types
BeaconEventType is the union the server accepts:
pageview- The arrival event sent automatically at construction; whatcollect()sends by default otherwisepageunload- Sent bytrackPageUnload()through the immediate path, and by the beacon's ownvisibilitychange/pagehidelisteners, when something changed since the last sendevidence- Sent automatically at an evidence transition (first interaction, evidence doubling, first untrusted input, posture staleness) or once, if usable, after the lazy signals chunk resolves later than the arrival roundheartbeat- No longer sent automatically. The type stays for existing deployed bundles and for callers that still invokecollect('heartbeat')directlycustom- WhattrackEvent()sends, with your name inmetadata.eventNameerrorandperformance- Accepted bycollect()for callers that want to mark a round as such
metadata.trigger on the sent event records why: arrival, interaction, untrusted, posture,
signals, hidden, pagehide, or custom.
There are no click, scroll, or form_submit event types. Interaction counts are collected
automatically by the InteractionCollector on every event; name your own moments with
trackEvent().
Browser Support
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
dist/beacon.min.js (the CDN build above) is built for exactly that floor: esbuild targets
chrome90, firefox88, safari14 and edge90, so only syntax those browsers lack is lowered.
There is no separate legacy build, and browsers older than the floor are not supported. CI parses
every built browser file for syntax esbuild can lower (nothing needed lowering at the floor), plus
a denylist of runtime APIs it cannot lower (.at(), Object.hasOwn, structuredClone,
AbortSignal.timeout, findLast, toSorted, groupBy, Promise.withResolvers,
crypto.randomUUID, Error cause, Array.fromAsync) and regex lookbehind. A hanging or failing
IndexedDB costs only the holder-of-key binding, never delivery: a send waits at most 1.6 seconds
for the key, then goes out without it while generation continues, and a failed key attempt is
retried at most once every 30 seconds. In worker mode the main thread decides and passes the key
to the worker: the first worker batch of a session carries it once, never for a Do Not Track
visitor, and the worker never waits for the key.
Bundle Sizes
beacon.min.js(CDN/classic<script>build): budgeted at 32 KB gzipped; a CI test fails the build past that (src/budget/thresholds.ts)beacon.worker.js(Web Worker script): about 8.2 KB gzipped, fetched only when usedbeacon-lazy-signals.min.js(lazy signals chunk): budgeted at 10 KB gzipped, fetched only when used- Measured on Node 22.23.1 at gzip level 9:
beacon.min.js31,618 bytes,beacon.worker.js8,150,beacon-lazy-signals.min.js9,563. The history of each budget change is indocs/bundle-budget.md - The npm entry (
dist/index.mjs) is marked side-effect free, so bundlers drop the exports you do not import
Troubleshooting
Worker never starts, or worker errors in development
Worker processing is enabled by default. Host the worker script on the same origin and
set workerUrl (see Web Worker). Check the worker request and your
worker-src CSP directive if processing falls back to the main thread. You can disable
the processing worker explicitly:
const beacon = new CheckpointBeacon({
projectId: 'your-project-id',
useWorker: false, // Disable workers
});Nothing logs even with debug: true
logLevel defaults to 'error'; set logLevel: 'debug' to see initialization and send logs.
The CDN build (beacon.min.js) strips console output entirely, so only the npm build logs.
"window is not defined" during server rendering
The constructor touches browser globals. Construct the beacon inside a client-side effect (a
'use client' component in Next.js) or a plain browser script.
Module Resolution Issues
If you get "Module not found" errors:
- Ensure you have the shared dependency:
npm install @kya-os/checkpoint-shared- Clear your module cache:
rm -rf node_modules/.cache
npm installTypeScript Issues
If TypeScript can't find types:
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}Documentation
The docs site is the canonical, verified reference; the guides that used to live in this package duplicated it and drifted, so they were removed in favour of these pages:
- Beacon guide - install, quick start, framework setup, troubleshooting
- Beacon reference - API, sessions, data collection, delivery, network and CSP
- Beacon cookbook - step-by-step React, Vue, and vanilla JS setup
- Package API reference - the exported classes and helpers beyond
CheckpointBeacon - Architecture overview and worker design - for contributors
NETWORK_CONTRACT.md- what the SDK sends, and to whom
Contributing
Contributions are welcome! Please read our Contributing Guide for details.
License
This project is licensed under the MIT OR Apache-2.0 license - see the LICENSE file for details.
Support
Durable ingest Worker
endpoint defaults to the origin. For a high-volume install, point it at the
durable ingest Worker:
endpoint: 'https://checkpoint-beacon-ingest.kya-os.workers.dev/api/v1/beacon',The Worker has one topology: every batch is durably enqueued at the edge and
acknowledged with a 202 { durableStatus: 'queued' } receipt — there is no
synchronous origin call on the request path. The receipt still carries the two
things this SDK needs from a receipt: an edge-issued nonce to echo on the next
batch, and the origin's posture answer (the token, or why it withheld one) once
an earlier batch has been replayed (the first receipts of a session say
postureStatus: 'pending', and the posture retry ladder picks the answer up).
Nothing about what the SDK sends changes.
Two things the host must arrange:
- The page's Content-Security-Policy must allow
connect-srcto the Worker's host (andscript-srcto wherever this bundle is served from). - The project id must be on the Worker's allowlist; an unlisted project receives
404for every batch, and a Worker whose allowlist is still empty answers503withRetry-Afteruntil one is added.
Browser integrity
For opt-in classification, signed posture and scoped consent step-up, see the browser integrity rollout runbook.
