@eventuras/fides-auth-next 0.7.1 → 0.8.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 +122 -20
- package/dist/auth.d.ts +76 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +97 -0
- package/dist/auth.js.map +1 -0
- package/dist/cookie-store.d.ts +1 -1
- package/dist/cookie-store.js +1 -2
- package/dist/cookies.d.ts +21 -9
- package/dist/cookies.d.ts.map +1 -1
- package/dist/cookies.js +8 -10
- package/dist/cookies.js.map +1 -1
- package/dist/heartbeat-handler.d.ts +18 -3
- package/dist/heartbeat-handler.d.ts.map +1 -1
- package/dist/heartbeat-handler.js +6 -4
- package/dist/heartbeat-handler.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/oidc-callback.d.ts +16 -2
- package/dist/oidc-callback.d.ts.map +1 -1
- package/dist/oidc-callback.js +7 -3
- package/dist/oidc-callback.js.map +1 -1
- package/dist/oidc-login.d.ts +14 -3
- package/dist/oidc-login.d.ts.map +1 -1
- package/dist/oidc-login.js +6 -4
- package/dist/oidc-login.js.map +1 -1
- package/dist/oidc-logout.d.ts +13 -1
- package/dist/oidc-logout.d.ts.map +1 -1
- package/dist/oidc-logout.js +5 -2
- package/dist/oidc-logout.js.map +1 -1
- package/dist/request.d.ts +8 -0
- package/dist/request.d.ts.map +1 -1
- package/dist/request.js +9 -2
- package/dist/request.js.map +1 -1
- package/package.json +16 -16
- package/dist/session.d.ts +0 -120
- package/dist/session.d.ts.map +0 -1
- package/dist/session.js +0 -152
- package/dist/session.js.map +0 -1
package/README.md
CHANGED
|
@@ -43,33 +43,135 @@ const { logout } = useAuthActions();
|
|
|
43
43
|
- **OAuth**: Complete OAuth flow with PKCE and RP-initiated logout
|
|
44
44
|
- **TypeScript**: Full type safety
|
|
45
45
|
|
|
46
|
-
##
|
|
46
|
+
## Server Setup
|
|
47
|
+
|
|
48
|
+
Create one instance and import it where you need it. The library never reads
|
|
49
|
+
the environment, so pass the secret in:
|
|
47
50
|
|
|
48
51
|
```typescript
|
|
49
|
-
//
|
|
50
|
-
import {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
} from "@eventuras/fides-auth-next";
|
|
57
|
-
|
|
58
|
-
// Route handlers
|
|
59
|
-
import { handleOidcLogin } from "@eventuras/fides-auth-next/oidc-login";
|
|
60
|
-
import { handleOidcCallback } from "@eventuras/fides-auth-next/oidc-callback";
|
|
61
|
-
import { handleOidcLogout } from "@eventuras/fides-auth-next/oidc-logout";
|
|
62
|
-
|
|
63
|
-
// Client-side
|
|
64
|
-
import { useAuthStore, useAuthActions } from "./auth-store";
|
|
52
|
+
// lib/auth.ts
|
|
53
|
+
import { createFidesAuth } from "@eventuras/fides-auth-next";
|
|
54
|
+
|
|
55
|
+
export const auth = createFidesAuth({
|
|
56
|
+
secret: process.env.SESSION_SECRET!, // openssl rand -hex 32
|
|
57
|
+
oauthConfig,
|
|
58
|
+
});
|
|
65
59
|
```
|
|
66
60
|
|
|
67
|
-
|
|
61
|
+
Route handlers:
|
|
68
62
|
|
|
69
|
-
```
|
|
70
|
-
|
|
63
|
+
```typescript
|
|
64
|
+
// app/api/auth/login/route.ts
|
|
65
|
+
export const GET = (request: Request) => auth.handleOidcLogin(request);
|
|
66
|
+
|
|
67
|
+
// app/api/auth/callback/oidc/route.ts
|
|
68
|
+
export const GET = (request: Request) =>
|
|
69
|
+
auth.handleOidcCallback(request, { applicationUrl: "https://app.example.com" });
|
|
70
|
+
|
|
71
|
+
// app/api/auth/logout/route.ts
|
|
72
|
+
export const POST = (request: Request) =>
|
|
73
|
+
auth.handleOidcLogout(request, { postLogoutRedirectUri: "https://app.example.com/" });
|
|
74
|
+
|
|
75
|
+
// app/api/auth/heartbeat/route.ts
|
|
76
|
+
export const POST = (request: Request) => auth.handleHeartbeat(request);
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Server components, server actions and route handlers:
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
const session = await auth.getCurrentSession();
|
|
83
|
+
const { reason } = await auth.tryGetCurrentSession();
|
|
84
|
+
const refreshed = await auth.tryRefreshCurrentSession();
|
|
85
|
+
await auth.clearCurrentSession();
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
API calls with the access token. On a 401, `authorizedFetch` refreshes the
|
|
89
|
+
session and retries once; parallel calls in one request share the refresh. The
|
|
90
|
+
refresh writes cookies, so it works only in Server Actions and Route Handlers.
|
|
91
|
+
In a Server Component pass `refresh: false`, and a 401 is an `http_error`:
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
const api = { allowedBase: "https://api.example.com/v1/" };
|
|
95
|
+
|
|
96
|
+
// Server Action or Route Handler
|
|
97
|
+
const { data } = await auth.authorizedFetch(session, "users/me", {
|
|
98
|
+
...api,
|
|
99
|
+
parse: (response) => response.json(),
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// Server Component
|
|
103
|
+
const { data } = await auth.authorizedFetch(session, "users/me", { ...api, refresh: false });
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The handlers are also exported on their own (`@eventuras/fides-auth-next/oidc-login`
|
|
107
|
+
and so on). Those take `oauthConfig` and `secret` in their config.
|
|
108
|
+
|
|
109
|
+
## Server sessions
|
|
110
|
+
|
|
111
|
+
By default the session lives in encrypted cookies. Pass a `sessionStore` to keep
|
|
112
|
+
it on the server instead. The browser then holds only a random handle, in the
|
|
113
|
+
`session_ref` cookie:
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
// lib/auth.ts
|
|
117
|
+
import { createFidesAuth, type SessionStore } from "@eventuras/fides-auth-next";
|
|
118
|
+
|
|
119
|
+
const sessionStore: SessionStore = {
|
|
120
|
+
get: (key) => db.sessions.find(key),
|
|
121
|
+
set: (key, record) => db.sessions.save(key, record),
|
|
122
|
+
delete: (key) => db.sessions.remove(key),
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
export const auth = createFidesAuth({
|
|
126
|
+
secret: process.env.SESSION_SECRET!,
|
|
127
|
+
oauthConfig,
|
|
128
|
+
sessionStore,
|
|
129
|
+
});
|
|
71
130
|
```
|
|
72
131
|
|
|
132
|
+
Every handler and helper on `auth` then uses the store, and logout deletes the
|
|
133
|
+
record. `secret` is still required: it encrypts the records and seals the login
|
|
134
|
+
transaction.
|
|
135
|
+
|
|
136
|
+
Use a store that every instance shares, such as a database, and add `withLock`
|
|
137
|
+
when you run more than one instance. `createMemorySessionStore()` from
|
|
138
|
+
`@eventuras/fides-auth/server` is for tests. See
|
|
139
|
+
[Server-side sessions](../fides-auth/docs/server-sessions.md) for the store
|
|
140
|
+
contract and an adapter example.
|
|
141
|
+
|
|
142
|
+
## Rate limiting
|
|
143
|
+
|
|
144
|
+
The route handlers use a default limiter. It is deprecated, together with
|
|
145
|
+
`globalGETRateLimit`, `globalPOSTRateLimit` and `TokenBucket`: it keys on the raw
|
|
146
|
+
`X-Forwarded-For` header, which a client can send itself, and lets requests
|
|
147
|
+
without the header through.
|
|
148
|
+
|
|
149
|
+
For a limiter of your own, add `@eventuras/fides-auth` and call its handler from
|
|
150
|
+
`/server` with the Next cookie store and a `rateLimit` callback. Key it on
|
|
151
|
+
something the app trusts, such as the client address your own proxy sets. The
|
|
152
|
+
handler answers 429 when the callback returns `false`:
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
// app/api/auth/login/route.ts
|
|
156
|
+
import { handleOidcLogin } from "@eventuras/fides-auth/server";
|
|
157
|
+
import { nextCookieStore } from "@eventuras/fides-auth-next";
|
|
158
|
+
|
|
159
|
+
export async function GET(request: Request) {
|
|
160
|
+
return handleOidcLogin(request, {
|
|
161
|
+
oauthConfig,
|
|
162
|
+
secret: process.env.SESSION_SECRET!,
|
|
163
|
+
cookies: await nextCookieStore(),
|
|
164
|
+
rateLimit: () => limiter.consume(clientKey(request)),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`handleOidcCallback`, `handleOidcLogout` and `handleHeartbeat` take the same option.
|
|
170
|
+
With a `sessionStore`, also pass those three
|
|
171
|
+
`persistence: serverPersistence({ store: sessionStore, secret })`, or they keep
|
|
172
|
+
the session in cookies. Build it once. It does not share refreshes with `auth`,
|
|
173
|
+
so give the store `withLock`.
|
|
174
|
+
|
|
73
175
|
## Documentation
|
|
74
176
|
|
|
75
177
|
- [Store API](./src/store/) - XState Store details
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session helpers and route handlers, bound to one secret and OAuth config.
|
|
3
|
+
* No module state: the config lives in the returned object, so a module that
|
|
4
|
+
* Next loads more than once behaves the same.
|
|
5
|
+
*/
|
|
6
|
+
import { AuthorizedFetchError, type AuthorizedFetchErrorReason, type AuthorizedFetchOptions, type AuthorizedFetchResult, type ClearSessionOptions, type ReadSessionResult, type RefreshSessionResult, type SessionSecret, type SessionStore, type StoredSession } from '@eventuras/fides-auth/server';
|
|
7
|
+
import type { OAuthConfig } from '@eventuras/fides-auth/oauth';
|
|
8
|
+
import type { CreateSessionOptions, Session } from '@eventuras/fides-auth/types';
|
|
9
|
+
import { type OidcCallbackConfig } from './oidc-callback';
|
|
10
|
+
import { type OidcLoginConfig } from './oidc-login';
|
|
11
|
+
import { type OidcLogoutConfig } from './oidc-logout';
|
|
12
|
+
export type { ClearSessionOptions, ReadSessionResult, RefreshSessionResult, SessionSecret };
|
|
13
|
+
export type { SessionStore, StoredSession };
|
|
14
|
+
export type { AuthorizedFetchErrorReason, AuthorizedFetchOptions, AuthorizedFetchResult };
|
|
15
|
+
export { AuthorizedFetchError };
|
|
16
|
+
export interface FidesAuthConfig {
|
|
17
|
+
/** Session encryption secret, e.g. 64 hex chars. Also seals the login transaction. */
|
|
18
|
+
secret: SessionSecret;
|
|
19
|
+
/** OAuth/OIDC configuration. */
|
|
20
|
+
oauthConfig: OAuthConfig;
|
|
21
|
+
/**
|
|
22
|
+
* Keeps sessions in this store, encrypted under `secret`; the cookie holds only a handle.
|
|
23
|
+
* Omit to keep them in encrypted cookies.
|
|
24
|
+
*/
|
|
25
|
+
sessionStore?: SessionStore;
|
|
26
|
+
}
|
|
27
|
+
/** A handler's config minus what the factory binds. */
|
|
28
|
+
type Bound<T> = Omit<T, 'oauthConfig' | 'secret' | 'persistence'>;
|
|
29
|
+
export type BoundAuthorizedFetchOptions<T = undefined> = Omit<AuthorizedFetchOptions<T>, 'refresh'> & {
|
|
30
|
+
/**
|
|
31
|
+
* `false` skips the refresh, so a 401 is an `http_error`. Use it in a Server Component:
|
|
32
|
+
* Next won't let it write cookies, and a refresh that can't be saved spends the refresh token.
|
|
33
|
+
*/
|
|
34
|
+
refresh?: false;
|
|
35
|
+
};
|
|
36
|
+
export interface FidesAuth {
|
|
37
|
+
/** The current session, or null. Cached per render; the access token may have expired. */
|
|
38
|
+
getCurrentSession(): Promise<Session<any> | null>;
|
|
39
|
+
/** The current session, or why there is none. Shares the cache with `getCurrentSession`. */
|
|
40
|
+
tryGetCurrentSession(): Promise<ReadSessionResult>;
|
|
41
|
+
/** Refreshes the session and saves it. Null on any failure. */
|
|
42
|
+
refreshCurrentSession(options?: CreateSessionOptions): Promise<Session | null>;
|
|
43
|
+
/** Refreshes the session and, on failure, says why. Prefer it over `refreshCurrentSession`. */
|
|
44
|
+
tryRefreshCurrentSession(options?: CreateSessionOptions): Promise<RefreshSessionResult>;
|
|
45
|
+
/** Persists a new session. Returns the session cookie's value: the encrypted session, or the handle. */
|
|
46
|
+
createAndPersistSession(session: Session): Promise<string>;
|
|
47
|
+
/** Deletes the session cookies and, with a `sessionStore`, the record. `trigger` defaults to `logout`. */
|
|
48
|
+
clearCurrentSession(options?: ClearSessionOptions): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* `authorizedFetch` that, on a 401, refreshes the session and retries once.
|
|
51
|
+
* Parallel calls in one request share one refresh. The refresh writes cookies, so it works
|
|
52
|
+
* only in Server Actions and Route Handlers; pass `refresh: false` in a Server Component.
|
|
53
|
+
*/
|
|
54
|
+
authorizedFetch<T = undefined>(session: Session, url: string | URL, options: BoundAuthorizedFetchOptions<T>): Promise<AuthorizedFetchResult<T>>;
|
|
55
|
+
handleOidcLogin(request: Request, options?: Bound<OidcLoginConfig>): Promise<Response>;
|
|
56
|
+
handleOidcCallback(request: Request, options: Bound<OidcCallbackConfig>): Promise<Response>;
|
|
57
|
+
handleOidcLogout(request: Request, options: Bound<OidcLogoutConfig>): Promise<Response>;
|
|
58
|
+
handleHeartbeat(request: Request): Promise<Response>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Creates the app's auth helpers. Call it once and import the result.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```ts
|
|
65
|
+
* // lib/auth.ts
|
|
66
|
+
* export const auth = createFidesAuth({ secret: process.env.SESSION_SECRET!, oauthConfig });
|
|
67
|
+
*
|
|
68
|
+
* // app/api/auth/login/route.ts
|
|
69
|
+
* export const GET = (request: Request) => auth.handleOidcLogin(request);
|
|
70
|
+
*
|
|
71
|
+
* // A server component
|
|
72
|
+
* const session = await auth.getCurrentSession();
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export declare function createFidesAuth({ secret, oauthConfig, sessionStore }: FidesAuthConfig): FidesAuth;
|
|
76
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAEL,oBAAoB,EAOpB,KAAK,0BAA0B,EAC/B,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EAEzB,KAAK,aAAa,EAClB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DED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { nextCookieStore } from "./cookie-store.js";
|
|
2
|
+
import { handleHeartbeat as handleHeartbeat$1 } from "./heartbeat-handler.js";
|
|
3
|
+
import { handleOidcCallback as handleOidcCallback$1 } from "./oidc-callback.js";
|
|
4
|
+
import { handleOidcLogin as handleOidcLogin$1 } from "./oidc-login.js";
|
|
5
|
+
import { handleOidcLogout as handleOidcLogout$1 } from "./oidc-logout.js";
|
|
6
|
+
import { cookies } from "next/headers";
|
|
7
|
+
import { AuthorizedFetchError, authorizedFetch, clearSession, persistSession, refreshSessionInStore, serverPersistence, tryReadSession, tryRefreshSessionInStore } from "@eventuras/fides-auth/server";
|
|
8
|
+
import { cache } from "react";
|
|
9
|
+
// src/auth.ts
|
|
10
|
+
/**
|
|
11
|
+
* The session helpers and route handlers, bound to one secret and OAuth config.
|
|
12
|
+
* No module state: the config lives in the returned object, so a module that
|
|
13
|
+
* Next loads more than once behaves the same.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Creates the app's auth helpers. Call it once and import the result.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* // lib/auth.ts
|
|
21
|
+
* export const auth = createFidesAuth({ secret: process.env.SESSION_SECRET!, oauthConfig });
|
|
22
|
+
*
|
|
23
|
+
* // app/api/auth/login/route.ts
|
|
24
|
+
* export const GET = (request: Request) => auth.handleOidcLogin(request);
|
|
25
|
+
*
|
|
26
|
+
* // A server component
|
|
27
|
+
* const session = await auth.getCurrentSession();
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
function createFidesAuth({ secret, oauthConfig, sessionStore }) {
|
|
31
|
+
let persistence;
|
|
32
|
+
const serverSessions = () => {
|
|
33
|
+
if (sessionStore) persistence ??= serverPersistence({
|
|
34
|
+
store: sessionStore,
|
|
35
|
+
secret
|
|
36
|
+
});
|
|
37
|
+
return persistence;
|
|
38
|
+
};
|
|
39
|
+
/** Where sessions live: the store, or else the cookies under `secret`. */
|
|
40
|
+
const storage = () => serverSessions() ?? secret;
|
|
41
|
+
const tryGetCurrentSession = cache(async () => tryReadSession(await nextCookieStore(), storage()));
|
|
42
|
+
const getCurrentSession = cache(async () => (await tryGetCurrentSession()).session);
|
|
43
|
+
const refreshes = /* @__PURE__ */ new WeakMap();
|
|
44
|
+
const refreshOncePerRequest = async () => {
|
|
45
|
+
const requestCookies = await cookies();
|
|
46
|
+
let refresh = refreshes.get(requestCookies);
|
|
47
|
+
if (!refresh) {
|
|
48
|
+
refresh = nextCookieStore().then((store) => tryRefreshSessionInStore(store, oauthConfig, storage()));
|
|
49
|
+
refreshes.set(requestCookies, refresh);
|
|
50
|
+
}
|
|
51
|
+
return refresh;
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
getCurrentSession,
|
|
55
|
+
tryGetCurrentSession,
|
|
56
|
+
refreshCurrentSession: async (options = {}) => refreshSessionInStore(await nextCookieStore(), oauthConfig, storage(), options),
|
|
57
|
+
tryRefreshCurrentSession: async (options = {}) => tryRefreshSessionInStore(await nextCookieStore(), oauthConfig, storage(), options),
|
|
58
|
+
createAndPersistSession: async (session) => persistSession(await nextCookieStore(), session, storage()),
|
|
59
|
+
clearCurrentSession: async (options = {}) => {
|
|
60
|
+
const sid = options.sid ?? (await tryGetCurrentSession()).session?.sid;
|
|
61
|
+
await clearSession(await nextCookieStore(), {
|
|
62
|
+
trigger: options.trigger ?? "logout",
|
|
63
|
+
sid,
|
|
64
|
+
persistence: serverSessions()
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
authorizedFetch: (session, url, options) => authorizedFetch(session, url, {
|
|
68
|
+
...options,
|
|
69
|
+
refresh: options.refresh === false ? void 0 : refreshOncePerRequest
|
|
70
|
+
}),
|
|
71
|
+
handleOidcLogin: (request, options = {}) => handleOidcLogin$1(request, {
|
|
72
|
+
...options,
|
|
73
|
+
oauthConfig,
|
|
74
|
+
secret
|
|
75
|
+
}),
|
|
76
|
+
handleOidcCallback: (request, options) => handleOidcCallback$1(request, {
|
|
77
|
+
...options,
|
|
78
|
+
oauthConfig,
|
|
79
|
+
secret,
|
|
80
|
+
persistence: serverSessions()
|
|
81
|
+
}),
|
|
82
|
+
handleOidcLogout: (request, options) => handleOidcLogout$1(request, {
|
|
83
|
+
...options,
|
|
84
|
+
oauthConfig,
|
|
85
|
+
secret,
|
|
86
|
+
persistence: serverSessions()
|
|
87
|
+
}),
|
|
88
|
+
handleHeartbeat: (request) => handleHeartbeat$1(request, {
|
|
89
|
+
oauthConfig,
|
|
90
|
+
secret,
|
|
91
|
+
persistence: serverSessions()
|
|
92
|
+
})
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
export { AuthorizedFetchError, createFidesAuth };
|
|
96
|
+
|
|
97
|
+
//# sourceMappingURL=auth.js.map
|
package/dist/auth.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.js","names":["handleOidcLogin","handleOidcCallback","handleOidcLogout","handleHeartbeat"],"sources":["../src/auth.ts"],"sourcesContent":["/**\n * The session helpers and route handlers, bound to one secret and OAuth config.\n * No module state: the config lives in the returned object, so a module that\n * Next loads more than once behaves the same.\n */\n\nimport {\n authorizedFetch,\n AuthorizedFetchError,\n clearSession,\n persistSession,\n refreshSessionInStore,\n serverPersistence,\n tryReadSession,\n tryRefreshSessionInStore,\n type AuthorizedFetchErrorReason,\n type AuthorizedFetchOptions,\n type AuthorizedFetchResult,\n type ClearSessionOptions,\n type ReadSessionResult,\n type RefreshSessionResult,\n type SessionPersistence,\n type SessionSecret,\n type SessionStore,\n type StoredSession,\n} from '@eventuras/fides-auth/server';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport type { CreateSessionOptions, Session } from '@eventuras/fides-auth/types';\nimport { cookies } from 'next/headers';\nimport { cache } from 'react';\n\nimport { nextCookieStore } from './cookie-store';\nimport { handleHeartbeat } from './heartbeat-handler';\nimport { handleOidcCallback, type OidcCallbackConfig } from './oidc-callback';\nimport { handleOidcLogin, type OidcLoginConfig } from './oidc-login';\nimport { handleOidcLogout, type OidcLogoutConfig } from './oidc-logout';\n\n// So consumers can name the helpers' types without reaching past this package.\nexport type { ClearSessionOptions, ReadSessionResult, RefreshSessionResult, SessionSecret };\nexport type { SessionStore, StoredSession };\nexport type { AuthorizedFetchErrorReason, AuthorizedFetchOptions, AuthorizedFetchResult };\nexport { AuthorizedFetchError };\n\nexport interface FidesAuthConfig {\n /** Session encryption secret, e.g. 64 hex chars. Also seals the login transaction. */\n secret: SessionSecret;\n\n /** OAuth/OIDC configuration. */\n oauthConfig: OAuthConfig;\n\n /**\n * Keeps sessions in this store, encrypted under `secret`; the cookie holds only a handle.\n * Omit to keep them in encrypted cookies.\n */\n sessionStore?: SessionStore;\n}\n\n/** A handler's config minus what the factory binds. */\ntype Bound<T> = Omit<T, 'oauthConfig' | 'secret' | 'persistence'>;\n\nexport type BoundAuthorizedFetchOptions<T = undefined> = Omit<\n AuthorizedFetchOptions<T>,\n 'refresh'\n> & {\n /**\n * `false` skips the refresh, so a 401 is an `http_error`. Use it in a Server Component:\n * Next won't let it write cookies, and a refresh that can't be saved spends the refresh token.\n */\n refresh?: false;\n};\n\nexport interface FidesAuth {\n /** The current session, or null. Cached per render; the access token may have expired. */\n getCurrentSession(): Promise<Session<any> | null>;\n\n /** The current session, or why there is none. Shares the cache with `getCurrentSession`. */\n tryGetCurrentSession(): Promise<ReadSessionResult>;\n\n /** Refreshes the session and saves it. Null on any failure. */\n refreshCurrentSession(options?: CreateSessionOptions): Promise<Session | null>;\n\n /** Refreshes the session and, on failure, says why. Prefer it over `refreshCurrentSession`. */\n tryRefreshCurrentSession(options?: CreateSessionOptions): Promise<RefreshSessionResult>;\n\n /** Persists a new session. Returns the session cookie's value: the encrypted session, or the handle. */\n createAndPersistSession(session: Session): Promise<string>;\n\n /** Deletes the session cookies and, with a `sessionStore`, the record. `trigger` defaults to `logout`. */\n clearCurrentSession(options?: ClearSessionOptions): Promise<void>;\n\n /**\n * `authorizedFetch` that, on a 401, refreshes the session and retries once.\n * Parallel calls in one request share one refresh. The refresh writes cookies, so it works\n * only in Server Actions and Route Handlers; pass `refresh: false` in a Server Component.\n */\n authorizedFetch<T = undefined>(\n session: Session,\n url: string | URL,\n options: BoundAuthorizedFetchOptions<T>,\n ): Promise<AuthorizedFetchResult<T>>;\n\n handleOidcLogin(request: Request, options?: Bound<OidcLoginConfig>): Promise<Response>;\n handleOidcCallback(request: Request, options: Bound<OidcCallbackConfig>): Promise<Response>;\n handleOidcLogout(request: Request, options: Bound<OidcLogoutConfig>): Promise<Response>;\n handleHeartbeat(request: Request): Promise<Response>;\n}\n\n/**\n * Creates the app's auth helpers. Call it once and import the result.\n *\n * @example\n * ```ts\n * // lib/auth.ts\n * export const auth = createFidesAuth({ secret: process.env.SESSION_SECRET!, oauthConfig });\n *\n * // app/api/auth/login/route.ts\n * export const GET = (request: Request) => auth.handleOidcLogin(request);\n *\n * // A server component\n * const session = await auth.getCurrentSession();\n * ```\n */\nexport function createFidesAuth({ secret, oauthConfig, sessionStore }: FidesAuthConfig): FidesAuth {\n // One per instance, so refreshes of one session are shared across requests. Built on first use.\n let persistence: SessionPersistence | undefined;\n const serverSessions = (): SessionPersistence | undefined => {\n if (sessionStore) persistence ??= serverPersistence({ store: sessionStore, secret });\n return persistence;\n };\n /** Where sessions live: the store, or else the cookies under `secret`. */\n const storage = (): SessionSecret | SessionPersistence => serverSessions() ?? secret;\n\n const tryGetCurrentSession = cache(\n async (): Promise<ReadSessionResult> => tryReadSession(await nextCookieStore(), storage()),\n );\n const getCurrentSession = cache(async () => (await tryGetCurrentSession()).session);\n\n // Keyed by the request's cookies, so parallel 401s don't each spend the refresh token.\n // Needed with a store too, which joins only refreshes that overlap.\n const refreshes = new WeakMap<object, Promise<RefreshSessionResult>>();\n const refreshOncePerRequest = async (): Promise<RefreshSessionResult> => {\n const requestCookies = await cookies();\n let refresh = refreshes.get(requestCookies);\n if (!refresh) {\n refresh = nextCookieStore().then((store) =>\n tryRefreshSessionInStore(store, oauthConfig, storage()),\n );\n refreshes.set(requestCookies, refresh);\n }\n return refresh;\n };\n\n return {\n getCurrentSession,\n tryGetCurrentSession,\n\n refreshCurrentSession: async (options = {}) =>\n refreshSessionInStore(await nextCookieStore(), oauthConfig, storage(), options),\n\n tryRefreshCurrentSession: async (options = {}) =>\n tryRefreshSessionInStore(await nextCookieStore(), oauthConfig, storage(), options),\n\n createAndPersistSession: async (session) =>\n persistSession(await nextCookieStore(), session, storage()),\n\n clearCurrentSession: async (options = {}) => {\n // The sid comes from the per-render cache, so correlating the logout costs nothing.\n const sid = options.sid ?? (await tryGetCurrentSession()).session?.sid;\n await clearSession(await nextCookieStore(), {\n trigger: options.trigger ?? 'logout',\n sid,\n persistence: serverSessions(),\n });\n },\n\n authorizedFetch: (session, url, options) =>\n authorizedFetch(session, url, {\n ...options,\n refresh: options.refresh === false ? undefined : refreshOncePerRequest,\n }),\n\n // Login only seals the transaction cookie, so it takes the secret alone.\n handleOidcLogin: (request, options = {}) =>\n handleOidcLogin(request, { ...options, oauthConfig, secret }),\n handleOidcCallback: (request, options) =>\n handleOidcCallback(request, {\n ...options,\n oauthConfig,\n secret,\n persistence: serverSessions(),\n }),\n handleOidcLogout: (request, options) =>\n handleOidcLogout(request, {\n ...options,\n oauthConfig,\n secret,\n persistence: serverSessions(),\n }),\n handleHeartbeat: (request) =>\n handleHeartbeat(request, { oauthConfig, secret, persistence: serverSessions() }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0HA,SAAgB,gBAAgB,EAAE,QAAQ,aAAa,gBAA4C;CAEjG,IAAI;CACJ,MAAM,uBAAuD;EAC3D,IAAI,cAAc,gBAAgB,kBAAkB;GAAE,OAAO;GAAc;EAAO,CAAC;EACnF,OAAO;CACT;;CAEA,MAAM,gBAAoD,eAAe,KAAK;CAE9E,MAAM,uBAAuB,MAC3B,YAAwC,eAAe,MAAM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AiB,SAAS;GACxB,GAAG;GACH;GACA;GACA,aAAa,eAAe;EAC9B,CAAC;EACH,kBAAkB,YAChBC,kBAAgB,SAAS;GAAE;GAAa;GAAQ,aAAa,eAAe;EAAE,CAAC;CACnF;AACF"}
|
package/dist/cookie-store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CookieStore } from '@eventuras/fides-auth/server';
|
|
1
|
+
import type { CookieStore } from '@eventuras/fides-auth/server';
|
|
2
2
|
/**
|
|
3
3
|
* Builds a {@link CookieStore} backed by Next.js's request cookie store, for the
|
|
4
4
|
* framework-agnostic server helpers in `@eventuras/fides-auth/server`.
|
package/dist/cookie-store.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { cookies } from "next/headers";
|
|
2
|
-
|
|
2
|
+
// src/cookie-store.ts
|
|
3
3
|
/**
|
|
4
4
|
* Builds a {@link CookieStore} backed by Next.js's request cookie store, for the
|
|
5
5
|
* framework-agnostic server helpers in `@eventuras/fides-auth/server`.
|
|
@@ -19,7 +19,6 @@ async function nextCookieStore() {
|
|
|
19
19
|
}
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
|
-
//#endregion
|
|
23
22
|
export { nextCookieStore };
|
|
24
23
|
|
|
25
24
|
//# sourceMappingURL=cookie-store.js.map
|
package/dist/cookies.d.ts
CHANGED
|
@@ -1,4 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Cookie helpers for Next.js authentication flows.
|
|
3
|
+
*
|
|
4
|
+
* IMPORTANT: These functions can ONLY be used in:
|
|
5
|
+
* - Server Actions (functions marked with 'use server')
|
|
6
|
+
* - Route Handlers (files in app/api directory)
|
|
7
|
+
* - Server Components (async React components)
|
|
8
|
+
*
|
|
9
|
+
* They CANNOT be used in:
|
|
10
|
+
* - Client Components (marked with 'use client')
|
|
11
|
+
* - Middleware (use NextResponse.cookies instead)
|
|
12
|
+
* - Edge Runtime without proper configuration
|
|
13
|
+
*/
|
|
14
|
+
import type { CookieOptions } from '@eventuras/fides-auth/cookies';
|
|
2
15
|
export { COOKIE_INFO_BYTES, COOKIE_MAX_BYTES, CookieTooLargeError, ACCESS_TOKEN_COOKIE_NAME, ID_TOKEN_COOKIE_NAME, defaultSessionCookieOptions, defaultOAuthCookieOptions, cookieByteSize, assertCookieWithinLimit, } from '@eventuras/fides-auth/cookies';
|
|
3
16
|
export type { CookieOptions } from '@eventuras/fides-auth/cookies';
|
|
4
17
|
/**
|
|
@@ -14,8 +27,8 @@ export type { CookieOptions } from '@eventuras/fides-auth/cookies';
|
|
|
14
27
|
* await setAuthCookie('session', encryptedJwt);
|
|
15
28
|
*
|
|
16
29
|
* // With custom options
|
|
17
|
-
* await setAuthCookie(
|
|
18
|
-
* maxAge: 60 *
|
|
30
|
+
* await setAuthCookie(ACCESS_TOKEN_COOKIE_NAME, encryptedAccessToken, {
|
|
31
|
+
* maxAge: 60 * 60, // 1 hour
|
|
19
32
|
* });
|
|
20
33
|
* ```
|
|
21
34
|
*/
|
|
@@ -49,15 +62,14 @@ export declare function getAuthCookie(name: string): Promise<string | null>;
|
|
|
49
62
|
*/
|
|
50
63
|
export declare function deleteAuthCookie(name: string): Promise<void>;
|
|
51
64
|
/**
|
|
52
|
-
* Deletes multiple cookies at once.
|
|
53
|
-
*
|
|
65
|
+
* Deletes multiple cookies at once. The login transaction cookie is cleared by
|
|
66
|
+
* `clearTransaction` from `@eventuras/fides-auth/server`.
|
|
54
67
|
*
|
|
55
68
|
* @param names - Array of cookie names to delete
|
|
56
69
|
*
|
|
57
70
|
* @example
|
|
58
71
|
* ```ts
|
|
59
|
-
*
|
|
60
|
-
* await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);
|
|
72
|
+
* await deleteAuthCookies(['session', ACCESS_TOKEN_COOKIE_NAME, ID_TOKEN_COOKIE_NAME]);
|
|
61
73
|
* ```
|
|
62
74
|
*/
|
|
63
75
|
export declare function deleteAuthCookies(names: string[]): Promise<void>;
|
|
@@ -70,7 +82,7 @@ export declare function deleteAuthCookies(names: string[]): Promise<void>;
|
|
|
70
82
|
*
|
|
71
83
|
* @example
|
|
72
84
|
* ```ts
|
|
73
|
-
* const jwt = await
|
|
85
|
+
* const jwt = await createEncryptedJWT(session, secret);
|
|
74
86
|
* await setSessionCookie(jwt);
|
|
75
87
|
* ```
|
|
76
88
|
*/
|
|
@@ -100,7 +112,7 @@ export declare function deleteAccessTokenCookie(): Promise<void>;
|
|
|
100
112
|
* ```ts
|
|
101
113
|
* const sessionToken = await getSessionCookie();
|
|
102
114
|
* if (sessionToken) {
|
|
103
|
-
* const { status, session } = await validateSessionJwt(sessionToken);
|
|
115
|
+
* const { status, session } = await validateSessionJwt(sessionToken, secret);
|
|
104
116
|
* // ...
|
|
105
117
|
* }
|
|
106
118
|
* ```
|
package/dist/cookies.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookies.d.ts","sourceRoot":"","sources":["../src/cookies.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAQnE,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,wBAAwB,EACxB,oBAAoB,EACpB,2BAA2B,EAC3B,yBAAyB,EACzB,cAAc,EACd,uBAAuB,GACxB,MAAM,+BAA+B,CAAC;AACvC,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAInE;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,aAAa,CACjC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,aAA2C,GACnD,OAAO,CAAC,IAAI,CAAC,CAuBf;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgBxE;AAED;;;;;;;;;;G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,IAAI,CAAC,CAKf;AAED;;GAEG;AACH,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAEnE;AAED;;GAEG;AACH,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,IAAI,CAAC,CAE7D;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAE/D;AAED;;;;;;;;;GASG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAGzD"}
|
package/dist/cookies.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { cookies } from "next/headers";
|
|
2
2
|
import { createLogger } from "@eventuras/fides-auth/logger";
|
|
3
3
|
import { ACCESS_TOKEN_COOKIE_NAME, ACCESS_TOKEN_COOKIE_NAME as ACCESS_TOKEN_COOKIE_NAME$1, COOKIE_INFO_BYTES, COOKIE_INFO_BYTES as COOKIE_INFO_BYTES$1, COOKIE_MAX_BYTES, CookieTooLargeError, ID_TOKEN_COOKIE_NAME, assertCookieWithinLimit, assertCookieWithinLimit as assertCookieWithinLimit$1, cookieByteSize, defaultOAuthCookieOptions, defaultSessionCookieOptions, defaultSessionCookieOptions as defaultSessionCookieOptions$1 } from "@eventuras/fides-auth/cookies";
|
|
4
|
-
|
|
4
|
+
// src/cookies.ts
|
|
5
5
|
/**
|
|
6
6
|
* Cookie helpers for Next.js authentication flows.
|
|
7
7
|
*
|
|
@@ -29,8 +29,8 @@ var logger = createLogger({ namespace: "fides-auth-next:cookies" });
|
|
|
29
29
|
* await setAuthCookie('session', encryptedJwt);
|
|
30
30
|
*
|
|
31
31
|
* // With custom options
|
|
32
|
-
* await setAuthCookie(
|
|
33
|
-
* maxAge: 60 *
|
|
32
|
+
* await setAuthCookie(ACCESS_TOKEN_COOKIE_NAME, encryptedAccessToken, {
|
|
33
|
+
* maxAge: 60 * 60, // 1 hour
|
|
34
34
|
* });
|
|
35
35
|
* ```
|
|
36
36
|
*/
|
|
@@ -116,15 +116,14 @@ async function deleteAuthCookie(name) {
|
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
118
|
/**
|
|
119
|
-
* Deletes multiple cookies at once.
|
|
120
|
-
*
|
|
119
|
+
* Deletes multiple cookies at once. The login transaction cookie is cleared by
|
|
120
|
+
* `clearTransaction` from `@eventuras/fides-auth/server`.
|
|
121
121
|
*
|
|
122
122
|
* @param names - Array of cookie names to delete
|
|
123
123
|
*
|
|
124
124
|
* @example
|
|
125
125
|
* ```ts
|
|
126
|
-
*
|
|
127
|
-
* await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);
|
|
126
|
+
* await deleteAuthCookies(['session', ACCESS_TOKEN_COOKIE_NAME, ID_TOKEN_COOKIE_NAME]);
|
|
128
127
|
* ```
|
|
129
128
|
*/
|
|
130
129
|
async function deleteAuthCookies(names) {
|
|
@@ -149,7 +148,7 @@ async function deleteAuthCookies(names) {
|
|
|
149
148
|
*
|
|
150
149
|
* @example
|
|
151
150
|
* ```ts
|
|
152
|
-
* const jwt = await
|
|
151
|
+
* const jwt = await createEncryptedJWT(session, secret);
|
|
153
152
|
* await setSessionCookie(jwt);
|
|
154
153
|
* ```
|
|
155
154
|
*/
|
|
@@ -194,7 +193,7 @@ async function deleteAccessTokenCookie() {
|
|
|
194
193
|
* ```ts
|
|
195
194
|
* const sessionToken = await getSessionCookie();
|
|
196
195
|
* if (sessionToken) {
|
|
197
|
-
* const { status, session } = await validateSessionJwt(sessionToken);
|
|
196
|
+
* const { status, session } = await validateSessionJwt(sessionToken, secret);
|
|
198
197
|
* // ...
|
|
199
198
|
* }
|
|
200
199
|
* ```
|
|
@@ -216,7 +215,6 @@ async function deleteSessionCookie() {
|
|
|
216
215
|
await deleteAuthCookie("session");
|
|
217
216
|
logger.info("Session cookie deleted");
|
|
218
217
|
}
|
|
219
|
-
//#endregion
|
|
220
218
|
export { ACCESS_TOKEN_COOKIE_NAME$1 as ACCESS_TOKEN_COOKIE_NAME, COOKIE_INFO_BYTES$1 as COOKIE_INFO_BYTES, COOKIE_MAX_BYTES, CookieTooLargeError, ID_TOKEN_COOKIE_NAME, assertCookieWithinLimit$1 as assertCookieWithinLimit, cookieByteSize, defaultOAuthCookieOptions, defaultSessionCookieOptions$1 as defaultSessionCookieOptions, deleteAccessTokenCookie, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAccessTokenCookie, getAuthCookie, getSessionCookie, setAccessTokenCookie, setAuthCookie, setSessionCookie };
|
|
221
219
|
|
|
222
220
|
//# sourceMappingURL=cookies.js.map
|
package/dist/cookies.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookies.js","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["/**\n * Cookie helpers for Next.js authentication flows.\n *\n * IMPORTANT: These functions can ONLY be used in:\n * - Server Actions (functions marked with 'use server')\n * - Route Handlers (files in app/api directory)\n * - Server Components (async React components)\n *\n * They CANNOT be used in:\n * - Client Components (marked with 'use client')\n * - Middleware (use NextResponse.cookies instead)\n * - Edge Runtime without proper configuration\n */\n\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n COOKIE_INFO_BYTES,\n assertCookieWithinLimit,\n defaultSessionCookieOptions,\n} from '@eventuras/fides-auth/cookies';\nimport type { CookieOptions } from '@eventuras/fides-auth/cookies';\nimport { createLogger } from '@eventuras/fides-auth/logger';\nimport { cookies } from 'next/headers';\n\n// Re-export the framework-agnostic cookie attributes, limits, and size guard from\n// the core package so existing import sites keep working. This Next adapter only\n// owns the actual cookie I/O (via next/headers); the values and the size check\n// itself live in @eventuras/fides-auth/cookies.\nexport {\n COOKIE_INFO_BYTES,\n COOKIE_MAX_BYTES,\n CookieTooLargeError,\n ACCESS_TOKEN_COOKIE_NAME,\n ID_TOKEN_COOKIE_NAME,\n defaultSessionCookieOptions,\n defaultOAuthCookieOptions,\n cookieByteSize,\n assertCookieWithinLimit,\n} from '@eventuras/fides-auth/cookies';\nexport type { CookieOptions } from '@eventuras/fides-auth/cookies';\n\nconst logger = createLogger({ namespace: 'fides-auth-next:cookies' });\n\n/**\n * Sets a cookie with the given name and value.\n *\n * @param name - Cookie name\n * @param value - Cookie value\n * @param options - Cookie options (defaults to session cookie options)\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await setAuthCookie('session', encryptedJwt);\n *\n * // With custom options\n * await setAuthCookie(
|
|
1
|
+
{"version":3,"file":"cookies.js","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["/**\n * Cookie helpers for Next.js authentication flows.\n *\n * IMPORTANT: These functions can ONLY be used in:\n * - Server Actions (functions marked with 'use server')\n * - Route Handlers (files in app/api directory)\n * - Server Components (async React components)\n *\n * They CANNOT be used in:\n * - Client Components (marked with 'use client')\n * - Middleware (use NextResponse.cookies instead)\n * - Edge Runtime without proper configuration\n */\n\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n COOKIE_INFO_BYTES,\n assertCookieWithinLimit,\n defaultSessionCookieOptions,\n} from '@eventuras/fides-auth/cookies';\nimport type { CookieOptions } from '@eventuras/fides-auth/cookies';\nimport { createLogger } from '@eventuras/fides-auth/logger';\nimport { cookies } from 'next/headers';\n\n// Re-export the framework-agnostic cookie attributes, limits, and size guard from\n// the core package so existing import sites keep working. This Next adapter only\n// owns the actual cookie I/O (via next/headers); the values and the size check\n// itself live in @eventuras/fides-auth/cookies.\nexport {\n COOKIE_INFO_BYTES,\n COOKIE_MAX_BYTES,\n CookieTooLargeError,\n ACCESS_TOKEN_COOKIE_NAME,\n ID_TOKEN_COOKIE_NAME,\n defaultSessionCookieOptions,\n defaultOAuthCookieOptions,\n cookieByteSize,\n assertCookieWithinLimit,\n} from '@eventuras/fides-auth/cookies';\nexport type { CookieOptions } from '@eventuras/fides-auth/cookies';\n\nconst logger = createLogger({ namespace: 'fides-auth-next:cookies' });\n\n/**\n * Sets a cookie with the given name and value.\n *\n * @param name - Cookie name\n * @param value - Cookie value\n * @param options - Cookie options (defaults to session cookie options)\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await setAuthCookie('session', encryptedJwt);\n *\n * // With custom options\n * await setAuthCookie(ACCESS_TOKEN_COOKIE_NAME, encryptedAccessToken, {\n * maxAge: 60 * 60, // 1 hour\n * });\n * ```\n */\nexport async function setAuthCookie(\n name: string,\n value: string,\n options: CookieOptions = defaultSessionCookieOptions\n): Promise<void> {\n try {\n const cookieStore = await cookies();\n const cookieOptions = { ...defaultSessionCookieOptions, ...options };\n\n // Fail loudly above the browser per-cookie limit (the browser would otherwise\n // drop the cookie silently). The size check lives in the core package.\n const size = assertCookieWithinLimit(name, value);\n if (size >= COOKIE_INFO_BYTES) {\n logger.info({ cookieName: name, size }, 'Cookie approaching browser size limit');\n }\n\n cookieStore.set(name, value, cookieOptions);\n\n logger.debug({\n cookieName: name,\n maxAge: cookieOptions.maxAge,\n secure: cookieOptions.secure\n }, 'Cookie set successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to set cookie');\n throw error;\n }\n}\n\n/**\n * Gets a cookie value by name.\n *\n * @param name - Cookie name\n * @returns Cookie value or null if not found\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * const sessionCookie = await getAuthCookie('session');\n * if (sessionCookie) {\n * // Validate and use session\n * }\n * ```\n */\nexport async function getAuthCookie(name: string): Promise<string | null> {\n try {\n const cookieStore = await cookies();\n const cookie = cookieStore.get(name);\n\n if (!cookie?.value) {\n logger.debug({ cookieName: name }, 'Cookie not found');\n return null;\n }\n\n logger.debug({ cookieName: name }, 'Cookie retrieved');\n return cookie.value;\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to get cookie');\n return null;\n }\n}\n\n/**\n * Deletes a cookie by name.\n *\n * @param name - Cookie name to delete\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await deleteAuthCookie('session');\n * ```\n */\nexport async function deleteAuthCookie(name: string): Promise<void> {\n try {\n const cookieStore = await cookies();\n cookieStore.delete(name);\n\n logger.debug({ cookieName: name }, 'Cookie deleted successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to delete cookie');\n throw error;\n }\n}\n\n/**\n * Deletes multiple cookies at once. The login transaction cookie is cleared by\n * `clearTransaction` from `@eventuras/fides-auth/server`.\n *\n * @param names - Array of cookie names to delete\n *\n * @example\n * ```ts\n * await deleteAuthCookies(['session', ACCESS_TOKEN_COOKIE_NAME, ID_TOKEN_COOKIE_NAME]);\n * ```\n */\nexport async function deleteAuthCookies(names: string[]): Promise<void> {\n try {\n const cookieStore = await cookies();\n\n for (const name of names) {\n cookieStore.delete(name);\n }\n\n logger.debug({ cookieNames: names }, 'Multiple cookies deleted successfully');\n } catch (error) {\n logger.error({ error, cookieNames: names }, 'Failed to delete cookies');\n throw error;\n }\n}\n\n/**\n * Sets the session cookie with proper security settings.\n * This is a convenience wrapper around setAuthCookie.\n *\n * @param encryptedJwt - The encrypted JWT session token\n * @param options - Optional cookie options (merged with defaults)\n *\n * @example\n * ```ts\n * const jwt = await createEncryptedJWT(session, secret);\n * await setSessionCookie(jwt);\n * ```\n */\nexport async function setSessionCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie('session', encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n\n logger.info('Session cookie set');\n}\n\n/**\n * Sets the access-token cookie (\"session_at\") with session cookie settings.\n *\n * @param encryptedJwt - The encrypted JWT wrapping the access token\n * @param options - Optional cookie options (merged with session defaults)\n */\nexport async function setAccessTokenCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie(ACCESS_TOKEN_COOKIE_NAME, encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n}\n\n/**\n * Gets the access-token cookie (\"session_at\") value, or null if absent.\n */\nexport async function getAccessTokenCookie(): Promise<string | null> {\n return await getAuthCookie(ACCESS_TOKEN_COOKIE_NAME);\n}\n\n/**\n * Deletes the access-token cookie (\"session_at\").\n */\nexport async function deleteAccessTokenCookie(): Promise<void> {\n await deleteAuthCookie(ACCESS_TOKEN_COOKIE_NAME);\n}\n\n/**\n * Gets the current session cookie value.\n * Returns null if no session cookie exists.\n *\n * @returns Encrypted JWT session token or null\n *\n * @example\n * ```ts\n * const sessionToken = await getSessionCookie();\n * if (sessionToken) {\n * const { status, session } = await validateSessionJwt(sessionToken, secret);\n * // ...\n * }\n * ```\n */\nexport async function getSessionCookie(): Promise<string | null> {\n return await getAuthCookie('session');\n}\n\n/**\n * Deletes the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await deleteSessionCookie();\n * redirect('/');\n * ```\n */\nexport async function deleteSessionCookie(): Promise<void> {\n await deleteAuthCookie('session');\n logger.info('Session cookie deleted');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyCA,IAAM,SAAS,aAAa,EAAE,WAAW,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;AAoBpE,eAAsB,cACpB,MACA,OACA,UAAyB,6BACV;CACf,IAAI;EACF,MAAM,cAAc,MAAM,QAAQ;EAClC,MAAM,gBAAgB;GAAE,GAAG;GAA6B,GAAG;EAAQ;EAInE,MAAM,OAAO,wBAAwB,MAAM,KAAK;EAChD,IAAI,QAAQ,mBACV,OAAO,KAAK;GAAE,YAAY;GAAM;EAAK,GAAG,uCAAuC;EAGjF,YAAY,IAAI,MAAM,OAAO,aAAa;EAE1C,OAAO,MAAM;GACX,YAAY;GACZ,QAAQ,cAAc;GACtB,QAAQ,cAAc;EACxB,GAAG,yBAAyB;CAC9B,SAAS,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,YAAY;EAAK,GAAG,sBAAsB;EAChE,MAAM;CACR;AACF;;;;;;;;;;;;;;;;AAiBA,eAAsB,cAAc,MAAsC;CACxE,IAAI;EAEF,MAAM,UAAS,MADW,QAAQ,EAAA,CACP,IAAI,IAAI;EAEnC,IAAI,CAAC,QAAQ,OAAO;GAClB,OAAO,MAAM,EAAE,Y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AAYA,eAAsB,sBAAqC;CACzD,MAAM,iBAAiB,SAAS;CAChC,OAAO,KAAK,wBAAwB;AACtC"}
|
|
@@ -1,10 +1,25 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Server-side heartbeat handler for Next.js route handlers — a thin wrapper over
|
|
3
|
+
* the framework-agnostic handler in `@eventuras/fides-auth/server`, wiring it to
|
|
4
|
+
* the Next cookie store and the global POST rate limiter.
|
|
5
|
+
*
|
|
6
|
+
* Pairs with the client-side `useHeartbeat` hook: when the user is active, the
|
|
7
|
+
* client POSTs here, and this handler exchanges the current refresh token for a
|
|
8
|
+
* fresh access token (and rotated refresh token, if the IdP rotates).
|
|
9
|
+
*/
|
|
10
|
+
import { type SessionPersistence, type SessionSecret } from '@eventuras/fides-auth/server';
|
|
11
|
+
import type { OAuthConfig } from '@eventuras/fides-auth/oauth';
|
|
2
12
|
export interface HeartbeatHandlerConfig {
|
|
3
13
|
/** OAuth/OIDC configuration used to refresh the access token. */
|
|
4
14
|
oauthConfig: OAuthConfig;
|
|
15
|
+
/** Session encryption secret. */
|
|
16
|
+
secret: SessionSecret;
|
|
17
|
+
/** Where the session lives. Defaults to the cookies under `secret`; see `serverPersistence`. */
|
|
18
|
+
persistence?: SessionPersistence;
|
|
5
19
|
}
|
|
6
20
|
/**
|
|
7
|
-
* Handles a heartbeat request in a Next.js route handler.
|
|
21
|
+
* Handles a heartbeat request in a Next.js route handler. `createFidesAuth`
|
|
22
|
+
* returns this with `oauthConfig` and `secret` bound.
|
|
8
23
|
*
|
|
9
24
|
* @example
|
|
10
25
|
* ```ts
|
|
@@ -13,7 +28,7 @@ export interface HeartbeatHandlerConfig {
|
|
|
13
28
|
* import { oauthConfig } from '@/utils/oauthConfig';
|
|
14
29
|
*
|
|
15
30
|
* export async function POST(request: Request) {
|
|
16
|
-
* return handleHeartbeat(request, { oauthConfig });
|
|
31
|
+
* return handleHeartbeat(request, { oauthConfig, secret: process.env.SESSION_SECRET! });
|
|
17
32
|
* }
|
|
18
33
|
* ```
|
|
19
34
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"heartbeat-handler.d.ts","sourceRoot":"","sources":["../src/heartbeat-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;
|
|
1
|
+
{"version":3,"file":"heartbeat-handler.d.ts","sourceRoot":"","sources":["../src/heartbeat-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAEL,KAAK,kBAAkB,EACvB,KAAK,aAAa,EACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAK/D,MAAM,WAAW,sBAAsB;IACrC,iEAAiE;IACjE,WAAW,EAAE,WAAW,CAAC;IAEzB,iCAAiC;IACjC,MAAM,EAAE,aAAa,CAAC;IAEtB,gGAAgG;IAChG,WAAW,CAAC,EAAE,kBAAkB,CAAC;CAClC;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,eAAe,CACnC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,sBAAsB,GAC7B,OAAO,CAAC,QAAQ,CAAC,CAQnB"}
|