Skip to Content
Server

Auth

Sessions, devices, API keys, phone codes, bearer tokens and client sign-in.

Usage

Stored sessions with a "your devices" list, behind a guard:

import { Hono } from "hono"
import { cloudflareKv } from "@dapplelight/signet-server/adapters/cloudflare"
import { kvSessionStore, startSession } from "@dapplelight/signet-server/auth/sessions"
import { readSessionCookie, sessionCookie } from "@dapplelight/signet-server/auth/session"
import { requireStoredSession, sessionRoutes } from "@dapplelight/signet-server/auth/hono"
import { clientIp } from "@dapplelight/signet-server/middleware/rate-limit"

type Bindings = { SESSIONS: KVNamespace; SESSION_SECRET: string }

// Config is built from bindings, never read at module scope.
const sessionOptions = (env: Bindings) => ({
  cookieName: "app_session",
  secret: env.SESSION_SECRET,
  store: kvSessionStore(cloudflareKv(env.SESSIONS)),
})

export function createApp(env: Bindings) {
  const opts = sessionOptions(env)
  const app = new Hono()

  app.post("/api/sign-in", async (c) => {
    const { token } = await startSession(opts, {
      sub: "user_123",
      userAgent: c.req.header("user-agent"),
      ip: clientIp(c, "cloudflare"),
      previousToken: readSessionCookie(c.req.header("cookie"), opts), // revoked: no session fixation
    })
    c.header("Set-Cookie", sessionCookie(token, opts))
    return c.json({ ok: true })
  })

  app.use("/api/me/*", requireStoredSession(opts))
  app.route("/api/sessions", sessionRoutes(opts)) // GET / · DELETE /:id · POST /revoke-others
  return app
}

sessionRoutes has its own guard. Add csrfMiddleware when the cookie is SameSite=None.

API

ExportWhat it does
issueSession(options, sub?, extra?)Signed token. extra: { sid, ttlSeconds }.
verifySession(token, options)Payload, or null. Refuses stored-session tokens (they carry sid).
checkSession(token, options){ payload, resigned? }. resigned when an old key matched.
sessionCookie(token, options, maxAgeSeconds?)Set-Cookie value (HttpOnly, Secure).
clearCookie(options)Set-Cookie value that clears it.
readSessionCookie(cookieHeader, options)The token from a Cookie header, or null.
hmacSha256(secret, data)HMAC-SHA256, base64url. Secret must be 32+ characters.
timingSafeEqual(a, b)Constant-time string compare.
SessionOptions, SessionPayloadTypes.
OptionTypeDefault
cookieNamestringrequiredNamespace per app.
secretstringrequired32+ characters, per environment.
previousSecretsstring[]noneKeys being rotated out. Old cookies verify and are re-signed.
ttlSecondsnumber14 days
sameSite"strict" | "lax" | "none""lax"none for a frontend on another origin.
domainstringnonee.g. ".example.com".

auth/sessions (stored sessions)

ExportWhat it does
kvSessionStore(kv, { prefix? })SessionStore on any KeyValue.
cachedSessionStore(store, { seconds })In-memory read cache. A revoke elsewhere lags by up to seconds.
startSession(options, input)Sign in: a new id, returns { token, record }.
validateSession(token, options, { ip?, defer? })Signature, expiry and still in the store.
rotateSession(token, options, { userAgent?, ip? })New id, old one revoked. Use on a password change.
deviceLabel(userAgent)"Chrome on macOS".
SessionRecord, SessionStore, StoredSessionOptions, StartSessionInput, ValidSessionTypes.

StoredSessionOptions is SessionOptions plus store and touchEverySeconds (default 300).

auth/hono (middleware and routes)

ExportWhat it does
requireStoredSession(options)Guard for stored sessions. Sets session. 401 if invalid or revoked.
sessionRoutes(options)GET /, DELETE /:id, POST /revoke-others.
requireSession(options)Guard for the stateless cookie. Sets session.
requireApiKey({ store, prefix, scopes? })Guard for API keys. Sets apiKey. 401, or 403 on a missing scope.
requireSharedToken(getExpected)Guard for one shared bearer token in a secret.
requireAuth(options)API token first, then session cookie. Sets user.
clientLoginRoutes(options)Routes for extension, desktop and CLI sign-in.
SessionRoutes, ClientLoginRoutesRoute types for hc (import type).
StoredSessionMiddlewareOptions, DualAuthOptions, ClientLoginRoutesOptionsTypes.
requireStoredSession optionTypeDefault
trustClientIpTrust"none"Which proxy to believe for the recorded IP.
defer(c) => DefernoneKeep the lastSeenAt write off the response.
bearerbooleanfalseAlso accept Authorization: Bearer <access token> from client login.

