Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
175 changes: 175 additions & 0 deletions .agents/skills/better-auth-best-practices/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
---
name: better-auth-best-practices
description: Configure Better Auth server and client, set up database adapters, manage sessions, add plugins, and handle environment variables. Use when users mention Better Auth, betterauth, auth.ts, or need to set up TypeScript authentication with email/password, OAuth, or plugin configuration.
---

# Better Auth Integration Guide

**Always consult [better-auth.com/docs](https://better-auth.com/docs) for code examples and latest API.**

---

## Setup Workflow

1. Install: `npm install better-auth`
2. Set env vars: `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL`
3. Create `auth.ts` with database + config
4. Create route handler for your framework
5. Run `npx @better-auth/cli@latest migrate`
6. Verify: call `GET /api/auth/ok` — should return `{ status: "ok" }`

---

## Quick Reference

### Environment Variables
- `BETTER_AUTH_SECRET` - Encryption secret (min 32 chars). Generate: `openssl rand -base64 32`
- `BETTER_AUTH_URL` - Base URL (e.g., `https://example.com`)

Only define `baseURL`/`secret` in config if env vars are NOT set.

### File Location
CLI looks for `auth.ts` in: `./`, `./lib`, `./utils`, or under `./src`. Use `--config` for custom path.

### CLI Commands
- `npx @better-auth/cli@latest migrate` - Apply schema (built-in adapter)
- `npx @better-auth/cli@latest generate` - Generate schema for Prisma/Drizzle
- `npx @better-auth/cli mcp --cursor` - Add MCP to AI tools

**Re-run after adding/changing plugins.**

---

## Core Config Options

| Option | Notes |
|--------|-------|
| `appName` | Optional display name |
| `baseURL` | Only if `BETTER_AUTH_URL` not set |
| `basePath` | Default `/api/auth`. Set `/` for root. |
| `secret` | Only if `BETTER_AUTH_SECRET` not set |
| `database` | Required for most features. See adapters docs. |
| `secondaryStorage` | Redis/KV for sessions & rate limits |
| `emailAndPassword` | `{ enabled: true }` to activate |
| `socialProviders` | `{ google: { clientId, clientSecret }, ... }` |
| `plugins` | Array of plugins |
| `trustedOrigins` | CSRF whitelist |

---

## Database

**Direct connections:** Pass `pg.Pool`, `mysql2` pool, `better-sqlite3`, or `bun:sqlite` instance.

**ORM adapters:** Import from `better-auth/adapters/drizzle`, `better-auth/adapters/prisma`, `better-auth/adapters/mongodb`.

**Critical:** Better Auth uses adapter model names, NOT underlying table names. If Prisma model is `User` mapping to table `users`, use `modelName: "user"` (Prisma reference), not `"users"`.

---

## Session Management

**Storage priority:**
1. If `secondaryStorage` defined → sessions go there (not DB)
2. Set `session.storeSessionInDatabase: true` to also persist to DB
3. No database + `cookieCache` → fully stateless mode

**Cookie cache strategies:**
- `compact` (default) - Base64url + HMAC. Smallest.
- `jwt` - Standard JWT. Readable but signed.
- `jwe` - Encrypted. Maximum security.

**Key options:** `session.expiresIn` (default 7 days), `session.updateAge` (refresh interval), `session.cookieCache.maxAge`, `session.cookieCache.version` (change to invalidate all sessions).

---

## User & Account Config

**User:** `user.modelName`, `user.fields` (column mapping), `user.additionalFields`, `user.changeEmail.enabled` (disabled by default), `user.deleteUser.enabled` (disabled by default).

**Account:** `account.modelName`, `account.accountLinking.enabled`, `account.storeAccountCookie` (for stateless OAuth).

**Required for registration:** `email` and `name` fields.

---

## Email Flows

- `emailVerification.sendVerificationEmail` - Must be defined for verification to work
- `emailVerification.sendOnSignUp` / `sendOnSignIn` - Auto-send triggers
- `emailAndPassword.sendResetPassword` - Password reset email handler

---

## Security

**In `advanced`:**
- `useSecureCookies` - Force HTTPS cookies
- `disableCSRFCheck` - ⚠️ Security risk
- `disableOriginCheck` - ⚠️ Security risk
- `crossSubDomainCookies.enabled` - Share cookies across subdomains
- `ipAddress.ipAddressHeaders` - Custom IP headers for proxies
- `database.generateId` - Custom ID generation or `"serial"`/`"uuid"`/`false`

**Rate limiting:** `rateLimit.enabled`, `rateLimit.window`, `rateLimit.max`, `rateLimit.storage` ("memory" | "database" | "secondary-storage").

---

## Hooks

**Endpoint hooks:** `hooks.before` / `hooks.after` - Array of `{ matcher, handler }`. Use `createAuthMiddleware`. Access `ctx.path`, `ctx.context.returned` (after), `ctx.context.session`.

**Database hooks:** `databaseHooks.user.create.before/after`, same for `session`, `account`. Useful for adding default values or post-creation actions.

**Hook context (`ctx.context`):** `session`, `secret`, `authCookies`, `password.hash()`/`verify()`, `adapter`, `internalAdapter`, `generateId()`, `tables`, `baseURL`.

---

## Plugins

**Import from dedicated paths for tree-shaking:**
```
import { twoFactor } from "better-auth/plugins/two-factor"
```
NOT `from "better-auth/plugins"`.

**Popular plugins:** `twoFactor`, `organization`, `passkey`, `magicLink`, `emailOtp`, `username`, `phoneNumber`, `admin`, `apiKey`, `bearer`, `jwt`, `multiSession`, `sso`, `oauthProvider`, `oidcProvider`, `openAPI`, `genericOAuth`.

Client plugins go in `createAuthClient({ plugins: [...] })`.

---

## Client

Import from: `better-auth/client` (vanilla), `better-auth/react`, `better-auth/vue`, `better-auth/svelte`, `better-auth/solid`.

Key methods: `signUp.email()`, `signIn.email()`, `signIn.social()`, `signOut()`, `useSession()`, `getSession()`, `revokeSession()`, `revokeSessions()`.

---

## Type Safety

Infer types: `typeof auth.$Infer.Session`, `typeof auth.$Infer.Session.user`.

For separate client/server projects: `createAuthClient<typeof auth>()`.

---

## Common Gotchas

1. **Model vs table name** - Config uses ORM model name, not DB table name
2. **Plugin schema** - Re-run CLI after adding plugins
3. **Secondary storage** - Sessions go there by default, not DB
4. **Cookie cache** - Custom session fields NOT cached, always re-fetched
5. **Stateless mode** - No DB = session in cookie only, logout on cache expiry
6. **Change email flow** - Sends to current email first, then new email

---

## Resources

- [Docs](https://better-auth.com/docs)
- [Options Reference](https://better-auth.com/docs/reference/options)
- [LLMs.txt](https://better-auth.com/llms.txt)
- [GitHub](https://github.com/better-auth/better-auth)
- [Init Options Source](https://github.com/better-auth/better-auth/blob/main/packages/core/src/types/init-options.ts)
8 changes: 4 additions & 4 deletions .claude/agents/ds-migration-reviewer.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: ds-migration-reviewer
description: Checks files for @comp/ui and lucide-react imports that can be migrated to @trycompai/design-system
description: Checks files for @trycompai/ui and lucide-react imports that can be migrated to @trycompai/design-system
tools: Read, Grep, Glob, Bash
---

Expand All @@ -10,7 +10,7 @@ You review frontend files for design system migration opportunities.

For each file provided, identify:

1. **`@comp/ui` imports** — check if `@trycompai/design-system` has an equivalent:
1. **`@trycompai/ui` imports** — check if `@trycompai/design-system` has an equivalent:
```bash
node -e "console.log(Object.keys(require('@trycompai/design-system')))"
```
Expand All @@ -20,7 +20,7 @@ For each file provided, identify:
node -e "const i = require('@trycompai/design-system/icons'); console.log(Object.keys(i).filter(k => k.match(/SearchTerm/i)))"
```

3. **`@comp/ui/button` Button** — DS Button has `loading`, `iconLeft`, `iconRight` props. Manual spinner/icon rendering inside buttons should use these props instead.
3. **`@trycompai/ui/button` Button** — DS Button has `loading`, `iconLeft`, `iconRight` props. Manual spinner/icon rendering inside buttons should use these props instead.

4. **Raw HTML layout** (`<div className="flex ...">`) — check if `Stack`, `HStack`, `PageLayout`, `PageHeader`, `Section` could replace it.

Expand All @@ -29,7 +29,7 @@ For each file provided, identify:
- DS `Text`, `Stack`, `HStack`, `Badge`, `Button` do NOT accept `className` — wrap in `<div>` if styling needed
- Icons come from `@trycompai/design-system/icons` (Carbon icons)
- Only flag migrations where a DS equivalent actually exists — verify by checking exports
- Don't flag `@comp/ui` usage for components that have no DS equivalent yet
- Don't flag `@trycompai/ui` usage for components that have no DS equivalent yet

## Output format

Expand Down
10 changes: 5 additions & 5 deletions .claude/skills/audit-design-system/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
---
name: audit-design-system
description: Audit & fix design system usage — migrate @comp/ui and lucide-react to @trycompai/design-system
description: Audit & fix design system usage — migrate @trycompai/ui and lucide-react to @trycompai/design-system
---

Audit the specified files for design system compliance. **Fix every issue found immediately.**

## Rules

1. **`@trycompai/design-system`** is the primary component library. `@comp/ui` is legacy — only use as last resort when no DS equivalent exists.
2. **Always check DS exports first** before reaching for `@comp/ui`. Run `node -e "console.log(Object.keys(require('@trycompai/design-system')))"` to check.
1. **`@trycompai/design-system`** is the primary component library. `@trycompai/ui` is legacy — only use as last resort when no DS equivalent exists.
2. **Always check DS exports first** before reaching for `@trycompai/ui`. Run `node -e "console.log(Object.keys(require('@trycompai/design-system')))"` to check.
3. **Icons**: Use `@trycompai/design-system/icons` (Carbon icons), NOT `lucide-react`. Check with `node -e "const i = require('@trycompai/design-system/icons'); console.log(Object.keys(i).filter(k => k.match(/YourSearch/i)))"`.
4. **DS components that do NOT accept `className`**: `Text`, `Stack`, `HStack`, `Badge`, `Button` — wrap in `<div>` for custom styling.
5. **Button**: Use DS `Button` with `loading`, `iconLeft`, `iconRight` props instead of manually rendering spinners/icons.
Expand All @@ -17,7 +17,7 @@ Audit the specified files for design system compliance. **Fix every issue found

## Process
1. Read files specified in `$ARGUMENTS`
2. Find `@comp/ui` imports — check if DS equivalent exists
2. Find `@trycompai/ui` imports — check if DS equivalent exists
3. Find `lucide-react` imports — find matching Carbon icons
4. Migrate components and icons
5. Run build to verify: `npx turbo run typecheck --filter=@comp/app`
5. Run build to verify: `npx turbo run typecheck --filter=@trycompai/app`
2 changes: 1 addition & 1 deletion .claude/skills/audit-hooks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@ Audit the specified files for hook and API usage compliance. **Fix every issue f
1. Read files specified in `$ARGUMENTS`
2. Find forbidden patterns and fix them
3. Ensure all data fetching uses SWR hooks
4. Run typecheck to verify: `npx turbo run typecheck --filter=@comp/app`
4. Run typecheck to verify: `npx turbo run typecheck --filter=@trycompai/app`
2 changes: 1 addition & 1 deletion .claude/skills/audit-rbac/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@ Audit the specified files or directories for RBAC and audit log compliance. **Fi
1. Read files specified in `$ARGUMENTS` (or scan the directory)
2. Check each rule above
3. **Fix every violation immediately** — don't just report
4. Run typecheck to verify: `npx turbo run typecheck --filter=@comp/api --filter=@comp/app`
4. Run typecheck to verify: `npx turbo run typecheck --filter=@trycompai/api --filter=@trycompai/app`
1 change: 1 addition & 0 deletions .claude/skills/better-auth-best-practices
2 changes: 1 addition & 1 deletion .claude/skills/production-readiness/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Use parallel subagents to run all four audits simultaneously:

Then run full monorepo verification:
```bash
npx turbo run typecheck --filter=@comp/api --filter=@comp/app
npx turbo run typecheck --filter=@trycompai/api --filter=@trycompai/app
cd apps/app && npx vitest run
```

Expand Down
4 changes: 2 additions & 2 deletions .cursor/rules/essentials.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ bunx <cmd> # Execute binary

## Components

**Use `@trycompai/design-system` first**, `@comp/ui` only as fallback.
**Use `@trycompai/design-system` first**, `@trycompai/ui` only as fallback.

```tsx
// ✅ Design system
import { Button, Card, Input, Select } from '@trycompai/design-system';
import { Add, Close } from '@trycompai/design-system/icons';

// ❌ Don't use when DS has the component
import { Button } from '@comp/ui/button';
import { Button } from '@trycompai/ui/button';
import { Plus } from 'lucide-react';
```

Expand Down
8 changes: 4 additions & 4 deletions .cursor/rules/infra.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ comp/
│ ├── app/ # Next.js main app
│ └── portal/ # Next.js portal
├── packages/
│ ├── db/ # Prisma (@comp/db)
│ ├── db/ # Prisma (@trycompai/db)
│ ├── ui/ # UI components (@trycompai/ui)
│ └── ...
├── turbo.json
Expand All @@ -44,7 +44,7 @@ bun run dev # Dev all

# Single package
bun run -F apps/app dev
bun run -F @comp/db prisma:generate
bun run -F @trycompai/db prisma:generate
turbo build --filter=@trycompai/ui
```

Expand All @@ -53,7 +53,7 @@ turbo build --filter=@trycompai/ui
```tsx
// ✅ Import from package name
import { Button } from '@trycompai/design-system';
import { prisma } from '@comp/db';
import { prisma } from '@trycompai/db';

// ❌ Never relative paths across packages
import { Button } from '../../../packages/ui/src/button';
Expand Down Expand Up @@ -116,7 +116,7 @@ mkdir packages/my-package
```json
// packages/my-package/tsconfig.json
{
"extends": "@comp/tsconfig/base.json",
"extends": "@trycompai/tsconfig/base.json",
"include": ["src"]
}
```
Expand Down
4 changes: 2 additions & 2 deletions .cursor/rules/ui.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ alwaysApply: true
## Design System Priority

1. **First choice:** `@trycompai/design-system`
2. **Fallback:** `@comp/ui` only if DS doesn't have the component
2. **Fallback:** `@trycompai/ui` only if DS doesn't have the component

```tsx
// ✅ Design system
import { Button, Card, Input, Sheet, Badge } from '@trycompai/design-system';
import { Add, Close, ArrowRight } from '@trycompai/design-system/icons';

// ❌ Don't use when DS has it
import { Button } from '@comp/ui/button';
import { Button } from '@trycompai/ui/button';
import { Plus } from 'lucide-react';
```

Expand Down
2 changes: 1 addition & 1 deletion .cursorrules
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Read CLAUDE.md at the repo root and apps/api/CLAUDE.md for comprehensive project
- **Max 300 lines** per file.
- **Session auth only** — no JWT. Use `credentials: 'include'` for API calls.
- **RBAC**: `@RequirePermission('resource', 'action')` on every API endpoint. Gate UI with `hasPermission()`.
- **Design system**: Always `@trycompai/design-system` first, `@comp/ui` only as fallback. Icons from `@trycompai/design-system/icons`.
- **Design system**: Always `@trycompai/design-system` first, `@trycompai/ui` only as fallback. Icons from `@trycompai/design-system/icons`.
- **Data fetching**: Server components use `serverApi`. Client components use SWR hooks with `apiClient`.
- **No server actions** for new features. Call NestJS API directly.
- **Tests required** for every new feature. TDD preferred.
Expand Down
17 changes: 9 additions & 8 deletions .github/workflows/maced-contract-canary.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
name: Maced contract canary

on:
pull_request:
paths:
- 'apps/api/src/security-penetration-tests/**'
- 'apps/api/test/maced-contract.e2e-spec.ts'
- 'apps/api/package.json'
- '.github/workflows/maced-contract-canary.yml'
schedule:
- cron: '0 * * * *'
# Temporarily disabled — Maced API is unavailable
# pull_request:
# paths:
# - 'apps/api/src/security-penetration-tests/**'
# - 'apps/api/test/maced-contract.e2e-spec.ts'
# - 'apps/api/package.json'
# - '.github/workflows/maced-contract-canary.yml'
# schedule:
# - cron: '0 * * * *'
workflow_dispatch:

permissions:
Expand Down
4 changes: 2 additions & 2 deletions .syncpackrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"semverGroups": [
{
"label": "Use exact versions for internal packages",
"packages": ["@comp/**"],
"dependencies": ["@comp/**"],
"packages": ["@trycompai/**"],
"dependencies": ["@trycompai/**"],
"range": "workspace:*"
}
],
Expand Down
Loading
Loading