@witchcraft/nuxt-auth 0.1.8 → 0.2.0

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 (29) hide show
  1. package/README.md +10 -6
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +2 -2
  4. package/dist/runtime/components/ExternalCallback.d.vue.ts +1 -1
  5. package/dist/runtime/components/ExternalCallback.vue +38 -34
  6. package/dist/runtime/components/ExternalCallback.vue.d.ts +1 -1
  7. package/dist/runtime/components/ExternalCode.vue +3 -6
  8. package/dist/runtime/components/Mocker.vue +1 -1
  9. package/dist/runtime/components/UserRegistration.vue +1 -0
  10. package/dist/runtime/composables/useAuth.d.ts +2 -2
  11. package/dist/runtime/composables/useAuth.js +2 -2
  12. package/dist/runtime/core/providers/github.d.ts +1 -1
  13. package/dist/runtime/core/providers/google.d.ts +1 -1
  14. package/dist/runtime/middleware/authProtected.js +2 -1
  15. package/dist/runtime/server/utils/Auth.d.ts +4 -3
  16. package/dist/runtime/server/utils/Auth.js +30 -29
  17. package/dist/runtime/server/utils/SessionManager.d.ts +4 -3
  18. package/dist/runtime/server/utils/SessionManager.js +4 -4
  19. package/dist/runtime/server/utils/createAuthHandler.d.ts +3 -2
  20. package/dist/runtime/server/utils/createAuthHandler.js +3 -3
  21. package/dist/runtime/server/utils/createAuthMiddleware.d.ts +2 -2
  22. package/dist/runtime/server/utils/createAuthMiddleware.js +5 -5
  23. package/dist/runtime/types.d.ts +41 -7
  24. package/dist/runtime/types.js +15 -0
  25. package/dist/runtime/utils/{createExternalAuthHandler.d.ts → createExternalAuthLoginHandler.d.ts} +3 -3
  26. package/dist/runtime/utils/{createExternalAuthHandler.js → createExternalAuthLoginHandler.js} +6 -5
  27. package/package.json +26 -21
  28. package/dist/runtime/utils/decodeQueryUri.d.ts +0 -2
  29. package/dist/runtime/utils/decodeQueryUri.js +0 -4
package/README.md CHANGED
@@ -187,7 +187,7 @@ In some cases you may want to customize this behavior, such as when calling this
187
187
 
188
188
  This can be customized with the `handleActions` option on the `useAuth` composable.
189
189
 
