@witchcraft/nuxt-auth 0.4.1 → 0.5.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.
Files changed (37) hide show
  1. package/dist/module.d.mts +9 -4
  2. package/dist/module.json +2 -2
  3. package/dist/module.mjs +1 -1
  4. package/dist/runtime/components/ExternalCallback.d.vue.ts +2 -6
  5. package/dist/runtime/components/ExternalCallback.vue +2 -37
  6. package/dist/runtime/components/ExternalCallback.vue.d.ts +2 -6
  7. package/dist/runtime/components/ExternalCode.vue +3 -20
  8. package/dist/runtime/components/LoginProviderButtons.client.d.vue.ts +17 -14
  9. package/dist/runtime/components/LoginProviderButtons.client.vue +26 -56
  10. package/dist/runtime/components/LoginProviderButtons.client.vue.d.ts +17 -14
  11. package/dist/runtime/components/Mocker.vue +2 -18
  12. package/dist/runtime/components/UserRegistration.d.vue.ts +15 -39
  13. package/dist/runtime/components/UserRegistration.vue +40 -144
  14. package/dist/runtime/components/UserRegistration.vue.d.ts +15 -39
  15. package/dist/runtime/composables/useAuthExternalCallback.d.ts +17 -0
  16. package/dist/runtime/composables/useAuthExternalCallback.js +47 -0
  17. package/dist/runtime/composables/useAuthExternalCode.d.ts +5 -0
  18. package/dist/runtime/composables/useAuthExternalCode.js +29 -0
  19. package/dist/runtime/composables/useAuthMocker.d.ts +7 -0
  20. package/dist/runtime/composables/useAuthMocker.js +33 -0
  21. package/dist/runtime/composables/useAuthUserRegistration.d.ts +43 -0
  22. package/dist/runtime/composables/useAuthUserRegistration.js +84 -0
  23. package/dist/runtime/core/providers/github.d.ts +1 -6
  24. package/dist/runtime/core/providers/github.js +1 -6
  25. package/dist/runtime/core/providers/google.d.ts +1 -6
  26. package/dist/runtime/core/providers/google.js +1 -6
  27. package/dist/runtime/server/helpers/signJwt.d.ts +1 -3
  28. package/dist/runtime/server/utils/Auth.d.ts +5 -4
  29. package/dist/runtime/server/utils/Auth.js +21 -6
  30. package/dist/runtime/server/utils/SessionManager.d.ts +3 -3
  31. package/dist/runtime/server/utils/SessionManager.js +6 -5
  32. package/dist/runtime/server/utils/createAuthHandler.d.ts +2 -2
  33. package/dist/runtime/server/utils/createAuthMiddleware.js +2 -2
  34. package/dist/runtime/types.d.ts +1 -7
  35. package/dist/runtime/utils/getAuthApiRoute.d.ts +6 -3
  36. package/dist/types.d.mts +3 -2
  37. package/package.json +7 -4
@@ -1,44 +1,20 @@
1
- import z from "zod";
2
- import { type Ref } from "#imports";
3
- type __VLS_Props = {
4
- debounce?: number;
5
- /** Can throw to indicate the username is invalid (before a request to properly check it is even made. The default throws if the default username schema isn't met. */
6
- getValidUsernameRoute?: (username: string) => string;
7
- onSubmitRegistration?: (event: Event, username: string, error: Ref<string>, redirectUrl: string, deeplink?: string) => void;
8
- id?: string;
9
- /**
10
- * When a validator is provided, if it errors, the server is not queried so as to avoid invalid queries. Any errors it produces are also shown.
11
- *
12
- * @default defaultZodUsernameSchema
13
- */
14
- usernameSchema?: z.ZodType<string, any, any>;
15
- };
16
- declare var __VLS_12: {}, __VLS_19: {}, __VLS_26: {}, __VLS_33: {}, __VLS_41: {
17
- error: import("nuxt/app").NuxtError<unknown> | undefined;
18
- registrationError: string;
19
- localUsernameError: string | undefined;
20
- id: string;
21
- };
22
- type __VLS_Slots = {} & {
23
- 'username-icon-loading'?: (props: typeof __VLS_12) => any;
24
- } & {
25
- 'username-icon-valid'?: (props: typeof __VLS_19) => any;
26
- } & {
27
- 'username-icon-invalid'?: (props: typeof __VLS_26) => any;
28
- } & {
29
- default?: (props: typeof __VLS_33) => any;
30
- } & {
31
- error?: (props: typeof __VLS_41) => any;
32
- };
33
- declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {
34
- debounce: number;
35
- getValidUsernameRoute: (username: string) => string;
36
- onSubmitRegistration: (event: Event, username: string, error: Ref<string>, redirectUrl: string, deeplink?: string) => void;
37
- usernameSchema: z.ZodType<string, any, any>;
38
- }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
39
- declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ /**
3
+ * @deprecated This component is deprecated and will be removed in a future version.
4
+ */
40
5
  declare const _default: typeof __VLS_export;
