Repository navigation
Guide
Two entry points:
-
@kodentuzo/spotkit, for the app's server (Node); -
@kodentuzo/spotkit/client, for the browser: no Node APIs and no dependencies.
Everything here is in Spotcraft's app contract, so an app can also do it by hand, or run elsewhere with the same env.
npm install @kodentuzo/spotkitOn Spotcraft, every app gets the instance's user pool at AUTH_URL
(<PUBLIC_URL>/_spotcraft/auth), with AUTH_ISSUER and AUTH_JWKS_URL. Locally,
spotcraft dev writes the same names to .env.
import { spotkit } from '@kodentuzo/spotkit'
const kit = spotkit() // reads AUTH_URL, AUTH_ISSUER and AUTH_JWKS_URL
export async function handle(request: Request) {
const user = await kit.user(request) // { id, isAnonymous } or null
if (!user) return new Response('Sign in first', { status: 401 })
// user.id is auth.users.id: reference it from your tables with a foreign key.
}kit.user(request) reads, in order:
-
Authorization: Bearer <JWT>: a token from the pool, checked as it is (signature against the JWKS, issuer, expiry). -
A session cookie, or
Authorization: Bearer <session token>from a client without cookies: the pool's/tokenturns it into a JWT, which is checked. The answer is kept until the token is about to expire (15 minutes), so the pool is asked once per session in that time.
It returns null when there's no session or the pool doesn't know it, and throws when the pool
fails, so a broken pool doesn't look like a signed-out visitor. kit.verifyToken(jwt) checks
one token on its own and returns { id, isAnonymous, expiresAt }.
Guests are made in the browser, with Better Auth's client pointed at the pool, so the pool limits new guests per visitor's address:
import { createAuthClient } from 'better-auth/client'
import { anonymousClient } from 'better-auth/client/plugins'
// On Spotcraft the pool is on the app's own domain; locally, use AUTH_URL from .env.
export const auth = createAuthClient({
baseURL: new URL('/_spotcraft/auth', location.origin).href,
plugins: [anonymousClient()],
})
await auth.signIn.anonymous()The session cookie is first-party on the app's domain, so the next request to the app's server
carries it, and kit.user(request) finds the guest. Expo and other clients without the app's
domain use https://auth.<apps domain>/main with the bearer plugin; their origin must be in the
instance's AUTH_TRUSTED_ORIGINS.
import { pgSchema, pgTable, uuid } from 'drizzle-orm/pg-core'
export const users = pgSchema('auth').table('users', { id: uuid('id').primaryKey() })
export const workouts = pgTable('workouts', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
})Deleting a user in the pool deletes their rows in every app. Spotcraft runs your migrations
from the image's dev.spotcraft.migrate label, so spotkit has no migration runner.
Who runs the apps and what the instance does with personal data, as data, for your privacy policy and legal notice (the contract). The owner sets their details in Spotcraft's dashboard; nothing goes into your repository.
// On the server: from LEGAL_FACTS, which Spotcraft sets (spotcraft dev writes example values).
import { legalFacts } from '@kodentuzo/spotkit'
const facts = legalFacts() // throws when LEGAL_FACTS is missing or isn't the facts
// In the browser, or a client-rendered or native app: from /_spotcraft/legal.json.
import { legal } from '@kodentuzo/spotkit/client'
const facts = await legal()facts.controller is the owner (null until they fill it in), facts.processing one entry per
processing, each with its id, legal basis, retentionDays, processor and any transfer
outside the EU. facts.updated is the policy's "last changed" date. Your page adds what your
app stores itself.
In the browser, for a "Your data" page:
import { deleteMe, exportMe } from '@kodentuzo/spotkit/client'
const pool = await exportMe() // the user, their sessions and accounts; null when signed out
// Offer it with your app's own rows, in one download.
await deleteMe() // deletes the guest, and their rows in every app with themdeleteMe() relies on your tables' on delete cascade keys to auth.users, so your app needs
no delete code. It returns false when nobody is signed in, and throws with the pool's message
when it can't delete (a foreign key that blocks it is a bug in that app).
A local-first app keeps data in the browser too: localStorage keys, its own cookies, and
IndexedDB databases such as an outbox. localData() downloads and clears them, the browser half
of "Your data":
import { deleteMe, exportMe, localData } from '@kodentuzo/spotkit/client'
const local = localData({
prefixes: ['myapp:'], // localStorage keys that are the app's
keys: ['nuxt-color-mode'], // and some by name
cookies: ['myapp-view'], // the app's own cookies (not the pool's session)
databases: ['offline-transactions'], // IndexedDB databases, e.g. the outbox
})
const file = { pool: await exportMe(), browser: await local.export() /*, your server's rows */ }
await deleteMe() // the account, and the app's rows on the server
await local.clear() // then this browser, the outbox included, so nothing uploads againexport() returns values as data (JSON where they are JSON) and names the databases; their
contents are the app's to add if it needs to. clear() waits until each database is gone (or
blocked by another open tab). Storage the browser blocks reads as empty. Spotstrap's YourData
block takes both halves.
Spotcraft counts visits with Spotless (and Umami behind it) on the instance, the way its owner chose
(ANALYTICS_MODE): opt-out (counted until the visitor turns it off), opt-in
(only after the visitor agrees) or server (nothing in the browser).
import { analytics } from '@kodentuzo/spotkit/client'
const a = await analytics() // reads /_spotcraft/config.json, loads the tracker if it may
if (a.mode === 'opt-in' && !a.counting()) showConsentPrompt()
a.consent() // the visitor agrees (or turns counting back on)
a.refuse() // the visitor says no, or takes their yes back
a.track('level-solved', { level: 3 })- The tracker is loaded once: if the page already has it, spotkit doesn't add a second one.
Spotcraft adds nothing to pages, so
analytics()is how a web app counts visits. - The visitor's choice is kept in
localStorage(spotless.disabled, the tracker's own switch, andspotcraft.analyticsfor an opt-in yes).umami.disabledis kept in step, for instances before Spotcraft 0.15, and an earlier no stored there is honoured. Where storage is blocked, an opt-in yes can't be kept, so nothing is counted. - Event data can't identify anyone: keys like
userId,email,iporsessionTokenthrow. - In
servermode, or when the app's analytics switch is off, nothing runs.
import { clientAddress } from '@kodentuzo/spotkit'
clientAddress(request.headers) // the last X-Forwarded-For entry, or 'unknown'Spotcraft's Caddy sets X-Forwarded-For to the address it resolved (the visitor's, from
Cloudflare behind a tunnel). Only trust it behind such a proxy.
import { health } from '@kodentuzo/spotkit'
// GET /health
return health(async () => (await db.query('select 1')).rowCount === 1)200 when ready resolves true (or right away without it), 503 otherwise or if it throws, never
cached. Spotcraft waits for a 2xx from /health before moving traffic to a new version of an
image without a HEALTHCHECK.
Published from docs/. Edit the files there; changes here are overwritten.