auth/api-keys

ExportWhat it does
createApiKey(store, input)Mint a key: { token, key }. Show token once.
listApiKeys(store, sub)Keys without their hash.
revokeApiKey(store, sub, id)true if it existed and was yours.
verifyApiKey(store, headers, options){ ok: true, key } or { ok: false, reason }.
kvApiKeyStore(kv, { prefix? })ApiKeyStore on any KeyValue.
ApiKeyRecord, ApiKeyInfo, ApiKeyStore, VerifyApiKeyResultTypes.
createApiKey inputTypeDefault
substringrequiredOwner.
namestringrequiredCut to 100 characters.
prefixstringrequired2-16 letters or digits, starting with a letter.
scopesstring[]none
expiresInSecondsnumbernever expires

auth/bearer

ExportWhat it does
readBearer(headers)The bearer token, or null.
verifySharedToken(headers, expected)Constant-time compare against a secret.
createApiToken(prefix){ token, hash }: prefix_<64 hex> and its SHA-256. Store only the hash.
hashIncomingToken(headers, prefix)Hash for lookup, or null on a wrong prefix.
sha256Hex(input)SHA-256 hex.

auth/passcode

ExportWhat it does
hashPasscode(passcode)iterations:salt:hash (PBKDF2). Run offline, store in a secret.
verifyPasscode(passcode, stored)Constant-time check. false on anything malformed.

auth/otp (phone codes)

ExportWhat it does
requestPhoneOtp(options, { phone, ip? })Send a code. { ok, phone, expiresInSeconds } or INVALID_PHONE / RATE_LIMITED.
verifyPhoneOtp(options, { phone, code, ip? }){ ok, phone } or INVALID_PHONE, CODE_EXPIRED, INVALID_CODE, TOO_MANY_ATTEMPTS.
normalizePhone(input)E.164, or null. Indian national forms accepted.
maskPhone(phone)+91******3210-style mask.
devSmsSender({ appEnv?, log? })Prints the SMS locally. Throws in production or staging.
SmsSender, PhoneOtpOptions, OtpRequestResult, OtpVerifyResultTypes. SmsSender is { send(to, message) }.
PhoneOtpOptionsTypeDefault
kvKeyValuerequired
secretstringrequired32+ characters.
senderSmsSenderrequired
rateLimitRateLimitStorerequiredUse an exact store.
codeLengthnumber6
ttlSecondsnumber300
maxAttemptsnumber5Wrong guesses per code.
perPhone{ max, windowSeconds }3 per 15 min
perIp{ max, windowSeconds }10 per hour
perUnknownIp{ max, windowSeconds }200 per hourUsed only when ip is null; one shared bucket, so keep it high. The per-phone limit still applies.
verifyFailuresPerIp{ max, windowSeconds }30 per hourSkipped when no ip is passed.
message(code, ttlSeconds) => stringbuilt-in text
prefixstring"signet-otp"

auth/client-login (extension, desktop, CLI)

Authorization code with PKCE (S256 only) and device code (RFC 8628). Both end in a short-lived access token and a rotating refresh token.

ExportWhat it does
authorizeClient(options, input)/authorize step for a signed-in user: where to redirect with the code.
exchangeToken(options, params, ctx?)Token endpoint: authorization_code, refresh_token or the device grant.
startDeviceLogin(options, { client_id, ip? })CLI step 1: device code and user code.
approveDeviceLogin(options, { user_code, sub })Web step 2: the signed-in user approves.
revokeClientToken(options, token)Revoke a refresh or access token.
pkceChallenge(verifier)S256 challenge.
redirectUriAllowed(registered, given)Exact match; a loopback entry without a port matches any port.
normalizeUserCode(input)"bcdf-ghjk" to "BCDFGHJK", or null.
DEVICE_CODE_GRANTThe device-code grant type URN.
ClientLoginClient, ClientLoginOptions, TokenResponse, OAuthErrorCode, OAuthFailure, DeviceCodeResponseTypes.
ClientLoginOptionsTypeDefault
sessionsStoredSessionOptionsrequiredAccess tokens are signed with its secret.
kvKeyValuerequiredCodes and refresh tokens. Use a store with incr.
rateLimitRateLimitStorerequiredUse an exact store.
clientsRecord<clientId, { redirectUris? }>requiredUnknown ids are refused.
verificationUristringrequiredPage where the user types the device code.
accessTtlSecondsnumber900
refreshTtlSecondsnumber30 daysAbsolute; refresh never extends it.
codeTtlSecondsnumber60
deviceTtlSecondsnumber600
pollIntervalSecondsnumber5
deviceStartsPerIp{ max, windowSeconds }10 per 10 min
approvalsPerUser{ max, windowSeconds }10 per 10 min
prefixstring"signet-cl"

