okayus/okayus-skills/cloudflare-workers-passkey-auth
Claude Code and agent skill by okayus/okayus-skills
- community
- ext:[{"type":"plugin","description":"Custom plugin integration"}]
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-authSemi-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-skeletonstack, and you've decided against OAuth / Cloudflare Access (decision table below) - Symptoms you are hitting:
- every iPhone / iCloud-Keychain user gets
401on login while Android/desktop works → signature-counter check without thecounter === 0exemption - all registered passkeys stopped working after a hostname change (account-subdomain rename, custom domain) → RP_ID lock broken
startRegistration/startAuthenticationthrowsNotAllowedError,InvalidStateError, orSecurityError→ see the client-flow reference- a session cookie shows up on a different Worker under the same
*.workers.devsubdomain →Domain=attribute / not host-only - the login endpoint returns
401even 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
arcticsetup) and the seeded-session e2e seam incloudflare-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)
| Option | Family-scale private app | Why 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/sessionstables migrated (Drizzle + SQL inreferences/schema.md) - [ ]
POST /api/auth/register/begin|verifyis public and dispatchesinitial(one-shot secret) vsinvite(space token) inside the handler; returns403 registration_closedwhenINITIAL_REGISTRATION_TOKENis unset - [ ]
POST /api/auth/credentials/add/begin|verify(add a device) sits behindsessionMiddleware()and usesexcludeCredentials - [ ]
POST /api/auth/login/begin|verifyis username-less (residentKey: "required", noallowCredentials); verify passesrequireUserVerification: false - [ ] WebAuthn challenge lives in a signed 5-minute cookie (
hono/jwtoverSESSION_SECRET) carrying the registration state; nochallengestable - [ ] Session = HS256 JWT with
sid+ asessionsrow; logout deletes the row; expiry slides (30 days) - [ ] Cookies are host-only (no
Domain),HttpOnly,SameSite=Lax,Path=/;secureand the__Host-prefix are derived from the `ORIGIN` scheme, never hardcoded - [ ] Non-GET
/api/*requests requireOrigin === ORIGIN(403 csrf_origin_mismatch) - [ ] The 4 unauthenticated auth routes are IP-rate-limited (
CF-Connecting-IP), config percloudflare-workers-bot-scan-defense - [ ]
DEV_BYPASS_USER_IDis honored only whenORIGINis a localhost origin;wrangler secret liston prod never shows it - [ ]
RP_ID/ORIGINare pinned inwrangler.jsoncvarsto the final production hostname before the first passkey is registered;.dev.varsoverrides them locally - [ ]
DELETE /api/auth/credentials/:idrefuses to delete the user's last credential (400 last_credential) - [ ]
.dev.vars.examplelistsSESSION_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
| Layer | Owns | Must not do | |
|---|---|---|---|
| WebAuthn ceremony | "is the holder of this authenticator real" | sessions, authorization | |
| Challenge cookie | one-shot state between begin and verify (signed, 5 min) | outlive the ceremony | |
| Session JWT | carry sid to the server with a signature | carry permissions | |
sessions table | truth about "is this sid alive" | duplicate JWT claims | |
sessionMiddleware | authenticate + 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 →verifyreads and deletes the cookie before validating it (single use).stateis a discriminated union:authentication|add-credential{uid}|initial{uid, displayName}|invite{uid, displayName, inviteId, spaceId}. Because the state is signed server-side,verifynever trusts client-supplied ids. (routine-tasks round-tripsregistration: {kind, pendingUserId, inviteId, spaceId}through the client body unsigned; an invite holder could then pickspaceId— keep it in the cookie.) - Session:
issueSessioninserts asessionsrow (sid = crypto.randomUUID(),expires_at = now+30d) and sets the JWT{ sid, aud: "app:session", exp }.sessionMiddlewareverifies the JWT, loadssessions ⋈ usersbysid, rejects missing/expired rows (401 session_expired, cookie cleared), setsc.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 aDomain=cookie is readable/tossable across your other apps. Name is__Host-sessionwhenORIGINstarts withhttps://(browser-enforced Secure + Path=/ + no Domain), plainsessionotherwise;secureisORIGIN.startsWith("https://"). Hardcodingsecure: true(nyalog) makes the cookie silently vanish onhttp://127.0.0.1e2e runs. Deleting uses the same attribute set (deleteCookie(c, name, cookieBase(c))): Hono throws on a__Host-name withoutsecure, 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_SECRETsigns both JWTs; the distinctaudvalues 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
| Route | Auth | Purpose | ||
|---|---|---|---|---|
POST /api/auth/register/begin | public + rate limit | Dispatch: 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/verify | public + rate limit | Consume challenge, verifyRegistrationResponse, then ONE db.batch: users + credentials (+ spaces/space_members/invites UPDATE per the sibling skill) → issueSession | ||
POST /api/auth/login/begin | public + rate limit | generateAuthenticationOptions({ rpID, userVerification: "preferred" }) — no allowCredentials → browser shows the passkey picker | ||
POST /api/auth/login/verify | public + rate limit | Look up credentials by response.id, verifyAuthenticationResponse, store newCounter + last_used_at, issueSession | ||
POST /api/auth/logout | session | delete the sessions row, clear cookie | ||
GET /api/auth/me | session | { id, displayName } (+ memberships, sibling skill) | ||
GET /api/auth/credentials | session | list devices (deviceName, backedUp, lastUsedAt) | ||
| `POST /api/auth/credentials/add/begin | verify` | session | add a device; excludeCredentials = user's existing ids; challenge state { kind: "add-credential", uid } must match c.var.userId | |
DELETE /api/auth/credentials/:id | session | scoped 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
- SKILL.md in the repositoryCheckingskills/cloudflare-workers-passkey-auth/SKILL.md
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
[](https://verified-skill.com/skills/okayus/okayus-skills/cloudflare-workers-passkey-auth)