41
6
  export default _default;
7
+ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
8
+ debounce?: number;
9
+ usernameSchema?: StandardSchemaV1<string, string>;
10
+ id?: string;
11
+ }, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{
12
+ debounce?: number;
13
+ usernameSchema?: StandardSchemaV1<string, string>;
14
+ id?: string;
15
+ }> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>, {
16
+ default?: (props: {}) => any;
17
+ }>;
42
18
  type __VLS_WithSlots<T, S> = T & {
43
19
  new (): {
44
20
  $slots: S;
@@ -0,0 +1,17 @@
1
+ import type { Ref } from "vue";
2
+ export type ExternalCallbackOptions = {
3
+ /** Called with the access token to create a session. */
4
+ saveSession: (accessToken: string) => Promise<void>;
5
+ /** Path to navigate to on success. Defaults to `postRegisteredLogin` from runtime config. */
6
+ successPath?: string;
7
+ /** Path to navigate to on cancel. Defaults to `login` from runtime config. */
8
+ cancelPath?: string;
9
+ };
10
+ export declare function useAuthExternalCallback(opts: ExternalCallbackOptions): {
11
+ authUri: string | undefined;
12
+ initialAccessToken: string | undefined;
13
+ manualAccessToken: Ref<string, string>;
14
+ error: Ref<string | undefined, string | undefined>;
15
+ authorize: (accessToken?: string, isInitial?: boolean) => Promise<void>;
16
+ cancel: () => Promise<void>;
17
+ };
@@ -0,0 +1,47 @@
1
+ import { ref } from "vue";
2
+ import z from "zod";
3
+ import {
4
+ navigateTo,
5
+ useRoute,
6
+ useRuntimeConfig
7
+ } from "#app";
8
+ import { zExternalCallbackPageQuery } from "../types.js";
9
+ export function useAuthExternalCallback(opts) {
10
+ const rc = useRuntimeConfig();
11
+ const query = useRoute().query;
12
+ const parsedQuery = zExternalCallbackPageQuery.safeParse(query);
13
+ if (parsedQuery.error) throw new Error(z.prettifyError(parsedQuery.error));
14
+ const initialAccessToken = "accessToken" in parsedQuery.data ? parsedQuery.data.accessToken : void 0;
15
+ const authUri = "authUri" in parsedQuery.data ? parsedQuery.data.authUri : void 0;
16
+ if (initialAccessToken) {
17
+ void authorize(initialAccessToken, true);
18
+ }
19
+ const manualAccessToken = ref("");
20
+ const error = ref(void 0);
21
+ async function authorize(accessToken, isInitial = false) {
22
+ if (!accessToken || accessToken.length === 0) {
23
+ if (!isInitial) {
24
+ error.value = "No code provided.";
25
+ }
26
+ return;
27
+ }
28
+ const res = await opts.saveSession(accessToken).catch((err) => {
29
+ error.value = err.message;
30
+ return err;
31
+ });
32
+ if (!(res instanceof Error)) {
33
+ await navigateTo(opts.successPath ?? rc.public.auth.authRoutes.postRegisteredLogin);
34
+ }
35
+ }
36
+ async function cancel() {
37
+ await navigateTo(opts.cancelPath ?? rc.public.auth.authRoutes.login);
38
+ }
39
+ return {
40
+ authUri,
41
+ initialAccessToken,
42
+ manualAccessToken,
43
+ error,
44
+ authorize,
45
+ cancel
46
+ };
47
+ }
@@ -0,0 +1,5 @@
1
+ export declare function useAuthExternalCode(): {
2
+ accessToken: string;
3
+ deepLinkUrl: string;
4
+ copyToken: () => void;
5
+ };
@@ -0,0 +1,29 @@
1
+ import { copyToClipboard } from "@alanscodelog/utils/copyToClipboard";
2
+ import { unreachable } from "@alanscodelog/utils/unreachable";
3
+ import { onMounted } from "vue";
4
+ import {
5
+ navigateTo,
6
+ useRoute
7
+ } from "#app";
8
+ import { zUriComponentCodec } from "../types.js";
9
+ export function useAuthExternalCode() {
10
+ const query = useRoute().query;
11
+ const accessToken = query.accessToken;
12
+ if (typeof accessToken !== "string") {
13
+ unreachable("No session_token.");
14
+ }
15
+ const deepLinkUrl = zUriComponentCodec.parse(query.deeplinkUri);
16
+ function copyToken() {
17
+ copyToClipboard(accessToken);
18
+ }
19
+ onMounted(() => {
20
+ if (accessToken) {
21
+ void navigateTo(deepLinkUrl, { external: true });
22
+ }
23
+ });
24
+ return {
25
+ accessToken,
26
+ deepLinkUrl,
27
+ copyToken
28
+ };
29
+ }
@@ -0,0 +1,7 @@
1
+ import type { Ref } from "vue";
2
+ export declare function useAuthMocker(): {
3
+ provider: string;
4
+ username: Ref<string, string>;
5
+ bypassRegistration: Ref<boolean, boolean>;
6
+ submit: () => Promise<void>;
7
+ };
@@ -0,0 +1,33 @@
1
+ import { ref } from "vue";
2
+ import {
3
+ navigateTo,
4
+ useRoute,
5
+ useRuntimeConfig
6
+ } from "#imports";
7
+ import { getAuthApiRoute } from "../utils/getAuthApiRoute.js";
8
+ export function useAuthMocker() {
9
+ const route = useRoute();
10
+ const username = ref("");
11
+ const bypassRegistration = ref(false);
12
+ const provider = route.query.provider;
13
+ if (!provider || typeof provider !== "string") {
14
+ throw new Error("Missing provider query param.");
15
+ }
16
+ async function submit() {
17
+ const query = route.query;
18
+ delete query.provider;
19
+ const callbackRoute = getAuthApiRoute(useRuntimeConfig().public, "callback", { provider }, {
20
+ devBypass: true,
21
+ username: username.value,
22
+ devBypassRegistration: bypassRegistration.value,
23
+ ...query
24
+ });
25
+ await navigateTo(callbackRoute, { external: true });
26
+ }
27
+ return {
28
+ provider,
29
+ username,
30
+ bypassRegistration,
31
+ submit
32
+ };
33
+ }
@@ -0,0 +1,43 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { NitroFetchOptions, NitroFetchRequest } from "nitropack";
3
+ /**
4
+ * Wraps all the async username validation and registration logic.
5
+ *
6
+ * Uses {@link useAsyncValidation} from `@witchcraft/nuxt-utils` under the hood.
7
+ *
8
+ * Notes:
9
+ * - Remember to gate the button with `v-if` canSubmit.
10
+ * - If wrapping handleSubmit, also remember to check `canSubmit` first. Prefer using modifyFetch if you need to add something to the request.
11
+ * - inputValid is only a visual indicator and is valid for empty inputs and when the server is validating a request. Username might still be invalid.
12
+ */
13
+ export declare function useAuthUserRegistration({ modifyFetch, debounce, statusTextMap, usernameSchema }?: {
14
+ modifyFetch?: (request: {
15
+ cache: "no-store";
16
+ method: "post";
17
+ body: {
18
+ username: string;
19
+ };
20
+ }) => NitroFetchOptions<NitroFetchRequest, any>;
21
+ debounce?: number;
22
+ usernameSchema?: StandardSchemaV1<string, string>;
23
+ statusTextMap?: {
24
+ loading: string;
25
+ valid: string;
26
+ invalid: string;
27
+ };
28
+ }): {
29
+ username: import("vue").Ref<string, string>;
30
+ errors: import("vue").ComputedRef<string[]>;
31
+ status: import("vue").ComputedRef<"loading" | "valid" | "invalid" | undefined>;
32
+ statusText: import("vue").ComputedRef<string>;
33
+ canSubmit: import("vue").ComputedRef<boolean>;
34
+ handleSubmit: (_event: Event) => Promise<void>;
35
+ inputValid: import("vue").ComputedRef<boolean>;
36
+ isDebouncing: import("vue").ComputedRef<boolean>;
37
+ _internal: {
38
+ requestStatus: import("vue").Ref<import("nuxt/app").AsyncDataRequestStatus, import("nuxt/app").AsyncDataRequestStatus>;
39
+ serverError: import("vue").Ref<import("nuxt/app").NuxtError<unknown> | undefined, import("nuxt/app").NuxtError<unknown> | undefined>;
40
+ isLoading: import("vue").ComputedRef<boolean>;
41
+ isServerValid: import("vue").Ref<boolean, boolean>;
42
+ };
43
+ };
@@ -0,0 +1,84 @@
1
+ import { refDebounced } from "@vueuse/core";
2
+ import { useAsyncValidation } from "@witchcraft/nuxt-utils/composables/useAsyncValidation";
3
+ import { computed, ref } from "vue";
4
+ import { navigateTo, useRoute, useRuntimeConfig } from "#app";
5
+ import { useAuth } from "../composables/useAuth.js";
6
+ import { AUTH_ERROR, defaultZodUsernameSchema } from "../types.js";
7
+ import { getAuthApiRoute } from "../utils/getAuthApiRoute.js";
8
+ export function useAuthUserRegistration({
9
+ modifyFetch,
10
+ debounce = 1e3,
11
+ statusTextMap = {
12
+ loading: "Checking availability...",
13
+ valid: "Username available.",
14
+ invalid: "Username unavailable."
15
+ },
16
+ usernameSchema = defaultZodUsernameSchema
17
+ } = {}) {
18
+ const config = useRuntimeConfig().public;
19
+ const query = useRoute().query;
20
+ const username = ref("");
21
+ const debouncedUsername = refDebounced(username, debounce);
22
+ const submitErrors = ref([]);
23
+ const {
24
+ errors,
25
+ status,
26
+ statusText,
27
+ canSubmit,
28
+ inputValid,
29
+ _internal
30
+ } = useAsyncValidation(
31
+ debouncedUsername,
32
+ "auth:username:valid",
33
+ getAuthApiRoute(
34
+ config,
35
+ "usernameValid"
36
+ ),
37
+ submitErrors,
38
+ {
39
+ debounce: 0,
40
+ // we already debounced
41
+ statusTextMap,
42
+ schema: usernameSchema,
43
+ getFetchOptions: () => ({
44
+ query: {
45
+ username: debouncedUsername.value
46
+ }
47
+ })
48
+ }
49
+ );
50
+ const deeplink = typeof query.deeplink === "string" ? query.deeplink : void 0;
51
+ const redirectUrl = deeplink ? config.auth.authRoutes.externalCode : config.auth.authRoutes.register;
52
+ if (!redirectUrl) throw new Error("No externalCode or register route defined.");
53
+ async function handleSubmit(_event) {
54
+ if (!canSubmit.value) return;
55
+ let request = {
56
+ cache: "no-store",
57
+ method: "post",
58
+ body: { username: username.value }
59
+ };
60
+ if (modifyFetch) request = modifyFetch(request);
61
+ const res = await $fetch(`${getAuthApiRoute(config, "register")}${deeplink ? `?deeplink=${deeplink}` : ""}`, request).catch(async (e) => {
62
+ submitErrors.value = [`Registration Error: ${e.data.message}`];
63
+ if (e?.data?.code === AUTH_ERROR.USER_ALREADY_REGISTERED) {
64
+ useAuth().setFetchUserOnNavigation(true);
65
+ await navigateTo(redirectUrl, { external: true });
66
+ }
67
+ });
68
+ if (typeof res === "object" && res.redirectUrl) {
69
+ await navigateTo(res.redirectUrl, { external: true });
70
+ }
71
+ }
72
+ const isDebouncing = computed(() => debouncedUsername.value !== username.value);
73
+ return {
74
+ username,
75
+ errors,
76
+ status,
77
+ statusText,
78
+ canSubmit,
79
+ handleSubmit,
80
+ inputValid,
81
+ isDebouncing,
82
+ _internal
83
+ };
84
+ }
@@ -80,10 +80,5 @@ export default class GithubProvider implements ProviderHandler<"oauth2", "github
80
80
  export declare const githubProviderStyle: {
81
81
  name: string;
82
82
  logo: import("vue").FunctionalComponent<import("vue").SVGAttributes, {}, any, {}>;
83
- style: {
84
- bg: string;
85
- bgDark: string;
86
- text: string;
87
- textDark: string;
88
- };
83
+ class: string;
89
84
  };
@@ -51,10 +51,5 @@ export default class GithubProvider {
51
51
  export const githubProviderStyle = {
52
52
  name: "Github",
53
53
  logo: GithubLogo,
54
- style: {
55
- bg: "#fff",
56
- bgDark: "#000",
57
- text: "#000",
58
- textDark: "#fff"
59
- }
54
+ class: "bg-white text-black dark:bg-black dark:text-white"
60
55
  };
@@ -61,10 +61,5 @@ export default class GoogleProvider implements ProviderHandler<"oauth2_pcke", "g
61
61
  export declare const googleProviderStyle: {
62
62
  name: string;
63
63
  logo: import("vue").FunctionalComponent<import("vue").SVGAttributes, {}, any, {}>;
64
- style: {
65
- bg: string;
66
- bgDark: string;
67
- text: string;
68
- textDark: string;
69
- };
64
+ class: string;
70
65
  };
@@ -45,10 +45,5 @@ export default class GoogleProvider {
45
45
  export const googleProviderStyle = {
46
46
  name: "Google",
47
47
  logo: GoogleLogo,
48
- style: {
49
- bg: "#fff",
50
- bgDark: "#000",
51
- text: "#000",
52
- textDark: "#fff"
53
- }
48
+ class: "bg-white text-black dark:bg-black dark:text-white"
54
49
  };
@@ -1,5 +1,3 @@
1
1
  import type { SignOptions } from "jsonwebtoken";
2
2
  /** Promisified version of jsonwebtoken.sign. */
3
- export declare function signJwt(payload: any, secret: string, opts?: Partial<SignOptions | {
4
- algorithm: "none";
5
- }>): Promise<string>;
3
+ export declare function signJwt(payload: any, secret: string, opts?: Partial<SignOptions>): Promise<string>;
@@ -5,14 +5,14 @@ import type { PgDatabase } from "drizzle-orm/pg-core";
5
5
  import type { PgliteDatabase } from "drizzle-orm/pglite";
6
6
  import type { EventHandler, H3Event, Router } from "h3";
7
7
  import type { JwtPayload } from "jsonwebtoken";
8
- import type { RuntimeConfig } from "nuxt/schema";
9
8
  import { z } from "zod";
10
9
  import type { AuthAccountsTable, UserTable } from "./createAuthSchema.js";
11
10
  import type { SessionManager } from "./SessionManager.js";
11
+ import type { ModuleRuntimeConfig } from "../../../module.js";
12
12
  import type { AuthOptions, AuthSession, AuthUser, BaseProviderAccountInfo, ProviderHandler, ProviderNames } from "../../types";
13
13
  export declare const zState: z.ZodObject<{
14
14
  oauthState: z.ZodString;
15
- additionalState: z.ZodAny;
15
+ additionalState: z.ZodOptional<z.ZodAny>;
16
16
  deeplink: z.ZodOptional<z.ZodString>;
17
17
  }, z.core.$strip>;
18
18
  type State = z.infer<typeof zState>;
@@ -32,6 +32,7 @@ export declare class Auth {
32
32
  /** The deeplink query param, if any. */
33
33
  deeplink?: string) => Promise<boolean>;
34
34
  eventHandler: EventHandler;
35
+ /** Careful with this, parse any input carefully before returning it. */
35
36
  getAdditionalState?: AuthOptions["additionalState"];
36
37
  modifyCallbackRedirect?: AuthOptions["modifyCallbackRedirect"];
37
38
  devBypassAuth?: AuthOptions["devBypassAuth"];
@@ -44,9 +45,9 @@ export declare class Auth {
44
45
  sessionManager: SessionManager;
45
46
  router: Router;
46
47
  logger: BaseLogger;
47
- rc: RuntimeConfig;
48
+ rc: ModuleRuntimeConfig;
48
49
  providerCookieOpts: CookieSerializeOptions;
49
- constructor(runtimeConfig: RuntimeConfig, db: Auth["db"], usersTable: Auth["usersTable"], authAccountsTable: Auth["authAccountsTable"], sessionManager: Auth["sessionManager"], router: Auth["router"], opts: AuthOptions, env: Record<`auth${string}${"ClientId" | "ClientSecret"}` | string, string>, logger: BaseLogger);
50
+ constructor(runtimeConfig: ModuleRuntimeConfig, db: Auth["db"], usersTable: Auth["usersTable"], authAccountsTable: Auth["authAccountsTable"], sessionManager: Auth["sessionManager"], router: Auth["router"], opts: AuthOptions, env: Record<`auth${string}${"ClientId" | "ClientSecret"}` | string, string>, logger: BaseLogger);
50
51
  assertValidProvider(provider?: string): asserts provider is ProviderNames;
51
52
  getProvider(provider: ProviderNames): ProviderHandler<"oauth2"> | ProviderHandler<"oauth2_pcke">;
52
53
  static assertAuthorizedUser(user: AuthUser | undefined | null): asserts user is AuthUser;
@@ -24,7 +24,7 @@ import { signJwt } from "../helpers/signJwt.js";
24
24
  import { verifyJwt as jwtVerify } from "../helpers/verifyJwt.js";
25
25
  export const zState = z.object({
26
26
  oauthState: z.string(),
27
- additionalState: z.any(),
27
+ additionalState: z.any().optional(),
28
28
  deeplink: z.string().optional()
29
29
  });
30
30
  export const oauth2CallbackQuery = z.object({
@@ -39,6 +39,7 @@ export class Auth {
39
39
  deeplinkSchemes;
40
40
  onRegister;
41
41
  eventHandler;
42
+ /** Careful with this, parse any input carefully before returning it. */
42
43
  getAdditionalState;
43
44
  modifyCallbackRedirect;
44
45
  devBypassAuth;
@@ -66,7 +67,7 @@ export class Auth {
66
67
  providerCookieOpts;
67
68
  constructor(runtimeConfig, db, usersTable, authAccountsTable, sessionManager, router, opts, env, logger) {
68
69
  this.rc = runtimeConfig;
69
- if (!import.meta.dev && !(this.rc.authSecret || this.rc.authSecret.length === 0)) {
70
+ if (!import.meta.dev && (!this.rc.authSecret || this.rc.authSecret.length === 0)) {
70
71
  throw new Error("FATAL: Missing or empty runtimeConfig.authSecret (i.e. should be set via NUXT_AUTH_SECRET) in production.");
71
72
  }
72
73
  this.providerCookieOpts = {
@@ -161,7 +162,15 @@ export class Auth {
161
162
  return user ?? false;
162
163
  }));
163
164
  router.get(apiRoutes.externalExchange, defineEventHandler(async (event) => {
164
- const accessToken = getRequestHeaders(event).authorization?.slice("Bearer ".length);
165
+ const authorization = getRequestHeaders(event).authorization;
166
+ if (!authorization || !/^Bearer\s+\S+$/.test(authorization)) {
167
+ throw createError({
168
+ status: 400,
169
+ statusMessage: "Invalid Authorization header. Expected 'Bearer <token>'.",
170
+ data: { code: AUTH_ERROR.INVALID_ACCESS_TOKEN }
171
+ });
172
+ }
173
+ const accessToken = authorization.slice("Bearer ".length);
165
174
  const decoded = await this.verifyAccessToken(accessToken).catch((err) => createError({
166
175
  status: 400,
167
176
  statusMessage: err.message,
@@ -466,7 +475,7 @@ export class Auth {
466
475
  });
467
476
  throw createError({
468
477
  status: 400,
469
- statusMessage: `Invalid provider: ${provider}, known: ${Object.keys(this.providers).join(", ")}`,
478
+ statusMessage: `Invalid provider: ${provider}`,
470
479
  data: { code: AUTH_ERROR.UNKNOWN_PROVIDER }
471
480
  });
472
481
  }
@@ -639,7 +648,11 @@ export class Auth {
639
648
  return `${scheme}${this.rc.public.auth.authRoutes.deeplink}`;
640
649
  }
641
650
  async verifyAccessToken(accessToken) {
642
- return jwtVerify(accessToken, this.rc.authSecret, {}).catch((err) => {
651
+ return jwtVerify(
652
+ accessToken,
653
+ this.rc.authSecret,
654
+ { algorithms: ["HS256"] }
655
+ ).catch((err) => {
643
656
  throw createError({
644
657
  status: 400,
645
658
  statusMessage: err.message,
@@ -650,7 +663,9 @@ export class Auth {
650
663
  async createAccessToken(userId, payload = {}) {
651
664
  return signJwt({ ...payload, userId }, this.rc.authSecret, {
652
665
  // ms is different package version so type doesn't match
653
- expiresIn: this.externalAccessTokenExpiresIn
666
+ expiresIn: this.externalAccessTokenExpiresIn,
667
+ // this is the default but just to be explicit
668
+ algorithm: "HS256"
654
669
  });
655
670
  }
656
671
  }
@@ -1,8 +1,8 @@
1
1
  import type { DeepPartial } from "@alanscodelog/utils";
2
2
  import type { PgDatabase } from "drizzle-orm/pg-core";
3
3
  import type { PgliteDatabase } from "drizzle-orm/pglite";
4
- import type { RuntimeConfig } from "nuxt/schema";
5
4
  import type { AuthSessionsTable, AuthUsersTable } from "./createAuthSchema.js";
5
+ import type { ModuleRuntimeConfig } from "../../../module.js";
6
6
  import type { AuthSession, SessionCookie, SessionCookieOptions, SessionValidationResult } from "../../types.js";
7
7
  export declare const defaultSessionCookieName = "authSession";
8
8
  export declare class SessionManager {
@@ -16,10 +16,10 @@ export declare class SessionManager {
16
16
  db: PgDatabase<any, any, any> | PgliteDatabase<any>;
17
17
  sessionTable: AuthSessionsTable;
18
18
  userTable: AuthUsersTable;
19
- constructor(rc: RuntimeConfig, db: SessionManager["db"], sessionTable: SessionManager["sessionTable"], userTable: SessionManager["userTable"], options?: DeepPartial<SessionManager["options"]>);
19
+ constructor(rc: ModuleRuntimeConfig, db: SessionManager["db"], sessionTable: SessionManager["sessionTable"], userTable: SessionManager["userTable"], options?: DeepPartial<SessionManager["options"]>);
20
20
  generateSessionToken(): string;
21
21
  createSession<TId = string>(sessionToken: string, userId: TId): Promise<AuthSession>;
22
- createSessionCookie(sessionId: string): SessionCookie;
22
+ createSessionCookie(hashedSessionId: string): SessionCookie;
23
23
  createBlankSessionCookie(): SessionCookie;
24
24
  validateSessionToken(sessionToken: string): Promise<SessionValidationResult>;
25
25
  invalidateSession(sessionId: string): Promise<void>;
@@ -41,10 +41,10 @@ export class SessionManager {
41
41
  await this.db.insert(this.sessionTable).values(session);
42
42
  return session;
43
43
  }
44
- createSessionCookie(sessionId) {
44
+ createSessionCookie(hashedSessionId) {
45
45
  return {
46
46
  name: this.options.sessionCookie.name,
47
- value: sessionId,
47
+ value: hashedSessionId,
48
48
  attributes: {
49
49
  ...this.options.sessionCookie.attributes,
50
50
  maxAge: (/* @__PURE__ */ new Date()).getTime() + this.options.expiresAt
@@ -62,8 +62,8 @@ export class SessionManager {
62
62
  };
63
63
  }
64
64
  async validateSessionToken(sessionToken) {
65
- const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(sessionToken)));
66
- const result = await this.db.select({ user: this.userTable, session: this.sessionTable }).from(this.sessionTable).innerJoin(this.userTable, eq(this.sessionTable.userId, this.userTable.id)).where(eq(this.sessionTable.id, sessionId));
65
+ const hashedSessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(sessionToken)));
66
+ const result = await this.db.select({ user: this.userTable, session: this.sessionTable }).from(this.sessionTable).innerJoin(this.userTable, eq(this.sessionTable.userId, this.userTable.id)).where(eq(this.sessionTable.id, hashedSessionId));
67
67
  if (result.length < 1) {
68
68
  return { session: null, user: null, fresh: false };
69
69
  }
@@ -88,6 +88,7 @@ export class SessionManager {
88
88
  };
89
89
  }
90
90
  async invalidateSession(sessionId) {
91
- await this.db.delete(this.sessionTable).where(eq(this.sessionTable.id, sessionId));
91
+ const hashedSessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(sessionId)));
92
+ await this.db.delete(this.sessionTable).where(eq(this.sessionTable.id, hashedSessionId));
92
93
  }
93
94
  }
@@ -2,8 +2,8 @@ import type { BaseLogger } from "@witchcraft/nuxt-logger/types";
2
2
  import type { PgDatabase } from "drizzle-orm/pg-core";
3
3
  import type { PgliteDatabase } from "drizzle-orm/pglite";
4
4
  import type { EventHandler } from "h3";
5
- import type { RuntimeConfig } from "nuxt/schema";
6
5
  import type { AuthAccountsTable, UserTable } from "./createAuthSchema.js";
7
6
  import type { SessionManager } from "./SessionManager.js";
7
+ import type { ModuleRuntimeConfig } from "../../../module.js";
8
8
  import type { AuthHandlerOptions } from "../../types.js";
9
- export declare function createAuthHandler(rc: RuntimeConfig, db: PgDatabase<any, any, any> | PgliteDatabase<any>, usersTable: UserTable, authAccountsTable: AuthAccountsTable, sessionManager: SessionManager, logger: BaseLogger, opts?: Partial<AuthHandlerOptions>): EventHandler;
9
+ export declare function createAuthHandler(rc: ModuleRuntimeConfig, db: PgDatabase<any, any, any> | PgliteDatabase<any>, usersTable: UserTable, authAccountsTable: AuthAccountsTable, sessionManager: SessionManager, logger: BaseLogger, opts?: Partial<AuthHandlerOptions>): EventHandler;
@@ -14,8 +14,8 @@ export function createAuthMiddleware(sessionManager, logger) {
14
14
  fresh,
15
15
  redact: { sessionToken, session }
16
16
  });
17
- if (fresh) {
18
- const cookie = sessionManager.createSessionCookie(session.id);
17
+ if (fresh && session) {
18
+ const cookie = sessionManager.createSessionCookie(sessionToken);
19
19
  setCookie(event, cookie.name, cookie.value, cookie.attributes);
20
20
  }
21
21
  if (!session) {
@@ -226,15 +226,9 @@ export interface BaseProviderAccountInfo extends AuthAccount, InitialAccountInfo
226
226
  export type ProviderStyle = {
227
227
  name: string;
228
228
  logo: any;
229
- style: {
230
- bg: string;
231
- text: string;
232
- bgDark: string;
233
- textDark: string;
234
- };
229
+ class?: string;
235
230
  };
236
231
  export declare const providerStylesInjectionKey: InjectionKey<Partial<Record<ProviderNames, Partial<ProviderStyle>>>>;
237
- export type FullProviderStyles = Record<"github" | "google", ProviderStyle> & Record<ProviderNames, Partial<ProviderStyle>>;
238
232
  export type UseAuthComposableOptions = {
239
233
  /**
240
234
  * Handle login and logout actions yourself.
@@ -1,3 +1,6 @@
1
- import type { PublicRuntimeConfig } from "@nuxt/schema";
2
- import type { ApiRoutesParams } from "../../module.js";
3
- export declare function getAuthApiRoute<T extends keyof PublicRuntimeConfig["auth"]["authApiRoutes"], TParams extends T extends keyof ApiRoutesParams ? ApiRoutesParams[T] : never>(rc: PublicRuntimeConfig, route: T, params?: TParams, queryParams?: Record<string, any>): string;
1
+ import type { ApiRoutesParams, ModulePublicRuntimeConfig } from "../../module.js";
2
+ export declare function getAuthApiRoute<T extends keyof ModulePublicRuntimeConfig["auth"]["authApiRoutes"], TParams extends T extends keyof ApiRoutesParams ? ApiRoutesParams[T] : never>(rc: {
3
+ auth: {
4
+ authApiRoutes: ModulePublicRuntimeConfig["auth"]["authApiRoutes"];
5
+ };
6
+ }, route: T, params?: TParams, queryParams?: Record<string, any>): string;
package/dist/types.d.mts CHANGED
@@ -1,12 +1,13 @@
1
- import type { ModulePublicRuntimeConfig } from './module.mjs'
1
+ import type { ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'
2
2
 
3
3
  declare module '@nuxt/schema' {
4
+ interface RuntimeConfig extends ModuleRuntimeConfig {}
4
5
  interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
5
6
  }
6
7
 
7
8
  export { default } from './module.mjs'
8
9
 
9
- export { type ModuleOptions, type ModulePublicRuntimeConfig } from './module.mjs'
10
+ export { type ModuleOptions, type ModulePrivateRuntimeConfig, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig } from './module.mjs'
10
11
 
11
12
  export * from '../dist/runtime/types.js'
12
13