clientLoginRoutes adds trust (required) and loginUrl(returnTo), and mounts GET /authorize, POST /token, POST /device/code, POST /device/approve and POST /revoke.

auth/better-auth

ExportWhat it does
betterAuthDefaults(env, options)A plain options object for Better Auth. No dependency on it.
socialProviders(creds, onSkip?)Keeps providers with both id and secret; reports half-configured ones.
BetterAuthEnv, BetterAuthDefaultsOptionsTypes.
OptionTypeDefault
crossOriginbooleanfalsetrue forces SameSite=None; Secure.
baseURLstringBETTER_AUTH_URL, else WEB_URL, else WORKER_URL
trustedOriginsstring[]built from WEB_URL, LANDING_URL, ADMIN_URLReplaces the list.
extraTrustedOriginsstring[]noneAdded to the list.
sessionSecondsnumberSESSION_DURATION_SECONDS, else 7 days
cookieCacheSecondsnumberoffA revoked session stays valid this long.
skipStateCookieCheckbooleanfalseThat check is OAuth callback CSRF protection.
rateLimit{ window, max }Better Auth's own

auth/guards

ExportWhat it does
isDevAuthEnabled(env)true only if DEV_AUTH_ENABLED=true outside production. Throws in production or staging.
requireEnv(env, keys)Values, or throws naming every missing key.
checkEnv(env, keys){ ok: true, values } or { ok: false, missing }.

auth/mcp

ExportWhat it does
authTools(options)MCP tools: list_my_sessions, revoke_session, list_api_keys, revoke_api_key.
AuthToolsOptionssessions?, apiKeys?, userOf?. A tool pair is added per store you pass.

Revokes go through requireApproval. No tool returns a secret, hash or code.

Examples

Passcode gate for an invite page

import { verifyPasscode } from "@dapplelight/signet-server/auth/passcode"
import { issueSession, sessionCookie } from "@dapplelight/signet-server/auth/session"
import { app } from "./app"
import { env } from "./env"

const opts = { cookieName: "rsvp_session", secret: env.SESSION_SECRET, sameSite: "none" as const }

app.post("/api/unlock", async (c) => {
  const { passcode } = await c.req.json()
  if (!(await verifyPasscode(passcode, env.PASSCODE_HASH))) return c.json({ error: "Wrong passcode" }, 401)
  c.header("Set-Cookie", sessionCookie(await issueSession(opts), opts))
  return c.json({ ok: true })
})

API key for a CI job

import { createApiKey, kvApiKeyStore } from "@dapplelight/signet-server/auth/api-keys"
import { requireApiKey } from "@dapplelight/signet-server/auth/hono"
import { app } from "./app"
import { kv } from "./kv"

const user = { id: "user_123" }
const keys = kvApiKeyStore(kv)
const { token, key } = await createApiKey(keys, {
  sub: user.id, name: "CI", prefix: "app", scopes: ["read"], expiresInSeconds: 90 * 86400,
})
// Show `token` once. `key` is safe to list.

app.use("/api/export/*", requireApiKey({ store: keys, prefix: "app", scopes: ["read"] }))

Phone sign-in

import { devSmsSender, requestPhoneOtp, verifyPhoneOtp } from "@dapplelight/signet-server/auth/otp"
import { upstashRateLimitStore } from "@dapplelight/signet-server/adapters/upstash"
import { clientIp } from "@dapplelight/signet-server/middleware/rate-limit"
import { app } from "./app"
import { env } from "./env"
import { kv } from "./kv"

const otp = {
  kv,
  secret: env.OTP_SECRET,
  sender: devSmsSender({ appEnv: env.APP_ENV }), // a real SMS provider in production
  rateLimit: upstashRateLimitStore({ url: env.UPSTASH_URL, token: env.UPSTASH_TOKEN }),
}

app.post("/api/phone/request", async (c) => {
  const body = await c.req.json()
  const ip = clientIp(c, "cloudflare")
  return c.json(await requestPhoneOtp(otp, { phone: body.phone, ip }))
})

app.post("/api/phone/verify", async (c) => {
  const body = await c.req.json()
  const ip = clientIp(c, "cloudflare")
  const checked = await verifyPhoneOtp(otp, { phone: body.phone, code: body.code, ip })
  if (checked.ok) {
    // sign in checked.phone with startSession
  }
  return c.json(checked)
})

Rotate the signing key without signing anyone out

import { env } from "./env"

const opts = { cookieName: "app_session", secret: env.SESSION_SECRET, previousSecrets: [env.SESSION_SECRET_OLD] }