okayus/okayus-skills/cloudflare-workers-passkey-auth

Claude Code and agent skill by okayus/okayus-skills

Trust tier 2
  • community
  • ext:[{"type":"plugin","description":"Custom plugin integration"}]
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Add passkey-only (WebAuthn) closed registration + revocable sessions to a Cloudflare Workers app (Hono + D1 + Drizzle) for a family-scale app — @simplewebauthn v13, a signed 5-minute challenge cookie (no D1 challenge table), an HS256 session JWT backed by a sessions table (revocable, 30-day sliding), and a public register endpoint dispatching initial-token vs space-invite registration. Use when building login for an invite-only app without passwords or OAuth, when "every iPhone user gets 401" on login (counter-regression check without the counter=0 exemption for synced passkeys), when all passkeys died after a domain/subdomain change (RP_ID lock), when startRegistration throws NotAllowedError / InvalidStateError / SecurityError, or when the session cookie must not leak to sibling *.workers.dev Workers (host-only, __Host- prefix). Covers schema, routes, dev-bypass twin guard, CSRF Origin check, auth rate limits, INITIAL_REGISTRATION_TOKEN cycle, SESSION_SECRET rotation, lost-passkey recovery.

Install

npx vskill@latest install okayus/okayus-skills/cloudflare-workers-passkey-auth

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as okayus/okayus-skills/cloudflare-workers-passkey-auth.

Cloudflare Workers Passkey Auth (closed registration, revocable sessions)

Get a Hono + D1 Worker to the state where the only way in is a passkey, registration is closed except through a one-shot bootstrap token (or a space invite), and any session can be killed server-side — with zero password, zero external IdP, and zero D1 table for WebAuthn challenges.

Extracted from nyalog (ADR-003, PR-level code) and routine-tasks (Phase 4a/4b walkthrough), 2026-08-22. Cookie/CSRF details from mazuoboeru.

Why this shape: a private app used by a handful of known people (a family) doesn't need sign-up, password reset, or a login screen with an email field. What it needs is phishing resistance (RP-ID-bound passkeys), instant revocation (a sessions row, not a bare JWT), and a registration door that is shut by default. Every piece here exists because the naive version (JWT-only sessions, secure: true hardcoded, a strict signature-counter check, a Domain= cookie) broke in production in one of the source projects.

When to use this skill

  • Building login for an invite-only app (family, household, 2–10 people) on the cloudflare-workers-deploy-skeleton stack, and you've decided against OAuth / Cloudflare Access (decision table below)
  • Symptoms you are hitting:
  • every iPhone / iCloud-Keychain user gets 401 on login while Android/desktop works → signature-counter check without the counter === 0 exemption
  • all registered passkeys stopped working after a hostname change (account-subdomain rename, custom domain) → RP_ID lock broken
  • startRegistration / startAuthentication throws NotAllowedError, InvalidStateError, or SecurityError → see the client-flow reference
  • a session cookie shows up on a different Worker under the same *.workers.dev subdomain → Domain= attribute / not host-only
  • the login endpoint returns 401 even though it should be public → protected sub-app mounted before the public auth routes
  • Adding "add this device as a passkey" / "revoke that device" management to an existing passkey app

