nuxt-auth-utils 0.5.20 → 0.5.22

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 CHANGED
@@ -156,6 +156,9 @@ const session = await requireUserSession(event)
156
156
 
157
157
  You can define the type for your user session by creating a type declaration file (for example, `auth.d.ts`) in your project to augment the `UserSession` type:
158
158
 
159
+ > [!NOTE]
160
+ > If you are using Nuxt >=4.0.0 or compatibility version 4 add the `auth.d.ts` file to the `shared` directory to get the correct types in server and client.
161
+
159
162
  ```ts
160
163
  // auth.d.ts
161
164
  declare module '#auth-utils' {
@@ -236,6 +239,7 @@ It can also be set using environment variables:
236
239
  - LinkedIn
237
240
  - LiveChat
238
241
  - Microsoft
242
+ - Okta
239
243
  - PayPal
240
244
  - Polar
241
245
  - Salesforce
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "auth-utils",
3
3
  "configKey": "auth",
4
- "version": "0.5.20",
4
+ "version": "0.5.22",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "0.8.4",
7
7
  "unbuild": "2.0.0"
package/dist/module.mjs CHANGED
@@ -353,6 +353,14 @@ const module = defineNuxtModule({
353
353
  redirectURL: "",
354
354
  scope: ""
355
355
  });
356
+ runtimeConfig.oauth.okta = defu(runtimeConfig.oauth.okta, {
357
+ clientId: "",
358
+ clientSecret: "",
359
+ domain: "",
360
+ audience: "",
361
+ scope: [],
362
+ redirectURL: ""
363
+ });
356
364
  }
357
365
  });
358
366
 
@@ -35,7 +35,7 @@ export function defineOAuthAzureB2CEventHandler({ config, onSuccess, onError })
35
35
  );
36
36
  }
37
37
  if (query.state !== state) {
38
- handleInvalidState(event, "azureb2c", onError);
38
+ return handleInvalidState(event, "azureb2c", onError);
39
39
  }
40
40
  console.info("code verifier", verifier.code_verifier);
41
41
  const tokens = await requestAccessToken(tokenURL, {
@@ -46,7 +46,7 @@ export function defineOAuthHerokuEventHandler({
46
46
  );
47
47
  }
48
48
  if (query.state !== state) {
49
- handleInvalidState(event, "heroku", onError);
49
+ return handleInvalidState(event, "heroku", onError);
50
50
  }
51
51
  const tokens = await requestAccessToken(config.tokenURL, {
52
52
  body: {
@@ -62,7 +62,7 @@ export function defineOAuthKeycloakEventHandler({
62
62
  }
63
63
  const accessToken = tokens.access_token;
64
64
  const user = await $fetch(
65
- `${realmURL}/protocol/openid-connect/userinfo`,
65
+ `${realmURLInternal}/protocol/openid-connect/userinfo`,
66
66
  {
67
67
  headers: {
68
68
  Authorization: `Bearer ${accessToken}`,
@@ -0,0 +1,88 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { OAuthConfig } from '#auth-utils';
3
+ export interface OpenIdConfig {
4
+ authorization_endpoint: string;
5
+ token_endpoint: string;
6
+ userinfo_endpoint: string;
7
+ end_session_endpoint?: string;
8
+ [key: string]: unknown;
9
+ }
10
+ export interface OAuthConfigExt<TConfig, TResult = {
11
+ user: Record<string, unknown>;
12
+ tokens: Record<string, unknown>;
13
+ openIdConfig: OpenIdConfig;
14
+ }> extends OAuthConfig<TConfig, TResult> {
15
+ config?: TConfig;
16
+ onSuccess: (event: H3Event, result: TResult) => Promise<void> | void;
17
+ onError?: (event: H3Event, error: unknown) => Promise<void> | void;
18
+ }
19
+ export interface OAuthOktaConfig {
20
+ /**
21
+ * Okta OAuth Client ID
22
+ * @default process.env.NUXT_OAUTH_OKTA_CLIENT_ID
23
+ */
24
+ clientId?: string;
25
+ /**
26
+ * Okta OAuth Client Secret
27
+ * @default process.env.NUXT_OAUTH_OKTA_CLIENT_SECRET
28
+ */
29
+ clientSecret?: string;
30
+ /**
31
+ * Okta OAuth Issuer
32
+ * @default process.env.NUXT_OAUTH_OKTA_DOMAIN
33
+ */
34
+ domain?: string;
35
+ /**
36
+ * Okta OAuth Authorization Server
37
+ * @see https://developer.okta.com/docs/guides/customize-authz-server/main/#create-an-authorization-server
38
+ * @default process.env.NUXT_OAUTH_OKTA_AUTHORIZATION_SERVER
39
+ */
40
+ authorizationServer?: string;
41
+ /**
42
+ * Okta OAuth Audience
43
+ * @default process.env.NUXT_OAUTH_OKTA_AUDIENCE
44
+ */
45
+ audience?: string;
46
+ /**
47
+ * Okta OAuth Scope
48
+ * @default []
49
+ * @see https://okta.com/docs/get-started/apis/scopes/openid-connect-scopes
50
+ * @example ['openid']
51
+ */
52
+ scope?: string | string[];
53
+ /**
54
+ * Require email from user, adds the ['email'] scope if not present
55
+ * @default false
56
+ */
57
+ emailRequired?: boolean;
58
+ /**
59
+ * Maximum Authentication Age. If the elapsed time is greater than this value, the OP must attempt to actively re-authenticate the end-user.
60
+ * @default 0
61
+ * @see https://okta.com/docs/authenticate/login/max-age-reauthentication
62
+ */
63
+ maxAge?: number;
64
+ /**
65
+ * Login connection. If no connection is specified, it will redirect to the standard Okta login page and show the Login Widget.
66
+ * @default ''
67
+ * @see https://okta.com/docs/api/authentication#social
68
+ * @example 'github'
69
+ */
70
+ connection?: string;
71
+ /**
72
+ * Extra authorization parameters to provide to the authorization URL
73
+ * @see https://okta.com/docs/api/authentication#social
74
+ * @example { display: 'popup' }
75
+ */
76
+ authorizationParams?: Record<string, string>;
77
+ /**
78
+ * Redirect URL to to allow overriding for situations like prod failing to determine public hostname
79
+ * @default process.env.NUXT_OAUTH_OKTA_REDIRECT_URL or current URL
80
+ */
81
+ redirectURL?: string;
82
+ /**
83
+ * OpenID Configuration cache TTL in milliseconds
84
+ * @default 86400000 (24 hours)
85
+ */
86
+ openIdConfigCacheTTL?: number;
87
+ }
88
+ export declare function defineOAuthOktaEventHandler({ config, onSuccess, onError }: OAuthConfigExt<OAuthOktaConfig>): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void>>;
@@ -0,0 +1,171 @@
1
+ import { eventHandler, getQuery, sendRedirect, createError, deleteCookie } from "h3";
2
+ import { withQuery } from "ufo";
3
+ import { defu } from "defu";
4
+ import { handleMissingConfiguration, handleState, handleInvalidState, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken } from "../utils.js";
5
+ import { useRuntimeConfig } from "#imports";
6
+ const openIdConfigCache = /* @__PURE__ */ new Map();
7
+ const DEFAULT_CACHE_TTL = 1e3 * 60 * 60 * 24;
8
+ export function defineOAuthOktaEventHandler({ config, onSuccess, onError }) {
9
+ function normalizeScope(scope, emailRequired) {
10
+ let result;
11
+ if (!scope || typeof scope === "string" && scope.trim() === "") {
12
+ result = ["openid", "email", "profile"];
13
+ } else if (typeof scope === "string") {
14
+ result = scope.split(/[,| ]+/).filter(Boolean);
15
+ } else if (Array.isArray(scope) && scope.length > 0) {
16
+ result = scope;
17
+ } else {
18
+ result = ["openid", "email", "profile"];
19
+ }
20
+ result = [...new Set(result)];
21
+ if (emailRequired && !result.includes("email")) {
22
+ result.push("email");
23
+ }
24
+ return result;
25
+ }
26
+ return eventHandler(async (event) => {
27
+ const runtimeConfig = useRuntimeConfig(event);
28
+ config = defu(config, runtimeConfig.oauth?.okta, {
29
+ authorizationParams: {}
30
+ });
31
+ if (!config.clientId || !config.clientSecret || !config.domain || typeof config.domain !== "string" || !config.domain.trim()) {
32
+ return handleMissingConfiguration(event, "okta", ["clientId", "clientSecret", "domain"], onError);
33
+ }
34
+ const query = getQuery(event);
35
+ if (query.error) {
36
+ const error = createError({
37
+ statusCode: 401,
38
+ message: `Okta login failed: ${query.error || "Unknown error"} - ${query.error_description || ""}`,
39
+ data: query
40
+ });
41
+ if (!onError) throw error;
42
+ return onError(event, error);
43
+ }
44
+ config.scope = normalizeScope(config.scope, config.emailRequired);
45
+ const getOpenIdConfig = async (openIdConfigurationUrl2, event2) => {
46
+ const now = Date.now();
47
+ const cacheTTL = config?.openIdConfigCacheTTL || DEFAULT_CACHE_TTL;
48
+ const cached = openIdConfigCache.get(openIdConfigurationUrl2);
49
+ if (cached) {
50
+ if (cached.expiresAt > now) {
51
+ return cached.data;
52
+ } else {
53
+ openIdConfigCache.delete(openIdConfigurationUrl2);
54
+ }
55
+ }
56
+ let openIdConfig2 = null;
57
+ try {
58
+ openIdConfig2 = await $fetch(openIdConfigurationUrl2);
59
+ if (openIdConfig2) {
60
+ openIdConfigCache.set(openIdConfigurationUrl2, {
61
+ data: openIdConfig2,
62
+ expiresAt: now + cacheTTL
63
+ });
64
+ }
65
+ } catch (error) {
66
+ if (config && config.domain) {
67
+ const authz = config.authorizationServer;
68
+ openIdConfig2 = {
69
+ authorization_endpoint: authz ? `https://${config.domain}/oauth2/${authz}/v1/authorize` : `https://${config.domain}/oauth2/v1/authorize`,
70
+ token_endpoint: authz ? `https://${config.domain}/oauth2/${authz}/v1/token` : `https://${config.domain}/oauth2/v1/token`,
71
+ userinfo_endpoint: authz ? `https://${config.domain}/oauth2/${authz}/v1/userinfo` : `https://${config.domain}/oauth2/v1/userinfo`,
72
+ end_session_endpoint: void 0
73
+ };
74
+ openIdConfigCache.set(openIdConfigurationUrl2, {
75
+ data: openIdConfig2,
76
+ expiresAt: now + Math.min(cacheTTL / 24, 1e3 * 60 * 60)
77
+ // 1 hour or 1/24th of configured TTL, whichever is smaller
78
+ });
79
+ } else {
80
+ console.error("Failed to fetch Okta OpenID configuration. Please check your Okta domain and network connectivity:", error);
81
+ const err = createError({
82
+ statusCode: 500,
83
+ message: "Could not get Okta OpenID configuration. Please verify that your Okta domain is correct and reachable, and that the OpenID configuration endpoint is accessible.",
84
+ data: error
85
+ });
86
+ if (onError) await onError(event2, err);
87
+ throw err;
88
+ }
89
+ }
90
+ return openIdConfig2;
91
+ };
92
+ const authServer = config.authorizationServer;
93
+ const openIdConfigurationUrl = authServer ? `https://${config.domain}/oauth2/${authServer}/.well-known/openid-configuration` : `https://${config.domain}/.well-known/openid-configuration`;
94
+ const openIdConfig = await getOpenIdConfig(openIdConfigurationUrl, event);
95
+ const authorizationURL = openIdConfig.authorization_endpoint;
96
+ const tokenURL = openIdConfig.token_endpoint;
97
+ const userInfoUrl = openIdConfig.userinfo_endpoint;
98
+ const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
99
+ const state = await handleState(event);
100
+ if (!query.code) {
101
+ return sendRedirect(
102
+ event,
103
+ withQuery(authorizationURL, {
104
+ response_type: "code",
105
+ client_id: config.clientId,
106
+ redirect_uri: redirectURL,
107
+ scope: config.scope.join(" "),
108
+ audience: config.audience || "",
109
+ max_age: config.maxAge || 0,
110
+ connection: config.connection || "",
111
+ state,
112
+ ...config.authorizationParams
113
+ })
114
+ );
115
+ }
116
+ if (query.state !== state) {
117
+ deleteCookie(event, "nuxt-auth-state");
118
+ return handleInvalidState(event, "okta", onError);
119
+ }
120
+ const tokens = await requestAccessToken(tokenURL, {
121
+ headers: {
122
+ "Content-Type": "application/x-www-form-urlencoded"
123
+ },
124
+ body: {
125
+ response_type: "code",
126
+ grant_type: "authorization_code",
127
+ client_id: config.clientId,
128
+ client_secret: config.clientSecret,
129
+ scope: config.scope?.join(" "),
130
+ redirect_uri: redirectURL,
131
+ code: query.code,
132
+ state: query.state
133
+ }
134
+ });
135
+ if (tokens.error) {
136
+ return handleAccessTokenErrorResponse(event, "okta", tokens, onError);
137
+ }
138
+ if (!tokens.access_token || typeof tokens.access_token !== "string" || !tokens.token_type || typeof tokens.token_type !== "string") {
139
+ const err = createError({
140
+ statusCode: 400,
141
+ message: "Invalid token response from Okta",
142
+ data: tokens
143
+ });
144
+ if (onError) return onError(event, err);
145
+ throw err;
146
+ }
147
+ const tokenType = tokens.token_type;
148
+ const accessToken = tokens.access_token;
149
+ let user;
150
+ try {
151
+ user = await $fetch(userInfoUrl, {
152
+ headers: {
153
+ Authorization: `${tokenType} ${accessToken}`
154
+ }
155
+ });
156
+ } catch (error) {
157
+ const err = createError({
158
+ statusCode: 410,
159
+ message: `Could not get Okta user info - ${error instanceof Error ? error.message : String(error)}`,
160
+ data: tokens
161
+ });
162
+ if (onError) return onError(event, err);
163
+ throw err;
164
+ }
165
+ return onSuccess(event, {
166
+ tokens,
167
+ user,
168
+ openIdConfig
169
+ });
170
+ });
171
+ }
@@ -46,7 +46,7 @@ export function defineOAuthSalesforceEventHandler({
46
46
  );
47
47
  }
