@witchcraft/nuxt-auth 0.1.7 → 0.1.9
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 +6 -2
- package/dist/module.json +1 -1
- package/dist/module.mjs +1 -1
- package/dist/runtime/components/ExternalCallback.d.vue.ts +1 -1
- package/dist/runtime/components/ExternalCallback.vue +38 -34
- package/dist/runtime/components/ExternalCallback.vue.d.ts +1 -1
- package/dist/runtime/components/ExternalCode.vue +3 -6
- package/dist/runtime/components/LoginProviderButtons.client.d.vue.ts +1 -1
- package/dist/runtime/components/LoginProviderButtons.client.vue +18 -14
- package/dist/runtime/components/LoginProviderButtons.client.vue.d.ts +1 -1
- package/dist/runtime/components/Mocker.vue +1 -1
- package/dist/runtime/components/UserRegistration.vue +1 -0
- package/dist/runtime/composables/useAuth.d.ts +2 -2
- package/dist/runtime/composables/useAuth.js +1 -0
- package/dist/runtime/core/providers/github.d.ts +1 -1
- package/dist/runtime/core/providers/google.d.ts +1 -1
- package/dist/runtime/middleware/authProtected.js +2 -1
- package/dist/runtime/server/utils/Auth.d.ts +2 -2
- package/dist/runtime/server/utils/Auth.js +30 -29
- package/dist/runtime/server/utils/SessionManager.d.ts +2 -2
- package/dist/runtime/server/utils/SessionManager.js +4 -4
- package/dist/runtime/server/utils/createAuthHandler.d.ts +1 -1
- package/dist/runtime/server/utils/createAuthHandler.js +3 -3
- package/dist/runtime/server/utils/createAuthMiddleware.d.ts +2 -2
- package/dist/runtime/server/utils/createAuthMiddleware.js +5 -5
- package/dist/runtime/types.d.ts +24 -2
- package/dist/runtime/types.js +15 -0
- package/package.json +26 -21
- package/dist/runtime/utils/decodeQueryUri.d.ts +0 -2
- package/dist/runtime/utils/decodeQueryUri.js +0 -4
package/README.md
CHANGED
|
@@ -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
|
-
|
|
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
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.
|
|
6
|
+
"@witchcraft/ui": "^0.3.5",
|
|
7
7
|
"nuxt-security": "^2.4.0"};
|
|
8
8
|
const pkg = {
|
|
9
9
|
dependencies: dependencies};
|
|
@@ -14,26 +14,34 @@
|
|
|
14
14
|
{{ authUri }}
|
|
15
15
|
</NuxtLink>
|
|
16
16
|
</div>
|
|
17
|
-
<
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
|
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 {
|
|
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
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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
|
|
80
|
+
const manualAccessToken = ref("");
|
|
77
81
|
const error = ref();
|
|
78
|
-
async function authorize(
|
|
79
|
-
if (!
|
|
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(
|
|
89
|
+
const res = await props.saveSession(accessToken).catch((err) => {
|
|
86
90
|
error.value = err.message;
|
|
87
91
|
return err;
|
|
88
92
|
});
|
|
@@ -54,16 +54,13 @@ import {
|
|
|
54
54
|
onMounted,
|
|
55
55
|
useRoute
|
|
56
56
|
} from "#imports";
|
|
57
|
-
import {
|
|
57
|
+
import { zUriComponentCodec } from "../types.js";
|
|
58
58
|
const query = useRoute().query;
|
|
59
|
-
const accessToken = query.
|
|
59
|
+
const accessToken = query.accessToken;
|
|
60
60
|
if (typeof accessToken !== "string") {
|
|
61
61
|
unreachable("No session_token.");
|
|
62
62
|
}
|
|
63
|
-
const deepLinkUrl =
|
|
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:" },
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
<template>
|
|
2
2
|
<div
|
|
3
|
-
class="
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"
|
|
3
|
+
:class="twMerge(`
|
|
4
|
+
flex-1
|
|
5
|
+
flex
|
|
6
|
+
flex-col
|
|
7
|
+
items-stretch
|
|
8
|
+
justify-center
|
|
9
|
+
gap-2
|
|
10
|
+
`, $attrs?.class)"
|
|
11
11
|
>
|
|
12
12
|
<template
|
|
13
13
|
v-for="provider in enabledProviders"
|
|
@@ -19,40 +19,44 @@
|
|
|
19
19
|
v-if="provider"
|
|
20
20
|
:id="'login-provider-' + provider"
|
|
21
21
|
type="button"
|
|
22
|
-
class="p-2
|
|
22
|
+
class="text-l p-2 px-4 [&_label]:justify-start [&_label]:gap-4"
|
|
23
23
|
:style="styles[provider]"
|
|
24
24
|
:key="provider"
|
|
25
25
|
@click="login(provider, loginOptions)"
|
|
26
26
|
>
|
|
27
27
|
<WIcon
|
|
28
28
|
v-if="styles[provider]?.logo"
|
|
29
|
-
class="
|
|
29
|
+
class="text-xl"
|
|
30
30
|
>
|
|
31
31
|
<component
|
|
32
32
|
:is="styles[provider]?.logo"
|
|
33
33
|
/>
|
|
34
34
|
</WIcon>
|
|
35
|
-
|
|
35
|
+
<div>
|
|
36
|
+
Sign in / Register with {{ styles[provider]?.name ?? provider }}
|
|
37
|
+
</div>
|
|
36
38
|
</WButton>
|
|
37
39
|
</template>
|
|
38
40
|
<slot
|
|
39
41
|
name="extra"
|
|
40
|
-
class="
|
|
41
|
-
|
|
42
|
+
icon-class="text-xl"
|
|
43
|
+
class="text-l p-2 px-4 [&_label]:justify-start [&_label]:gap-4"
|
|
42
44
|
/>
|
|
43
45
|
</div>
|
|
44
46
|
</template>
|
|
45
47
|
|
|
46
48
|
<script setup>
|
|
47
49
|
import { useInjectedDarkMode } from "@witchcraft/ui/composables/useInjectedDarkMode";
|
|
50
|
+
import { twMerge } from "@witchcraft/ui/utils/twMerge";
|
|
48
51
|
import defu from "defu";
|
|
49
52
|
import { useRuntimeConfig } from "#app";
|
|
50
|
-
import { computed } from "#imports";
|
|
53
|
+
import { computed, useAttrs } from "#imports";
|
|
51
54
|
import { useAuth } from "../composables/useAuth.js";
|
|
52
55
|
import { providerStyles as baseProviderStyles } from "../core/providerStyles.js";
|
|
53
56
|
const rc = useRuntimeConfig();
|
|
54
57
|
const config = rc.public.auth;
|
|
55
58
|
const enabledProviders = config.enabledProviders;
|
|
59
|
+
const $attrs = useAttrs();
|
|
56
60
|
const { darkMode: isDark } = useInjectedDarkMode();
|
|
57
61
|
const props = defineProps({
|
|
58
62
|
providerStyles: { type: Object, required: false, default: () => ({}) },
|
|
@@ -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 "
|
|
1
|
+
import type { 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("
|
|
7
|
+
user: import("vue").Ref<import("../types.js").AuthUserFields | null, import("../types.js").AuthUserFields | 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). */
|
|
@@ -41,6 +41,7 @@ export const useAuth = ({ handleActions } = {}) => {
|
|
|
41
41
|
const handled = handleActions?.("logout", getAuthApiRoute(useRuntimeConfig().public, "logout"));
|
|
42
42
|
userData.value = null;
|
|
43
43
|
if (!handled) {
|
|
44
|
+
localStorage.removeItem("auth:user");
|
|
44
45
|
const res = wasSemiAuthed ? true : await $fetch(getAuthApiRoute(useRuntimeConfig().public, "logout"), {
|
|
45
46
|
cache: "no-store",
|
|
46
47
|
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,
|
|
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,4 +1,4 @@
|
|
|
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";
|
|
@@ -70,7 +70,7 @@ export declare class Auth {
|
|
|
70
70
|
handleMaybeTokenError(valid: boolean, tokens: OAuth2Tokens | OAuth2RequestError, redirectToLogin?: Record<string, string>): Promise<void>;
|
|
71
71
|
createSession(event: H3Event, sessionUserId: string): Promise<{
|
|
72
72
|
session: AuthSession;
|
|
73
|
-
|
|
73
|
+
sessionToken: string;
|
|
74
74
|
}>;
|
|
75
75
|
createRedirect(event: H3Event, userId: string, isRegistered: boolean, additionalState?: any, deeplink?: string): Promise<void>;
|
|
76
76
|
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
|
-
|
|
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 {
|
|
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 =
|
|
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 {
|
|
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
|
|
567
|
-
const session = await this.sessionManager.createSession(
|
|
568
|
-
const sessionCookie = this.sessionManager.createSessionCookie(
|
|
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,
|
|
579
|
+
return { session, sessionToken };
|
|
579
580
|
}
|
|
580
581
|
async createRedirect(event, userId, isRegistered, additionalState, deeplink) {
|
|
581
|
-
let
|
|
582
|
-
if (!
|
|
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
|
-
|
|
592
|
+
redirectPath,
|
|
592
593
|
userId,
|
|
593
594
|
isRegistered,
|
|
594
595
|
additionalState,
|
|
595
596
|
deeplink
|
|
596
597
|
);
|
|
597
|
-
|
|
598
|
+
redirectPath = modified ?? redirectPath;
|
|
598
599
|
if (!modified) {
|
|
599
|
-
|
|
600
|
-
|
|
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
|
-
|
|
611
|
+
redirectPath,
|
|
611
612
|
isRegistered,
|
|
612
613
|
redact: { additionalState }
|
|
613
614
|
});
|
|
614
|
-
return sendRedirect(event,
|
|
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
|
-
|
|
623
|
+
accessToken
|
|
623
624
|
})}`;
|
|
624
625
|
return `${this.rc.public.auth.authRoutes.externalCode}?${new URLSearchParams({
|
|
625
|
-
|
|
626
|
+
accessToken,
|
|
626
627
|
deeplinkUri
|
|
627
628
|
}).toString()}`;
|
|
628
629
|
}
|
|
@@ -17,9 +17,9 @@ export declare class SessionManager {
|
|
|
17
17
|
userTable: AuthUsersTable;
|
|
18
18
|
constructor(rc: RuntimeConfig, db: SessionManager["db"], sessionTable: SessionManager["sessionTable"], userTable: SessionManager["userTable"], options?: DeepPartial<SessionManager["options"]>);
|
|
19
19
|
generateSessionToken(): string;
|
|
20
|
-
createSession<TId = string>(
|
|
20
|
+
createSession<TId = string>(sessionToken: string, userId: TId): Promise<AuthSession>;
|
|
21
21
|
createSessionCookie(sessionId: string): SessionCookie;
|
|
22
22
|
createBlankSessionCookie(): SessionCookie;
|
|
23
|
-
validateSessionToken(
|
|
23
|
+
validateSessionToken(sessionToken: string): Promise<SessionValidationResult>;
|
|
24
24
|
invalidateSession(sessionId: string): Promise<void>;
|
|
25
25
|
}
|
|
@@ -31,8 +31,8 @@ export class SessionManager {
|
|
|
31
31
|
const token = encodeBase32LowerCaseNoPadding(bytes);
|
|
32
32
|
return token;
|
|
33
33
|
}
|
|
34
|
-
async createSession(
|
|
35
|
-
const hashedSessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(
|
|
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(
|
|
65
|
-
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(
|
|
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,4 +1,4 @@
|
|
|
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
3
|
import type { EventHandler } from "h3";
|
|
4
4
|
import type { RuntimeConfig } from "nuxt/schema";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { createRouter } from "h3";
|
|
1
2
|
import { Auth } from "./Auth.js";
|
|
2
|
-
import github from "
|
|
3
|
-
import google from "
|
|
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):
|
|
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 "
|
|
1
|
+
import { defineEventHandler, getCookie, setCookie } from "h3";
|
|
2
2
|
export function createAuthMiddleware(sessionManager, logger) {
|
|
3
3
|
return defineEventHandler(async (event) => {
|
|
4
|
-
const
|
|
5
|
-
if (!
|
|
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(
|
|
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: {
|
|
15
|
+
redact: { sessionToken, session }
|
|
16
16
|
});
|
|
17
17
|
if (fresh) {
|
|
18
18
|
const cookie = sessionManager.createSessionCookie(session.id);
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -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
|
*
|
package/dist/runtime/types.js
CHANGED
|
@@ -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([
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@witchcraft/nuxt-auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
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
|
|
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.
|
|
49
|
-
"@iconify/json": "^2.2.
|
|
50
|
-
"@nuxt/kit": "^4.1.
|
|
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.
|
|
55
|
-
"@witchcraft/ui": "^0.3.
|
|
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.
|
|
63
|
-
"unplugin-vue-components": "^29.
|
|
64
|
-
"zod": "^4.1.
|
|
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.
|
|
76
|
+
"@nuxt/schema": "^4.1.3",
|
|
72
77
|
"@nuxt/test-utils": "^3.19.2",
|
|
73
|
-
"@tailwindcss/cli": "^4.1.
|
|
78
|
+
"@tailwindcss/cli": "^4.1.14",
|
|
74
79
|
"@types/node": "latest",
|
|
75
80
|
"changelogen": "^0.6.2",
|
|
76
|
-
"cross-env": "^10.
|
|
77
|
-
"drizzle-orm": "^0.44.
|
|
78
|
-
"electron": "^38.
|
|
79
|
-
"eslint": "^9.
|
|
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.
|
|
82
|
-
"reka-ui": "^2.5.
|
|
83
|
-
"tailwindcss": "^4.1.
|
|
84
|
-
"typescript": "^5.9.
|
|
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.
|
|
91
|
+
"vue-tsc": "^3.1.1"
|
|
87
92
|
},
|
|
88
93
|
"release": {
|
|
89
94
|
"extends": [
|