Skip to content

cianfhoghlaim/cianchosaint / .agents/skills/better-auth

better-auth

Verified

<!--
CIANCHOSAINT wholesale-copy of cianfhoghlaim/cianfhoghlaim @ main branch.

Original: cianfhoghlaim/cianfhoghlaim (per the openspec/changes/cianchosaint-repo-bootstrap-v2/specs/cianchosaint-bootstrap-v2/spec.md).
Migrated to cianchosaint: 2026-08-23
Licence: BUSL-1.1 (per LICENSE.md)

Wholesale-copied from cianfhoghlaim/cianfhoghlaim@better-auth/SKILL.md.
-->
---
name: better-auth
description: BetterAuth authentication framework for TypeScript + React. Use for OAuth (Google, GitHub, Apple), email/password, magic links, SIWE (Sign-In With Ethereum), passkeys, and 2FA. Integrates with Drizzle ORM, Convex, and Hono. Cianfhoghlaim: multi-layer auth architecture (BetterAuth customer-facing → PocketID admin → TinyAuth proxy → Infisical secrets).
---

# BetterAuth

## When to use this skill

Use when you need to:

- "Add Google OAuth to the Tuatha game front-end"
- "Implement Sign-In With Ethereum (SIWE) for the crypteolas
  crypto platform"
- "Set up email + password + magic-link auth in web/apps/croilar-portal"
- "Add passkeys (WebAuthn) to the oideachais web app"
- "Wire BetterAuth into a Hono API"
- "Add 2FA (TOTP) to the admin dashboard"

## Overview

