@eventuras/fides-auth-next 0.7.2 → 0.8.1

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/dist/session.js DELETED
@@ -1,152 +0,0 @@
1
- import { nextCookieStore } from "./cookie-store.js";
2
- import { createLogger } from "@eventuras/fides-auth/logger";
3
- import { createEncryptedJWT, getSessionSecret } from "@eventuras/fides-auth/utils";
4
- import { clearSession, persistSession, refreshSessionInStore, tryReadSession, tryRefreshSessionInStore } from "@eventuras/fides-auth/server";
5
- import { cache } from "react";
6
- //#region src/session.ts
7
- var logger = createLogger({ namespace: "fides-auth-next:session" });
8
- /**
9
- * Creates an encrypted JWT containing session data.
10
- *
11
- * Pre-split API: this serializes the whole session, raw tokens included, into one
12
- * value. Prefer {@link createAndPersistSession}, which splits the large JWTs across
13
- * cookies instead of spending one cookie's byte budget on all of them.
14
- *
15
- * @param session - Session data (tokens, user, etc.)
16
- * @param options - Configuration options (e.g., sessionDurationDays)
17
- * @returns Encrypted JWT string
18
- */
19
- async function createSession(session, options = {}) {
20
- const { sessionDurationDays = 7 } = options;
21
- try {
22
- const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());
23
- logger.info({ sessionDurationDays }, "Session created successfully");
24
- return jwt;
25
- } catch (error) {
26
- logger.error({ error }, "Failed to create session");
27
- throw error;
28
- }
29
- }
30
- /**
31
- * Retrieves the current session from cookies, if any. Wraps the framework-
32
- * agnostic {@link readSession} with React's `cache` so repeated calls within one
33
- * server render share a single read.
34
- *
35
- * The session may carry an expired access token — check `accessTokenExpires`
36
- * before using it, or refresh via `refreshCurrentSession`.
37
- *
38
- * @param _config - Unused; kept for backwards compatibility.
39
- * @returns Session object or null if no session exists.
40
- *
41
- * @example
42
- * ```ts
43
- * const session = await getCurrentSession();
44
- * if (session) console.log('User:', session.user);
45
- * ```
46
- */
47
- var getCurrentSession = cache(async (_config) => {
48
- return (await tryGetCurrentSession()).session;
49
- });
50
- /**
51
- * Reads the current session and, when there isn't one, says why.
52
- *
53
- * The reason comes from the package-wide vocabulary, so a proxy or a status
54
- * route logs the same word for the same situation that the heartbeat endpoint
55
- * logs — which is the point of having a vocabulary at all. Cached per render
56
- * like {@link getCurrentSession}, and shared with it, so asking for the reason
57
- * costs no extra decrypt.
58
- *
59
- * @example
60
- * ```ts
61
- * import {
62
- * SESSION_EVENT,
63
- * createLogger,
64
- * logSessionEvent,
65
- * tryGetCurrentSession,
66
- * } from '@eventuras/fides-auth-next';
67
- * import { redirect } from 'next/navigation';
68
- *
69
- * const logger = createLogger({ namespace: 'my-app:proxy' });
70
- *
71
- * const { session, reason } = await tryGetCurrentSession();
72
- * if (!session) {
73
- * logSessionEvent(logger, { event: SESSION_EVENT.REJECTED, reason, source: 'proxy' });
74
- * redirect('/login');
75
- * }
76
- * ```
77
- */
78
- var tryGetCurrentSession = cache(async () => {
79
- return tryReadSession(await nextCookieStore(), getSessionSecret());
80
- });
81
- /**
82
- * Refreshes the current session using its refresh token and updates the cookies.
83
- *
84
- * @param config - OAuth configuration
85
- * @param options - Session creation options
86
- * @returns Updated session or null if refresh failed
87
- *
88
- * @example
89
- * ```ts
90
- * const updated = await refreshCurrentSession(oauthConfig);
91
- * if (!updated) redirect('/login');
92
- * ```
93
- */
94
- async function refreshCurrentSession(config, options = {}) {
95
- return refreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);
96
- }
97
- /**
98
- * Refreshes the current session and, on failure, says why.
99
- *
100
- * Prefer this over {@link refreshCurrentSession} anywhere the answer decides
101
- * whether the user stays logged in: a bare null cannot tell "the provider says
102
- * this refresh token is dead" apart from "we could not reach the provider", and
103
- * ending a session on the second is how a provider blip becomes a logout.
104
- *
105
- * @example
106
- * ```ts
107
- * const result = await tryRefreshCurrentSession(oauthConfig);
108
- * if (!result.ok && result.cause === 'invalid_grant') redirect('/login');
109
- * // transport / idp_error: keep the session and retry.
110
- * ```
111
- */
112
- async function tryRefreshCurrentSession(config, options = {}) {
113
- return tryRefreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);
114
- }
115
- /**
116
- * Creates and persists a new session across the session/session_at cookies.
117
- *
118
- * @param session - Session data
119
- * @param _options - Session creation options (reserved; not currently applied)
120
- * @returns The encrypted JWT stored in the main "session" cookie.
121
- *
122
- * @example
123
- * ```ts
124
- * await createAndPersistSession({
125
- * tokens: { accessToken: tokens.access_token, refreshToken: tokens.refresh_token },
126
- * user: { name: 'John Doe', email: 'john@example.com' },
127
- * });
128
- * ```
129
- */
130
- async function createAndPersistSession(session, _options = {}) {
131
- return persistSession(await nextCookieStore(), session, getSessionSecret());
132
- }
133
- /**
134
- * Clears the current session by deleting the session cookies.
135
- *
136
- * @example
137
- * ```ts
138
- * await clearCurrentSession();
139
- * redirect('/');
140
- * ```
141
- */
142
- async function clearCurrentSession(options = {}) {
143
- const sid = options.sid ?? (await tryGetCurrentSession()).session?.sid;
144
- await clearSession(await nextCookieStore(), {
145
- trigger: options.trigger ?? "logout",
146
- sid
147
- });
148
- }
149
- //#endregion
150
- export { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession, tryGetCurrentSession, tryRefreshCurrentSession };
151
-
152
- //# sourceMappingURL=session.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { createEncryptedJWT, getSessionSecret } from '@eventuras/fides-auth/utils';\nimport {\n persistSession,\n readSession,\n tryReadSession,\n refreshSessionInStore,\n tryRefreshSessionInStore,\n clearSession,\n type ClearSessionOptions,\n type ReadSessionResult,\n type RefreshSessionResult,\n} from '@eventuras/fides-auth/server';\nimport type { Session, CreateSessionOptions } from '@eventuras/fides-auth/types';\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport { createLogger } from '@eventuras/fides-auth/logger';\nimport { cache } from 'react';\n\nimport { nextCookieStore } from './cookie-store';\n\nconst logger = createLogger({ namespace: 'fides-auth-next:session' });\n\n// The result shapes the try* helpers below return, so consumers can name them\n// without reaching past this package.\nexport type { ClearSessionOptions, ReadSessionResult, RefreshSessionResult };\n\n/**\n * Creates an encrypted JWT containing session data.\n *\n * Pre-split API: this serializes the whole session, raw tokens included, into one\n * value. Prefer {@link createAndPersistSession}, which splits the large JWTs across\n * cookies instead of spending one cookie's byte budget on all of them.\n *\n * @param session - Session data (tokens, user, etc.)\n * @param options - Configuration options (e.g., sessionDurationDays)\n * @returns Encrypted JWT string\n */\nexport async function createSession<TData = Record<string, unknown>>(\n session: Session<TData>,\n options: CreateSessionOptions = {}\n): Promise<string> {\n const { sessionDurationDays = 7 } = options;\n try {\n const jwt = await createEncryptedJWT({ ...session }, getSessionSecret());\n logger.info({ sessionDurationDays }, 'Session created successfully');\n return jwt;\n } catch (error) {\n logger.error({ error }, 'Failed to create session');\n throw error;\n }\n}\n\n/**\n * Retrieves the current session from cookies, if any. Wraps the framework-\n * agnostic {@link readSession} with React's `cache` so repeated calls within one\n * server render share a single read.\n *\n * The session may carry an expired access token — check `accessTokenExpires`\n * before using it, or refresh via `refreshCurrentSession`.\n *\n * @param _config - Unused; kept for backwards compatibility.\n * @returns Session object or null if no session exists.\n *\n * @example\n * ```ts\n * const session = await getCurrentSession();\n * if (session) console.log('User:', session.user);\n * ```\n */\nexport const getCurrentSession = cache(\n async (_config?: OAuthConfig): Promise<Session<any> | null> => {\n return (await tryGetCurrentSession()).session;\n },\n);\n\n/**\n * Reads the current session and, when there isn't one, says why.\n *\n * The reason comes from the package-wide vocabulary, so a proxy or a status\n * route logs the same word for the same situation that the heartbeat endpoint\n * logs — which is the point of having a vocabulary at all. Cached per render\n * like {@link getCurrentSession}, and shared with it, so asking for the reason\n * costs no extra decrypt.\n *\n * @example\n * ```ts\n * import {\n * SESSION_EVENT,\n * createLogger,\n * logSessionEvent,\n * tryGetCurrentSession,\n * } from '@eventuras/fides-auth-next';\n * import { redirect } from 'next/navigation';\n *\n * const logger = createLogger({ namespace: 'my-app:proxy' });\n *\n * const { session, reason } = await tryGetCurrentSession();\n * if (!session) {\n * logSessionEvent(logger, { event: SESSION_EVENT.REJECTED, reason, source: 'proxy' });\n * redirect('/login');\n * }\n * ```\n */\nexport const tryGetCurrentSession = cache(\n async (): Promise<ReadSessionResult> => {\n return tryReadSession(await nextCookieStore(), getSessionSecret());\n },\n);\n\n/**\n * Refreshes the current session using its refresh token and updates the cookies.\n *\n * @param config - OAuth configuration\n * @param options - Session creation options\n * @returns Updated session or null if refresh failed\n *\n * @example\n * ```ts\n * const updated = await refreshCurrentSession(oauthConfig);\n * if (!updated) redirect('/login');\n * ```\n */\nexport async function refreshCurrentSession(\n config: OAuthConfig,\n options: CreateSessionOptions = {}\n): Promise<Session | null> {\n return refreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);\n}\n\n/**\n * Refreshes the current session and, on failure, says why.\n *\n * Prefer this over {@link refreshCurrentSession} anywhere the answer decides\n * whether the user stays logged in: a bare null cannot tell \"the provider says\n * this refresh token is dead\" apart from \"we could not reach the provider\", and\n * ending a session on the second is how a provider blip becomes a logout.\n *\n * @example\n * ```ts\n * const result = await tryRefreshCurrentSession(oauthConfig);\n * if (!result.ok && result.cause === 'invalid_grant') redirect('/login');\n * // transport / idp_error: keep the session and retry.\n * ```\n */\nexport async function tryRefreshCurrentSession(\n config: OAuthConfig,\n options: CreateSessionOptions = {}\n): Promise<RefreshSessionResult> {\n return tryRefreshSessionInStore(await nextCookieStore(), config, getSessionSecret(), options);\n}\n\n/**\n * Creates and persists a new session across the session/session_at cookies.\n *\n * @param session - Session data\n * @param _options - Session creation options (reserved; not currently applied)\n * @returns The encrypted JWT stored in the main \"session\" cookie.\n *\n * @example\n * ```ts\n * await createAndPersistSession({\n * tokens: { accessToken: tokens.access_token, refreshToken: tokens.refresh_token },\n * user: { name: 'John Doe', email: 'john@example.com' },\n * });\n * ```\n */\nexport async function createAndPersistSession(\n session: Session,\n _options: CreateSessionOptions = {}\n): Promise<string> {\n return persistSession(await nextCookieStore(), session, getSessionSecret());\n}\n\n/**\n * Clears the current session by deleting the session cookies.\n *\n * @example\n * ```ts\n * await clearCurrentSession();\n * redirect('/');\n * ```\n */\nexport async function clearCurrentSession(\n options: ClearSessionOptions = {},\n): Promise<void> {\n // Defaults to `logout` because that is what this function is for; pass a\n // trigger explicitly when clearing for some other reason. The sid comes from\n // the per-render cache, so correlating the logout costs nothing extra.\n const sid = options.sid ?? (await tryGetCurrentSession()).session?.sid;\n await clearSession(await nextCookieStore(), {\n trigger: options.trigger ?? 'logout',\n sid,\n });\n}\n"],"mappings":";;;;;;AAmBA,IAAM,SAAS,aAAa,EAAE,WAAW,0BAA0B,CAAC;;;;;;;;;;;;AAiBpE,eAAsB,cACpB,SACA,UAAgC,CAAC,GAChB;CACjB,MAAM,EAAE,sBAAsB,MAAM;CACpC,IAAI;EACF,MAAM,MAAM,MAAM,mBAAmB,EAAE,GAAG,QAAQ,GAAG,iBAAiB,CAAC;EACvE,OAAO,KAAK,EAAE,oBAAoB,GAAG,8BAA8B;EACnE,OAAO;CACT,SAAS,OAAO;EACd,OAAO,MAAM,EAAE,MAAM,GAAG,0BAA0B;EAClD,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;AAmBA,IAAa,oBAAoB,MAC/B,OAAO,YAAwD;CAC7D,QAAQ,MAAM,qBAAqB,EAAA,CAAG;AACxC,CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,uBAAuB,MAClC,YAAwC;CACtC,OAAO,eAAe,MAAM,gBAAgB,GAAG,iBAAiB,CAAC;AACnE,CACF;;;;;;;;;;;;;;AAeA,eAAsB,sBACpB,QACA,UAAgC,CAAC,GACR;CACzB,OAAO,sBAAsB,MAAM,gBAAgB,GAAG,QAAQ,iBAAiB,GAAG,OAAO;AAC3F;;;;;;;;;;;;;;;;AAiBA,eAAsB,yBACpB,QACA,UAAgC,CAAC,GACF;CAC/B,OAAO,yBAAyB,MAAM,gBAAgB,GAAG,QAAQ,iBAAiB,GAAG,OAAO;AAC9F;;;;;;;;;;;;;;;;AAiBA,eAAsB,wBACpB,SACA,WAAiC,CAAC,GACjB;CACjB,OAAO,eAAe,MAAM,gBAAgB,GAAG,SAAS,iBAAiB,CAAC;AAC5E;;;;;;;;;;AAWA,eAAsB,oBACpB,UAA+B,CAAC,GACjB;CAIf,MAAM,MAAM,QAAQ,QAAQ,MAAM,qBAAqB,EAAA,CAAG,SAAS;CACnE,MAAM,aAAa,MAAM,gBAAgB,GAAG;EAC1C,SAAS,QAAQ,WAAW;EAC5B;CACF,CAAC;AACH"}