nuxt-auth-utils 0.3.4 → 0.3.6

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.
Files changed (34) hide show
  1. package/README.md +2 -1
  2. package/dist/module.d.mts +1 -1
  3. package/dist/module.d.ts +1 -1
  4. package/dist/module.json +2 -2
  5. package/dist/module.mjs +5 -0
  6. package/dist/runtime/app/plugins/session.client.js +3 -1
  7. package/dist/runtime/server/lib/oauth/auth0.js +18 -34
  8. package/dist/runtime/server/lib/oauth/battledotnet.js +23 -37
  9. package/dist/runtime/server/lib/oauth/cognito.d.ts +5 -0
  10. package/dist/runtime/server/lib/oauth/cognito.js +21 -30
  11. package/dist/runtime/server/lib/oauth/discord.js +15 -36
  12. package/dist/runtime/server/lib/oauth/facebook.js +8 -24
  13. package/dist/runtime/server/lib/oauth/github.js +14 -26
  14. package/dist/runtime/server/lib/oauth/google.js +16 -36
  15. package/dist/runtime/server/lib/oauth/keycloak.js +14 -37
  16. package/dist/runtime/server/lib/oauth/linkedin.d.ts +2 -11
  17. package/dist/runtime/server/lib/oauth/linkedin.js +15 -36
  18. package/dist/runtime/server/lib/oauth/microsoft.d.ts +2 -11
  19. package/dist/runtime/server/lib/oauth/microsoft.js +16 -35
  20. package/dist/runtime/server/lib/oauth/paypal.js +17 -35
  21. package/dist/runtime/server/lib/oauth/spotify.js +17 -34
  22. package/dist/runtime/server/lib/oauth/steam.js +2 -6
  23. package/dist/runtime/server/lib/oauth/tiktok.d.ts +45 -0
  24. package/dist/runtime/server/lib/oauth/tiktok.js +84 -0
  25. package/dist/runtime/server/lib/oauth/twitch.js +16 -35
  26. package/dist/runtime/server/lib/oauth/x.d.ts +1 -6
  27. package/dist/runtime/server/lib/oauth/x.js +19 -60
  28. package/dist/runtime/server/lib/oauth/xsuaa.js +15 -34
  29. package/dist/runtime/server/lib/oauth/yandex.js +14 -36
  30. package/dist/runtime/server/lib/utils.d.ts +36 -0
  31. package/dist/runtime/server/lib/utils.js +46 -0
  32. package/dist/runtime/types/index.d.ts +1 -1
  33. package/dist/runtime/types/oauth-config.d.ts +3 -1
  34. package/package.json +12 -11