[BetterAuth](https://www.better-auth.com/) is a modern
TypeScript authentication framework. It's a drop-in
replacement for Auth.js (NextAuth) with a much better
TypeScript API and built-in support for OAuth providers,
email/password, magic links, SIWE, passkeys, and 2FA.

| Feature | BetterAuth | Auth.js (NextAuth) |
|:--|:--|:--|
| TypeScript-first | ✅ | ⚠️ |
| OAuth providers | 30+ | 50+ |
| Email/password | ✅ | ⚠️ (via adapter) |
| Magic links | ✅ | ⚠️ |
| **SIWE (Ethereum)** | ✅ built-in | ❌ via plugin |
| **Passkeys (WebAuthn)** | ✅ built-in | ⚠️ experimental |
| 2FA (TOTP) | ✅ built-in | ❌ via plugin |
| Drizzle ORM | ✅ native | ⚠️ |
| Convex | ✅ adapter | ❌ |
| Hono | ✅ native | ❌ |

## Cianfhoghlaim multi-layer auth architecture

The Cianfhoghlaim platform uses 4 auth layers, each with a
different threat model:

```
┌─────────────────────────────────────────────────────────────┐
│  Layer 1: Customer-facing (BetterAuth)                     │
│  → OAuth (Google, GitHub, Apple) + SIWE for crypto users   │
│  → Convex backend (real-time state)                         │
│  → Magic links + email/password for traditional users       │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│  Layer 2: Admin (PocketID OIDC passkey)                     │
│  → WebAuthn passkeys (no passwords)                        │
│  → OIDC provider for internal apps                          │
│  → Hosted at `pocketid.cianfhoghlaim.ie`                    │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│  Layer 3: Zero-trust proxy (TinyAuth / Pangolin)            │
│  → Service-to-service auth                                  │
│  → mTLS + short-lived JWTs                                  │
│  → WireGuard tunnel (Pangolin)                              │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│  Layer 4: Secret hydration (Infisical + mise)              │
│  → Service-to-secret-store auth                              │
│  → JWT + short-lived session tokens                          │
│  → `bun run secrets:init` to hydrate                        │
└─────────────────────────────────────────────────────────────┘
```

**Never collapse the layers.** Each has a different threat
model and is breached independently.

## Install

```bash
# Tuatha game front-end (TanStack Start)
cd web/apps/tuatha-ui
bun add better-auth

# oideachais web (no auth; BetterAuth only for web/apps/croilar-portal)
cd web/apps/croilar-portal
bun add better-auth @better-auth/cli
```

## Basic setup (TanStack Start + Drizzle)

```typescript
// src/lib/auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/server/db";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg",
    schema: { /* generated by `bunx @better-auth/cli generate` */ },
  }),

  // Email + password
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: true,
    sendResetPassword: async ({ user, url }) => {
      await sendEmail({ to: user.email, subject: "Reset password", body: `Click ${url}` });
    },
  },

  // OAuth providers
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
    github: {
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    },
  },

  // Email verification
  emailVerification: {
    sendOnSignUp: true,
    autoSignInAfterVerification: true,
  },

  // Plugins
  plugins: [
    magicLink({ /* ... */ }),
    siwe(),  // Sign-In With Ethereum
    twoFactor(),  // TOTP 2FA
    passkey(),  // WebAuthn
  ],
});

export type Auth = typeof auth;
```

## Convex adapter

```typescript
import { convexAdapter } from "better-auth/adapters/convex";
import { ConvexHttpClient } from "convex/browser";

const convex = new ConvexHttpClient(process.env.CONVEX_URL!);

export const auth = betterAuth({
  database: convexAdapter(convex, {
    // Convex tables for users, sessions, accounts, verifications
  }),
  // ... rest of the config
});
```

## Hono integration

```typescript
import { Hono } from "hono";
import { auth } from "@/lib/auth";

const app = new Hono();

app.on(["GET", "POST"], "/api/auth/*", (c) => auth.handler(c.req.raw));

// Protected route
app.get("/api/me", async (c) => {
  const session = await auth.api.getSession({ headers: c.req.raw.headers });
  if (!session) return c.json({ error: "Unauthorized" }, 401);
  return c.json({ user: session.user });
});
```

## SIWE (Sign-In With Ethereum)

For the crypteolas crypto platform, users sign in with their
Ethereum wallet (no email required):

```typescript
import { siwe } from "better-auth/plugins";

// 1. Get a nonce
app.get("/api/auth/siwe/nonce", async (c) => {
  const nonce = await auth.api.getSiweNonce();
  return c.json({ nonce });
});

// 2. Sign in with signed message
app.post("/api/auth/siwe/verify", async (c) => {
  const { message, signature, nonce } = await c.req.json();
  const result = await auth.api.signInWithEthereum({
    message,
    signature,
    nonce,
    walletAddress: deriveAddress(message, signature),
  });
  return c.json({ user: result.user, session: result.session });
});
```

## Passkeys (WebAuthn)

```typescript
import { passkey } from "better-auth/plugins";

export const auth = betterAuth({
  // ...
  plugins: [passkey({
    rpName: "Cianfhoghlaim",
    rpID: "cianfhoghlaim.ie",
    origin: "https://tuatha.cianfhoghlaim.ie",
  })],
});
```

## 2FA (TOTP)

```typescript
import { twoFactor } from "better-auth/plugins";

export const auth = betterAuth({
  // ...
  plugins: [twoFactor({
    issuer: "Cianfhoghlaim",
    otpOptions: { digits: 6, period: 30 },
  })],
});

// Enable for a user
await auth.api.enable2FA({ userId, password });
```

## Magic links

```typescript
import { magicLink } from "better-auth/plugins";

export const auth = betterAuth({
  // ...
  plugins: [magicLink({
    sendMagicLink: async ({ email, url }) => {
      await sendEmail({ to: email, subject: "Sign in", body: `Click ${url}` });
    },
    expiresIn: 600,  // 10 minutes
  })],
});
```

## Cianfhoghlaim integration

- **Tuatha game front-end** (`web/apps/tuatha-ui/`): BetterAuth + Convex
  adapter; users sign in with SIWE (crypto) or Google OAuth
- **web/apps/croilar-portal** (`web/apps/croilar-portal/`): BetterAuth +
  Drizzle adapter; users sign in with email + 2FA
- **web/apps/cianfhoghlaim-web**: NO auth (public lakehouse)
- **PocketID** (`pocketid.cianfhoghlaim.ie`): admin OIDC
  provider for the engineering team
- **TinyAuth / Pangolin**: zero-trust proxy for
  service-to-service auth
- **Infisical + mise**: secret hydration (Layer 4)

## When to use BetterAuth vs alternatives

✅ **Use BetterAuth**:
- TypeScript-only project
- Need SIWE, passkeys, or 2FA
- Convex or Drizzle backend
- Modern Next.js / TanStack / Hono stack

❌ **Use Auth.js (NextAuth)**:
- Next.js-only project
- Don't need SIWE / passkeys
- Large ecosystem of community plugins

❌ **Use Clerk / Auth0**:
- Want managed auth (pay-per-user)
- Don't want to self-host

## Self-hosted stack (BetterAuth OIDC + Convex + Hono + Supabase)

The canonical Cianfhoghlaim self-hosting pattern (from
`references/self-hosted-stack.md`):

```
┌─────────────────────────────────────────────────────────┐
│  BetterAuth     OIDC IdP + user/session store           │
│  + Postgres     (Supabase self-hosted, single container)│
└────────────┬────────────────────────────────────────────┘
             │ JWKS at /.well-known/jwks.json
             ▼
┌─────────────────────────────────────────────────────────┐
│  Hono           mounts BetterAuth handler at /api/auth/*│
│  (auth + API)   validates JWTs against JWKS             │
└────────────┬────────────────────────────────────────────┘
             │ Authorization: Bearer <token>
             ▼
┌─────────────────────────────────────────────────────────┐
│  Convex         configured to trust BetterAuth issuer;  │
│  (self-hosted)  uses auth domain + client ID for audience│
└────────────┬────────────────────────────────────────────┘
             │ token from BetterAuth login
             ▼
┌─────────────────────────────────────────────────────────┐
│  TanStack Start calls /api/auth/* via BetterAuth client,│
│  receives cookies + JWT, then attaches Bearer to every  │
│  Hono + Convex request                                 │
└─────────────────────────────────────────────────────────┘
```

**Setup checklist:**

1. **Database** — single Postgres container (Supabase or
   plain); create the BetterAuth schema with
   `bunx @better-auth/cli generate` (drizzle adapter)
2. **BetterAuth** — `betterAuth({ database: drizzleAdapter(db,
   { provider: "pg" }), emailAndPassword: { enabled: true,
   requireEmailVerification: true }, socialProviders: {...} })`
3. **Hono** — mount with `app.on(["GET", "POST"],
   "/api/auth/*", (c) => auth.handler(c.req.raw))`; add
   `authMiddleware` to protect API routes
4. **Convex** — set `auth.config.ts` with BetterAuth's
   `domain` + `applicationID`; Convex verifies the JWT
   automatically on every query/mutation
5. **Frontend** — `createAuthClient()` on TanStack Start;
   tokens stored in HttpOnly cookies; use the
   `tanstackStartCookies` plugin so `signInEmail` /
   `signUpEmail` set cookies correctly

The critical insight: **Convex and Hono do not manage
passwords or sessions** — they defer to BetterAuth for all
identity. The OIDC JWKS is the single source of truth for
token verification. This means a single sign-on across
`web/apps/cianfhoghlaim-web` (no auth), `web/apps/croilar-portal` (BetterAuth),
and any Convex-powered surface.

## Cianfhoghlaim multi-layer auth (round-9 deep dive)

The 4-layer model from `references/clippings/` is unchanged,
but the round-9 synthesised **layer-to-technology mapping**:

| Layer | Cianfhoghlaim tech | Cianfhoghlaim URL pattern | Threat model |
|:--|:--|:--|:--|
| 1. Customer-facing | BetterAuth + Convex | `*.cianfhoghlaim.ie` | OAuth / SIWE brute force |
| 2. Admin (OIDC) | PocketID (WebAuthn passkeys) | `pocketid.cianfhoghlaim.ie` | No-password admin breach |
| 3. Zero-trust proxy | TinyAuth / Pangolin | WireGuard mesh | mTLS / JWT forgery |
| 4. Secret hydration | Infisical + mise + Locket | `dev-baile` env | Long-lived secret leak |

**Clipping references (canonical deep-dives):**

- `references/clippings/basic-usage.md` — full
  email/password + social sign-up flow
- `references/clippings/drizzle-adapter.md` — Drizzle
  schema generation with `bunx @better-auth/cli generate`
- `references/clippings/expo-integration.md` — BetterAuth
  client for Expo (React Native) — used in the Tuatha
  mobile app
- `references/clippings/postgresql-adapter.md` — direct
  Postgres adapter (alternative to Drizzle)
- `references/clippings/siwe-plugin.md` — ERC-4361
  Sign-In With Ethereum for the crypteolas platform
  (also see `upstream-mirrors/references/clippings/better-auth-siwe.md`)
- `references/clippings/tanstack-start-integration.md` —
  canonical `/api/auth/$.ts` mount point + the
  `tanstackStartCookies` plugin pattern

See `references/self-hosted-stack.md` for the full
1,264-line OIDC self-hosting implementation plan
(BetterAuth + Convex + Supabase + Hono + TanStack Start).

## Resources

- BetterAuth docs: <https://www.better-auth.com/docs>
- SIWE plugin: <https://www.better-auth.com/docs/plugins/siwe>
- Convex adapter: <https://www.better-auth.com/docs/adapters/convex>
- PocketID: <https://pocketid.io/>
- Pangolin: <https://pangolin.net/>
- Infisical: <https://infisical.com/>
- Cianfhoghlaim: `.agents/skills/convex/SKILL.md`, `.agents/skills/hono/SKILL.md`,
  `.agents/skills/tanstack-start/SKILL.md`
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall