nuxt-auth-utils 0.5.26 → 0.5.28

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
@@ -236,8 +236,10 @@ It can also be set using environment variables:
236
236
  - LinkedIn
237
237
  - LiveChat
238
238
  - Microsoft
239
+ - OIDC / OpenID Connect (Generic)
239
240
  - Okta
240
241
  - Ory
242
+ - osu!
241
243
  - PayPal
242
244
  - Polar
243
245
  - Salesforce
@@ -420,7 +422,7 @@ export default defineWebAuthnRegisterEventHandler({
420
422
  // If he registers a new account with credentials
421
423
  return z.object({
422
424
  // we want the userName to be a valid email
423
- userName: z.string().email()
425
+ userName: z.string().email()
424
426
  }).parse(userBody)
425
427
  },
426
428
  async onSuccess(event, { credential, user }) {
@@ -448,6 +450,8 @@ export default defineWebAuthnRegisterEventHandler({
448
450
  },
449
451
  })
450
452
  ```
453
+ > [!TIP]
454
+ > If you want to plug in and use the [Community sourced list of AAGUIDS](https://github.com/passkeydeveloper/passkey-authenticator-aaguids) to decorate your display of added passkeys, you can access the the ID via `credential.aaguid` inside `onSuccess`
451
455
 
452
456
  ```ts
453
457
  // server/api/webauthn/authenticate.post.ts
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "auth-utils",
3
3
  "configKey": "auth",
4
- "version": "0.5.26",
4
+ "version": "0.5.28",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { readFile, writeFile } from 'node:fs/promises';
2
1
  import { defineNuxtModule, createResolver, addComponentsDir, addImports, addPlugin, addServerPlugin, addServerImportsDir, logger, addServerHandler } from '@nuxt/kit';
3
- import { join } from 'pathe';
4
2
  import { defu } from 'defu';
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ import { join } from 'pathe';
5
5
  import { randomUUID } from 'uncrypto';
6
6
  import { atprotoProviders, atprotoProviderDefaultClientMetadata, getClientMetadataFilename } from '../dist/runtime/utils/atproto.js';
7
7
 
@@ -393,6 +393,19 @@ const module$1 = defineNuxtModule({
393
393
  redirectURL: "",
394
394
  scope: []
395
395
  });
396
+ runtimeConfig.oauth.oidc = defu(runtimeConfig.oauth.oidc, {
397
+ clientId: "",
398
+ clientSecret: "",
399
+ openidConfig: "",
400
+ redirectURL: "",
401
+ scope: []
402
+ });
403
+ runtimeConfig.oauth.osu = defu(runtimeConfig.oauth.osu, {
404
+ clientId: "",
405
+ clientSecret: "",
406
+ redirectURL: "",
407
+ scope: []
408
+ });
396
409
  }
397
410
  });
398
411
 
@@ -35,4 +35,21 @@ export interface OAuthKickConfig {
35
35
  */
36
36
  redirectURL?: string;
37
37
  }
38
- export declare function defineOAuthKickEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthKickConfig>): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
38
+ interface KickUser {
39
+ email: string;
40
+ name: string;
41
+ profile_picture: string;
42
+ user_id: string;
43
+ }
44
+ interface KickTokens {
45
+ access_token: string;
46
+ expires_in: number;
47
+ refresh_token: string;
48
+ scope: string;
49
+ token_type: string;
50
+ }
51
+ export declare function defineOAuthKickEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthKickConfig, {
52
+ user: KickUser;
53
+ tokens: KickTokens;
54
+ }>): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
55
+ export {};
@@ -0,0 +1,215 @@
1
+ import type { OAuthConfig } from '#auth-utils';
2
+ export interface OAuthOidcConfig {
3
+ /**
4
+ * OAuth Client ID
5
+ *
6
+ * @default process.env.NUXT_OAUTH_OIDC_CLIENT_ID
7
+ */
8
+ clientId?: string;
9
+ /**
10
+ * OAuth Client secret.
11
+ *
12
+ * @default process.env.NUXT_OAUTH_OIDC_CLIENT_SECRET
13
+ */
14
+ clientSecret?: string;
15
+ /**
16
+ * OpenID configuration. If a string is passed, it is considered to be the full URL to the OpenID configuration endpoint
17
+ * where all required endpoints are listed and fetched from automatically.
18
+ *
19
+ * Alternatively, an object can be set with the required endpoint URLs.
20
+ *
21
+ * @default process.env.NUXT_OAUTH_OIDC_OPENID_CONFIG
22
+ * @example "https://my-provider.com/.well-known/openid-configuration"
23
+ */
24
+ openidConfig?: string | OIDCConfiguration;
25
+ /**
26
+ * OAuth Scope
27
+ *
28
+ * @default ['openid']
29
+ * @example ['openid', 'profile', 'email']
30
+ */
31
+ scope?: string[];
32
+ /**
33
+ * Redirect URL to to allow overriding for situations like prod failing to determine public hostname
34
+ *
35
+ * @default process.env.NUXT_OAUTH_OIDC_REDIRECT_URL
36
+ */
37
+ redirectURL?: string;
38
+ /**
39
+ * Additional custom params that are passed to the specific endpoint requests.
40
+ * Can be used to provide custom (query) params.
41
+ */
42
+ params?: Partial<Record<'authorization_endpoint' | 'token_endpoint' | 'userinfo_endpoint', object>>;
43
+ }
44
+ /**
45
+ * Standard OIDC claims.
46
+ *
47
+ * @see: https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
48
+ */
49
+ interface OidcUser {
50
+ /**
51
+ * Subject - Identifier for the End-User at the Issuer.
52
+ */
53
+ sub: string;
54
+ /**
55
+ * End-User's full name in displayable form including all name parts,
56
+ * possibly including titles and suffixes, ordered according to the
57
+ * End-User's locale and preferences.
58
+ */
59
+ name?: string;
60
+ /**
61
+ * Given name(s) or first name(s) of the End-User. Note that in some cultures,
62
+ * people can have multiple given names; all can be present, with the names
63
+ * being separated by space characters.
64
+ */
65
+ given_name?: string;
66
+ /**
67
+ * Surname(s) or last name(s) of the End-User. Note that in some cultures,
68
+ * people can have multiple family names or no family name; all can be present,
69
+ * with the names being separated by space characters.
70
+ */
71
+ family_name?: string;
72
+ /**
73
+ * Middle name(s) of the End-User. Note that in some cultures, people can have
74
+ * multiple middle names; all can be present, with the names being separated by
75
+ * space characters. Also note that in some cultures, middle names are not used.
76
+ */
77
+ middle_name?: string;
78
+ /**
79
+ * Casual name of the End-User that may or may not be the same as the given_name.
80
+ * For instance, a nickname value of Mike might be returned alongside a given_name
81
+ * value of Michael.
82
+ */
83
+ nickname?: string;
84
+ /**
85
+ * Shorthand name by which the End-User wishes to be referred to at the RP, such as
86
+ * janedoe or j.doe. This value MAY be any valid JSON string including special
87
+ * characters such as @, /, or whitespace. The RP MUST NOT rely upon this value
88
+ * being unique.
89
+ */
90
+ preferred_username?: string;
91
+ /**
92
+ * URL of the End-User's profile page. The contents of this Web page SHOULD be
93
+ * about the End-User.
94
+ */
95
+ profile?: string;
96
+ /**
97
+ * URL of the End-User's profile picture. This URL MUST refer to an image file
98
+ * (for example, a PNG, JPEG, or GIF image file), rather than to a Web page
99
+ * containing an image. Note that this URL SHOULD specifically reference a profile
100
+ * photo of the End-User suitable for displaying when describing the End-User,
101
+ * rather than an arbitrary photo taken by the End-User.
102
+ */
103
+ picture?: string;
104
+ /**
105
+ * URL of the End-User's Web page or blog. This Web page SHOULD contain information
106
+ * published by the End-User or an organization that the End-User is affiliated with.
107
+ */
108
+ website?: string;
109
+ /**
110
+ * End-User's preferred e-mail address. Its value MUST conform to the RFC 5322
111
+ * addr-spec syntax. The RP MUST NOT rely upon this value being unique.
112
+ */
113
+ email?: string;
114
+ /**
115
+ * True if the End-User's e-mail address has been verified; otherwise false.
116
+ * When this Claim Value is true, this means that the OP took affirmative steps
117
+ * to ensure that this e-mail address was controlled by the End-User at the time
118
+ * the verification was performed. The means by which an e-mail address is verified
119
+ * is context specific, and dependent upon the trust framework or contractual
120
+ * agreements within which the parties are operating.
121
+ */
122
+ email_verified?: boolean;
123
+ /**
124
+ * End-User's gender. Values defined by this specification are female and male.
125
+ * Other values MAY be used when neither of the defined values are applicable.
126
+ */
127
+ gender?: string;
128
+ /**
129
+ * End-User's birthday, represented as an ISO 8601-1 YYYY-MM-DD format. The year
130
+ * MAY be 0000, indicating that it is omitted. To represent only the year, YYYY
131
+ * format is allowed. Note that depending on the underlying platform's date related
132
+ * function, providing just year can result in varying month and day, so the
133
+ * implementers need to take this factor into account to correctly process the dates.
134
+ */
135
+ birthdate?: string;
136
+ /**
137
+ * String from IANA Time Zone Database representing the End-User's time zone.
138
+ * For example, Europe/Paris or America/Los_Angeles.
139
+ */
140
+ zoneinfo?: string;
141
+ /**
142
+ * End-User's locale, represented as a BCP47 language tag. This is typically an
143
+ * ISO 639 Alpha-2 language code in lowercase and an ISO 3166-1 Alpha-2 country
144
+ * code in uppercase, separated by a dash. For example, en-US or fr-CA. As a
145
+ * compatibility note, some implementations have used an underscore as the separator
146
+ * rather than a dash, for example, en_US; Relying Parties MAY choose to accept
147
+ * this locale syntax as well.
148
+ */
149
+ locale?: string;
150
+ /**
151
+ * End-User's preferred telephone number. E.164 is RECOMMENDED as the format of
152
+ * this Claim, for example, +1 (555) 555-5555 or +56 (2) 687 2400. If the phone
153
+ * number contains an extension, it is RECOMMENDED that the extension be represented
154
+ * using the RFC 3966 extension syntax, for example, +1 (555) 555-5555;ext=5678.
155
+ */
156
+ phone_number?: string;
157
+ /**
158
+ * True if the End-User's phone number has been verified; otherwise false. When
159
+ * this Claim Value is true, this means that the OP took affirmative steps to
160
+ * ensure that this phone number was controlled by the End-User at the time the
161
+ * verification was performed. The means by which a phone number is verified is
162
+ * context specific, and dependent upon the trust framework or contractual
163
+ * agreements within which the parties are operating. When true, the phone_number
164
+ * Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.
165
+ */
166
+ phone_number_verified?: boolean;
167
+ /**
168
+ * End-User's preferred postal address.
169
+ */
170
+ address?: AddressClaim;
171
+ /**
172
+ * Time the End-User's information was last updated. Its value is a JSON number
173
+ * representing the number of seconds from 1970-01-01T00:00:00Z as measured in
174
+ * UTC until the date/time.
175
+ */
176
+ updated_at?: number;
177
+ }
178
+ /**
179
+ * Address claim structure as defined in OpenID Connect specification
180
+ */
181
+ interface AddressClaim {
182
+ /** Full mailing address, formatted for display or use on a mailing label */
183
+ formatted?: string;
184
+ /** Full street address component, which may include house number, street name, post office box, and multi-line extended street address information */
185
+ street_address?: string;
186
+ /** City or locality component */
187
+ locality?: string;
188
+ /** State, province, prefecture, or region component */
189
+ region?: string;
190
+ /** Zip code or postal code component */
191
+ postal_code?: string;
192
+ /** Country name component */
193
+ country?: string;
194
+ }
195
+ interface OidcTokens {
196
+ access_token: string;
197
+ token_type: string;
198
+ scope?: string;
199
+ id_token?: string;
200
+ refresh_token?: string;
201
+ expires_in?: number;
202
+ }
203
+ interface OIDCConfiguration {
204
+ authorization_endpoint: string;
205
+ token_endpoint: string;
206
+ userinfo_endpoint?: string;
207
+ }
208
+ /**
209
+ * Event handler for generic OAuth using OIDC and PKCE.
210
+ */
211
+ export declare function defineOAuthOidcEventHandler<TUser = OidcUser>({ config, onSuccess, onError }: OAuthConfig<OAuthOidcConfig, {
212
+ user: TUser;
213
+ tokens: OidcTokens;
214
+ }>): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
215
+ export {};
@@ -0,0 +1,92 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ import { defu } from "defu";
3
+ import { createError, eventHandler, getQuery, sendRedirect } from "h3";
4
+ import { withQuery } from "ufo";
5
+ import { getOAuthRedirectURL, handleAccessTokenErrorResponse, handleInvalidState, handleMissingConfiguration, handlePkceVerifier, handleState, requestAccessToken, handleNonce, parseJwt } from "../utils.js";
6
+ export function defineOAuthOidcEventHandler({ config, onSuccess, onError }) {
7
+ return eventHandler(async (event) => {
8
+ config = defu(config, useRuntimeConfig(event).oauth.oidc, {
9
+ scope: ["openid"]
10
+ });
11
+ const query = getQuery(event);
12
+ if (query.error) {
13
+ const error = createError({
14
+ statusCode: 401,
15
+ message: `OIDC login failed: ${query.error || "Unknown error"}`,
16
+ data: query
17
+ });
18
+ if (!onError) throw error;
19
+ return onError(event, error);
20
+ }
21
+ if (!config.clientId || !config.openidConfig) {
22
+ return handleMissingConfiguration(event, "oidc", ["clientId", "openidConfig"], onError);
23
+ }
24
+ const oidcConfig = typeof config.openidConfig === "string" ? await $fetch(config.openidConfig) : config.openidConfig;
25
+ const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
26
+ const state = await handleState(event);
27
+ const verifier = await handlePkceVerifier(event);
28
+ const nonce = handleNonce(event);
29
+ if (!query.code) {
30
+ config.scope = config.scope || [];
31
+ const authQuery = {
32
+ client_id: config.clientId,
33
+ redirect_uri: redirectURL,
34
+ scope: config.scope.join(" "),
35
+ state,
36
+ nonce,
37
+ response_type: "code",
38
+ ...config.params?.authorization_endpoint
39
+ };
40
+ authQuery.code_challenge = verifier.code_challenge;
41
+ authQuery.code_challenge_method = verifier.code_challenge_method;
42
+ return sendRedirect(
43
+ event,
44
+ withQuery(oidcConfig.authorization_endpoint, authQuery)
45
+ );
46
+ }
47
+ if (query.state !== state) {
48
+ return handleInvalidState(event, "oidc", onError);
49
+ }
50
+ const tokenQuery = {
51
+ grant_type: "authorization_code",
52
+ client_id: config.clientId,
53
+ client_secret: config.clientSecret,
54
+ redirect_uri: redirectURL,
55
+ code: query.code,
56
+ code_verifier: verifier.code_verifier,
57
+ ...config.params?.token_endpoint
58
+ };
59
+ const tokens = await requestAccessToken(oidcConfig.token_endpoint, {
60
+ body: tokenQuery
61
+ });
62
+ if (tokens.error) {
63
+ return handleAccessTokenErrorResponse(event, "oidc", tokens, onError);
64
+ }
65
+ if (tokens.id_token) {
66
+ const claims = parseJwt(tokens.id_token);
67
+ if (claims.nonce !== nonce) {
68
+ const error = createError({
69
+ statusCode: 401,
70
+ message: "OIDC login failed: nonce mismatch"
71
+ });
72
+ if (!onError) throw error;
73
+ return onError(event, error);
74
+ }
75
+ }
76
+ let user = {};
77
+ if (oidcConfig.userinfo_endpoint) {
78
+ user = await $fetch(oidcConfig.userinfo_endpoint, {
79
+ headers: {
80
+ Authorization: `${tokens.token_type} ${tokens.access_token}`
81
+ },
82
+ params: {
83
+ ...config.params?.userinfo_endpoint
84
+ }
85
+ });
86
+ }
87
+ return onSuccess(event, {
88
+ user,
89
+ tokens
90
+ });
91
+ });
92
+ }
@@ -0,0 +1,42 @@
1
+ import type { OAuthConfig } from '#auth-utils';
2
+ export interface OAuthOsuConfig {
3
+ /**
4
+ * osu! OAuth Client ID
5
+ * @default process.env.NUXT_OAUTH_OSU_CLIENT_ID
6
+ */
7
+ clientId?: string;
8
+ /**
9
+ * osu! OAuth Client Secret
10
+ * @default process.env.NUXT_OAUTH_OSU_CLIENT_SECRET
11
+ */
12
+ clientSecret?: string;
13
+ /**
14
+ * osu! OAuth Scope
15
+ *
16
+ * The identify scope is always implicitly provided.
17
+ * @default []
18
+ * @see https://osu.ppy.sh/docs/#scopes
19
+ */
20
+ scope?: string[];
21
+ /**
22
+ * osu! OAuth Authorization URL
23
+ * @default 'https://osu.ppy.sh/oauth/authorize'
24
+ */
25
+ authorizationURL?: string;
26
+ /**
27
+ * osu! OAuth Token URL
28
+ * @default 'https://osu.ppy.sh/oauth/token'
29
+ */
30
+ tokenURL?: string;
31
+ /**
32
+ * Extra authorization parameters to provide to the authorization URL
33
+ * @see 'https://osu.ppy.sh/docs/#authorization-code-grant'
34
+ */
35
+ authorizationParams?: Record<string, string>;
36
+ /**
37
+ * Redirect URL to to allow overriding for situations like prod failing to determine public hostname
38
+ * @default process.env.NUXT_OAUTH_OSU_REDIRECT_URL or current URL
39
+ */
40
+ redirectURL?: string;
41
+ }
42
+ export declare function defineOAuthOsuEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthOsuConfig>): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
@@ -0,0 +1,63 @@
1
+ import { eventHandler, getQuery, sendRedirect } from "h3";
2
+ import { withQuery } from "ufo";
3
+ import { defu } from "defu";
4
+ import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken, handleState, handleInvalidState } from "../utils.js";
5
+ import { useRuntimeConfig } from "#imports";
6
+ export function defineOAuthOsuEventHandler({ config, onSuccess, onError }) {
7
+ return eventHandler(async (event) => {
8
+ config = defu(config, useRuntimeConfig(event).oauth?.osu, {
9
+ authorizationURL: "https://osu.ppy.sh/oauth/authorize",
10
+ tokenURL: "https://osu.ppy.sh/oauth/token",
11
+ authorizationParams: {}
12
+ });
13
+ const query = getQuery(event);
14
+ if (!config.clientId || !config.clientSecret) {
15
+ return handleMissingConfiguration(event, "osu", ["clientId", "clientSecret"], onError);
16
+ }
17
+ if (query.error) {
18
+ return handleAccessTokenErrorResponse(event, "osu", query, onError);
19
+ }
20
+ const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
21
+ const state = await handleState(event);
22
+ if (!query.code) {
23
+ config.scope = config.scope || [];
24
+ return sendRedirect(
25
+ event,
26
+ withQuery(config.authorizationURL, {
27
+ response_type: "code",
28
+ client_id: config.clientId,
29
+ redirect_uri: redirectURL,
30
+ scope: config.scope.join(" "),
31
+ state,
32
+ ...config.authorizationParams
33
+ })
34
+ );
35
+ }
36
+ if (query.state !== state) {
37
+ return handleInvalidState(event, "osu", onError);
38
+ }
39
+ const tokens = await requestAccessToken(config.tokenURL, {
40
+ body: {
41
+ client_id: config.clientId,
42
+ client_secret: config.clientSecret,
43
+ grant_type: "authorization_code",
44
+ redirect_uri: redirectURL,
45
+ code: query.code
46
+ }
47
+ });
48
+ if (tokens.error) {
49
+ return handleAccessTokenErrorResponse(event, "osu", tokens, onError);
50
+ }
51
+ const accessToken = tokens.access_token;
52
+ const user = await $fetch("https://osu.ppy.sh/api/v2/me", {
53
+ headers: {
54
+ "user-agent": "Nuxt Auth Utils",
55
+ "Authorization": `Bearer ${accessToken}`
56
+ }
57
+ });
58
+ return onSuccess(event, {
59
+ tokens,
60
+ user
61
+ });
62
+ });
63
+ }
@@ -44,4 +44,28 @@ export interface OAuthTwitchConfig {
44
44
  */
45
45
  redirectURL?: string;
46
46
  }