48
48
  if (query.state !== state) {
49
- handleInvalidState(event, "salesforce", onError);
49
+ return handleInvalidState(event, "salesforce", onError);
50
50
  }
51
51
  const tokens = await requestAccessToken(config.tokenURL, {
52
52
  body: {
@@ -46,7 +46,7 @@ export function defineOAuthSlackEventHandler({
46
46
  );
47
47
  }
48
48
  if (query.state !== state) {
49
- handleInvalidState(event, "slack", onError);
49
+ return handleInvalidState(event, "slack", onError);
50
50
  }
51
51
  const tokens = await requestAccessToken(config.tokenURL, {
52
52
  body: {
@@ -1,7 +1,7 @@
1
1
  import { eventHandler, getQuery, sendRedirect } from "h3";
2
2
  import { withQuery } from "ufo";
3
3
  import { defu } from "defu";
4
- import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken } from "../utils.js";
4
+ import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken, handleState, handlePkceVerifier, handleInvalidState } from "../utils.js";
5
5
  import { useRuntimeConfig, createError } from "#imports";
6
6
  export function defineOAuthZitadelEventHandler({ config, onSuccess, onError }) {
7
7
  return eventHandler(async (event) => {
@@ -18,12 +18,14 @@ export function defineOAuthZitadelEventHandler({ config, onSuccess, onError }) {
18
18
  if (!onError) throw error;
19
19
  return onError(event, error);
20
20
  }
21
- if (!config.clientId || !config.clientSecret || !config.domain) {
22
- return handleMissingConfiguration(event, "zitadel", ["clientId", "clientSecret", "issuerUrl"], onError);
21
+ if (!config.clientId || !config.domain) {
22
+ return handleMissingConfiguration(event, "zitadel", ["clientId", "domain"], onError);
23
23
  }
24
24
  const authorizationURL = `https://${config.domain}/oauth/v2/authorize`;
25
25
  const tokenURL = `https://${config.domain}/oauth/v2/token`;
26
26
  const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
27
+ const verifier = await handlePkceVerifier(event);
28
+ const state = await handleState(event);
27
29
  if (!query.code) {
28
30
  config.scope = config.scope || ["openid"];
29
31
  return sendRedirect(
@@ -33,22 +35,33 @@ export function defineOAuthZitadelEventHandler({ config, onSuccess, onError }) {
33
35
  client_id: config.clientId,
34
36
  redirect_uri: redirectURL,
35
37
  scope: config.scope.join(" "),
38
+ state,
39
+ code_challenge: verifier.code_challenge,
40
+ code_challenge_method: verifier.code_challenge_method,
36
41
  ...config.authorizationParams
37
42
  })
38
43
  );
39
44
  }
40
- const tokens = await requestAccessToken(tokenURL, {
41
- headers: {
42
- "Authorization": `Basic ${Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64")}`,
43
- "Content-Type": "application/x-www-form-urlencoded"
44
- },
45
+ if (query.state !== state) {
46
+ return handleInvalidState(event, "zitadel", onError);
47
+ }
48
+ const request = {
45
49
  body: {
46
50
  grant_type: "authorization_code",
47
51
  client_id: config.clientId,
48
52
  redirect_uri: redirectURL,
49
- code: query.code
53
+ code: query.code,
54
+ code_verifier: verifier.code_verifier
50
55
  }
51
- });
56
+ };
57
+ if (config.clientSecret) {
58
+ const basicAuthorization = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64");
59
+ request.headers = {
60
+ "Authorization": `Basic ${basicAuthorization}`,
61
+ "Content-Type": "application/x-www-form-urlencoded"
62
+ };
63
+ }
64
+ const tokens = await requestAccessToken(tokenURL, request);
52
65
  if (tokens.error) {
53
66
  return handleAccessTokenErrorResponse(event, "zitadel", tokens, onError);
54
67
  }
@@ -14,7 +14,7 @@ export interface RequestAccessTokenBody {
14
14
  client_secret?: string;
15
15
  [key: string]: string | undefined;
16
16
  }
17
- interface RequestAccessTokenOptions {
17
+ export interface RequestAccessTokenOptions {
18
18
  body?: RequestAccessTokenBody;
19
19
  params?: Record<string, string | undefined>;
20
20
  headers?: Record<string, string>;
@@ -1,6 +1,6 @@
1
1
  import type { H3Event, H3Error } from 'h3';
2
2
  export type ATProtoProvider = 'bluesky';
3
- export type OAuthProvider = ATProtoProvider | 'atlassian' | 'auth0' | 'authentik' | 'azureb2c' | 'battledotnet' | 'cognito' | 'discord' | 'dropbox' | 'facebook' | 'gitea' | 'github' | 'gitlab' | 'google' | 'hubspot' | 'instagram' | 'kick' | 'keycloak' | 'line' | 'linear' | 'linkedin' | 'microsoft' | 'paypal' | 'polar' | 'spotify' | 'seznam' | 'steam' | 'strava' | 'tiktok' | 'twitch' | 'vk' | 'workos' | 'x' | 'xsuaa' | 'yandex' | 'zitadel' | 'apple' | 'livechat' | 'salesforce' | 'slack' | 'heroku' | (string & {});
3
+ export type OAuthProvider = ATProtoProvider | 'atlassian' | 'auth0' | 'authentik' | 'azureb2c' | 'battledotnet' | 'cognito' | 'discord' | 'dropbox' | 'facebook' | 'gitea' | 'github' | 'gitlab' | 'google' | 'hubspot' | 'instagram' | 'kick' | 'keycloak' | 'line' | 'linear' | 'linkedin' | 'microsoft' | 'paypal' | 'polar' | 'spotify' | 'seznam' | 'steam' | 'strava' | 'tiktok' | 'twitch' | 'vk' | 'workos' | 'x' | 'xsuaa' | 'yandex' | 'zitadel' | 'apple' | 'livechat' | 'salesforce' | 'slack' | 'heroku' | 'okta' | (string & {});
4
4
  export type OnError = (event: H3Event, error: H3Error) => Promise<void> | void;
5
5
  export interface OAuthConfig<TConfig, TResult = {
6
6
  user: any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-auth-utils",
3
- "version": "0.5.20",
3
+ "version": "0.5.22",
4
4
  "description": "Add Authentication to Nuxt applications with secured & sealed cookies sessions.",
5
5
  "repository": {
6
6
  "type": "git",