Do not use for:

  • A public SaaS with self-service sign-up — use OAuth (mazuoboeru's arctic setup) and the seeded-session e2e seam in cloudflare-workers-e2e-playwright; passkeys there are a Phase-2 add-on, not the front door
  • Apps that must stay behind Cloudflare Access (allowlist-by-dashboard) — different threat model, nothing here applies
  • Password or magic-link auth — none of the challenge/counter/RP_ID machinery transfers

Decision: why passkeys here (and when not)

OptionFamily-scale private appWhy it lost / won (source)
Cloudflare Access (Google IdP)✗OTP/SSO round-trip on every mobile open; authz lives in the dashboard, no in-app logout/device management (nyalog ADR-002 → ADR-003)
Google OAuth✗Per-project Google Cloud console work (OAuth client + consent screen) that doesn't scale across hobby projects (mazuoboeru ADR-0001 addendum)
GitHub OAuth✗Family members don't have GitHub accounts — developer-only audience
Passkeys (WebAuthn)✓Login = unlock gesture; RP-ID binding = phishing resistance; no shared secret server-side; closed registration is natural
Auth SaaS / Better Auth / Lucia✗Lucia deprecated 2025-03; the rest are oversized for ~4 users and add classes/lock-in

Constraints you accept with passkeys: RP_ID is permanent (see below), each person should register two authenticators (no password reset exists), and a lost-everything recovery needs an operator (runbook in references/ops-and-recovery.md).

Deliverables (completion criteria)

  • [ ] users / credentials / sessions tables migrated (Drizzle + SQL in references/schema.md)
  • [ ] POST /api/auth/register/begin|verify is public and dispatches initial (one-shot secret) vs invite (space token) inside the handler; returns 403 registration_closed when INITIAL_REGISTRATION_TOKEN is unset
  • [ ] POST /api/auth/credentials/add/begin|verify (add a device) sits behind sessionMiddleware() and uses excludeCredentials
  • [ ] POST /api/auth/login/begin|verify is username-less (residentKey: "required", no allowCredentials); verify passes requireUserVerification: false
  • [ ] WebAuthn challenge lives in a signed 5-minute cookie (hono/jwt over SESSION_SECRET) carrying the registration state; no challenges table
  • [ ] Session = HS256 JWT with sid + a sessions row; logout deletes the row; expiry slides (30 days)
  • [ ] Cookies are host-only (no Domain), HttpOnly, SameSite=Lax, Path=/; secure and the __Host- prefix are derived from the `ORIGIN` scheme, never hardcoded
  • [ ] Non-GET /api/* requests require Origin === ORIGIN (403 csrf_origin_mismatch)
  • [ ] The 4 unauthenticated auth routes are IP-rate-limited (CF-Connecting-IP), config per cloudflare-workers-bot-scan-defense
  • [ ] DEV_BYPASS_USER_ID is honored only when ORIGIN is a localhost origin; wrangler secret list on prod never shows it
  • [ ] RP_ID / ORIGIN are pinned in wrangler.jsonc vars to the final production hostname before the first passkey is registered; .dev.vars overrides them locally
  • [ ] DELETE /api/auth/credentials/:id refuses to delete the user's last credential (400 last_credential)
  • [ ] .dev.vars.example lists SESSION_SECRET, RP_ID, ORIGIN, INITIAL_REGISTRATION_TOKEN, DEV_BYPASS_USER_ID (keys only)
  • [ ] Every UNVERIFIED: bullet below has been checked on the real app and the result written back into this skill

Architecture in one screen

Browser ──HTTPS + cookies──▶ Worker (Hono)
├─ secureHeaders (CSP/HSTS — deploy-skeleton)
├─ csrfOriginCheck on /api/* (non-GET: Origin === ORIGIN)
├─ /api/auth/{register,login}/* PUBLIC + authRateLimit
├─ sessionMiddleware (JWT → sessions row → c.var.userId)
└─ everything else under /api (domain routes)
D1: users · credentials (public keys) · sessions (revocation)
@simplewebauthn/server: verify{Registration,Authentication}Response
LayerOwnsMust not do
WebAuthn ceremony"is the holder of this authenticator real"sessions, authorization
Challenge cookieone-shot state between begin and verify (signed, 5 min)outlive the ceremony
Session JWTcarry sid to the server with a signaturecarry permissions
sessions tabletruth about "is this sid alive"duplicate JWT claims
sessionMiddlewareauthenticate + load c.var.userId (+ space memberships, sibling skill)decide per-resource access

Schema — three tables

users(id, display_name, created_at), credentials(id = WebAuthn credential id base64url, user_id, public_key, counter, transports JSON, device_name, backed_up, created_at, last_used_at), sessions(id = sid, user_id, expires_at, created_at). public_key is stored as base64url TEXT (nyalog), not BLOB (routine-tasks): readable in SQL dumps/wrangler d1 execute output, no Drizzle blob-mode typing questions; the 4/3 size inflation on a ~80-byte key is irrelevant. Both child tables cascade on user delete. Full Drizzle + SQL and the migration-order note in references/schema.md.

Design NOT NULL columns from day one — users is a parent with ON DELETE CASCADE children, and a later table-rebuild migration on it is exactly the D1 cascade-delete trap in cloudflare-d1-drizzle-migration.

Challenge cookie and session cookie

  • Challenge: generate*Options() → put { challenge, state, aud: "app:challenge", exp: now+300s } into a signed cookie → verify reads and deletes the cookie before validating it (single use). state is a discriminated union: authentication | add-credential{uid} | initial{uid, displayName} | invite{uid, displayName, inviteId, spaceId}. Because the state is signed server-side, verify never trusts client-supplied ids. (routine-tasks round-trips registration: {kind, pendingUserId, inviteId, spaceId} through the client body unsigned; an invite holder could then pick spaceId — keep it in the cookie.)
  • Session: issueSession inserts a sessions row (sid = crypto.randomUUID(), expires_at = now+30d) and sets the JWT { sid, aud: "app:session", exp }. sessionMiddleware verifies the JWT, loads sessions ⋈ users by sid, rejects missing/expired rows (401 session_expired, cookie cleared), sets c.var.userId / c.var.displayName, and slides the expiry when less than half remains (one DB write per ~15 days per session; mazuoboeru's alternative is "refresh at most once a day").
  • Cookie attributes (both cookies): HttpOnly, SameSite=Lax, Path=/, no `Domain` — sibling Workers share <account>.workers.dev, so a Domain= cookie is readable/tossable across your other apps. Name is __Host-session when ORIGIN starts with https:// (browser-enforced Secure + Path=/ + no Domain), plain session otherwise; secure is ORIGIN.startsWith("https://"). Hardcoding secure: true (nyalog) makes the cookie silently vanish on http://127.0.0.1 e2e runs. Deleting uses the same attribute set (deleteCookie(c, name, cookieBase(c))): Hono throws on a __Host- name without secure, and a browser ignores a non-Secure __Host- Set-Cookie, so { path: "/" } alone leaves the session cookie alive on https (verified 2026-08-30 in matatabetai).
  • One SESSION_SECRET signs both JWTs; the distinct aud values stop a session token from being replayed as a challenge and vice versa.

Templates: references/session-and-challenge.md.

Routes and the public register dispatch

RouteAuthPurpose
POST /api/auth/register/beginpublic + rate limitDispatch: body has inviteToken → validate invite (sibling skill) ; else initialRegistrationToken must equal the INITIAL_REGISTRATION_TOKEN secret, else 403 registration_closed. Issue challenge with {kind, uid: fresh UUID, displayName, …}
POST /api/auth/register/verifypublic + rate limitConsume challenge, verifyRegistrationResponse, then ONE db.batch: users + credentials (+ spaces/space_members/invites UPDATE per the sibling skill) → issueSession
POST /api/auth/login/beginpublic + rate limitgenerateAuthenticationOptions({ rpID, userVerification: "preferred" }) — no allowCredentials → browser shows the passkey picker
POST /api/auth/login/verifypublic + rate limitLook up credentials by response.id, verifyAuthenticationResponse, store newCounter + last_used_at, issueSession
POST /api/auth/logoutsessiondelete the sessions row, clear cookie
GET /api/auth/mesession{ id, displayName } (+ memberships, sibling skill)
GET /api/auth/credentialssessionlist devices (deviceName, backedUp, lastUsedAt)
`POST /api/auth/credentials/add/beginverify`sessionadd a device; excludeCredentials = user's existing ids; challenge state { kind: "add-credential", uid } must match c.var.userId
DELETE /api/auth/credentials/:idsessionscoped to user_id; 400 last_credential when it's the only one

Why `register/*` is public and dispatches inside the handler: the caller is, by definition, not logged in (initial owner or invited newcomer). routine-tasks also folded the "add a device" path into the same public endpoint by re-verifying the session cookie inline; mounting credentials/add/* behind sessionMiddleware() (nyalog) is the same thing with less duplicated verification code — do that.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Extension points

  • pluginCustom plugin integration

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/okayus/okayus-skills/cloudflare-workers-passkey-auth/badge)](https://verified-skill.com/skills/okayus/okayus-skills/cloudflare-workers-passkey-auth)

Something wrong with this skill or its page? Tell us.