@glinr/theauth-nextjs-auth 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/LICENSE +21 -0
- package/README.md +230 -0
- package/dist/index.d.ts +290 -0
- package/dist/index.js +459 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +168 -0
- package/dist/middleware.js +161 -0
- package/dist/middleware.js.map +1 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TheAuth
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# @glinr/theauth-nextjs-auth
|
|
2
|
+
|
|
3
|
+
Next.js 14/15/16 adapter for projects with an **external auth backend**. Handles cookies, proactive token refresh, CSRF double-submit, `getServerSession`, and middleware — all typed end-to-end.
|
|
4
|
+
|
|
5
|
+
## When to use this vs `@glinr/theauth-nextjs`
|
|
6
|
+
|
|
7
|
+
| | `@glinr/theauth-nextjs-auth` | `@glinr/theauth-nextjs` |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| **Use case** | You have an external auth backend (Spring, Rails, Hono, Express, etc.) and need session management on the Next.js FE | You're using the TheAuth agent-management runtime with its built-in auth |
|
|
10
|
+
| **Auth source** | External REST API (`/api/auth/*`) | In-process TheAuth SDK |
|
|
11
|
+
| **Zero deps on** | `@glinr/theauth` core, `@glinr/theauth-nextjs` | — |
|
|
12
|
+
| **Key exports** | `getServerSession`, `withAuth`, `refreshSession`, `fetchWithRefresh` | `kavachNextjs()` handler |
|
|
13
|
+
|
|
14
|
+
vs **next-auth**: next-auth requires a database adapter and runs auth in-process. Use `@glinr/theauth-nextjs-auth` when your backend already handles session state and you just want the FE plumbing.
|
|
15
|
+
|
|
16
|
+
vs **better-auth**: better-auth also runs in-process (or via a hosted service). Use this adapter when you cannot or do not want to run auth logic inside the Next.js process — only a REST call over the wire.
|
|
17
|
+
|
|
18
|
+
## Quickstart
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pnpm add @glinr/@glinr/theauth-nextjs-auth
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### 1. Create your config
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// src/lib/auth/config.ts
|
|
28
|
+
import "server-only";
|
|
29
|
+
import { createAuthConfig } from "@glinr/theauth-nextjs-auth";
|
|
30
|
+
|
|
31
|
+
export const authConfig = createAuthConfig({
|
|
32
|
+
backendUrl: process.env.NEXT_PUBLIC_API_BASE_URL!,
|
|
33
|
+
appUrl: process.env.NEXT_PUBLIC_APP_URL!,
|
|
34
|
+
tenantDomain: "myapp.com",
|
|
35
|
+
endpoints: {
|
|
36
|
+
me: "/api/v1/auth/me",
|
|
37
|
+
refresh: "/api/auth/refresh",
|
|
38
|
+
signOut: "/api/v1/auth/logout",
|
|
39
|
+
},
|
|
40
|
+
cookies: { sessionPrefix: "myapp" },
|
|
41
|
+
mapUser: (raw) => {
|
|
42
|
+
if (!raw || typeof raw !== "object") return null;
|
|
43
|
+
const r = raw as Record<string, unknown>;
|
|
44
|
+
return { id: String(r.id), email: String(r.email ?? ""), name: String(r.name ?? "") };
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 2. Get the session in Server Components
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
// app/dashboard/page.tsx
|
|
53
|
+
import { getServerSession } from "@glinr/theauth-nextjs-auth";
|
|
54
|
+
import { authConfig } from "@/lib/auth/config";
|
|
55
|
+
import { redirect } from "next/navigation";
|
|
56
|
+
|
|
57
|
+
export default async function DashboardPage() {
|
|
58
|
+
const session = await getServerSession(authConfig);
|
|
59
|
+
if (!session) redirect("/signin");
|
|
60
|
+
return <h1>Hello {session.user.name}</h1>;
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 3. Add middleware
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// middleware.ts (project root)
|
|
68
|
+
import { withAuth } from "@glinr/theauth-nextjs-auth/middleware";
|
|
69
|
+
import { authConfig } from "@/lib/auth/config";
|
|
70
|
+
|
|
71
|
+
export default withAuth(authConfig, {
|
|
72
|
+
protectedPaths: ["/app", "/dashboard"],
|
|
73
|
+
signInPath: "/signin",
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
export const config = {
|
|
77
|
+
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
|
|
78
|
+
};
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 4. Sign out
|
|
82
|
+
|
|
83
|
+
The adapter returns a plain async function — you add `"use server"` in **your own** file so Next.js can statically analyse it:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// src/app/auth/actions.ts ← your file, your directive
|
|
87
|
+
"use server";
|
|
88
|
+
import { createSignOutHandler } from "@glinr/theauth-nextjs-auth";
|
|
89
|
+
import { authConfig } from "@/lib/auth/config.server";
|
|
90
|
+
|
|
91
|
+
export const signOut = createSignOutHandler(authConfig);
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
// In any component
|
|
96
|
+
import { signOut } from "@/app/auth/actions";
|
|
97
|
+
<button onClick={signOut}>Sign out</button>
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
#### Why no inline `"use server"`?
|
|
101
|
+
|
|
102
|
+
The adapter is imported by both server and client module graphs (e.g. a client component that imports a shared config file). Next.js forbids inline `"use server"` directives in any module reachable from a client component — the compiler errors out. By keeping the directive out of the adapter, the compiled output is a plain async function that is safe to import anywhere. The `"use server"` annotation belongs in **consumer code** (a dedicated `actions.ts` file), where Next.js can statically verify it belongs to a server-action boundary.
|
|
103
|
+
|
|
104
|
+
## API Reference
|
|
105
|
+
|
|
106
|
+
### `createAuthConfig(input)` → `ResolvedAuthConfig<TUser>`
|
|
107
|
+
|
|
108
|
+
Factory that resolves all defaults. Returns an immutable config object passed to every other function.
|
|
109
|
+
|
|
110
|
+
| Option | Type | Default | Description |
|
|
111
|
+
|---|---|---|---|
|
|
112
|
+
| `backendUrl` | `string` | required | Backend base URL, no trailing slash |
|
|
113
|
+
| `appUrl` | `string` | required | Public app URL for Origin headers |
|
|
114
|
+
| `tenantDomain` | `string` | `""` | Sent as `X-Tenant-Domain` |
|
|
115
|
+
| `endpoints.me` | `string` | `"/api/auth/me"` | GET current user |
|
|
116
|
+
| `endpoints.refresh` | `string` | `"/api/auth/refresh"` | POST refresh token |
|
|
117
|
+
| `endpoints.signOut` | `string` | `"/api/auth/logout"` | POST sign out |
|
|
118
|
+
| `cookies.sessionPrefix` | `string` | `"glinr"` | Cookie name prefix |
|
|
119
|
+
| `cookies.refresh` | `string` | `"{prefix}-refresh-token"` | Refresh cookie name |
|
|
120
|
+
| `cookieCacheMaxAgeMs` | `number` | `300_000` (5 min) | Session cache TTL, `0` to disable |
|
|
121
|
+
| `expiryRefreshBufferS` | `number` | `60` | Proactive refresh threshold |
|
|
122
|
+
| `mapUser` | `(raw) => TUser \| null` | identity | Map backend payload to your User type |
|
|
123
|
+
| `isProd` | `boolean` | `NODE_ENV === "production"` | Controls `__Host-` cookie prefix |
|
|
124
|
+
|
|
125
|
+
### `getServerSession(config)` → `Promise<AuthSession<TUser> | null>`
|
|
126
|
+
|
|
127
|
+
Server-only. Returns the authenticated session or null.
|
|
128
|
+
|
|
129
|
+
Performance: memoized per render via `React.cache()` + cookie cache (5 min TTL by default). On cache miss, calls `GET /api/auth/me`. On 401, attempts one token refresh and retries.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
const session = await getServerSession(authConfig);
|
|
133
|
+
// session.user — your TUser shape
|
|
134
|
+
// session.expiresAt — Date | null (from JWT exp claim)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### `refreshSession(config)` → `Promise<RefreshResult | null>`
|
|
138
|
+
|
|
139
|
+
Server-only (Server Actions / Route Handlers). Reads the refresh token cookie, calls the backend, writes fresh cookies via `next/headers`. Returns null on failure or missing cookie.
|
|
140
|
+
|
|
141
|
+
### `fetchWithRefresh(config, path, init?)` → `Promise<Response>`
|
|
142
|
+
|
|
143
|
+
Server-only. Authenticated `fetch` with 401-retry. Builds auth headers, fires the request; on 401, refreshes once and retries.
|
|
144
|
+
|
|
145
|
+
### `graphqlWithRefresh<T>(config, document, variables?, opts?)` → `Promise<T>`
|
|
146
|
+
|
|
147
|
+
Server-only. Like `fetchWithRefresh` but for GraphQL. Throws `GraphQLRequestError` on GraphQL errors.
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
const data = await graphqlWithRefresh<MyQuery>(authConfig, MY_QUERY, { id: "123" });
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### `createSignOutHandler(config)` → `() => Promise<{ success: boolean }>`
|
|
154
|
+
|
|
155
|
+
Server-only. Returns an async function that calls the backend logout endpoint (best-effort) and clears all auth cookies. Does **not** include an inline `"use server"` directive — wrap it in your own `"use server"` file (see [Sign out](#4-sign-out)).
|
|
156
|
+
|
|
157
|
+
> `createSignOutAction` is a deprecated alias for `createSignOutHandler` and will be removed in v0.2.
|
|
158
|
+
|
|
159
|
+
### `buildAuthHeaders(config, opts?)` → `Promise<Record<string, string>>`
|
|
160
|
+
|
|
161
|
+
Server-only. Returns headers for server → backend calls: `Authorization`, `Origin`, `X-Client-Origin`, `X-Tenant-Domain`, `X-CSRF-Token`, `Cookie`.
|
|
162
|
+
|
|
163
|
+
### `buildClientHeaders(config)` → `Record<string, string>`
|
|
164
|
+
|
|
165
|
+
Client-safe. Returns minimal headers for browser → backend fetches (no auth headers, no Origin). The browser sends auth cookies and Origin automatically.
|
|
166
|
+
|
|
167
|
+
### `withAuth(config, options?)` (from `@glinr/theauth-nextjs-auth/middleware`)
|
|
168
|
+
|
|
169
|
+
Edge-runtime safe. Returns a Next.js middleware function.
|
|
170
|
+
|
|
171
|
+
Options:
|
|
172
|
+
- `protectedPaths: string[]` — paths requiring auth; redirects to `signInPath?next=<path>` when unauthenticated
|
|
173
|
+
- `signInPath: string` — default `"/signin"`
|
|
174
|
+
- `refreshTimeoutMs: number` — default `4000`
|
|
175
|
+
|
|
176
|
+
## TypeScript — custom User shape
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
interface MyUser {
|
|
180
|
+
id: string;
|
|
181
|
+
email: string;
|
|
182
|
+
role: "admin" | "member";
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export const authConfig = createAuthConfig<MyUser>({
|
|
186
|
+
backendUrl: "...",
|
|
187
|
+
appUrl: "...",
|
|
188
|
+
mapUser: (raw) => {
|
|
189
|
+
const r = raw as Record<string, unknown>;
|
|
190
|
+
if (!r.id) return null;
|
|
191
|
+
return { id: String(r.id), email: String(r.email), role: r.role as "admin" | "member" };
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// getServerSession returns AuthSession<MyUser>
|
|
196
|
+
const session = await getServerSession(authConfig);
|
|
197
|
+
session?.user.role; // typed as "admin" | "member"
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
## Cookie cache tradeoffs
|
|
201
|
+
|
|
202
|
+
The session cache stores `{ user, expiresAt, stampedAt }` in a short-lived httpOnly cookie. On cache hit (within `cookieCacheMaxAgeMs`), `getServerSession` returns immediately without calling the backend.
|
|
203
|
+
|
|
204
|
+
**Benefits**: reduces backend load; avoids 50–200ms network hop per RSC render.
|
|
205
|
+
|
|
206
|
+
**Tradeoffs**:
|
|
207
|
+
- Stale user data for up to `cookieCacheMaxAgeMs`. Acceptable for display data (name, email); not suitable for permission checks that need real-time accuracy.
|
|
208
|
+
- v0.1 stores plain JSON (no HMAC signing). The cookie is httpOnly+sameSite=lax — an attacker needs TLS access to read or forge it. v0.2 will add HMAC-SHA256 signing for defence-in-depth.
|
|
209
|
+
- Set `cookieCacheMaxAgeMs: 0` to disable caching entirely (every RSC render hits the backend).
|
|
210
|
+
|
|
211
|
+
Better-auth uses the same approach: a `session_data` cookie with configurable `maxAge` avoiding DB round-trips. Their v1 uses compact base64url+HMAC, JWT, or JWE encoding. We start with plain JSON for simplicity.
|
|
212
|
+
|
|
213
|
+
## CSRF protection
|
|
214
|
+
|
|
215
|
+
Uses the double-submit cookie pattern:
|
|
216
|
+
1. On login, the server sets a CSRF token in a **non-httpOnly** cookie so JS can read it.
|
|
217
|
+
2. On mutating requests, the client echoes it as `X-CSRF-Token`.
|
|
218
|
+
3. The backend compares header value vs. cookie value; they must match.
|
|
219
|
+
4. An attacker on a different origin cannot read the cookie → cannot forge the header.
|
|
220
|
+
|
|
221
|
+
`buildAuthHeaders` includes both `X-CSRF-Token` and a `Cookie` echo of the plain (non-`__Host-`) CSRF cookie name, matching TheAuth Spring backends that use a `CsrfDoubleSubmitFilter`.
|
|
222
|
+
|
|
223
|
+
## Cookie prefix policy
|
|
224
|
+
|
|
225
|
+
- **Production (HTTPS)**: `__Host-{prefix}-token`, `__Host-{prefix}-csrf`
|
|
226
|
+
- `__Host-` requires `Secure`, no `Domain`, `Path=/` — maximally restrictive
|
|
227
|
+
- **Development (HTTP)**: `{prefix}-token`, `{prefix}-csrf`
|
|
228
|
+
- Browsers reject `__Host-` without `Secure`; plain names are used instead
|
|
229
|
+
- **Refresh token**: never `__Host-` prefixed (longer-lived, `sameSite=lax`)
|
|
230
|
+
- Auto-detected from `isProd` / `NODE_ENV`
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
|
|
3
|
+
interface DefaultUser {
|
|
4
|
+
id: string;
|
|
5
|
+
email?: string | null;
|
|
6
|
+
name?: string | null;
|
|
7
|
+
avatarUrl?: string | null;
|
|
8
|
+
}
|
|
9
|
+
interface AuthSession<TUser = DefaultUser> {
|
|
10
|
+
user: TUser;
|
|
11
|
+
/** Parsed from JWT `exp` claim, or null when JWT has no exp. */
|
|
12
|
+
expiresAt: Date | null;
|
|
13
|
+
}
|
|
14
|
+
/** All endpoint path overrides. Defaults to TheAuth/glinr.me conventions. */
|
|
15
|
+
interface AuthEndpoints {
|
|
16
|
+
/** GET — returns current user payload. Default: "/api/auth/me" */
|
|
17
|
+
me: string;
|
|
18
|
+
/** POST body: { refreshToken }. Default: "/api/auth/refresh" */
|
|
19
|
+
refresh: string;
|
|
20
|
+
/** POST — invalidates session on backend. Default: "/api/auth/logout" */
|
|
21
|
+
signOut: string;
|
|
22
|
+
}
|
|
23
|
+
/** Cookie name / prefix overrides. */
|
|
24
|
+
interface AuthCookieConfig {
|
|
25
|
+
/**
|
|
26
|
+
* Prefix used to derive the session + CSRF cookie names.
|
|
27
|
+
* Default: "glinr"
|
|
28
|
+
* Prod: __Host-{prefix}-token / __Host-{prefix}-csrf
|
|
29
|
+
* Dev: {prefix}-token / {prefix}-csrf
|
|
30
|
+
*/
|
|
31
|
+
sessionPrefix: string;
|
|
32
|
+
/** Override the refresh-token cookie name. Default: "{prefix}-refresh-token" */
|
|
33
|
+
refresh: string;
|
|
34
|
+
}
|
|
35
|
+
interface AuthConfig<TUser = DefaultUser> {
|
|
36
|
+
/** Backend URL, no trailing slash. E.g. "https://api.example.com" */
|
|
37
|
+
backendUrl: string;
|
|
38
|
+
/** Public app URL used for Origin / X-Client-Origin headers. */
|
|
39
|
+
appUrl: string;
|
|
40
|
+
/** Tenant identifier sent as X-Tenant-Domain. Optional. */
|
|
41
|
+
tenantDomain?: string;
|
|
42
|
+
/** Endpoint path overrides. Defaults to TheAuth conventions. */
|
|
43
|
+
endpoints?: Partial<AuthEndpoints>;
|
|
44
|
+
/** Cookie name overrides. */
|
|
45
|
+
cookies?: Partial<AuthCookieConfig>;
|
|
46
|
+
/**
|
|
47
|
+
* Skip calling the backend for getServerSession() if the session cache
|
|
48
|
+
* cookie is fresher than this many milliseconds. Set to 0 to disable.
|
|
49
|
+
* Default: 300_000 (5 minutes — matches better-auth's cookie cache TTL).
|
|
50
|
+
*/
|
|
51
|
+
cookieCacheMaxAgeMs?: number;
|
|
52
|
+
/**
|
|
53
|
+
* Proactively refresh the access token when fewer than this many seconds
|
|
54
|
+
* of life remain on the JWT. Default: 60.
|
|
55
|
+
*/
|
|
56
|
+
expiryRefreshBufferS?: number;
|
|
57
|
+
/**
|
|
58
|
+
* Map the raw backend response from the /me endpoint to your TUser shape.
|
|
59
|
+
* If omitted, the raw response is cast to TUser directly.
|
|
60
|
+
*/
|
|
61
|
+
mapUser?: (raw: unknown) => TUser | null;
|
|
62
|
+
/**
|
|
63
|
+
* Whether the app is running on HTTPS. Controls __Host-/plain cookie
|
|
64
|
+
* prefix selection. Auto-detected from NODE_ENV when omitted.
|
|
65
|
+
*/
|
|
66
|
+
isProd?: boolean;
|
|
67
|
+
}
|
|
68
|
+
/** Fully resolved config with all defaults applied. */
|
|
69
|
+
interface ResolvedAuthConfig<TUser = DefaultUser> {
|
|
70
|
+
backendUrl: string;
|
|
71
|
+
appUrl: string;
|
|
72
|
+
tenantDomain: string;
|
|
73
|
+
endpoints: AuthEndpoints;
|
|
74
|
+
cookies: AuthCookieConfig & {
|
|
75
|
+
/** Computed full session cookie name (env-aware). */
|
|
76
|
+
sessionName: string;
|
|
77
|
+
/** Computed full CSRF cookie name (env-aware). */
|
|
78
|
+
csrfName: string;
|
|
79
|
+
/** Session cache cookie name. */
|
|
80
|
+
cacheName: string;
|
|
81
|
+
};
|
|
82
|
+
cookieCacheMaxAgeMs: number;
|
|
83
|
+
expiryRefreshBufferS: number;
|
|
84
|
+
mapUser: (raw: unknown) => TUser | null;
|
|
85
|
+
isProd: boolean;
|
|
86
|
+
}
|
|
87
|
+
/** Returned by refreshSession() on success. */
|
|
88
|
+
interface RefreshResult {
|
|
89
|
+
accessToken: string;
|
|
90
|
+
refreshToken?: string;
|
|
91
|
+
csrfToken: string;
|
|
92
|
+
}
|
|
93
|
+
/** Shape stored inside the session cache cookie. */
|
|
94
|
+
interface SessionCacheEntry<TUser = DefaultUser> {
|
|
95
|
+
user: TUser;
|
|
96
|
+
expiresAt: string | null;
|
|
97
|
+
stampedAt: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Authenticated server-side fetch for REST endpoints with automatic 401-retry.
|
|
102
|
+
*
|
|
103
|
+
* On 401: refreshes the session once and retries. If still 401 after refresh,
|
|
104
|
+
* returns the failed Response — callers decide how to handle.
|
|
105
|
+
*
|
|
106
|
+
* Returns the raw Response. Throws only on network errors.
|
|
107
|
+
*/
|
|
108
|
+
declare function fetchWithRefresh<TUser>(config: ResolvedAuthConfig<TUser>, path: string, init?: RequestInit): Promise<Response>;
|
|
109
|
+
declare class GraphQLRequestError extends Error {
|
|
110
|
+
readonly errors: Array<{
|
|
111
|
+
message: string;
|
|
112
|
+
extensions?: {
|
|
113
|
+
code?: string;
|
|
114
|
+
};
|
|
115
|
+
}>;
|
|
116
|
+
readonly status: number;
|
|
117
|
+
constructor(errors: Array<{
|
|
118
|
+
message: string;
|
|
119
|
+
extensions?: {
|
|
120
|
+
code?: string;
|
|
121
|
+
};
|
|
122
|
+
}>, status: number);
|
|
123
|
+
}
|
|
124
|
+
interface GraphQLOptions {
|
|
125
|
+
graphqlUrl?: string;
|
|
126
|
+
/** Additional HTTP headers to merge in. */
|
|
127
|
+
extraHeaders?: Record<string, string>;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Executes a GraphQL request against the backend, with auth-retry on failure.
|
|
131
|
+
*
|
|
132
|
+
* Retry is triggered by either:
|
|
133
|
+
* - HTTP 401 (load-balancer / WAF level rejection)
|
|
134
|
+
* - HTTP 200 with errors[].extensions.code === "UNAUTHENTICATED" or "UNAUTHORIZED"
|
|
135
|
+
* (GraphQL-level auth errors from Apollo Server, Hasura, GraphQL-Java, etc.)
|
|
136
|
+
*
|
|
137
|
+
* Only one retry attempt is made regardless of which path triggers it.
|
|
138
|
+
* Throws GraphQLRequestError on GraphQL errors or non-JSON responses.
|
|
139
|
+
*/
|
|
140
|
+
declare function graphqlWithRefresh<T, TUser>(config: ResolvedAuthConfig<TUser>, document: string, variables?: Record<string, unknown>, opts?: GraphQLOptions): Promise<T>;
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Factory that resolves defaults and returns an immutable config object.
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```ts
|
|
147
|
+
* // src/lib/auth/config.ts
|
|
148
|
+
* import "server-only";
|
|
149
|
+
* import { createAuthConfig } from "@glinr/theauth-nextjs-auth";
|
|
150
|
+
*
|
|
151
|
+
* export const authConfig = createAuthConfig({
|
|
152
|
+
* backendUrl: process.env.NEXT_PUBLIC_API_BASE_URL!,
|
|
153
|
+
* appUrl: process.env.NEXT_PUBLIC_APP_URL!,
|
|
154
|
+
* tenantDomain: "myapp.com",
|
|
155
|
+
* mapUser: (raw) => {
|
|
156
|
+
* if (!raw || typeof raw !== "object") return null;
|
|
157
|
+
* const r = raw as Record<string, unknown>;
|
|
158
|
+
* return { id: String(r.id), email: String(r.email ?? ""), name: String(r.name ?? "") };
|
|
159
|
+
* },
|
|
160
|
+
* });
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
declare function createAuthConfig<TUser = DefaultUser>(input: AuthConfig<TUser>): ResolvedAuthConfig<TUser>;
|
|
164
|
+
|
|
165
|
+
/** Returns the session access token, checking prefixed + unprefixed names. */
|
|
166
|
+
declare function getSessionToken<TUser>(config: ResolvedAuthConfig<TUser>): Promise<string>;
|
|
167
|
+
/** Returns the CSRF token, checking prefixed + unprefixed names. */
|
|
168
|
+
declare function getCsrfToken<TUser>(config: ResolvedAuthConfig<TUser>): Promise<string>;
|
|
169
|
+
/** Cheap check: does the request carry a session access token? */
|
|
170
|
+
declare function hasSessionCookie<TUser>(config: ResolvedAuthConfig<TUser>): Promise<boolean>;
|
|
171
|
+
interface SessionCookieValues {
|
|
172
|
+
accessToken: string;
|
|
173
|
+
csrfToken: string;
|
|
174
|
+
refreshToken?: string;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Writes all session cookies onto a NextResponse with consistent options.
|
|
178
|
+
* Uses __Host- prefix in prod, plain names in dev.
|
|
179
|
+
*/
|
|
180
|
+
declare function setSessionCookies<TUser>(response: NextResponse, { accessToken, csrfToken, refreshToken }: SessionCookieValues, config: ResolvedAuthConfig<TUser>): void;
|
|
181
|
+
/**
|
|
182
|
+
* Clears all auth cookies on a NextResponse.
|
|
183
|
+
* Deletes both __Host- prefixed and plain variants for clean migration.
|
|
184
|
+
*/
|
|
185
|
+
declare function clearAllAuthCookies<TUser>(response: NextResponse, config: ResolvedAuthConfig<TUser>): void;
|
|
186
|
+
/** Clears session cookies via next/headers cookies() store (server actions). */
|
|
187
|
+
declare function clearAllAuthCookiesFromStore<TUser>(config: ResolvedAuthConfig<TUser>): Promise<void>;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* CSRF token generation using Web Crypto.
|
|
191
|
+
* Works in Node.js 18+, Edge runtime, and browsers.
|
|
192
|
+
*
|
|
193
|
+
* We use the double-submit cookie pattern:
|
|
194
|
+
* - A short-lived CSRF token is set in a non-httpOnly cookie so JavaScript
|
|
195
|
+
* can read it.
|
|
196
|
+
* - On mutating requests the client echoes it as the X-CSRF-Token header.
|
|
197
|
+
* - The backend compares header value vs. cookie value; they must match.
|
|
198
|
+
* - An attacker on another origin cannot read the cookie, so they cannot
|
|
199
|
+
* forge the header value.
|
|
200
|
+
*/
|
|
201
|
+
declare function generateCsrfToken(): string;
|
|
202
|
+
|
|
203
|
+
interface BuildAuthHeadersOptions {
|
|
204
|
+
/** Include Authorization: Bearer <token>. Default: true. */
|
|
205
|
+
withAuth?: boolean;
|
|
206
|
+
/** Include X-CSRF-Token + Cookie echo. Default: true. */
|
|
207
|
+
withCsrf?: boolean;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Builds HTTP headers for SERVER → backend calls.
|
|
211
|
+
*
|
|
212
|
+
* Includes: Content-Type, Origin, X-Client-Origin, X-Tenant-Domain,
|
|
213
|
+
* Authorization Bearer (when withAuth), X-CSRF-Token + Cookie echo (when withCsrf).
|
|
214
|
+
*
|
|
215
|
+
* IMPORTANT: Do NOT use these in browser-side fetches. X-Client-Origin
|
|
216
|
+
* triggers a CORS preflight that backends typically reject from browser
|
|
217
|
+
* clients. Use buildClientHeaders() for client-side fetches instead.
|
|
218
|
+
*/
|
|
219
|
+
declare function buildAuthHeaders<TUser>(config: ResolvedAuthConfig<TUser>, opts?: BuildAuthHeadersOptions): Promise<Record<string, string>>;
|
|
220
|
+
/**
|
|
221
|
+
* Builds HTTP headers for BROWSER → backend fetches.
|
|
222
|
+
* Safe to import from "use client" components.
|
|
223
|
+
*
|
|
224
|
+
* Does NOT include Origin or X-Client-Origin — the browser sets Origin
|
|
225
|
+
* automatically on cross-origin requests. Does NOT include auth headers —
|
|
226
|
+
* the browser sends auth cookies automatically.
|
|
227
|
+
*/
|
|
228
|
+
declare function buildClientHeaders<TUser>(config: ResolvedAuthConfig<TUser>): Record<string, string>;
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Calls the backend refresh endpoint with the stored refresh-token cookie.
|
|
232
|
+
*
|
|
233
|
+
* On success: writes fresh access + CSRF cookies (and optionally a rotated
|
|
234
|
+
* refresh token) via next/headers cookies(). Returns the new token values so
|
|
235
|
+
* callers can immediately retry with fresh credentials.
|
|
236
|
+
*
|
|
237
|
+
* On failure:
|
|
238
|
+
* - Network error → returns null, does NOT clear cookies (may be transient).
|
|
239
|
+
* - 401/403 → clears all session cookies, returns null.
|
|
240
|
+
*
|
|
241
|
+
* Note: cookies() writes are only honoured from Server Actions and Route
|
|
242
|
+
* Handlers. Calling from a Server Component will succeed in-memory for this
|
|
243
|
+
* request but the browser will not receive Set-Cookie headers.
|
|
244
|
+
*/
|
|
245
|
+
declare function refreshSession<TUser>(config: ResolvedAuthConfig<TUser>): Promise<RefreshResult | null>;
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Returns an async function that signs the user out: POSTs to the backend
|
|
249
|
+
* sign-out endpoint (best-effort) and clears all session/csrf/refresh
|
|
250
|
+
* cookies on the response.
|
|
251
|
+
*
|
|
252
|
+
* IMPORTANT — usage:
|
|
253
|
+
* The adapter does NOT inline a `"use server"` directive. Wrap the returned
|
|
254
|
+
* handler in your OWN server-action file:
|
|
255
|
+
*
|
|
256
|
+
* // app/auth/actions.ts
|
|
257
|
+
* "use server";
|
|
258
|
+
* import { createSignOutHandler } from "@glinr/theauth-nextjs-auth";
|
|
259
|
+
* import { authConfig } from "@/lib/auth/config.server";
|
|
260
|
+
* export const signOut = createSignOutHandler(authConfig);
|
|
261
|
+
*
|
|
262
|
+
* This keeps the directive in your code (where Next.js can statically
|
|
263
|
+
* analyse it) and lets the adapter be safely imported from any client/
|
|
264
|
+
* server module without polluting client bundles.
|
|
265
|
+
*/
|
|
266
|
+
declare function createSignOutHandler<TUser>(config: ResolvedAuthConfig<TUser>): () => Promise<{
|
|
267
|
+
success: boolean;
|
|
268
|
+
}>;
|
|
269
|
+
/** @deprecated Use createSignOutHandler instead. createSignOutAction's inline
|
|
270
|
+
* "use server" directive breaks when the adapter is imported by a client
|
|
271
|
+
* component graph. */
|
|
272
|
+
declare const createSignOutAction: typeof createSignOutHandler;
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Fetches the authenticated session.
|
|
276
|
+
*
|
|
277
|
+
* Performance strategy (better-auth-inspired):
|
|
278
|
+
* 1. Per-request memo via React.cache() — repeated calls in the same render
|
|
279
|
+
* pass return instantly without any I/O.
|
|
280
|
+
* 2. Cookie cache — if the session cache cookie is fresher than
|
|
281
|
+
* config.cookieCacheMaxAgeMs, return cached user data without a backend call.
|
|
282
|
+
* 3. Backend call to config.endpoints.me — on 401, attempts one refresh;
|
|
283
|
+
* on second 401, returns null.
|
|
284
|
+
* 4. Writes the session cache cookie so subsequent RSCs skip the backend call.
|
|
285
|
+
*
|
|
286
|
+
* Cookie cache TTL default: 5 minutes (matches better-auth's cookieCache.maxAge).
|
|
287
|
+
*/
|
|
288
|
+
declare const getServerSession: <TUser>(config: ResolvedAuthConfig<TUser>) => Promise<AuthSession<TUser> | null>;
|
|
289
|
+
|
|
290
|
+
export { type AuthConfig, type AuthCookieConfig, type AuthEndpoints, type AuthSession, type DefaultUser, GraphQLRequestError, type RefreshResult, type ResolvedAuthConfig, type SessionCacheEntry, buildAuthHeaders, buildClientHeaders, clearAllAuthCookies, clearAllAuthCookiesFromStore, createAuthConfig, createSignOutAction, createSignOutHandler, fetchWithRefresh, generateCsrfToken, getCsrfToken, getServerSession, getSessionToken, graphqlWithRefresh, hasSessionCookie, refreshSession, setSessionCookies };
|