@1aboveio/app-dev-skills 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -2
- package/package.json +33 -4
- package/skills/airflow/LICENSE +3 -0
- package/skills/airflow/SKILL.md +199 -0
- package/skills/airflow/release-check.mjs +93 -0
- package/skills/android-foundation/LICENSE +3 -0
- package/skills/android-foundation/SKILL.md +192 -0
- package/skills/android-foundation/assets/android-ci-job.yml +217 -0
- package/skills/android-foundation/references/ci.md +87 -0
- package/skills/android-foundation/references/gotchas.md +221 -0
- package/skills/android-foundation/references/setup.md +164 -0
- package/skills/android-foundation/release-check.mjs +93 -0
- package/skills/android-foundation/scripts/device-run.sh +176 -0
- package/skills/android-foundation/scripts/device-run.test.mjs +172 -0
- package/skills/app-debug/LICENSE +3 -0
- package/skills/app-debug/SKILL.md +110 -0
- package/skills/app-debug/references/common-errors.md +128 -0
- package/skills/app-debug/release-check.mjs +93 -0
- package/skills/better-auth/LICENSE +3 -0
- package/skills/better-auth/SKILL.md +598 -0
- package/skills/better-auth/references/feishu-api.md +270 -0
- package/skills/better-auth/release-check.mjs +93 -0
- package/skills/ios-foundation/LICENSE +3 -0
- package/skills/ios-foundation/SKILL.md +184 -0
- package/skills/ios-foundation/references/setup.md +243 -0
- package/skills/ios-foundation/release-check.mjs +93 -0
- package/skills/monorepo/LICENSE +3 -0
- package/skills/monorepo/SKILL.md +462 -0
- package/skills/monorepo/release-check.mjs +93 -0
- package/skills/nextjs-fullstack/LICENSE +3 -0
- package/skills/nextjs-fullstack/SKILL.md +211 -0
- package/skills/nextjs-fullstack/conventions.md +318 -0
- package/skills/nextjs-fullstack/frontend-conventions.md +61 -0
- package/skills/nextjs-fullstack/nextjs16.md +287 -0
- package/skills/nextjs-fullstack/release-check.mjs +93 -0
- package/skills/nextjs-fullstack/server-actions.md +409 -0
- package/skills/prisma-setup/LICENSE +3 -0
- package/skills/prisma-setup/SKILL.md +181 -0
- package/skills/prisma-setup/nextjs.md +258 -0
- package/skills/prisma-setup/release-check.mjs +93 -0
- package/skills/prisma-setup/turborepo.md +301 -0
- package/skills/pyspark/LICENSE +3 -0
- package/skills/pyspark/SKILL.md +127 -0
- package/skills/pyspark/assets/templates/etl.py +748 -0
- package/skills/pyspark/assets/templates/utils/__init__.py +1 -0
- package/skills/pyspark/assets/templates/utils/hudi_metadata.py +14 -0
- package/skills/pyspark/references/diagnosis-and-profiling.md +169 -0
- package/skills/pyspark/references/etl-contract.md +129 -0
- package/skills/pyspark/references/production-validation.md +131 -0
- package/skills/pyspark/references/reconciliation.md +38 -0
- package/skills/pyspark/references/transformation-design.md +190 -0
- package/skills/pyspark/references/velocity-feature-calculation.md +193 -0
- package/skills/pyspark/release-check.mjs +93 -0
- package/skills/pyspark/scripts/spark_eventlog_summary.py +223 -0
- package/skills/python-backend/LICENSE +3 -0
- package/skills/python-backend/SKILL.md +325 -0
- package/skills/python-backend/assets/uv-install.sh +48 -0
- package/skills/python-backend/references/uv-installs.md +83 -0
- package/skills/python-backend/release-check.mjs +93 -0
- package/skills/shadcn/LICENSE +3 -0
- package/skills/shadcn/SKILL.md +120 -0
- package/skills/shadcn/assets/shadcn-small.png +0 -0
- package/skills/shadcn/assets/shadcn.png +0 -0
- package/skills/shadcn/cli.md +411 -0
- package/skills/shadcn/customization.md +224 -0
- package/skills/shadcn/mcp.md +101 -0
- package/skills/shadcn/release-check.mjs +93 -0
- package/skills/shadcn/rules/base-vs-radix.md +323 -0
- package/skills/shadcn/rules/component-selection.md +67 -0
- package/skills/shadcn/rules/composition.md +195 -0
- package/skills/shadcn/rules/data-table.md +201 -0
- package/skills/shadcn/rules/forms.md +255 -0
- package/skills/shadcn/rules/icons.md +103 -0
- package/skills/shadcn/rules/styling.md +167 -0
- package/skills/zod-v4/LICENSE +3 -0
- package/skills/zod-v4/SKILL.md +286 -0
- package/skills/zod-v4/release-check.mjs +93 -0
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: better-auth
|
|
3
|
+
description: "Add or debug Better Auth for Next.js App Router: login, sessions, protected routes, middleware, OAuth (including Feishu/Lark), cookies, Prisma, and Auth.js migration."
|
|
4
|
+
release-version: 0.36.0
|
|
5
|
+
---
|
|
6
|
+
**Updates:** Once/session run `node <skill-base-dir>/release-check.mjs`.
|
|
7
|
+
# Better Auth for Next.js
|
|
8
|
+
|
|
9
|
+
## Auth Strategy Matrix
|
|
10
|
+
|
|
11
|
+
| Action | Source | Method |
|
|
12
|
+
|--------|--------|--------|
|
|
13
|
+
| Get session | RSC (server) | `getSession()` wrapper |
|
|
14
|
+
| Get session | Client component | Session React context |
|
|
15
|
+
| Get preferences | RSC (server) | Direct DB / wrapper |
|
|
16
|
+
| Get preferences | Client component | Session context |
|
|
17
|
+
| Update preferences | RSC / client | Server actions + `router.refresh()` |
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Setup
|
|
22
|
+
|
|
23
|
+
### Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install better-auth
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Environment Variables
|
|
30
|
+
|
|
31
|
+
```env
|
|
32
|
+
DATABASE_URL="your-database-url"
|
|
33
|
+
BETTER_AUTH_SECRET="your-secret-key"
|
|
34
|
+
NEXT_PUBLIC_APP_URL="http://localhost:3000"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Run Migrations
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npx better-auth migrate
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Core Configuration
|
|
46
|
+
|
|
47
|
+
### Server Auth (lib/auth.ts)
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
import { betterAuth } from "better-auth"
|
|
51
|
+
|
|
52
|
+
export const auth = betterAuth({
|
|
53
|
+
database: {
|
|
54
|
+
provider: "postgres",
|
|
55
|
+
url: process.env.DATABASE_URL,
|
|
56
|
+
},
|
|
57
|
+
emailAndPassword: {
|
|
58
|
+
enabled: true,
|
|
59
|
+
},
|
|
60
|
+
// Add OAuth providers as needed
|
|
61
|
+
})
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### API Route Handler
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
// app/api/auth/[...all]/route.ts
|
|
68
|
+
import { auth } from "@/lib/auth"
|
|
69
|
+
|
|
70
|
+
export const { GET, POST } = auth.handler()
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Client Auth (lib/auth-client.ts)
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
import { createAuthClient } from "better-auth/client"
|
|
77
|
+
|
|
78
|
+
export const authClient = createAuthClient({
|
|
79
|
+
baseURL: process.env.NEXT_PUBLIC_APP_URL,
|
|
80
|
+
})
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## NextAuth Migration Mappings
|
|
86
|
+
|
|
87
|
+
### Client-side Sign In
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
// Before (NextAuth)
|
|
91
|
+
import { signIn } from "next-auth/react"
|
|
92
|
+
await signIn("github")
|
|
93
|
+
|
|
94
|
+
// After (Better Auth)
|
|
95
|
+
import { authClient } from "@/lib/auth-client"
|
|
96
|
+
const { data, error } = await authClient.signIn.social({
|
|
97
|
+
provider: "github",
|
|
98
|
+
})
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Client-side Sign Out
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
// Before
|
|
105
|
+
import { signOut } from "next-auth/react"
|
|
106
|
+
await signOut()
|
|
107
|
+
|
|
108
|
+
// After
|
|
109
|
+
import { authClient } from "@/lib/auth-client"
|
|
110
|
+
const { data, error } = await authClient.signOut()
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Client-side Session
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
// Before
|
|
117
|
+
import { useSession } from "next-auth/react"
|
|
118
|
+
const { data, status } = useSession()
|
|
119
|
+
|
|
120
|
+
// After
|
|
121
|
+
import { authClient } from "@/lib/auth-client"
|
|
122
|
+
const { data, isPending, error } = authClient.useSession?.() ?? {}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Server-side Sign In
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
// Before
|
|
129
|
+
import { signIn } from "@/lib/auth"
|
|
130
|
+
await signIn("github")
|
|
131
|
+
|
|
132
|
+
// After
|
|
133
|
+
import { auth } from "@/lib/auth"
|
|
134
|
+
const { redirect, url } = await auth.api.signInSocial({
|
|
135
|
+
body: { provider: "github" },
|
|
136
|
+
})
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Server-side Sign Out
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
// Before
|
|
143
|
+
import { signOut } from "@/lib/auth"
|
|
144
|
+
await signOut()
|
|
145
|
+
|
|
146
|
+
// After
|
|
147
|
+
import { auth } from "@/lib/auth"
|
|
148
|
+
import { headers } from "next/headers"
|
|
149
|
+
const { success } = await auth.api.signOut({
|
|
150
|
+
headers: await headers(),
|
|
151
|
+
})
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### Server-side Session
|
|
155
|
+
|
|
156
|
+
```typescript
|
|
157
|
+
// Before
|
|
158
|
+
import { auth } from "@/lib/auth"
|
|
159
|
+
const session = await auth()
|
|
160
|
+
|
|
161
|
+
// After
|
|
162
|
+
import { auth } from "@/lib/auth"
|
|
163
|
+
import { headers } from "next/headers"
|
|
164
|
+
const session = await auth.api.getSession({
|
|
165
|
+
headers: await headers(),
|
|
166
|
+
})
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## Session Enrichment Pattern
|
|
172
|
+
|
|
173
|
+
### Server-side Wrapper (lib/auth-server.ts)
|
|
174
|
+
|
|
175
|
+
```typescript
|
|
176
|
+
"use server"
|
|
177
|
+
|
|
178
|
+
import { auth } from "./auth"
|
|
179
|
+
import { headers } from "next/headers"
|
|
180
|
+
import { db } from "./db"
|
|
181
|
+
|
|
182
|
+
export async function getSession() {
|
|
183
|
+
const session = await auth.api.getSession({
|
|
184
|
+
headers: await headers(),
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
if (!session) return null
|
|
188
|
+
|
|
189
|
+
const userData = await db.user.findUnique({
|
|
190
|
+
where: { id: session.user.id },
|
|
191
|
+
include: {
|
|
192
|
+
profile: true,
|
|
193
|
+
preferences: true,
|
|
194
|
+
},
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
...session,
|
|
199
|
+
user: {
|
|
200
|
+
...session.user,
|
|
201
|
+
...userData,
|
|
202
|
+
},
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Session Context Provider (React 19)
|
|
208
|
+
|
|
209
|
+
```tsx
|
|
210
|
+
// context/session-context.tsx
|
|
211
|
+
"use client"
|
|
212
|
+
|
|
213
|
+
import { createContext, useContext, ReactNode, use } from "react"
|
|
214
|
+
import type { getSession } from "@/lib/auth-server"
|
|
215
|
+
|
|
216
|
+
type EnrichedSession = Awaited<ReturnType<typeof getSession>>
|
|
217
|
+
|
|
218
|
+
const SessionContext = createContext<EnrichedSession | null>(null)
|
|
219
|
+
|
|
220
|
+
export function SessionProvider({
|
|
221
|
+
children,
|
|
222
|
+
sessionPromise,
|
|
223
|
+
}: {
|
|
224
|
+
children: ReactNode
|
|
225
|
+
sessionPromise: Promise<EnrichedSession>
|
|
226
|
+
}) {
|
|
227
|
+
const session = use(sessionPromise) // React 19 pattern
|
|
228
|
+
|
|
229
|
+
return (
|
|
230
|
+
<SessionContext.Provider value={session}>
|
|
231
|
+
{children}
|
|
232
|
+
</SessionContext.Provider>
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function useSession() {
|
|
237
|
+
const context = useContext(SessionContext)
|
|
238
|
+
if (context === undefined) {
|
|
239
|
+
throw new Error("useSession must be used within SessionProvider")
|
|
240
|
+
}
|
|
241
|
+
return context
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Root Layout Integration
|
|
246
|
+
|
|
247
|
+
```tsx
|
|
248
|
+
// app/layout.tsx
|
|
249
|
+
import { SessionProvider } from "@/context/session-context"
|
|
250
|
+
import { getSession } from "@/lib/auth-server"
|
|
251
|
+
|
|
252
|
+
export default async function RootLayout({
|
|
253
|
+
children,
|
|
254
|
+
}: {
|
|
255
|
+
children: React.ReactNode
|
|
256
|
+
}) {
|
|
257
|
+
const sessionPromise = getSession()
|
|
258
|
+
|
|
259
|
+
return (
|
|
260
|
+
<html lang="en">
|
|
261
|
+
<body>
|
|
262
|
+
<SessionProvider sessionPromise={sessionPromise}>
|
|
263
|
+
{children}
|
|
264
|
+
</SessionProvider>
|
|
265
|
+
</body>
|
|
266
|
+
</html>
|
|
267
|
+
)
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### Usage in Client Components
|
|
272
|
+
|
|
273
|
+
```tsx
|
|
274
|
+
"use client"
|
|
275
|
+
|
|
276
|
+
import { useSession } from "@/context/session-context"
|
|
277
|
+
|
|
278
|
+
export function UserProfile() {
|
|
279
|
+
const session = useSession()
|
|
280
|
+
|
|
281
|
+
if (!session) return <div>Not logged in</div>
|
|
282
|
+
|
|
283
|
+
return (
|
|
284
|
+
<div>
|
|
285
|
+
<h1>Welcome, {session.user.name}</h1>
|
|
286
|
+
<p>Theme: {session.user.preferences?.theme}</p>
|
|
287
|
+
</div>
|
|
288
|
+
)
|
|
289
|
+
}
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
## Protected Routes
|
|
295
|
+
|
|
296
|
+
### Client-side Protection
|
|
297
|
+
|
|
298
|
+
```tsx
|
|
299
|
+
"use client"
|
|
300
|
+
|
|
301
|
+
import { authClient } from "@/lib/auth-client"
|
|
302
|
+
import { redirect } from "next/navigation"
|
|
303
|
+
|
|
304
|
+
export default function DashboardPage() {
|
|
305
|
+
const { data, error, isPending } = authClient.useSession?.() ?? {}
|
|
306
|
+
|
|
307
|
+
if (isPending) return <div>Loading...</div>
|
|
308
|
+
if (!data || error) redirect("/sign-in")
|
|
309
|
+
|
|
310
|
+
return <div>Welcome {data.user.name}</div>
|
|
311
|
+
}
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
### Server-side Protection
|
|
315
|
+
|
|
316
|
+
```tsx
|
|
317
|
+
import { auth } from "@/lib/auth"
|
|
318
|
+
import { headers } from "next/headers"
|
|
319
|
+
import { redirect } from "next/navigation"
|
|
320
|
+
|
|
321
|
+
export default async function DashboardPage() {
|
|
322
|
+
const session = await auth.api.getSession({
|
|
323
|
+
headers: await headers(),
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
if (!session) redirect("/sign-in")
|
|
327
|
+
|
|
328
|
+
return <div>Welcome {session.user.name}</div>
|
|
329
|
+
}
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
---
|
|
333
|
+
|
|
334
|
+
## Preferences Update Pattern
|
|
335
|
+
|
|
336
|
+
```tsx
|
|
337
|
+
"use client"
|
|
338
|
+
|
|
339
|
+
import { useRouter } from "next/navigation"
|
|
340
|
+
import { updateUserPreferences } from "@/lib/actions"
|
|
341
|
+
|
|
342
|
+
export function UpdatePreferences() {
|
|
343
|
+
const router = useRouter()
|
|
344
|
+
|
|
345
|
+
async function handleUpdate(preferences: any) {
|
|
346
|
+
await updateUserPreferences(preferences)
|
|
347
|
+
router.refresh() // Refetch session via layout
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
return (
|
|
351
|
+
<button onClick={() => handleUpdate({ theme: "dark" })}>
|
|
352
|
+
Update Theme
|
|
353
|
+
</button>
|
|
354
|
+
)
|
|
355
|
+
}
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
|
|
360
|
+
## File Structure
|
|
361
|
+
|
|
362
|
+
```
|
|
363
|
+
app/
|
|
364
|
+
├── api/
|
|
365
|
+
│ └── auth/
|
|
366
|
+
│ └── [...all]/
|
|
367
|
+
│ └── route.ts # Better Auth handler
|
|
368
|
+
├── (auth)/
|
|
369
|
+
│ ├── login/
|
|
370
|
+
│ │ └── page.tsx
|
|
371
|
+
│ ├── register/
|
|
372
|
+
│ │ └── page.tsx
|
|
373
|
+
│ └── layout.tsx
|
|
374
|
+
└── dashboard/
|
|
375
|
+
└── page.tsx # Protected route
|
|
376
|
+
lib/
|
|
377
|
+
├── auth.ts # Server config
|
|
378
|
+
├── auth-client.ts # Client instance
|
|
379
|
+
└── auth-server.ts # Enriched session wrapper
|
|
380
|
+
context/
|
|
381
|
+
└── session-context.tsx # Provider + hook
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
---
|
|
385
|
+
|
|
386
|
+
## Database Model Changes (from NextAuth)
|
|
387
|
+
|
|
388
|
+
| NextAuth | Better Auth |
|
|
389
|
+
|----------|-------------|
|
|
390
|
+
| `sessionToken` | `token` |
|
|
391
|
+
| `expires` | `expiresAt` |
|
|
392
|
+
| `emailVerified` (Date) | `emailVerified` (boolean) |
|
|
393
|
+
|
|
394
|
+
Additional Better Auth fields:
|
|
395
|
+
- `ipAddress`, `userAgent` on Session
|
|
396
|
+
- `createdAt`, `updatedAt` on all models
|
|
397
|
+
- `password` field on Account for credentials
|
|
398
|
+
|
|
399
|
+
---
|
|
400
|
+
|
|
401
|
+
## Rules
|
|
402
|
+
|
|
403
|
+
1. **Server session:** Always use `getSession()` from `lib/auth-server.ts`
|
|
404
|
+
2. **Client session:** Always use `useSession()` from context
|
|
405
|
+
3. **Single source of truth:** Don't re-fetch user data inconsistently
|
|
406
|
+
4. **Type safety:** Infer types from `getSession` return type
|
|
407
|
+
5. **Prefer async RSC patterns** and `use()` in appropriate boundaries
|
|
408
|
+
|
|
409
|
+
---
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
# Feishu + Better Auth OAuth Integration
|
|
413
|
+
|
|
414
|
+
Integrate Feishu (飞书) / Lark OAuth login with Better Auth in Next.js using the `genericOAuth` plugin.
|
|
415
|
+
|
|
416
|
+
## Architecture
|
|
417
|
+
|
|
418
|
+
```
|
|
419
|
+
Browser → /api/auth/sign-in/social {provider:"feishu"}
|
|
420
|
+
→ 302 → accounts.feishu.cn/open-apis/authen/v1/authorize
|
|
421
|
+
→ user approves → callback with ?code=...
|
|
422
|
+
→ Better Auth exchanges code for token (POST tokenUrl)
|
|
423
|
+
→ Better Auth calls getUserInfo → creates/links user + account
|
|
424
|
+
→ session cookie set → redirect to app
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
## Prerequisites
|
|
428
|
+
|
|
429
|
+
- Better Auth v1.5+ with `genericOAuth` plugin
|
|
430
|
+
- Feishu App (Internal Enterprise or Marketplace) with **Web Application** capability enabled
|
|
431
|
+
- `verification` table in DB (required by genericOAuth plugin)
|
|
432
|
+
|
|
433
|
+
## Step 1 — Feishu App Setup
|
|
434
|
+
|
|
435
|
+
1. Create app at [Feishu Open Platform](https://open.feishu.cn/app)
|
|
436
|
+
2. Enable **Web Application** capability (Security Settings → Redirect URLs)
|
|
437
|
+
3. Add redirect URL: `https://<your-domain>/api/auth/oauth2/callback/feishu`
|
|
438
|
+
4. Note your **App ID** (`cli_xxx`) and **App Secret**
|
|
439
|
+
5. Request scopes:
|
|
440
|
+
- `contact:user.email:readonly` — **requires admin approval** (高级权限: Enable → Create version → Submit → Admin approve)
|
|
441
|
+
|
|
442
|
+
> ⚠️ Until email permission is approved, Feishu returns empty string `""` for email (not omitted). Use fallback pattern.
|
|
443
|
+
|
|
444
|
+
## Step 2 — Server Auth Config
|
|
445
|
+
|
|
446
|
+
```typescript
|
|
447
|
+
// src/lib/auth.ts
|
|
448
|
+
import { betterAuth } from "better-auth";
|
|
449
|
+
import { prismaAdapter } from "@better-auth/prisma-adapter";
|
|
450
|
+
import { genericOAuth } from "better-auth/plugins";
|
|
451
|
+
import prisma from "@/lib/db";
|
|
452
|
+
|
|
453
|
+
const FEISHU_BASE = process.env.FEISHU_BASE_URL ?? "feishu.cn";
|
|
454
|
+
|
|
455
|
+
export const auth = betterAuth({
|
|
456
|
+
database: prismaAdapter(prisma, { provider: "postgresql" }),
|
|
457
|
+
emailAndPassword: { enabled: true },
|
|
458
|
+
session: {
|
|
459
|
+
expiresIn: 60 * 60 * 24 * 7,
|
|
460
|
+
updateAge: 60 * 60 * 24,
|
|
461
|
+
},
|
|
462
|
+
trustedOrigins: [
|
|
463
|
+
process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
|
|
464
|
+
],
|
|
465
|
+
plugins: [
|
|
466
|
+
genericOAuth({
|
|
467
|
+
config: [
|
|
468
|
+
{
|
|
469
|
+
providerId: "feishu",
|
|
470
|
+
clientId: process.env.FEISHU_APP_ID!,
|
|
471
|
+
clientSecret: process.env.FEISHU_APP_SECRET!,
|
|
472
|
+
authorizationUrl: `https://accounts.${FEISHU_BASE}/open-apis/authen/v1/authorize`,
|
|
473
|
+
tokenUrl: `https://open.${FEISHU_BASE}/open-apis/authen/v2/oauth/token`,
|
|
474
|
+
scopes: ["contact:user.email:readonly"],
|
|
475
|
+
authentication: "post",
|
|
476
|
+
getUserInfo: async (tokens) => {
|
|
477
|
+
const res = await fetch(
|
|
478
|
+
`https://open.${FEISHU_BASE}/open-apis/authen/v1/user_info`,
|
|
479
|
+
{ headers: { Authorization: `Bearer ${tokens.accessToken}` } },
|
|
480
|
+
);
|
|
481
|
+
if (!res.ok) throw new Error(`Feishu userinfo failed: ${res.status}`);
|
|
482
|
+
const json = await res.json();
|
|
483
|
+
const profile = json.data || json;
|
|
484
|
+
return {
|
|
485
|
+
id: profile.open_id,
|
|
486
|
+
name: profile.name || profile.en_name,
|
|
487
|
+
email: profile.email || `${profile.open_id}@feishu.local`,
|
|
488
|
+
image: profile.avatar_url,
|
|
489
|
+
emailVerified: false,
|
|
490
|
+
};
|
|
491
|
+
},
|
|
492
|
+
},
|
|
493
|
+
],
|
|
494
|
+
}),
|
|
495
|
+
],
|
|
496
|
+
});
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
### Critical details
|
|
500
|
+
|
|
501
|
+
- **`authentication: "post"`** — Feishu token endpoint requires `client_id`/`client_secret` in JSON body (not Basic auth header)
|
|
502
|
+
- **`getUserInfo` over `mapProfileToUser`** — when `getUserInfo` is provided, `mapProfileToUser` is ignored; don't use both
|
|
503
|
+
- **`tokens.accessToken`** — Better Auth normalizes to camelCase; NOT `access_token`
|
|
504
|
+
- **`json.data`** — Feishu nests all user info under a `data` key; unwrap exactly once
|
|
505
|
+
- **`emailVerified: false`** — must be Boolean, not DateTime (Better Auth schema requirement)
|
|
506
|
+
- **Fallback email** — `${open_id}@feishu.local` when email scope not yet approved
|
|
507
|
+
|
|
508
|
+
## Step 3 — Client Config
|
|
509
|
+
|
|
510
|
+
```typescript
|
|
511
|
+
// src/lib/auth-client.ts
|
|
512
|
+
import { createAuthClient } from "better-auth/react";
|
|
513
|
+
import { genericOAuthClient } from "better-auth/client/plugins";
|
|
514
|
+
|
|
515
|
+
export const authClient = createAuthClient({
|
|
516
|
+
baseURL: process.env.NEXT_PUBLIC_APP_URL,
|
|
517
|
+
plugins: [genericOAuthClient()],
|
|
518
|
+
});
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
## Step 4 — Route Handler
|
|
522
|
+
|
|
523
|
+
```typescript
|
|
524
|
+
// src/app/api/auth/[...all]/route.ts
|
|
525
|
+
import { toNextJsHandler } from "better-auth/next-js";
|
|
526
|
+
import { auth } from "@/lib/auth";
|
|
527
|
+
|
|
528
|
+
export const { GET, POST } = toNextJsHandler(auth);
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
> ⚠️ **Must use `toNextJsHandler`** from `better-auth/next-js`. Manual `auth.handler(req as unknown as Request)` breaks in Next.js 16 standalone mode.
|
|
532
|
+
|
|
533
|
+
## Step 5 — Database Schema
|
|
534
|
+
|
|
535
|
+
See [references/feishu-api.md](references/feishu-api.md) for the complete Prisma models (User, Session, Account, Verification).
|
|
536
|
+
|
|
537
|
+
**Schema gotchas to watch for:**
|
|
538
|
+
|
|
539
|
+
| Issue | Cause | Fix |
|
|
540
|
+
|-------|-------|-----|
|
|
541
|
+
| `emailVerified` insert fails | Schema has `DateTime` not `Boolean` | Migrate: `ALTER COLUMN TYPE BOOLEAN` |
|
|
542
|
+
| Account insert fails | Missing `At` suffix | Rename: `accessTokenExpires` → `accessTokenExpiresAt` |
|
|
543
|
+
| 500 on sign-in | Missing `Verification` model | Add Verification model, run migration |
|
|
544
|
+
|
|
545
|
+
## Step 6 — Environment Variables
|
|
546
|
+
|
|
547
|
+
```bash
|
|
548
|
+
# Feishu OAuth
|
|
549
|
+
FEISHU_APP_ID=cli_xxxxxxxxxxxx # From Feishu Dev Console
|
|
550
|
+
FEISHU_APP_SECRET=xxxxxxxxxxxx # Store in Secret Manager — no trailing newline!
|
|
551
|
+
FEISHU_BASE_URL=feishu.cn # or larksuite.com for international
|
|
552
|
+
|
|
553
|
+
# Better Auth
|
|
554
|
+
BETTER_AUTH_SECRET=<random-string>
|
|
555
|
+
BETTER_AUTH_URL=https://your-app.example.com # Required for deployed apps
|
|
556
|
+
|
|
557
|
+
# App URL (compile-time)
|
|
558
|
+
NEXT_PUBLIC_APP_URL=https://your-app.example.com
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
### Secret Manager warning
|
|
562
|
+
|
|
563
|
+
When storing secrets via `gcloud secrets versions add`:
|
|
564
|
+
```bash
|
|
565
|
+
# ✅ CORRECT — no trailing newline
|
|
566
|
+
printf '%s' 'your-secret-value' | gcloud secrets versions add SECRET_NAME --data-file=-
|
|
567
|
+
|
|
568
|
+
# ❌ WRONG — echo/add adds \n which breaks OAuth token exchange
|
|
569
|
+
echo 'your-secret-value' | gcloud secrets versions add SECRET_NAME --data-file=-
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
## Step 7 — Trigger Login
|
|
573
|
+
|
|
574
|
+
```typescript
|
|
575
|
+
// In a React component
|
|
576
|
+
import { authClient } from "@/lib/auth-client";
|
|
577
|
+
|
|
578
|
+
const handleFeishuLogin = () => {
|
|
579
|
+
authClient.signIn.social({ provider: "feishu", callbackURL: "/" });
|
|
580
|
+
};
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
## Troubleshooting
|
|
584
|
+
|
|
585
|
+
| Symptom | Cause | Fix |
|
|
586
|
+
|---------|-------|-----|
|
|
587
|
+
| `email_is_missing` or empty email | `contact:user.email:readonly` not approved | Request admin approval; use `@feishu.local` fallback |
|
|
588
|
+
| Token exchange fails | Trailing `\n` in app secret | Re-create secret with `printf '%s'` |
|
|
589
|
+
| 404 on `/api/auth/*` | Missing `toNextJsHandler` | Use `better-auth/next-js` adapter, not manual handler |
|
|
590
|
+
| Session not persisting | `BETTER_AUTH_URL` not set | Set env var to deployed URL |
|
|
591
|
+
| Error 20029 | Redirect URL not registered | Add exact callback URL in Feishu app settings |
|
|
592
|
+
|
|
593
|
+
## References
|
|
594
|
+
|
|
595
|
+
- [Feishu Open Platform](https://open.feishu.cn/app)
|
|
596
|
+
- [Better Auth genericOAuth Plugin](https://www.better-auth.com/docs/plugins/generic-oauth)
|
|
597
|
+
- [Better Auth Next.js Adapter](https://www.better-auth.com/docs/integrations/next-js)
|
|
598
|
+
- **API reference:** [references/feishu-api.md](references/feishu-api.md) — OAuth endpoints, request/response formats, user info fields, error codes, Prisma schema, and Feishu/Lark domain differences. Load this when implementing the OAuth flow or debugging auth errors.
|