@@ -17,11 +17,6 @@ export interface OAuthXConfig {
17
17
  * @example ['tweet.read', 'users.read', 'offline.access'],
18
18
  */
19
19
  scope?: string[];
20
- /**
21
- * Require email from user
22
- * @default false
23
- */
24
- emailRequired?: boolean;
25
20
  /**
26
21
  * X OAuth Authorization URL
27
22
  * @default 'https://twitter.com/i/oauth2/authorize'
@@ -41,7 +36,7 @@ export interface OAuthXConfig {
41
36
  * Extra authorization parameters to provide to the authorization URL
42
37
  * @see https://developer.x.com/en/docs/authentication/oauth-2-0/user-access-token
43
38
  */
44
- authorizationParams: Record<string, string>;
39
+ authorizationParams?: Record<string, string>;
45
40
  /**
46
41
  * Redirect URL to to allow overriding for situations like prod failing to determine public hostname
47
42
  * @default process.env.NUXT_OAUTH_X_REDIRECT_URL or current URL
@@ -1,13 +1,12 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import {
3
2
  eventHandler,
4
- createError,
5
3
  getQuery,
6
- getRequestURL,
7
4
  sendRedirect
8
5
  } from "h3";
9
- import { withQuery, parsePath } from "ufo";
6
+ import { withQuery } from "ufo";
10
7
  import { defu } from "defu";
8
+ import { randomUUID } from "uncrypto";
9
+ import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken } from "../utils.js";
11
10
  import { useRuntimeConfig } from "#imports";
12
11
  export function oauthXEventHandler({
13
12
  config,
@@ -16,25 +15,20 @@ export function oauthXEventHandler({
16
15
  }) {
17
16
  return eventHandler(async (event) => {
18
17
  config = defu(config, useRuntimeConfig(event).oauth?.x, {
19
- authorizationURL: "https://twitter.com/i/oauth2/authorize",
20
- tokenURL: "https://api.twitter.com/2/oauth2/token",
21
- userURL: "https://api.twitter.com/2/users/me",
18
+ authorizationURL: "https://x.com/i/oauth2/authorize",
19
+ tokenURL: "https://api.x.com/2/oauth2/token",
20
+ userURL: "https://api.x.com/2/users/me",
22
21
  authorizationParams: {
23
22
  state: randomUUID(),
24
23
  code_challenge: randomUUID()
25
24
  }
26
25
  });
27
- const { code } = getQuery(event);
26
+ const query = getQuery(event);
28
27
  if (!config.clientId) {
29
- const error = createError({
30
- statusCode: 500,
31
- message: "Missing NUXT_OAUTH_X_CLIENT_ID env variables."
32
- });
33
- if (!onError) throw error;
34
- return onError(event, error);
28
+ return handleMissingConfiguration(event, "x", ["clientId"], onError);
35
29
  }
36
- const redirectURL = config.redirectURL || getRequestURL(event).href;
37
- if (!code) {
30
+ const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
31
+ if (!query.code) {
38
32
  config.scope = config.scope || ["tweet.read", "users.read", "offline.access"];
39
33
  return sendRedirect(
40
34
  event,
@@ -48,31 +42,19 @@ export function oauthXEventHandler({
48
42
  })
49
43
  );
50
44
  }
51
- const params = {
52
- grant_type: "authorization_code",
53
- code_verifier: config.authorizationParams.code_challenge,
54
- redirect_uri: parsePath(redirectURL).pathname,
55
- code
56
- };
57
- const authCode = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64");
58
- const tokens = await $fetch(config.tokenURL, {
59
- method: "POST",
45
+ const tokens = await requestAccessToken(config.tokenURL, {
60
46
  headers: {
61
- "Content-Type": "application/x-www-form-urlencoded",
62
- "Authorization": `Basic ${authCode}`
47
+ Authorization: `Basic ${Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64")}`
63
48
  },
64
- params
65
- }).catch((error) => {
66
- return { error };
49
+ params: {
50
+ grant_type: "authorization_code",
51
+ code_verifier: config.authorizationParams?.code_challenge,
52
+ redirect_uri: redirectURL,
53
+ code: query.code
54
+ }
67
55
  });
68
56
  if (tokens.error) {
69
- const error = createError({
70
- statusCode: 401,
71
- message: `X login failed: ${tokens.error?.data?.error_description || "Unknown error"}`,
72
- data: tokens
73
- });
74
- if (!onError) throw error;
75
- return onError(event, error);
57
+ return handleAccessTokenErrorResponse(event, "x", tokens, onError);
76
58
  }
77
59
  const accessToken = tokens.access_token;
78
60
  const user = await $fetch(
@@ -88,29 +70,6 @@ export function oauthXEventHandler({
88
70
  ).catch((error) => {
89
71
  return error;
90
72
  });
91
- if (config.emailRequired) {
92
- const emailData = await $fetch("https://api.twitter.com/1.1/account/verify_credentials.json", {
93
- headers: {
94
- Authorization: `Bearer ${accessToken}`
95
- },
96
- query: {
97
- include_email: "true",
98
- skip_status: "true"
99
- }
100
- }).catch((error) => {
101
- return error;
102
- });
103
- if (emailData && emailData.email) {
104
- user.email = emailData.email;
105
- } else {
106
- const error = createError({
107
- statusCode: 401,
108
- message: "Twitter login failed: no user email found"
109
- });
110
- if (!onError) throw error;
111
- return onError(event, error);
112
- }
113
- }
114
73
  return onSuccess(event, {
115
74
  tokens,
116
75
  user: user?.data
@@ -1,23 +1,19 @@
1
- import { eventHandler, createError, getQuery, getRequestURL, sendRedirect } from "h3";
2
- import { withQuery, parsePath } from "ufo";
1
+ import { eventHandler, getQuery, sendRedirect } from "h3";
2
+ import { withQuery } from "ufo";
3
3
  import { defu } from "defu";
4
+ import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken } from "../utils.js";
4
5
  import { useRuntimeConfig } from "#imports";
5
6
  export function oauthXSUAAEventHandler({ config, onSuccess, onError }) {
6
7
  return eventHandler(async (event) => {
7
8
  config = defu(config, useRuntimeConfig(event).oauth?.xsuaa);
8
- const { code } = getQuery(event);
9
+ const query = getQuery(event);
9
10
  if (!config.clientId || !config.clientSecret || !config.domain) {
10
- const error = createError({
11
- statusCode: 500,
12
- message: "Missing NUXT_OAUTH_XSUAA_CLIENT_ID or NUXT_OAUTH_XSUAA_CLIENT_SECRET or NUXT_OAUTH_XSUAA_DOMAIN env variables."
13
- });
14
- if (!onError) throw error;
15
- return onError(event, error);
11
+ return handleMissingConfiguration(event, "xsuaa", ["clientId", "clientSecret", "domain"], onError);
16
12
  }
17
13
  const authorizationURL = `https://${config.domain}/oauth/authorize`;
18
14
  const tokenURL = `https://${config.domain}/oauth/token`;
19
- const redirectURL = config.redirectURL || getRequestURL(event).href;
20
- if (!code) {
15
+ const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
16
+ if (!query.code) {
21
17
  config.scope = config.scope || [];
22
18
  return sendRedirect(
23
19
  event,
@@ -29,32 +25,17 @@ export function oauthXSUAAEventHandler({ config, onSuccess, onError }) {
29
25
  })
30
26
  );
31
27
  }
32
- const tokens = await $fetch(
33
- tokenURL,
34
- {
35
- method: "POST",
36
- headers: {
37
- "Content-Type": "application/x-www-form-urlencoded"
38
- },
39
- body: new URLSearchParams({
40
- grant_type: "authorization_code",
41
- client_id: config.clientId,
42
- client_secret: config.clientSecret,
43
- redirect_uri: parsePath(redirectURL).pathname,
44
- code: `${code}`
45
- })
28
+ const tokens = await requestAccessToken(tokenURL, {
29
+ body: {
30
+ grant_type: "authorization_code",
31
+ client_id: config.clientId,
32
+ client_secret: config.clientSecret,
33
+ redirect_uri: redirectURL,
34
+ code: query.code
46
35
  }
47
- ).catch((error) => {
48
- return { error };
49
36
  });
50
37
  if (tokens.error) {
51
- const error = createError({
52
- statusCode: 401,
53
- message: `XSUAA login failed: ${tokens.error?.data?.error_description || "Unknown error"}`,
54
- data: tokens
55
- });
56
- if (!onError) throw error;
57
- return onError(event, error);
38
+ return handleAccessTokenErrorResponse(event, "auth0", tokens, onError);
58
39
  }
59
40
  const tokenType = tokens.token_type;
60
41
  const accessToken = tokens.access_token;
@@ -1,12 +1,7 @@
1
- import {
2
- eventHandler,
3
- createError,
4
- getQuery,
5
- getRequestURL,
6
- sendRedirect
7
- } from "h3";
8
- import { withQuery, parseURL, stringifyParsedURL } from "ufo";
1
+ import { eventHandler, getQuery, sendRedirect } from "h3";
2
+ import { withQuery } from "ufo";
9
3
  import { defu } from "defu";
4
+ import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken } from "../utils.js";
10
5
  import { useRuntimeConfig } from "#imports";
11
6
  export function oauthYandexEventHandler({
12
7
  config,
@@ -19,17 +14,12 @@ export function oauthYandexEventHandler({
19
14
  tokenURL: "https://oauth.yandex.ru/token",
20
15
  userURL: "https://login.yandex.ru/info"
21
16
  });
22
- const { code } = getQuery(event);
17
+ const query = getQuery(event);
23
18
  if (!config.clientId || !config.clientSecret) {
24
- const error = createError({
25
- statusCode: 500,
26
- message: "Missing NUXT_OAUTH_YANDEX_CLIENT_ID or NUXT_OAUTH_YANDEX_CLIENT_SECRET env variables."
27
- });
28
- if (!onError) throw error;
29
- return onError(event, error);
19
+ return handleMissingConfiguration(event, "yandex", ["clientId", "clientSecret"], onError);
30
20
  }
31
- const redirectURL = config.redirectURL || getRequestURL(event).href;
32
- if (!code) {
21
+ const redirectURL = config.redirectURL || getOAuthRedirectURL(event);
22
+ if (!query.code) {
33
23
  config.scope = config.scope || [];
34
24
  if (config.emailRequired && !config.scope.includes("login:email")) {
35
25
  config.scope.push("login:email");
@@ -44,29 +34,17 @@ export function oauthYandexEventHandler({
44
34
  })
45
35
  );
46
36
  }
47
- const tokens = await $fetch(config.tokenURL, {
48
- method: "POST",
49
- headers: {
50
- "Content-Type": "application/x-www-form-urlencoded"
51
- },
52
- body: new URLSearchParams({
37
+ const tokens = await requestAccessToken(config.tokenURL, {
38
+ body: {
39
+ grant_type: "authorization_code",
40
+ code: query.code,
53
41
  client_id: config.clientId,
54
42
  client_secret: config.clientSecret,
55
- grant_type: "authorization_code",
56
- redirect_uri: stringifyParsedURL(parseURL(redirectURL)),
57
- code
58
- }).toString()
59
- }).catch((error) => {
60
- return { error };
43
+ redirect_uri: redirectURL
44
+ }
61
45
  });
62
46
  if (tokens.error) {
63
- const error = createError({
64
- statusCode: 401,
65
- message: `Yandex login failed: ${tokens.error?.data?.error_description || "Unknown error"}`,
66
- data: tokens
67
- });
68
- if (!onError) throw error;
69
- return onError(event, error);
47
+ return handleAccessTokenErrorResponse(event, "yandex", tokens, onError);
70
48
  }
71
49
  const accessToken = tokens.access_token;
72
50
  const user = await $fetch(config.userURL, {
@@ -0,0 +1,36 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { OAuthProvider, OnError } from '#auth-utils';
3
+ export declare function getOAuthRedirectURL(event: H3Event): string;
4
+ /**
5
+ * Request an access token body.
6
+ *
7
+ * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
8
+ */
9
+ export interface RequestAccessTokenBody {
10
+ grant_type: 'authorization_code';
11
+ code: string;
12
+ redirect_uri: string;
13
+ client_id: string;
14
+ client_secret?: string;
15
+ }
16
+ interface RequestAccessTokenOptions {
17
+ body?: RequestAccessTokenBody;
18
+ params?: Record<string, string | undefined>;
19
+ headers?: Record<string, string>;
20
+ }
21
+ /**
22
+ * Request an access token from the OAuth provider.
23
+ *
24
+ * When an error occurs, only the error data is returned.
25
+ *
26
+ * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
27
+ */
28
+ export declare function requestAccessToken(url: string, options: RequestAccessTokenOptions): Promise<any>;
29
+ /**
30
+ * Handle OAuth access token error response
31
+ *
32
+ * @see https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
33
+ */
34
+ export declare function handleAccessTokenErrorResponse(event: H3Event, oauthProvider: OAuthProvider, oauthError: any, onError?: OnError): void | Promise<void>;
35
+ export declare function handleMissingConfiguration(event: H3Event, provider: OAuthProvider, missingKeys: string[], onError?: OnError): void | Promise<void>;
36
+ export {};
@@ -0,0 +1,46 @@
1
+ import { getRequestURL } from "h3";
2
+ import { FetchError } from "ofetch";
3
+ import { snakeCase, upperFirst } from "scule";
4
+ import { createError } from "#imports";
5
+ export function getOAuthRedirectURL(event) {
6
+ const requestURL = getRequestURL(event);
7
+ return `${requestURL.protocol}//${requestURL.host}${requestURL.pathname}`;
8
+ }
9
+ export async function requestAccessToken(url, options) {
10
+ const headers = {
11
+ "Content-Type": "application/x-www-form-urlencoded",
12
+ ...options.headers
13
+ };
14
+ const body = headers["Content-Type"] === "application/x-www-form-urlencoded" ? new URLSearchParams(
15
+ options.body || options.params || {}
16
+ ).toString() : options.body;
17
+ return $fetch(url, {
18
+ method: "POST",
19
+ headers,
20
+ body
21
+ }).catch((error) => {
22
+ if (error instanceof FetchError && error.status === 401) {
23
+ return error.data;
24
+ }
25
+ throw error;
26
+ });
27
+ }
28
+ export function handleAccessTokenErrorResponse(event, oauthProvider, oauthError, onError) {
29
+ const message = `${upperFirst(oauthProvider)} login failed: ${oauthError.error_description || oauthError.error || "Unknown error"}`;
30
+ const error = createError({
31
+ statusCode: 401,
32
+ message,
33
+ data: oauthError
34
+ });
35
+ if (!onError) throw error;
36
+ return onError(event, error);
37
+ }
38
+ export function handleMissingConfiguration(event, provider, missingKeys, onError) {
39
+ const environmentVariables = missingKeys.map((key) => `NUXT_OAUTH_${provider.toUpperCase()}_${snakeCase(key).toUpperCase()}`);
40
+ const error = createError({
41
+ statusCode: 500,
42
+ message: `Missing ${environmentVariables.join(" or ")} env ${missingKeys.length > 1 ? "variables" : "variable"}.`
43
+ });
44
+ if (!onError) throw error;
45
+ return onError(event, error);
46
+ }
@@ -1,2 +1,2 @@
1
1
  export type { User, UserSession, UserSessionRequired, UserSessionComposable } from './session.js';
2
- export type { OAuthConfig } from './oauth-config.js';
2
+ export type { OAuthConfig, OAuthProvider, OnError } from './oauth-config.js';
@@ -1,9 +1,11 @@
1
1
  import type { H3Event, H3Error } from 'h3';
2
+ export type OAuthProvider = 'auth0' | 'battledotnet' | 'cognito' | 'discord' | 'facebook' | 'github' | 'google' | 'keycloak' | 'linkedin' | 'microsoft' | 'paypal' | 'spotify' | 'steam' | 'tiktok' | 'twitch' | 'x' | 'xsuaa' | 'yandex' | (string & {});
3
+ export type OnError = (event: H3Event, error: H3Error) => Promise<void> | void;
2
4
  export interface OAuthConfig<TConfig, TUser = any, TTokens = any> {
3
5
  config?: TConfig;
4
6
  onSuccess: (event: H3Event, result: {
5
7
  user: TUser;
6
8
  tokens: TTokens;
7
9
  }) => Promise<void> | void;
8
- onError?: (event: H3Event, error: H3Error) => Promise<void> | void;
10
+ onError?: OnError;
9
11
  }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "nuxt-auth-utils",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "Minimalist Auth module for Nuxt with SSR",
5
5
  "repository": "Atinux/nuxt-auth-utils",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
- "packageManager": "pnpm@9.7.0",
8
+ "packageManager": "pnpm@9.9.0",
9
9
  "exports": {
10
10
  ".": {
11
11
  "types": "./dist/types.d.ts",
@@ -32,28 +32,29 @@
32
32
  "test:watch": "vitest watch"
33
33
  },
34
34
  "dependencies": {
35
- "@nuxt/kit": "^3.12.4",
35
+ "@nuxt/kit": "^3.13.1",
36
36
  "defu": "^6.1.4",
37
37
  "hookable": "^5.5.3",
38
38
  "ofetch": "^1.3.4",
39
39
  "ohash": "^1.1.3",
40
40
  "pathe": "^1.1.2",
41
+ "scule": "^1.3.0",
41
42
  "uncrypto": "^0.1.3"
42
43
  },
43
44
  "devDependencies": {
44
- "@iconify-json/simple-icons": "^1.1.113",
45
+ "@iconify-json/simple-icons": "^1.2.1",
45
46
  "@nuxt/devtools": "latest",
46
- "@nuxt/eslint-config": "^0.5.0",
47
- "@nuxt/module-builder": "^0.8.1",
48
- "@nuxt/schema": "^3.12.4",
49
- "@nuxt/test-utils": "^3.14.0",
47
+ "@nuxt/eslint-config": "^0.5.5",
48
+ "@nuxt/module-builder": "^0.8.3",
49
+ "@nuxt/schema": "^3.13.1",
50
+ "@nuxt/test-utils": "^3.14.1",
50
51
  "@nuxt/ui": "^2.18.4",
51
52
  "@nuxt/ui-pro": "^1.4.1",
52
53
  "changelogen": "^0.5.5",
53
- "eslint": "^9.9.0",
54
- "nuxt": "^3.12.4",
54
+ "eslint": "^9.9.1",
55
+ "nuxt": "^3.13.1",
55
56
  "typescript": "^5.5.4",
56
57
  "vitest": "^2.0.5",
57
- "vue-tsc": "^2.0.29"
58
+ "vue-tsc": "^2.1.4"
58
59
  }
59
60
  }