47
- export declare function defineOAuthTwitchEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthTwitchConfig>): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
47
+ interface TwitchUser {
48
+ id: string;
49
+ login: string;
50
+ display_name: string;
51
+ type: string;
52
+ broadcaster_type: string;
53
+ description: string;
54
+ profile_image_url: string;
55
+ offline_image_url: string;
56
+ view_count: number;
57
+ email?: string;
58
+ created_at: string;
59
+ }
60
+ interface TwitchTokens {
61
+ access_token: string;
62
+ expires_in: number;
63
+ refresh_token: string;
64
+ scope: string[];
65
+ token_type: string;
66
+ }
67
+ export declare function defineOAuthTwitchEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthTwitchConfig, {
68
+ user: TwitchUser;
69
+ tokens: TwitchTokens;
70
+ }>): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
71
+ export {};
@@ -1,14 +1,16 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ import { defu } from "defu";
1
3
  import { eventHandler, getQuery, sendRedirect } from "h3";
2
4
  import { withQuery } from "ufo";
3
- import { defu } from "defu";
4
- import { randomUUID } from "uncrypto";
5
5
  import {
6
- handleMissingConfiguration,
7
- handleAccessTokenErrorResponse,
8
6
  getOAuthRedirectURL,
7
+ handleAccessTokenErrorResponse,
8
+ handleInvalidState,
9
+ handleMissingConfiguration,
10
+ handlePkceVerifier,
11
+ handleState,
9
12
  requestAccessToken
10
13
  } from "../utils.js";