190
- There is also a `createExternalAuthHandler` helper and related utils, see [External Auth Handlers](#external-auth-handlers).
190
+ There is also a `createExternalAuthLoginHandler` helper and related utils, see [External Auth Handlers](#external-auth-handlers).
191
191
 
192
192
  ### Changing Routes
193
193
 
@@ -411,7 +411,7 @@ definePageMeta({
411
411
 
412
412
  ```
413
413
 
414
- Then in the login page, we can use the `createExternalAuthHandler` to intercept the action of the `LoginProviderButtons` only when the user is on electron.
414
+ Then in the login page, we can use the `createExternalAuthLoginHandler` to intercept the action of the `LoginProviderButtons` only when the user is on electron.
415
415
 
416
416
 
417
417
  ```vue [pages/auth/login.vue]
@@ -425,14 +425,14 @@ import { useRuntimeConfig } from "#app"
425
425
  const rc = useRuntimeConfig()
426
426
 
427
427
  const handleActions: ActionHandler = (action, url) =>
428
- createExternalAuthHandler(
428
+ createExternalAuthLoginHandler(
429
429
  "electron", // for the query param
430
430
  isElectron, // platform check
431
431
  publicServerUrl, // you must define this somehow
432
432
  window?.electron?.api.open,
433
433
  "auth/code", // the default
434
434
  )(action, url)
435
- || createExternalAuthHandler(...) // they can be chained
435
+ || createExternalAuthLoginHandler(...) // they can be chained
436
436
 
437
437
  </script>
438
438
  ```
@@ -453,18 +453,22 @@ You can use the `AuthExternalCallback` component to handle this.
453
453
 
454
454
  const rc = useRuntimeConfig()
455
455
  async function saveSession(token: string) {
456
- // you would need to define an api similar to this in electron's preload script
456
+ // you would need to define an api similar to this in electron's preload script that exchanges the token and saves the returned session token to a cookie on the session
457
457
  // @witchcraft/nuxt-electron provides utilities for helping to create
458
458
  // async functions like these which are normally a pain
459
459
  await window.electron.api.auth.saveSession(
460
460
  rc.public.auth.authRoutes.postRegisteredLogin,
461
461
  token
462
462
  )
463
+ // alternatively exchange it here, then ask electron to save it to a cookie
463
464
  }
464
465
  </script>
465
466
  ```
466
467
 
467
- This query param will be forwarded throughout (see the red area).
468
+ Note that if you allow multiple users (per os user) and you're using one session partition per user, you might be better off exchanging the token client side, then passing the sessionToken + userInfo to electron, relaunching electron with that info as an argument (make sure not to log this arg), and creating the session partition at that point when you have the username + id. This way it's easier to notify the user of any errors.
469
+
470
+
471
+ The query param will be forwarded throughout (see the red area).
468
472
 
469
473
  For the login action, the app will open `/api/auth/login/{provider}?deeplink=electron` which will open the provider page, saving the deeplink query param in the state passed to it.
470
474
 
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "auth",
3
3
  "configKey": "auth",
4
- "version": "0.1.8",
4
+ "version": "0.2.0",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -3,7 +3,7 @@ import { defineNuxtModule, useLogger, createResolver, addComponentsDir, addImpor
3
3
  import { defu } from 'defu';
4
4
 
5
5
  const dependencies = {
6
- "@witchcraft/ui": "^0.3.2",
6
+ "@witchcraft/ui": "^0.3.5",
7
7
  "nuxt-security": "^2.4.0"};
8
8
  const pkg = {
9
9
  dependencies: dependencies};
@@ -109,7 +109,7 @@ const module = defineNuxtModule({
109
109
  "runtime/utils/getAuthApiRoute",
110
110
  "runtime/core/providers/google",
111
111
  "runtime/core/providers/github",
112
- "runtime/utils/createExternalAuthHandler"
112
+ "runtime/utils/createExternalAuthLoginHandler"
113
113
  ]) {
114
114
  nuxt.options.build.transpile.push(resolve(file));
115
115
  }
@@ -1,5 +1,5 @@
1
1
  type __VLS_Props = {
2
- saveSession: (token: string) => Promise<void>;
2
+ saveSession: (accessToken: string) => Promise<void>;
3
3
  successPath?: string;
4
4
  cancelPath?: string;
5
5
  };
@@ -14,26 +14,34 @@
14
14
  {{ authUri }}
15
15
  </NuxtLink>
16
16
  </div>
17
- <WInputDeprecated
18
- placeholder="Paste Code Here"
19
- v-model="accessToken"
20
- @update:model-value="error = void 0"
21
- />
22
- <div
23
- v-if="error"
24
- class="border-2 border-red-500 bg-red-100 dark:bg-red-900 rounded-md p-2"
17
+ <form
18
+ class="flex flex-col gap-4"
19
+ @submit.prevent="authorize(manualAccessToken)"
25
20
  >
26
- {{ error }}
27
- </div>
28
- <WButton
29
- :disabled="!accessToken || accessToken.length === 0"
30
- @click="authorize(accessToken)"
31
- >
32
- Submit
33
- </WButton>
34
- <WButton @click="cancel">
35
- Cancel
36
- </WButton>
21
+ <WInputDeprecated
22
+ placeholder="Paste Code Here"
23
+ v-model="manualAccessToken"
24
+ @update:model-value="error = void 0"
25
+ />
26
+ <div
27
+ v-if="error"
28
+ class="border-2 border-red-500 bg-red-100 dark:bg-red-900 rounded-md p-2"
29
+ >
30
+ {{ error }}
31
+ </div>
32
+ <WButton
33
+ :disabled="!manualAccessToken || manualAccessToken.length === 0"
34
+ type="submit"
35
+ >
36
+ Submit
37
+ </WButton>
38
+ <WButton
39
+ type="button"
40
+ @click="cancel"
41
+ >
42
+ Cancel
43
+ </WButton>
44
+ </form>
37
45
  </template>
38
46
  <template v-else>
39
47
  <div class="text-xl text-center">
@@ -47,14 +55,14 @@
47
55
  </template>
48
56
 
49
57
  <script setup>
50
- import { unreachable } from "@alanscodelog/utils/unreachable";
58
+ import z from "zod";
51
59
  import { useRuntimeConfig } from "#app";
52
60
  import {
53
61
  navigateTo,
54
62
  ref,
55
63
  useRoute
56
64
  } from "#imports";
57
- import { decodeQueryUri } from "../utils/decodeQueryUri.js";
65
+ import { zExternalCallbackPageQuery } from "../types.js";
58
66
  const props = defineProps({
59
67
  saveSession: { type: Function, required: true },
60
68
  successPath: { type: String, required: false },
@@ -62,27 +70,23 @@ const props = defineProps({
62
70
  });
63
71
  const rc = useRuntimeConfig();
64
72
  const query = useRoute().query;
65
- const initialAccessToken = query.access_token;
66
- const authUri = decodeQueryUri(query.authUri);
67
- if (!authUri && typeof initialAccessToken !== "string") {
68
- throw new Error(`access_token parameter is not a string, got query: ${JSON.stringify(query)}`);
69
- }
70
- if (!authUri && !initialAccessToken) {
71
- unreachable("Server should have passed authUri or access_token.");
72
- }
73
- if (typeof initialAccessToken === "string") {
73
+ const parsedQuery = zExternalCallbackPageQuery.safeParse(query);
74
+ if (parsedQuery.error) throw new Error(z.prettifyError(parsedQuery.error));
75
+ const initialAccessToken = "accessToken" in parsedQuery.data ? parsedQuery.data.accessToken : void 0;
76
+ const authUri = "authUri" in parsedQuery.data ? parsedQuery.data.authUri : void 0;
77
+ if (initialAccessToken) {
74
78
  void authorize(initialAccessToken, true);
75
79
  }
76
- const accessToken = ref("");
80
+ const manualAccessToken = ref("");
77
81
  const error = ref();
78
- async function authorize(token, initial = false) {
79
- if (!token || token.length === 0) {
82
+ async function authorize(accessToken, initial = false) {
83
+ if (!accessToken || accessToken.length === 0) {
80
84
  if (!initial) {
81
85
  error.value = "No code provided.";
82
86
  }
83
87
  return;
84
88
  }
85
- const res = await props.saveSession(token).catch((err) => {
89
+ const res = await props.saveSession(accessToken).catch((err) => {
86
90
  error.value = err.message;
87
91
  return err;
88
92
  });
@@ -1,5 +1,5 @@
1
1
  type __VLS_Props = {
2
- saveSession: (token: string) => Promise<void>;
2
+ saveSession: (accessToken: string) => Promise<void>;
3
3
  successPath?: string;
4
4
  cancelPath?: string;
5
5
  };
@@ -54,16 +54,13 @@ import {
54
54
  onMounted,
55
55
  useRoute
56
56
  } from "#imports";
57
- import { decodeQueryUri } from "../utils/decodeQueryUri.js";
57
+ import { zUriComponentCodec } from "../types.js";
58
58
  const query = useRoute().query;
59
- const accessToken = query.access_token;
59
+ const accessToken = query.accessToken;
60
60
  if (typeof accessToken !== "string") {
61
61
  unreachable("No session_token.");
62
62
  }
63
- const deepLinkUrl = decodeQueryUri(query.deeplinkUri);
64
- if (!deepLinkUrl) {
65
- unreachable("No deeplinkUrl could be decoded.");
66
- }
63
+ const deepLinkUrl = zUriComponentCodec.parse(query.deeplinkUri);
67
64
  defineProps({
68
65
  openAppText: { type: String, required: false, default: "Open App and Authorize" },
69
66
  promptText: { type: String, required: false, default: "If you are not prompted to open the app, try clicking below or copy this token into the app:" },
@@ -19,7 +19,7 @@
19
19
 
20
20
  <script setup>
21
21
  import { navigateTo, useRoute } from "#app";
22
- import { ref } from "#imports";
22
+ import { ref, useRuntimeConfig } from "#imports";
23
23
  import { getAuthApiRoute } from "../utils/getAuthApiRoute.js";
24
24
  const username = ref("");
25
25
  const bypassRegistration = ref(false);
@@ -146,6 +146,7 @@ const isLoading = computed(() => username.value !== "" && (status.value === "pen
146
146
  const anyError = computed(() => error.value || registrationError.value);
147
147
  const deeplink = typeof query.deeplink === "string" ? query.deeplink : void 0;
148
148
  const redirect = deeplink ? useRuntimeConfig().public.auth.authRoutes.externalCode : useRuntimeConfig().public.auth.authRoutes.register;
149
+ if (!redirect) throw new Error("No externalCode or register route defined.");
149
150
  function handleSubmit(event) {
150
151
  props.onSubmitRegistration(
151
152
  event,
@@ -1,10 +1,10 @@
1
- import type { ProviderNames, UseAuthComposableOptions } from "#auth/types.js";
1
+ import type { AuthUser, ProviderNames, UseAuthComposableOptions } from "../types.js";
2
2
  type AuthListenerHook = () => void;
3
3
  type AuthListenerHooks = "beforeLogout";
4
4
  export declare const useAuth: ({ handleActions }?: UseAuthComposableOptions) => {
5
5
  on: (hook: AuthListenerHooks, listener: AuthListenerHook) => Promise<void>;
6
6
  off: (hook: AuthListenerHooks, listener: AuthListenerHook) => Promise<void>;
7
- user: import("vue").Ref<import("#auth/types.js").AuthUserFields | null, import("#auth/types.js").AuthUserFields | null>;
7
+ user: import("vue").Ref<AuthUser | null, AuthUser | null>;
8
8
  setFetchUserOnNavigation: (value?: boolean) => void;
9
9
  login: (provider: ProviderNames, { devBypass }?: {
10
10
  /** Send the request with the devBypass query param (This will only actually bypass auth if the server permits it). */
@@ -28,8 +28,7 @@ export const useAuth = ({ handleActions } = {}) => {
28
28
  setFetchUserOnNavigation();
29
29
  const loginRoute = getAuthApiRoute(useRuntimeConfig().public, "login", { provider: provider.toLowerCase() }, { devBypass });
30
30
  const external = provider ? true : void 0;
31
- let handled = handleActions?.("login", loginRoute, provider);
32
- if (handled instanceof Promise) handled = await handled;
31
+ const handled = handleActions?.("login", loginRoute, provider);
33
32
  if (!handled) {
34
33
  await navigateTo(loginRoute, { external });
35
34
  }
@@ -41,6 +40,7 @@ export const useAuth = ({ handleActions } = {}) => {
41
40
  const handled = handleActions?.("logout", getAuthApiRoute(useRuntimeConfig().public, "logout"));
42
41
  userData.value = null;
43
42
  if (!handled) {
43
+ localStorage.removeItem("auth:user");
44
44
  const res = wasSemiAuthed ? true : await $fetch(getAuthApiRoute(useRuntimeConfig().public, "logout"), {
45
45
  cache: "no-store",
46
46
  method: "post"
@@ -70,8 +70,8 @@ export default class GithubProvider implements ProviderHandler<"oauth2", "github
70
70
  };
71
71
  getAccountInfo(tokens: OAuth2Tokens): Promise<{
72
72
  info: null;
73
- name: string;
74
73
  email: string;
74
+ name: string;
75
75
  providerId: string;
76
76
  provider: string;
77
77
  isVerified: boolean;
@@ -51,8 +51,8 @@ export default class GoogleProvider implements ProviderHandler<"oauth2_pcke", "g
51
51
  };
52
52
  getAccountInfo(tokens: OAuth2Tokens): Promise<{
53
53
  info: null;
54
- name: string;
55
54
  email: string;
55
+ name: string;
56
56
  providerId: string;
57
57
  provider: string;
58
58
  isVerified: boolean;
@@ -1,7 +1,8 @@
1
1
  import { isArray } from "@alanscodelog/utils/isArray";
2
2
  import { keys } from "@alanscodelog/utils/keys";
3
3
  import { pick } from "@alanscodelog/utils/pick";
4
- import { defineNuxtRouteMiddleware, navigateTo, useAuth, useRuntimeConfig } from "#imports";
4
+ import { defineNuxtRouteMiddleware, navigateTo, useRuntimeConfig } from "#imports";
5
+ import { useAuth } from "../composables/useAuth.js";
5
6
  export default defineNuxtRouteMiddleware(async (to, from) => {
6
7
  const rc = useRuntimeConfig();
7
8
  const config = rc.public.auth;
@@ -1,7 +1,8 @@
1
- import type { BaseLogger } from "@witchcraft/nuxt-logger/createUseLogger";
1
+ import type { BaseLogger } from "@witchcraft/nuxt-logger/shared/createUseLogger";
2
2
  import { type OAuth2RequestError, type OAuth2Tokens } from "arctic";
3
3
  import type { CookieSerializeOptions } from "cookie-es";
4
4
  import type { PgDatabase } from "drizzle-orm/pg-core";
5
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
5
6
  import type { EventHandler, H3Event, Router } from "h3";
6
7
  import type { JwtPayload } from "jsonwebtoken";
7
8
  import type { RuntimeConfig } from "nuxt/schema";
@@ -37,7 +38,7 @@ export declare class Auth {
37
38
  createMockUser: AuthOptions["createMockUser"];
38
39
  generateUser: AuthOptions["generateUser"];
39
40
  static defaultCreateMockUser(_username: string | undefined, id: string | undefined, provider: string): Omit<BaseProviderAccountInfo, "userId">;
40
- db: PgDatabase<any, any, any>;
41
+ db: PgDatabase<any, any, any> | PgliteDatabase<any>;
41
42
  usersTable: UserTable;
42
43
  authAccountsTable: AuthAccountsTable;
43
44
  sessionManager: SessionManager;
@@ -70,7 +71,7 @@ export declare class Auth {
70
71
  handleMaybeTokenError(valid: boolean, tokens: OAuth2Tokens | OAuth2RequestError, redirectToLogin?: Record<string, string>): Promise<void>;
71
72
  createSession(event: H3Event, sessionUserId: string): Promise<{
72
73
  session: AuthSession;
73
- token: string;
74
+ sessionToken: string;
74
75
  }>;
75
76
  createRedirect(event: H3Event, userId: string, isRegistered: boolean, additionalState?: any, deeplink?: string): Promise<void>;
76
77
  getRedirect(route: string, isRegistered: boolean, deeplink: string | undefined, accessToken: string): string;
@@ -3,19 +3,20 @@ import { unreachable } from "@alanscodelog/utils/unreachable";
3
3
  import { generateState } from "arctic";
4
4
  import { and, eq } from "drizzle-orm";
5
5
  import {
6
+ createError,
6
7
  defineEventHandler,
7
8
  deleteCookie,
8
9
  getCookie,
9
10
  getQuery,
10
- getRequestHeader,
11
+ getRequestHeaders,
11
12
  getValidatedQuery,
12
13
  sendRedirect,
13
14
  setCookie,
14
15
  useBase
15
16
  } from "h3";
16
17
  import { z } from "zod";
17
- import { createError, useRuntimeConfig } from "#imports";
18
- import { AUTH_ERROR } from "../../types.js";
18
+ import { useRuntimeConfig } from "#imports";
19
+ import { AUTH_ERROR, zLoginQuery } from "../../types.js";
19
20
  import { getAuthApiRoute } from "../../utils/getAuthApiRoute.js";
20
21
  import { getSafeSecretsInfo } from "../helpers/getSafeSecretsInfo.js";
21
22
  import { logSafeRoute } from "../helpers/logSafeRoute.js";
@@ -26,10 +27,6 @@ export const zState = z.object({
26
27
  additionalState: z.any(),
27
28
  deeplink: z.string().optional()
28
29
  });
29
- const zLoginQuery = z.object({
30
- devBypass: z.enum(["true", "false"]).optional(),
31
- deeplink: z.string().optional()
32
- });
33
30
  export const oauth2CallbackQuery = z.object({
34
31
  code: z.string(),
35
32
  state: z.string()
@@ -152,7 +149,8 @@ export class Auth {
152
149
  });
153
150
  const apiRoutes = this.rc.public.auth.authApiRoutes;
154
151
  const authRoutes = this.rc.public.auth.authRoutes;
155
- router.get(apiRoutes.usersInfo, defineEventHandler((event) => {
152
+ router.get(apiRoutes.usersInfo, defineEventHandler(async (event) => {
153
+ Auth.assertEventWithAuthorizedUser(event);
156
154
  const user = event.context.user;
157
155
  const id = getCookie(event, "userId");
158
156
  this.logger.debug({
@@ -163,7 +161,7 @@ export class Auth {
163
161
  return user ?? false;
164
162
  }));
165
163
  router.get(apiRoutes.externalExchange, defineEventHandler(async (event) => {
166
- const accessToken = getRequestHeader(event, "Authorization")?.slice("Bearer ".length);
164
+ const accessToken = getRequestHeaders(event).authorization?.slice("Bearer ".length);
167
165
  const decoded = await this.verifyAccessToken(accessToken).catch((err) => createError({
168
166
  status: 400,
169
167
  statusMessage: err.message,
@@ -171,13 +169,16 @@ export class Auth {
171
169
  }));
172
170
  if (decoded instanceof Error) throw decoded;
173
171
  const res = await this.createSession(event, decoded.userId);
172
+ const { user } = await sessionManager.validateSessionToken(res.sessionToken);
173
+ if (!user) throw createError({ status: 500, statusMessage: "Failed to validate session token." });
174
174
  this.logger.debug({
175
175
  ns: "auth:callback:createdSession",
176
- redact: { res, decoded }
176
+ redact: { res, decoded, user }
177
177
  });
178
- return { token: res.token };
178
+ return { sessionToken: res.sessionToken, user };
179
179
  }));
180
180
  router.get(apiRoutes.usersIdAccounts, defineEventHandler(async (event) => {
181
+ Auth.assertEventWithAuthorizedUser(event);
181
182
  const id = event.context.user?.id;
182
183
  Auth.assertAuthorizedUserAndId(event.context.user, id);
183
184
  this.logger.trace({
@@ -212,7 +213,7 @@ export class Auth {
212
213
  const devBypassAuth = query.devBypass === "true" && this.devBypassAuth === true;
213
214
  const deeplink = query.deeplink;
214
215
  if (devBypassAuth) {
215
- return sendRedirect(event, `${authRoutes.mockAuth}?provider=${providerName}${deeplink ? `&deeplink=${deeplink}` : ""}`);
216
+ return await sendRedirect(event, `${authRoutes.mockAuth}?provider=${providerName}${deeplink ? `&deeplink=${deeplink}` : ""}`, 302);
216
217
  }
217
218
  const state = {
218
219
  oauthState: generateState(),
@@ -250,7 +251,7 @@ export class Auth {
250
251
  }
251
252
  });
252
253
  }
253
- return sendRedirect(event, info.url.toString());
254
+ return await sendRedirect(event, info.url.toString(), 302);
254
255
  }));
255
256
  router.get(apiRoutes.callback, defineEventHandler(async (event) => {
256
257
  const providerName = event.context.params.provider;
@@ -330,7 +331,7 @@ export class Auth {
330
331
  this.logger.debug({
331
332
  ns: "auth:callback:existingProviderAccount"
332
333
  });
333
- return this.createRedirect(
334
+ return await this.createRedirect(
334
335
  event,
335
336
  sessionUserId,
336
337
  isRegistered,
@@ -401,7 +402,7 @@ export class Auth {
401
402
  }
402
403
  if (!sessionUserId || typeof sessionUserId !== "string") unreachable();
403
404
  await this.createSession(event, sessionUserId);
404
- return this.createRedirect(
405
+ return await this.createRedirect(
405
406
  event,
406
407
  sessionUserId,
407
408
  bypassRegistration ?? isRegistered,
@@ -563,9 +564,9 @@ export class Auth {
563
564
  }
564
565
  }
565
566
  async createSession(event, sessionUserId) {
566
- const token = this.sessionManager.generateSessionToken();
567
- const session = await this.sessionManager.createSession(token, sessionUserId);
568
- const sessionCookie = this.sessionManager.createSessionCookie(token);
567
+ const sessionToken = this.sessionManager.generateSessionToken();
568
+ const session = await this.sessionManager.createSession(sessionToken, sessionUserId);
569
+ const sessionCookie = this.sessionManager.createSessionCookie(sessionToken);
569
570
  this.logger.debug({
570
571
  ns: "auth:createSession",
571
572
  redact: {
@@ -575,11 +576,11 @@ export class Auth {
575
576
  });
576
577
  setCookie(event, sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
577
578
  setCookie(event, `userId`, sessionUserId, sessionCookie.attributes);
578
- return { session, token };
579
+ return { session, sessionToken };
579
580
  }
580
581
  async createRedirect(event, userId, isRegistered, additionalState, deeplink) {
581
- let redirect = isRegistered ? this.rc.public.auth.authRoutes.postRegisteredLogin : this.rc.public.auth.authRoutes.register;
582
- if (!redirect) {
582
+ let redirectPath = isRegistered ? this.rc.public.auth.authRoutes.postRegisteredLogin : this.rc.public.auth.authRoutes.register;
583
+ if (!redirectPath) {
583
584
  throw createError({
584
585
  status: 500,
585
586
  statusMessage: "No register/postRegisteredLogin route defined.",
@@ -588,16 +589,16 @@ export class Auth {
588
589
  }
589
590
  const modified = this.modifyCallbackRedirect?.(
590
591
  event,
591
- redirect,
592
+ redirectPath,
592
593
  userId,
593
594
  isRegistered,
594
595
  additionalState,
595
596
  deeplink
596
597
  );
597
- redirect = modified ?? redirect;
598
+ redirectPath = modified ?? redirectPath;
598
599
  if (!modified) {
599
- redirect = this.getRedirect(
600
- redirect,
600
+ redirectPath = this.getRedirect(
601
+ redirectPath,
601
602
  isRegistered,
602
603
  deeplink,
603
604
  await this.createAccessToken(userId)
@@ -607,11 +608,11 @@ export class Auth {
607
608
  ns: "auth:callback:createdSessionAndRedirecting",
608
609
  modified,
609
610
  deeplink,
610
- redirect,
611
+ redirectPath,
611
612
  isRegistered,
612
613
  redact: { additionalState }
613
614
  });
614
- return sendRedirect(event, redirect);
615
+ return sendRedirect(event, redirectPath, 302);
615
616
  }
616
617
  getRedirect(route, isRegistered, deeplink, accessToken) {
617
618
  if (!deeplink) return route;
@@ -619,10 +620,10 @@ export class Auth {
619
620
  return `${route}?${new URLSearchParams({ deeplink }).toString()}`;
620
621
  }
621
622
  const deeplinkUri = `${this.getDeeplinkScheme(deeplink)}?${new URLSearchParams({
622
- access_token: accessToken
623
+ accessToken
623
624
  })}`;
624
625
  return `${this.rc.public.auth.authRoutes.externalCode}?${new URLSearchParams({
625
- access_token: accessToken,
626
+ accessToken,
626
627
  deeplinkUri
627
628
  }).toString()}`;
628
629
  }
@@ -1,5 +1,6 @@
1
1
  import type { DeepPartial } from "@alanscodelog/utils";
2
2
  import type { PgDatabase } from "drizzle-orm/pg-core";
3
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
3
4
  import type { RuntimeConfig } from "nuxt/schema";
4
5
  import type { AuthSessionsTable, AuthUsersTable } from "./createAuthSchema.js";
5
6
  import type { AuthSession, SessionCookie, SessionCookieOptions, SessionValidationResult } from "../../types.js";
@@ -12,14 +13,14 @@ export declare class SessionManager {
12
13
  attributes: Omit<SessionCookieOptions, "maxAge">;
13
14
  };
14
15
  };
15
- db: PgDatabase<any, any, any>;
16
+ db: PgDatabase<any, any, any> | PgliteDatabase<any>;
16
17
  sessionTable: AuthSessionsTable;
17
18
  userTable: AuthUsersTable;
18
19
  constructor(rc: RuntimeConfig, db: SessionManager["db"], sessionTable: SessionManager["sessionTable"], userTable: SessionManager["userTable"], options?: DeepPartial<SessionManager["options"]>);
19
20
  generateSessionToken(): string;
20
- createSession<TId = string>(token: string, userId: TId): Promise<AuthSession>;
21
+ createSession<TId = string>(sessionToken: string, userId: TId): Promise<AuthSession>;
21
22
  createSessionCookie(sessionId: string): SessionCookie;
22
23
  createBlankSessionCookie(): SessionCookie;
23
- validateSessionToken(token: string): Promise<SessionValidationResult>;
24
+ validateSessionToken(sessionToken: string): Promise<SessionValidationResult>;
24
25
  invalidateSession(sessionId: string): Promise<void>;
25
26
  }
@@ -31,8 +31,8 @@ export class SessionManager {
31
31
  const token = encodeBase32LowerCaseNoPadding(bytes);
32
32
  return token;
33
33
  }
34
- async createSession(token, userId) {
35
- const hashedSessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
34
+ async createSession(sessionToken, userId) {
35
+ const hashedSessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(sessionToken)));
36
36
  const session = {
37
37
  id: hashedSessionId,
38
38
  userId,
@@ -61,8 +61,8 @@ export class SessionManager {
61
61
  }
62
62
  };
63
63
  }
64
- async validateSessionToken(token) {
65
- const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
64
+ async validateSessionToken(sessionToken) {
65
+ const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(sessionToken)));
66
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));
67
67
  if (result.length < 1) {
68
68
  return { session: null, user: null, fresh: false };
@@ -1,8 +1,9 @@
1
- import type { BaseLogger } from "@witchcraft/nuxt-logger/createUseLogger";
1
+ import type { BaseLogger } from "@witchcraft/nuxt-logger/shared/createUseLogger";
2
2
  import type { PgDatabase } from "drizzle-orm/pg-core";
3
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
3
4
  import type { EventHandler } from "h3";
4
5
  import type { RuntimeConfig } from "nuxt/schema";
5
6
  import type { AuthAccountsTable, UserTable } from "./createAuthSchema.js";
6
7
  import type { SessionManager } from "./SessionManager.js";
7
8
  import type { AuthHandlerOptions } from "../../types.js";
8
- export declare function createAuthHandler(rc: RuntimeConfig, db: PgDatabase<any, any, any>, usersTable: UserTable, authAccountsTable: AuthAccountsTable, sessionManager: SessionManager, logger: BaseLogger, opts?: Partial<AuthHandlerOptions>): EventHandler;
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;
@@ -1,7 +1,7 @@
1
+ import { createRouter } from "h3";
1
2
  import { Auth } from "./Auth.js";
2
- import github from "#auth/core/providers/github.js";
3
- import google from "#auth/core/providers/google.js";
4
- import { createRouter } from "#imports";
3
+ import github from "../../core/providers/github.js";
4
+ import google from "../../core/providers/google.js";
5
5
  export function createAuthHandler(rc, db, usersTable, authAccountsTable, sessionManager, logger, opts = {}) {
6
6
  const router = createRouter();
7
7
  const auth = new Auth(
@@ -1,7 +1,7 @@
1
- import type { BaseLogger } from "@witchcraft/nuxt-logger/createUseLogger";
1
+ import type { BaseLogger } from "@witchcraft/nuxt-logger/shared/createUseLogger";
2
2
  import type { SessionManager } from "./SessionManager.js";
3
3
  import type { AuthSession, AuthUser } from "../../types.js";
4
- export declare function createAuthMiddleware(sessionManager: SessionManager, logger: BaseLogger): any;
4
+ export declare function createAuthMiddleware(sessionManager: SessionManager, logger: BaseLogger): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void>>;
5
5
  declare module "h3" {
6
6
  interface H3EventContext {
7
7
  user: AuthUser | null;
@@ -1,18 +1,18 @@
1
- import { defineEventHandler, getCookie, setCookie } from "#imports";
1
+ import { defineEventHandler, getCookie, setCookie } from "h3";
2
2
  export function createAuthMiddleware(sessionManager, logger) {
3
3
  return defineEventHandler(async (event) => {
4
- const sessionId = getCookie(event, sessionManager.options.sessionCookie.name) ?? null;
5
- if (!sessionId) {
4
+ const sessionToken = getCookie(event, sessionManager.options.sessionCookie.name) ?? null;
5
+ if (!sessionToken) {
6
6
  event.context.session = null;
7
7
  event.context.user = null;
8
8
  return;
9
9
  }
10
- const { session, user, fresh } = await sessionManager.validateSessionToken(sessionId);
10
+ const { session, user, fresh } = await sessionManager.validateSessionToken(sessionToken);
11
11
  logger.debug({
12
12
  ns: "auth:middleware:session",
13
13
  user,
14
14
  fresh,
15
- redact: { sessionId, session }
15
+ redact: { sessionToken, session }
16
16
  });
17
17
  if (fresh) {
18
18
  const cookie = sessionManager.createSessionCookie(session.id);
@@ -4,11 +4,33 @@ import type { H3Event, Router } from "h3";
4
4
  import type { StringValue } from "ms";
5
5
  import type { InjectionKey } from "vue";
6
6
  import { z } from "zod";
7
- import "./core/providers/github.js";
8
- import "./core/providers/google.js";
9
7
  import type { AuthAccount, AuthSession as DbAuthSession, AuthUserFields as DbAuthUser } from "./server/utils/createAuthSchema.js";
10
8
  import type { ModulePublicRuntimeConfig } from "../module.js";
11
9
  export type * from "./server/utils/createAuthSchema.js";
10
+ export declare const zLoginQuery: z.ZodObject<{
11
+ devBypass: z.ZodOptional<z.ZodEnum<{
12
+ true: "true";
13
+ false: "false";
14
+ }>>;
15
+ deeplink: z.ZodOptional<z.ZodString>;
16
+ }, z.core.$strip>;
17
+ export type ExternalExchangeResponse = {
18
+ sessionToken: string;
19
+ user: AuthUser;
20
+ };
21
+ export type LogoutResponse = true;
22
+ export type LoginResponse = undefined;
23
+ export type UserInfoResponse = AuthUser | false;
24
+ export type RegisterResponse = true | {
25
+ redirectUrl: string;
26
+ };
27
+ export type CallbackResponse = undefined;
28
+ export declare const zUriComponentCodec: z.ZodCodec<z.ZodString, z.ZodString>;
29
+ export declare const zExternalCallbackPageQuery: z.ZodUnion<[z.ZodObject<{
30
+ accessToken: z.ZodString;
31
+ }, z.core.$strip>, z.ZodObject<{
32
+ authUri: z.ZodCodec<z.ZodString, z.ZodString>;
33
+ }, z.core.$strip>]>;
12
34
  /**
13
35
  * This is the minimum information providers need to return.
14
36
  *
@@ -70,10 +92,10 @@ export type AdditionalAccountInfo = Register extends {
70
92
  } ? T : never;
71
93
  export type AdditionalApiRoutes = (Register extends {
72
94
  ApiRoutes: infer T;
73
- } ? T extends Record<string, any> ? T : {} : {});
95
+ } ? T extends Record<string, any> ? T : object : object);
74
96
  export type ApiRoutesParams = (Register extends {
75
97
  ApiRoutesParams: infer T;
76
- } ? T extends Record<string, any> ? T : {} : {}) & {
98
+ } ? T extends Record<string, any> ? T : object : object) & {
77
99
  userIdAccounts: Record<"id", string>;
78
100
  login: Record<"provider", string>;
79
101
  callback: Record<"provider", string>;
@@ -81,10 +103,10 @@ export type ApiRoutesParams = (Register extends {
81
103
  };
82
104
  export type AuthSession = (Register extends {
83
105
  AuthSession: infer T;
84
- } ? T extends Record<string, any> ? T : {} : {}) & DbAuthSession;
106
+ } ? T extends Record<string, any> ? T : object : object) & DbAuthSession;
85
107
  export type AuthUser = (Register extends {
86
108
  AuthUser: infer T;
87
- } ? T extends Record<string, any> ? T : {} : {}) & DbAuthUser;
109
+ } ? T extends Record<string, any> ? T : object : object) & DbAuthUser;
88
110
  export type SessionValidationResult = {
89
111
  session: AuthSession;
90
112
  user: AuthUser;
@@ -218,13 +240,25 @@ export type UseAuthComposableOptions = {
218
240
  * Handle login and logout actions yourself.
219
241
  *
220
242
  * Return `true` to let prevent the handler from handling the action.
243
+ *
244
+ * To run an async function while returning true you can do:
245
+ *
246
+ * ```
247
+ * setTimeout(() => {
248
+ * void (async function() {})()
249
+ * })
250
+ * return true
251
+ * ```
252
+ *
253
+ * The reason handlers cna't return a promise is to allow handler chaining (see the docs).
221
254
  */
222
255
  handleActions?: ActionHandler;
223
256
  };
257
+ export type ActionReturnType = undefined | false | true;
224
258
  /**
225
259
  * See {@link UseAuthComposableOptions.handleActions}
226
260
  */
227
- export type ActionHandler = ((action: "login", url: string, provider: ProviderNames) => any | false) & ((action: "logout", url: string) => any | false);
261
+ export type ActionHandler = ((action: "login", url: string, provider: ProviderNames) => ActionReturnType) & ((action: "logout", url: string) => ActionReturnType);
228
262
  export declare const AUTH_ERROR: {
229
263
  USER_ALREADY_REGISTERED: "AUTH.USER_ALREADY_REGISTERED";
230
264
  UNKNOWN_PROVIDER: "AUTH.UNKNOWN_PROVIDER";
@@ -1,5 +1,20 @@
1
1
  import { enumFromArray } from "@alanscodelog/utils/enumFromArray";
2
2
  import { z } from "zod";
3
+ export const zLoginQuery = z.object({
4
+ devBypass: z.enum(["true", "false"]).optional(),
5
+ deeplink: z.string().optional()
6
+ });
7
+ export const zUriComponentCodec = z.codec(z.string(), z.string(), {
8
+ decode: (encodedString) => decodeURIComponent(encodedString),
9
+ encode: (decodedString) => encodeURIComponent(decodedString)
10
+ });
11
+ export const zExternalCallbackPageQuery = z.object({
12
+ accessToken: z.string()
13
+ }).or(
14
+ z.object({
15
+ authUri: zUriComponentCodec
16
+ })
17
+ );
3
18
  export const defaultZodUsernameSchema = z.string().min(3).max(32).regex(/^[\w.]+$/, "Username can only contain letters, numbers, underscores, and periods.");
4
19
  export const providerStylesInjectionKey = Symbol("providerStyles");
5
20
  export const AUTH_ERROR = enumFromArray([
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Creates an external (e.g. desktop) auth handler.
2
+ * Creates an external (e.g. desktop) auth login handler. A logout one doesn't exist as that is very platform dependant.
3
3
  */
4
- export declare function createExternalAuthHandler(
4
+ export declare function createExternalAuthLoginHandler(
5
5
  /**
6
6
  * The name of the platform.
7
7
  *
@@ -33,4 +33,4 @@ open: ((url: string) => void | Promise<void>) | undefined,
33
33
  *
34
34
  * @default runctimeConfig().public.auth.authRoutes.deeplink
35
35
  */
36
- deeplinkCallbackPath?: string): (_action: "login" | "logout", url: string) => Promise<boolean>;
36
+ deeplinkCallbackPath?: string): (action: "login" | "logout", url: string) => Promise<boolean>;
@@ -1,12 +1,13 @@
1
1
  import { navigateTo, useRuntimeConfig } from "#imports";
2
- export function createExternalAuthHandler(name, isExternal, serverUrl, open, deeplinkCallbackPath = useRuntimeConfig().public.auth.authRoutes.deeplink) {
3
- return async (_action, url) => {
2
+ export function createExternalAuthLoginHandler(name, isExternal, serverUrl, open, deeplinkCallbackPath = useRuntimeConfig().public.auth.authRoutes.deeplink) {
3
+ return async (action, url) => {
4
+ if (action !== "login") return false;
4
5
  if (!isExternal()) return false;
5
6
  if (deeplinkCallbackPath === void 0) {
6
- throw new Error("createExternalAuthHandler: deeplinkCallbackPath cannot be undefined. See docs for more info.");
7
+ throw new Error("createExternalAuthLoginHandler: deeplinkCallbackPath cannot be undefined. See docs for more info.");
7
8
  }
8
- if (!serverUrl) throw new Error("createExternalAuthHandler: serverUrl cannot be undefined when isExternal returns true. See docs for more info.");
9
- if (!open) throw new Error("createExternalAuthHandler: open cannot be undefined when isExternal returns true. See docs for more info.");
9
+ if (!serverUrl) throw new Error("createExternalAuthLoginHandler: serverUrl cannot be undefined when isExternal returns true. See docs for more info.");
10
+ if (!open) throw new Error("createExternalAuthLoginHandler: open cannot be undefined when isExternal returns true. See docs for more info.");
10
11
  let origin = typeof serverUrl === "function" ? serverUrl() : serverUrl;
11
12
  if (origin instanceof Promise) {
12
13
  origin = await origin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@witchcraft/nuxt-auth",
3
- "version": "0.1.8",
3
+ "version": "0.2.0",
4
4
  "description": "Nuxt module for logging.",
5
5
  "repository": "witchcraftjs/nuxt-auth",
6
6
  "license": "MIT",
@@ -30,8 +30,10 @@
30
30
  "//": "drizzle requires we run from playground",
31
31
  "dev:playground": "cd playground && pnpm dev",
32
32
  "dev:prepare": "cross-env-shell DISABLE_POSTGRES_ENSURE_ENV=true 'pnpm nuxt-module-build build --stub && pnpm nuxt-module-build prepare && pnpm nuxi prepare playground'",
33
- "lint": "eslint \"{src,test,playground/app}/**/*.{ts,vue}\" \"*.{js,cjs,mjs,ts}\"",
33
+ "lint": "pnpm lint:eslint && pnpm lint:types && pnpm lint:commits",
34
+ "lint:eslint": "eslint \"{src,test,playground/app}/**/*.{ts,vue}\" \"*.{js,cjs,mjs,ts}\"",
34
35
  "lint:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
36
+ "lint:commits": "commitlint --from-last-tag --to HEAD --verbose",
35
37
  "test": "echo no tests and not working yet vitest run --exclude .direnv",
36
38
  "test:watch": "vitest watch --exclude .direnv"
37
39
  },
@@ -45,45 +47,48 @@
45
47
  },
46
48
  "dependencies": {
47
49
  "@alanscodelog/tsconfigs": "^6.2.0",
48
- "@alanscodelog/utils": "^6.0.1",
49
- "@iconify/json": "^2.2.384",
50
- "@nuxt/kit": "^4.1.2",
50
+ "@alanscodelog/utils": "^6.0.2",
51
+ "@iconify/json": "^2.2.393",
52
+ "@nuxt/kit": "^4.1.3",
51
53
  "@oslojs/crypto": "^1.0.1",
52
54
  "@oslojs/encoding": "^1.1.0",
55
+ "@types/jsonwebtoken": "^9.0.10",
53
56
  "@vueuse/core": "^13.9.0",
54
- "@witchcraft/nuxt-logger": "^0.0.2",
55
- "@witchcraft/ui": "^0.3.2",
57
+ "@witchcraft/nuxt-logger": "^0.0.6",
58
+ "@witchcraft/ui": "^0.3.5",
56
59
  "arctic": "~3.7.0",
57
60
  "cookie-es": "^2.0.0",
58
61
  "defu": "latest",
62
+ "h3": "1.15.4",
59
63
  "jsonwebtoken": "^9.0.2",
60
64
  "ms": "^2.1.3",
61
65
  "nuxt-security": "^2.4.0",
62
- "unplugin-icons": "^22.3.0",
63
- "unplugin-vue-components": "^29.0.0",
64
- "zod": "^4.1.8"
66
+ "unplugin-icons": "^22.4.2",
67
+ "unplugin-vue-components": "^29.1.0",
68
+ "zod": "^4.1.12"
65
69
  },
66
70
  "devDependencies": {
67
71
  "@alanscodelog/eslint-config": "^6.3.1",
68
72
  "@alanscodelog/semantic-release-config": "^5.0.4",
73
+ "@commitlint/cli": "^20.1.0",
69
74
  "@nuxt/eslint-config": "^1.9.0",
70
75
  "@nuxt/module-builder": "^1.0.2",
71
- "@nuxt/schema": "^4.1.2",
76
+ "@nuxt/schema": "^4.1.3",
72
77
  "@nuxt/test-utils": "^3.19.2",
73
- "@tailwindcss/cli": "^4.1.13",
78
+ "@tailwindcss/cli": "^4.1.14",
74
79
  "@types/node": "latest",
75
80
  "changelogen": "^0.6.2",
76
- "cross-env": "^10.0.0",
77
- "drizzle-orm": "^0.44.5",
78
- "electron": "^38.1.0",
79
- "eslint": "^9.35.0",
81
+ "cross-env": "^10.1.0",
82
+ "drizzle-orm": "^0.44.6",
83
+ "electron": "^38.2.2",
84
+ "eslint": "^9.37.0",
80
85
  "husky": "^9.1.7",
81
- "nuxt": "^4.1.2",
82
- "reka-ui": "^2.5.0",
83
- "tailwindcss": "^4.1.13",
84
- "typescript": "^5.9.2",
86
+ "nuxt": "^4.1.3",
87
+ "reka-ui": "^2.5.1",
88
+ "tailwindcss": "^4.1.14",
89
+ "typescript": "^5.9.3",
85
90
  "vitest": "^3.2.4",
86
- "vue-tsc": "^3.0.7"
91
+ "vue-tsc": "^3.1.1"
87
92
  },
88
93
  "release": {
89
94
  "extends": [
@@ -1,2 +0,0 @@
1
- import type { LocationQueryValue } from "vue-router";
2
- export declare function decodeQueryUri(queryValueryValue: string | LocationQueryValue | LocationQueryValue[]): string | undefined;
@@ -1,4 +0,0 @@
1
- export function decodeQueryUri(queryValueryValue) {
2
- if (typeof queryValueryValue !== "string") return void 0;
3
- return decodeURIComponent(queryValueryValue);
4
- }