11
- import { useRuntimeConfig } from "#imports";
12
14
  export function defineOAuthXEventHandler({
13
15
  config,
14
16
  onSuccess,
@@ -19,16 +21,15 @@ export function defineOAuthXEventHandler({
19
21
  authorizationURL: "https://x.com/i/oauth2/authorize",
20
22
  tokenURL: "https://api.x.com/2/oauth2/token",
21
23
  userURL: "https://api.x.com/2/users/me",
22
- authorizationParams: {
23
- state: randomUUID(),
24
- code_challenge: randomUUID()
25
- }
24
+ authorizationParams: {}
26
25
  });
27
26
  const query = getQuery(event);
28
27
  if (!config.clientId || !config.clientSecret) {
29
28
  return handleMissingConfiguration(event, "x", ["clientId", "clientSecret"], onError);
30
29
  }
31
30
  const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
31
+ const pkce = await handlePkceVerifier(event);
32
+ const state = await handleState(event);
32
33
  if (!query.code) {
33
34
  config.scope = config.scope || [
34
35
  "tweet.read",
@@ -40,13 +41,18 @@ export function defineOAuthXEventHandler({
40
41
  withQuery(config.authorizationURL, {
41
42
  response_type: "code",
42
43
  client_id: config.clientId,
43
- code_challenge_method: "plain",
44
44
  redirect_uri: redirectURL,
45
45
  scope: config.scope.join(" "),
46
- ...config.authorizationParams
46
+ ...config.authorizationParams,
47
+ code_challenge: pkce.code_challenge,
48
+ code_challenge_method: pkce.code_challenge_method,
49
+ state
47
50
  })
48
51
  );
49
52
  }
53
+ if (query.state !== state) {
54
+ return handleInvalidState(event, "x", onError);
55
+ }
50
56
  const tokens = await requestAccessToken(config.tokenURL, {
51
57
  headers: {
52
58
  Authorization: `Basic ${Buffer.from(
@@ -55,7 +61,7 @@ export function defineOAuthXEventHandler({
55
61
  },
56
62
  params: {
57
63
  grant_type: "authorization_code",
58
- code_verifier: config.authorizationParams?.code_challenge,
64
+ code_verifier: pkce.code_verifier,
59
65
  redirect_uri: redirectURL,
60
66
  code: query.code
61
67
  }
@@ -1,4 +1,5 @@
1
1
  import { type H3Event } from 'h3';
2
+ import * as jose from 'jose';
2
3
  import type { OAuthProvider, OnError } from '#auth-utils';
3
4
  export declare function getOAuthRedirectURL(event: H3Event): string;
4
5
  /**
@@ -26,7 +27,7 @@ export interface RequestAccessTokenOptions {
26
27
  *
27
28
  * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
28
29
  */
29
- export declare function requestAccessToken(url: string, options: RequestAccessTokenOptions): Promise<any>;
30
+ export declare function requestAccessToken<T = any>(url: string, options: RequestAccessTokenOptions): Promise<T>;
30
31
  /**
31
32
  * Handle OAuth access token error response
32
33
  *
@@ -70,4 +71,6 @@ export declare function handlePkceVerifier(event: H3Event): Promise<{
70
71
  code_challenge_method?: undefined;
71
72
  }>;
72
73
  export declare function handleState(event: H3Event): Promise<string | undefined>;
74
+ export declare function parseJwt(token: string): jose.JWTPayload;
75
+ export declare function handleNonce(event: H3Event): string | undefined;
73
76
  export {};
@@ -121,3 +121,23 @@ export async function handleState(event) {
121
121
  });
122
122
  return state;
123
123
  }
124
+ export function parseJwt(token) {
125
+ return jose.decodeJwt(token);
126
+ }
127
+ export function handleNonce(event) {
128
+ const query = getQuery(event);
129
+ if (query.code) {
130
+ const nonce2 = getCookie(event, "nuxt-auth-nonce");
131
+ deleteCookie(event, "nuxt-auth-nonce");
132
+ return nonce2;
133
+ }
134
+ const nonce = encodeBase64Url(getRandomBytes(8));
135
+ setCookie(event, "nuxt-auth-nonce", nonce, {
136
+ httpOnly: true,
137
+ secure: !isDevelopment,
138
+ sameSite: "lax",
139
+ maxAge: OAUTH_COOKIE_MAX_AGE,
140
+ path: "/"
141
+ });
142
+ return nonce;
143
+ }
@@ -84,7 +84,8 @@ export function defineWebAuthnRegisterEventHandler({
84
84
  publicKey: bufferToBase64URLString(verification.registrationInfo.credential.publicKey.buffer),
85
85
  counter: verification.registrationInfo.credential.counter,
86
86
  backedUp: verification.registrationInfo.credentialBackedUp,
87
- transports: verification.registrationInfo.credential.transports
87
+ transports: verification.registrationInfo.credential.transports,
88
+ aaguid: verification.registrationInfo.aaguid
88
89
  },
89
90
  registrationInfo: verification.registrationInfo
90
91
  });
@@ -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' | 'roblox' | 'okta' | 'ory' | 'shopifyCustomer' | (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' | 'roblox' | 'okta' | 'ory' | 'shopifyCustomer' | 'oidc' | 'osu' | (string & {});
4
4
  export type OnError = (event: H3Event, error: H3Error) => Promise<void> | void;
5
5
  export interface OAuthConfig<TConfig, TResult = {
6
6
  user: any;
@@ -8,6 +8,7 @@ export interface WebAuthnCredential {
8
8
  counter: number;
9
9
  backedUp: boolean;
10
10
  transports?: AuthenticatorTransportFuture[];
11
+ aaguid?: string;
11
12
  [key: string]: unknown;
12
13
  }
13
14
  export interface WebAuthnUser {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-auth-utils",
3
- "version": "0.5.26",
3
+ "version": "0.5.28",
4
4
  "description": "Add Authentication to Nuxt applications with secured & sealed cookies sessions.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "license": "MIT",
10
10
  "type": "module",
11
- "packageManager": "pnpm@10.25.0",
11
+ "packageManager": "pnpm@10.28.0",
12
12
  "exports": {
13
13
  ".": {
14
14
  "types": "./dist/types.d.mts",
@@ -40,10 +40,10 @@
40
40
  },
41
41
  "dependencies": {
42
42
  "@adonisjs/hash": "^9.1.1",
43
- "@nuxt/kit": "^4.2.1",
43
+ "@nuxt/kit": "^4.2.2",
44
44
  "defu": "^6.1.4",
45
45
  "h3": "^1.15.4",
46
- "hookable": "^5.5.3",
46
+ "hookable": "^6.0.1",
47
47
  "jose": "^6.1.3",
48
48
  "ofetch": "^1.5.1",
49
49
  "openid-client": "^6.8.1",
@@ -72,20 +72,20 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@iconify-json/simple-icons": "^1.2.62",
75
+ "@iconify-json/simple-icons": "^1.2.66",
76
76
  "@nuxt/devtools": "3.1.1",
77
- "@nuxt/eslint-config": "^1.11.0",
77
+ "@nuxt/eslint-config": "^1.12.1",
78
78
  "@nuxt/module-builder": "^1.0.2",
79
- "@nuxt/schema": "^4.2.1",
80
- "@nuxt/test-utils": "^3.21.0",
79
+ "@nuxt/schema": "^4.2.2",
80
+ "@nuxt/test-utils": "^3.23.0",
81
81
  "@types/node": "latest",
82
- "@nuxt/ui": "^4.2.1",
82
+ "@nuxt/ui": "^4.3.0",
83
83
  "@simplewebauthn/types": "^12.0.0",
84
84
  "changelogen": "^0.6.2",
85
- "eslint": "^9.39.1",
86
- "nuxt": "^4.2.1",
85
+ "eslint": "^9.39.2",
86
+ "nuxt": "^4.2.2",
87
87
  "typescript": "5.9.3",
88
- "vitest": "^4.0.15",
89
- "vue-tsc": "^3.1.8"
88
+ "vitest": "^4.0.17",
89
+ "vue-tsc": "^3.2.2"
90
90
  }
91
91
  }