@witchcraft/nuxt-auth 0.6.0-beta.4 → 0.6.0-beta.5
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 +7 -2
- package/dist/module.d.mts +1 -2
- package/dist/module.json +1 -1
- package/dist/module.mjs +1 -1
- package/dist/runtime/build/genAuthSecretKeys.d.ts +1 -1
- package/dist/runtime/components/ExternalCallback.vue +2 -2
- package/dist/runtime/components/ExternalCode.vue +2 -2
- package/dist/runtime/components/LoginProviderButtons.client.vue +9 -9
- package/dist/runtime/components/MockBypassRegistrationFields.vue +2 -2
- package/dist/runtime/components/SessionStatus.vue +4 -4
- package/dist/runtime/components/UserRegistration.vue +8 -8
- package/dist/runtime/composables/useAuth.d.ts +5 -5
- package/dist/runtime/composables/useAuth.js +9 -9
- package/dist/runtime/composables/useAuthExternalCallback.js +2 -2
- package/dist/runtime/composables/useAuthExternalCode.js +1 -1
- package/dist/runtime/electron/main/ElectronAuth.d.ts +29 -29
- package/dist/runtime/electron/main/ElectronAuth.js +13 -21
- package/dist/runtime/electron/main/setupElectronAuthMain.d.ts +9 -33
- package/dist/runtime/electron/main/setupElectronAuthMain.js +19 -16
- package/dist/runtime/electron/preload/index.d.ts +1 -1
- package/dist/runtime/electron/preload/index.js +1 -1
- package/dist/runtime/plugins/server/devMock.js +2 -1
- package/dist/runtime/server/utils/assertEventWithAuthorizedUser.d.ts +1 -1
- package/dist/runtime/server/utils/createAuthMiddleware.d.ts +1 -1
- package/dist/runtime/server/utils/createAuthSchema.d.ts +1 -1
- package/dist/runtime/server/utils/createBetterAuth.d.ts +2 -2
- package/dist/runtime/server/utils/createBetterAuth.js +5 -4
- package/dist/types.d.mts +0 -2
- package/package.json +7 -4
package/README.md
CHANGED
|
@@ -341,11 +341,16 @@ sequenceDiagram
|
|
|
341
341
|
Preload->>Main: ipc
|
|
342
342
|
Main->>Server: GET /get-session
|
|
343
343
|
Server-->>Main: { user }
|
|
344
|
-
Main->>Main:
|
|
345
|
-
|
|
344
|
+
Main->>Main: persistExternalSession: beforePersistExternalSession, cookies, localStorage auth:user
|
|
345
|
+
alt replacement window
|
|
346
|
+
Main->>Renderer: loadURL /auth/register or postRegisteredLogin, the middleware sees auth:user
|
|
347
|
+
else same window
|
|
348
|
+
Renderer->>Renderer: getSession then navigateTo, the middleware sees auth:user
|
|
349
|
+
end
|
|
346
350
|
Renderer->>Server: proxied requests carry the cookie
|
|
347
351
|
```
|
|
348
352
|
|
|
353
|
+
Apps that switch windows should make the replacement window and its session current in `beforePersistExternalSession`. Main loads the final route only when the window changed. Otherwise `useAuthExternalCallback` navigates the original renderer after `exchangeSession` returns.
|
|
349
354
|
|
|
350
355
|
Note that unlike better-auth's default implementation, `@witchcraft/nuxt-electron`'s proxy allows us the real cookie on the session, stored against the origin of `publicServerUrl` (your auth server), and it will be sent with proxied requests.
|
|
351
356
|
|
package/dist/module.d.mts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import * as _nuxt_schema from '@nuxt/schema';
|
|
2
2
|
import { CookieSerializeOptions } from 'cookie-es';
|
|
3
|
+
import { useAuth } from '../dist/runtime/composables/useAuth.js';
|
|
3
4
|
import { SessionCookieOptions } from '../dist/runtime/types.js';
|
|
4
5
|
export * from '../dist/runtime/types.js';
|
|
5
|
-
export * from '../dist/runtime/server/utils/createAuthSchema.js';
|
|
6
|
-
import { useAuth } from '../dist/runtime/composables/useAuth.js';
|
|
7
6
|
|
|
8
7
|
declare global {
|
|
9
8
|
}
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -64,7 +64,7 @@ const module$1 = defineNuxtModule({
|
|
|
64
64
|
prefix: "Auth",
|
|
65
65
|
global: true
|
|
66
66
|
});
|
|
67
|
-
if (process.env.NODE_ENV !== "production" && (!process.env.NUXT_AUTH_SECRET || process.env.NUXT_AUTH_SECRET
|
|
67
|
+
if (process.env.NODE_ENV !== "production" && (!process.env.NUXT_AUTH_SECRET || process.env.NUXT_AUTH_SECRET?.length === 0)) {
|
|
68
68
|
logger.warn("$NUXT_AUTH_SECRET is missing or empty. This is not recommended.");
|
|
69
69
|
}
|
|
70
70
|
nuxt.options.runtimeConfig.public.auth = defu(
|
|
@@ -18,8 +18,8 @@
|
|
|
18
18
|
@submit.prevent="authorize(manualAccessToken)"
|
|
19
19
|
>
|
|
20
20
|
<WInputDeprecated
|
|
21
|
-
placeholder="Paste Code Here"
|
|
22
21
|
v-model="manualAccessToken"
|
|
22
|
+
placeholder="Paste Code Here"
|
|
23
23
|
@update:model-value="error = void 0"
|
|
24
24
|
/>
|
|
25
25
|
<div
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
{{ error }}
|
|
30
30
|
</div>
|
|
31
31
|
<WButton
|
|
32
|
-
:disabled="!manualAccessToken || manualAccessToken.length === 0"
|
|
33
32
|
type="submit"
|
|
33
|
+
:disabled="!manualAccessToken || manualAccessToken.length === 0"
|
|
34
34
|
>
|
|
35
35
|
Submit
|
|
36
36
|
</WButton>
|
|
@@ -22,7 +22,6 @@
|
|
|
22
22
|
{{ openAppText }}
|
|
23
23
|
</NuxtLink>
|
|
24
24
|
<WButton
|
|
25
|
-
:title="copyTitle"
|
|
26
25
|
class="
|
|
27
26
|
text-xl
|
|
28
27
|
bg-accent-100
|
|
@@ -39,6 +38,7 @@
|
|
|
39
38
|
hover:text-accent-500
|
|
40
39
|
break-all
|
|
41
40
|
"
|
|
41
|
+
:title="copyTitle"
|
|
42
42
|
@click="copyToken"
|
|
43
43
|
>
|
|
44
44
|
{{ accessToken }}
|
|
@@ -48,10 +48,10 @@
|
|
|
48
48
|
|
|
49
49
|
<script setup>
|
|
50
50
|
import { useAuthExternalCode } from "../composables/useAuthExternalCode.js";
|
|
51
|
-
const { accessToken, deepLinkUrl, copyToken } = useAuthExternalCode();
|
|
52
51
|
defineProps({
|
|
53
52
|
openAppText: { type: String, required: false, default: "Open App and Authorize" },
|
|
54
53
|
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:" },
|
|
55
54
|
copyTitle: { type: String, required: false, default: "Click to Copy" }
|
|
56
55
|
});
|
|
56
|
+
const { accessToken, deepLinkUrl, copyToken } = useAuthExternalCode();
|
|
57
57
|
</script>
|
|
@@ -15,30 +15,30 @@
|
|
|
15
15
|
</template>
|
|
16
16
|
|
|
17
17
|
<script>
|
|
18
|
-
|
|
18
|
+
|
|
19
19
|
</script>
|
|
20
20
|
|
|
21
21
|
<script setup>
|
|
22
22
|
import { pick } from "@alanscodelog/utils/pick";
|
|
23
23
|
import WAuth from "@witchcraft/ui/components/WAuth";
|
|
24
|
-
import defu from "defu";
|
|
24
|
+
import { defu } from "defu";
|
|
25
25
|
import { useRuntimeConfig } from "#app";
|
|
26
26
|
import { computed, useAttrs } from "#imports";
|
|
27
27
|
import { providerStyles as baseProviderStyles } from "../core/providerStyles.js";
|
|
28
|
-
if (import.meta.dev) {
|
|
29
|
-
console.warn("[nuxt-auth] <LoginProviderButtons> is deprecated and will be removed in a future version.");
|
|
30
|
-
}
|
|
31
28
|
defineOptions({
|
|
32
29
|
inheritAttrs: false
|
|
33
30
|
});
|
|
34
|
-
const rc = useRuntimeConfig();
|
|
35
|
-
const config = rc.public.auth;
|
|
36
|
-
const enabledProviders = config.enabledProviders;
|
|
37
|
-
const $attrs = useAttrs();
|
|
38
31
|
const emit = defineEmits(["login"]);
|
|
39
32
|
const props = defineProps({
|
|
40
33
|
providerStyles: { type: Object, required: false, default: () => ({}) }
|
|
41
34
|
});
|
|
35
|
+
if (import.meta.dev) {
|
|
36
|
+
console.warn("[nuxt-auth] <LoginProviderButtons> is deprecated and will be removed in a future version.");
|
|
37
|
+
}
|
|
38
|
+
const rc = useRuntimeConfig();
|
|
39
|
+
const config = rc.public.auth;
|
|
40
|
+
const enabledProviders = config.enabledProviders;
|
|
41
|
+
const $attrs = useAttrs();
|
|
42
42
|
const fullProviderStyles = computed(() => defu(
|
|
43
43
|
props.providerStyles,
|
|
44
44
|
pick(baseProviderStyles, enabledProviders)
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
<template>
|
|
2
2
|
<WSimpleInput
|
|
3
|
+
v-model="username"
|
|
3
4
|
class="bg-bg dark:bg-neutral-800"
|
|
4
5
|
aria-label="Username"
|
|
5
6
|
placeholder="Username"
|
|
6
|
-
v-model="username"
|
|
7
7
|
/>
|
|
8
8
|
<WCheckbox
|
|
9
|
+
v-model="bypassRegistration"
|
|
9
10
|
class="bg-bg dark:bg-neutral-800 dark:checked:after:border-neutral-800"
|
|
10
11
|
label="Bypass Registration for New Users"
|
|
11
|
-
v-model="bypassRegistration"
|
|
12
12
|
/>
|
|
13
13
|
</template>
|
|
14
14
|
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
</span>
|
|
30
30
|
</slot>
|
|
31
31
|
<WButton
|
|
32
|
-
:unstyle="true"
|
|
33
32
|
class=""
|
|
33
|
+
:unstyle="true"
|
|
34
34
|
@click="logout()"
|
|
35
35
|
>
|
|
36
36
|
Logout
|
|
@@ -76,6 +76,9 @@
|
|
|
76
76
|
import { computed, useRuntimeConfig, useState } from "#imports";
|
|
77
77
|
import { useAuth } from "../composables/useAuth";
|
|
78
78
|
import { isExpiredStateKey } from "../types.js";
|
|
79
|
+
const props = defineProps({
|
|
80
|
+
usernameLink: { type: Function, required: false, default: void 0 }
|
|
81
|
+
});
|
|
79
82
|
const {
|
|
80
83
|
logout,
|
|
81
84
|
user,
|
|
@@ -83,9 +86,6 @@ const {
|
|
|
83
86
|
isAuthenticated,
|
|
84
87
|
isExternal
|
|
85
88
|
} = useAuth();
|
|
86
|
-
const props = defineProps({
|
|
87
|
-
usernameLink: { type: Function, required: false, default: void 0 }
|
|
88
|
-
});
|
|
89
89
|
const publicServerUrl = useRuntimeConfig().public.auth.publicServerUrl;
|
|
90
90
|
const isExpired = useState(isExpiredStateKey, () => false);
|
|
91
91
|
const isExternalExpiredUser = computed(() => user.value?.type === "external" && isExpired.value);
|
|
@@ -14,27 +14,27 @@
|
|
|
14
14
|
>
|
|
15
15
|
<div class="flex flex-col items-stretch">
|
|
16
16
|
<label
|
|
17
|
-
:for="usernameId"
|
|
18
17
|
class="text-sm"
|
|
18
|
+
:for="usernameId"
|
|
19
19
|
>
|
|
20
20
|
Username
|
|
21
21
|
</label>
|
|
22
22
|
<WAsyncValidatedInput
|
|
23
23
|
:id="usernameId"
|
|
24
|
+
v-model="username"
|
|
24
25
|
:errors="isDebouncing || username === '' ? [] : errors"
|
|
25
26
|
:status="status"
|
|
26
27
|
:status-text="statusText"
|
|
27
28
|
:can-submit="canSubmit"
|
|
28
29
|
:input-valid="isDebouncing || inputValid"
|
|
29
|
-
v-model="username"
|
|
30
30
|
/>
|
|
31
31
|
</div>
|
|
32
|
-
<slot/>
|
|
32
|
+
<slot />
|
|
33
33
|
<WButton
|
|
34
34
|
:id="submitId"
|
|
35
|
-
:disabled="!canSubmit"
|
|
36
35
|
class="w-full"
|
|
37
36
|
type="submit"
|
|
37
|
+
:disabled="!canSubmit"
|
|
38
38
|
>
|
|
39
39
|
Register
|
|
40
40
|
</WButton>
|
|
@@ -42,22 +42,22 @@
|
|
|
42
42
|
</template>
|
|
43
43
|
|
|
44
44
|
<script>
|
|
45
|
-
|
|
45
|
+
|
|
46
46
|
</script>
|
|
47
47
|
|
|
48
48
|
<script setup>
|
|
49
49
|
import { WAsyncValidatedInput } from "@witchcraft/ui/components";
|
|
50
50
|
import { useId } from "#imports";
|
|
51
51
|
import { useAuthUserRegistration } from "../composables/useAuthUserRegistration.js";
|
|
52
|
-
if (import.meta.dev) {
|
|
53
|
-
console.warn("[nuxt-auth] <UserRegistration> is deprecated and will be removed in a future version.");
|
|
54
|
-
}
|
|
55
52
|
const props = defineProps({
|
|
56
53
|
auth: { type: null, required: false },
|
|
57
54
|
debounce: { type: Number, required: false },
|
|
58
55
|
usernameSchema: { type: Object, required: false },
|
|
59
56
|
id: { type: String, required: false }
|
|
60
57
|
});
|
|
58
|
+
if (import.meta.dev) {
|
|
59
|
+
console.warn("[nuxt-auth] <UserRegistration> is deprecated and will be removed in a future version.");
|
|
60
|
+
}
|
|
61
61
|
const usernameId = props.id ?? useId();
|
|
62
62
|
const submitId = useId();
|
|
63
63
|
const {
|
|
@@ -3,25 +3,25 @@ import type { BetterAuthClientOptions } from "better-auth";
|
|
|
3
3
|
import type { AuthUser } from "../types.js";
|
|
4
4
|
type AuthListenerHook = (options: {
|
|
5
5
|
scope?: "all" | "others";
|
|
6
|
-
}) => void
|
|
6
|
+
}) => void | Promise<void>;
|
|
7
7
|
type AuthListenerHooks = "beforeLogout" | "beforeDelete" | "afterDelete";
|
|
8
8
|
declare const hooks: {
|
|
9
9
|
beforeLogout: AuthListenerHook[];
|
|
10
10
|
beforeDelete: (({ id }: {
|
|
11
11
|
id: string;
|
|
12
|
-
}) => void)[];
|
|
12
|
+
}) => void | Promise<void>)[];
|
|
13
13
|
afterDelete: (({ id }: {
|
|
14
14
|
id: string;
|
|
15
|
-
}) => void)[];
|
|
15
|
+
}) => void | Promise<void>)[];
|
|
16
16
|
};
|
|
17
|
-
export declare
|
|
17
|
+
export declare function useAuth({ usernameSchema, userSchema, clientOptions }?: {
|
|
18
18
|
/** Username schema used when a local-only user checks availability locally. */
|
|
19
19
|
usernameSchema?: StandardSchemaV1<string, string>;
|
|
20
20
|
/** Validates users read from storage, e.g. `zAuthUserStored`. */
|
|
21
21
|
userSchema?: StandardSchemaV1;
|
|
22
22
|
/** Options passed to the better-auth client in full, merged over the module defaults with `defu`. */
|
|
23
23
|
clientOptions?: BetterAuthClientOptions;
|
|
24
|
-
})
|
|
24
|
+
}): {
|
|
25
25
|
on: <TKey extends AuthListenerHooks>(hook: TKey, listener: (typeof hooks)[TKey][number]) => void;
|
|
26
26
|
off: <TKey extends AuthListenerHooks>(hook: TKey, listener: (typeof hooks)[TKey][number]) => void;
|
|
27
27
|
user: import("vue").Ref<{
|
|
@@ -17,7 +17,7 @@ const hooks = {
|
|
|
17
17
|
beforeDelete: [],
|
|
18
18
|
afterDelete: []
|
|
19
19
|
};
|
|
20
|
-
export
|
|
20
|
+
export function useAuth({ usernameSchema = defaultZodUsernameSchema, userSchema, clientOptions } = {}) {
|
|
21
21
|
const config = useRuntimeConfig().public.auth;
|
|
22
22
|
const doFetch = useState(fetchStateKey);
|
|
23
23
|
const userData = useState(userStorageKey, () => void 0);
|
|
@@ -34,7 +34,7 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
34
34
|
// on electron, the relative paths used resolve to app://... instead of publicServerUrl
|
|
35
35
|
// this would be fine (electron proxies the requests to the app) except better auth errors on such a schema
|
|
36
36
|
// so we have to write the url for it to fetch from
|
|
37
|
-
customFetchImpl: config.publicServerUrl ? (input, init) => {
|
|
37
|
+
customFetchImpl: config.publicServerUrl ? async (input, init) => {
|
|
38
38
|
const url = new URL(
|
|
39
39
|
typeof input === "string" ? input : input.url ?? String(input),
|
|
40
40
|
config.publicServerUrl
|
|
@@ -67,7 +67,7 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
67
67
|
const key = "externalApiActionsKey" in plugin ? plugin.externalApiActionsKey : void 0;
|
|
68
68
|
if (typeof key !== "string") continue;
|
|
69
69
|
const actions = client[key];
|
|
70
|
-
if (actions.isActive()
|
|
70
|
+
if (actions.isActive() && typeof actions.login === "function") return actions;
|
|
71
71
|
}
|
|
72
72
|
return void 0;
|
|
73
73
|
}
|
|
@@ -127,7 +127,7 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
127
127
|
assertIsOnClient("logout");
|
|
128
128
|
setFetchUserOnNavigation();
|
|
129
129
|
const isLocal = userData.value?.type === "local";
|
|
130
|
-
await Promise.allSettled(hooks.beforeLogout.map((listener) => listener({ scope })));
|
|
130
|
+
await Promise.allSettled(hooks.beforeLogout.map(async (listener) => listener({ scope })));
|
|
131
131
|
if (scope === "others") {
|
|
132
132
|
if (!isLocal) {
|
|
133
133
|
await client.revokeOtherSessions();
|
|
@@ -138,7 +138,7 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
138
138
|
client.localOnlyUsers.logout();
|
|
139
139
|
}
|
|
140
140
|
if (!isLocal) {
|
|
141
|
-
await (scope === "all" ? client.revokeSessions() : client.signOut()).catch(() => void 0).finally(() => navigateTo(authRoutes.unauthenticated, { external: true }));
|
|
141
|
+
await (scope === "all" ? client.revokeSessions() : client.signOut()).catch(() => void 0).finally(async () => navigateTo(authRoutes.unauthenticated, { external: true }));
|
|
142
142
|
}
|
|
143
143
|
userData.value = void 0;
|
|
144
144
|
localStorage.removeItem(externalExpiryStorageKey);
|
|
@@ -163,7 +163,7 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
163
163
|
if (!target) throw new Error("delete: there is no active user and no id was given.");
|
|
164
164
|
const isLocal = target === current?.id ? current.type === "local" : true;
|
|
165
165
|
setFetchUserOnNavigation();
|
|
166
|
-
await Promise.allSettled(hooks.beforeDelete.map((listener) => listener({ id: target })));
|
|
166
|
+
await Promise.allSettled(hooks.beforeDelete.map(async (listener) => listener({ id: target })));
|
|
167
167
|
if (isLocal) {
|
|
168
168
|
assertIsOnClient("delete");
|
|
169
169
|
if (external?.local) await external.local.delete(target);
|
|
@@ -175,7 +175,7 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
175
175
|
userData.value = void 0;
|
|
176
176
|
await navigateTo(authRoutes.unauthenticated, { external: true });
|
|
177
177
|
}
|
|
178
|
-
await Promise.allSettled(hooks.afterDelete.map((listener) => listener({ id: target })));
|
|
178
|
+
await Promise.allSettled(hooks.afterDelete.map(async (listener) => listener({ id: target })));
|
|
179
179
|
}
|
|
180
180
|
async function update(patch) {
|
|
181
181
|
const current = userData.value;
|
|
@@ -203,7 +203,7 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
203
203
|
}
|
|
204
204
|
async function list() {
|
|
205
205
|
assertIsOnClient("list");
|
|
206
|
-
if (external?.local) return
|
|
206
|
+
if (external?.local) return external.local.list();
|
|
207
207
|
return client.localOnlyUsers.list();
|
|
208
208
|
}
|
|
209
209
|
function on(hook, listener) {
|
|
@@ -234,4 +234,4 @@ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema,
|
|
|
234
234
|
list,
|
|
235
235
|
client
|
|
236
236
|
};
|
|
237
|
-
}
|
|
237
|
+
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { ref } from "vue";
|
|
2
|
-
import { useAuth } from "./useAuth.js";
|
|
3
2
|
import {
|
|
4
3
|
navigateTo,
|
|
5
4
|
useRoute,
|
|
6
5
|
useRuntimeConfig
|
|
7
6
|
} from "#app";
|
|
8
7
|
import { deserializeAuthLocalUser } from "../utils/deserializeAuthLocalUser.js";
|
|
8
|
+
import { useAuth } from "./useAuth.js";
|
|
9
9
|
export function useAuthExternalCallback(opts) {
|
|
10
10
|
const rc = useRuntimeConfig();
|
|
11
11
|
const route = useRoute();
|
|
@@ -36,7 +36,7 @@ export function useAuthExternalCallback(opts) {
|
|
|
36
36
|
const { data } = await client.getSession().catch(() => ({ data: void 0 }));
|
|
37
37
|
const user = data?.user ? deserializeAuthLocalUser(data.user) : void 0;
|
|
38
38
|
const routes = rc.public.auth.authRoutes;
|
|
39
|
-
const successPath = user && user.isRegistered
|
|
39
|
+
const successPath = user && !user.isRegistered ? routes.register : routes.postRegisteredLogin;
|
|
40
40
|
await navigateTo(opts.successPath ?? successPath);
|
|
41
41
|
}
|
|
42
42
|
async function requestExternalAuth() {
|
|
@@ -2,7 +2,7 @@ import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
|
2
2
|
import type { BaseLogger } from "@witchcraft/nuxt-logger/types";
|
|
3
3
|
import type { BrowserWindow, Session } from "electron";
|
|
4
4
|
import type { ModulePublicRuntimeConfig } from "../../../module.js";
|
|
5
|
-
import {
|
|
5
|
+
import type { AuthUserStored, SessionCookieOptions } from "../../types.js";
|
|
6
6
|
/**
|
|
7
7
|
* Main-process auth helper for Electron apps.
|
|
8
8
|
*
|
|
@@ -15,33 +15,31 @@ import { type SessionCookieOptions } from "../../types.js";
|
|
|
15
15
|
* - keeping the stored expiry in step when the server rolls the session
|
|
16
16
|
* - local-user session injection
|
|
17
17
|
*/
|
|
18
|
-
export declare class ElectronAuth {
|
|
19
|
-
private scheme;
|
|
20
|
-
private callbackPath;
|
|
21
|
-
private publicServerUrl;
|
|
22
|
-
private getSession;
|
|
23
|
-
private getWindow;
|
|
24
|
-
private getActiveUserId;
|
|
25
|
-
private sessionCookieOpts;
|
|
26
|
-
private sessionExpiresAt;
|
|
27
|
-
private cookiePrefix;
|
|
28
|
-
private userIdCookieName;
|
|
29
|
-
private useSecureCookies;
|
|
30
|
-
private logger;
|
|
31
|
-
private userSchema;
|
|
32
|
-
private
|
|
18
|
+
export declare class ElectronAuth<TUser extends AuthUserStored = AuthUserStored> {
|
|
19
|
+
private readonly scheme;
|
|
20
|
+
private readonly callbackPath;
|
|
21
|
+
private readonly publicServerUrl;
|
|
22
|
+
private readonly getSession;
|
|
23
|
+
private readonly getWindow;
|
|
24
|
+
private readonly getActiveUserId;
|
|
25
|
+
private readonly sessionCookieOpts;
|
|
26
|
+
private readonly sessionExpiresAt;
|
|
27
|
+
private readonly cookiePrefix;
|
|
28
|
+
private readonly userIdCookieName;
|
|
29
|
+
private readonly useSecureCookies;
|
|
30
|
+
private readonly logger;
|
|
31
|
+
private readonly userSchema;
|
|
32
|
+
private readonly beforePersistExternalSession;
|
|
33
33
|
/** Sessions whose cookie changes are already watched, so a window switch does not watch twice. */
|
|
34
|
-
private watchedSessions;
|
|
35
|
-
constructor({ scheme, userSchema, callbackPath, publicServerUrl, getSession, getWindow, getActiveUserId, sessionCookieOpts, sessionExpiresAt, cookiePrefix, userIdCookieName, logger,
|
|
34
|
+
private readonly watchedSessions;
|
|
35
|
+
constructor({ scheme, userSchema, callbackPath, publicServerUrl, getSession, getWindow, getActiveUserId, sessionCookieOpts, sessionExpiresAt, cookiePrefix, userIdCookieName, logger, beforePersistExternalSession }: {
|
|
36
36
|
/** Custom protocol scheme, from `rc.auth.deeplinkSchemes.electron`. No trailing colon. */
|
|
37
37
|
scheme: string;
|
|
38
38
|
/**
|
|
39
39
|
* Parses the user before it is written to the window, e.g. `zAuthUserStored`.
|
|
40
40
|
* Build it from the db table so there is one source of truth for the user shape.
|
|
41
41
|
*/
|
|
42
|
-
userSchema: StandardSchemaV1<unknown,
|
|
43
|
-
id: string;
|
|
44
|
-
}>;
|
|
42
|
+
userSchema: StandardSchemaV1<unknown, TUser>;
|
|
45
43
|
/** Deeplink path the code page bounces to, from `rc.auth.authRoutes.deeplink`. */
|
|
46
44
|
callbackPath: string;
|
|
47
45
|
/**
|
|
@@ -50,7 +48,7 @@ export declare class ElectronAuth {
|
|
|
50
48
|
publicServerUrl: string;
|
|
51
49
|
/** Returns the session the window uses, e.g. `() => ses`, undefined until the window is created. Its cookies are what the proxy sends. */
|
|
52
50
|
getSession: () => Session | undefined;
|
|
53
|
-
/** Returns the window auth
|
|
51
|
+
/** Returns the window auth flows use. It receives deeplink callbacks and is where the module writes window-local auth data, e.g. `() => win`, null when none exists yet. */
|
|
54
52
|
getWindow: () => BrowserWindow | undefined | null;
|
|
55
53
|
/** Returns the id of the user the app treats as active, e.g. `() => activeUserId`. */
|
|
56
54
|
getActiveUserId: () => string | undefined;
|
|
@@ -63,13 +61,15 @@ export declare class ElectronAuth {
|
|
|
63
61
|
/** Name of the cookie that records which user a window's session belongs to. @default "userId" */
|
|
64
62
|
userIdCookieName?: string;
|
|
65
63
|
logger?: BaseLogger;
|
|
66
|
-
/**
|
|
67
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Called after token exchange and before the external session is written.
|
|
66
|
+
*
|
|
67
|
+
* If the app switches windows, it must make the replacement window and its session current before returning, since `getWindow` and `getSession` are read after this runs.
|
|
68
|
+
* If the app does not switch windows, it should record the active user here so the existing window and session stay in step.
|
|
69
|
+
*/
|
|
70
|
+
beforePersistExternalSession?: (info: {
|
|
68
71
|
win: BrowserWindow;
|
|
69
|
-
user:
|
|
70
|
-
id: string;
|
|
71
|
-
username: string;
|
|
72
|
-
};
|
|
72
|
+
user: TUser;
|
|
73
73
|
}) => void | Promise<void>;
|
|
74
74
|
},
|
|
75
75
|
/**
|
|
@@ -104,7 +104,7 @@ export declare class ElectronAuth {
|
|
|
104
104
|
* folder setup, reload) after the await. No hooks, the class stays
|
|
105
105
|
* unaware of app details.
|
|
106
106
|
*/
|
|
107
|
-
|
|
107
|
+
persistExternalSession(win: BrowserWindow, { user, sessionToken, expiresAt }: {
|
|
108
108
|
user: unknown;
|
|
109
109
|
sessionToken: string;
|
|
110
110
|
/** Epoch ms, written to both cookies and to the expiry key. Defaults to `sessionExpiresAt` from now. */
|
|
@@ -13,7 +13,7 @@ export class ElectronAuth {
|
|
|
13
13
|
useSecureCookies;
|
|
14
14
|
logger;
|
|
15
15
|
userSchema;
|
|
16
|
-
|
|
16
|
+
beforePersistExternalSession;
|
|
17
17
|
/** Sessions whose cookie changes are already watched, so a window switch does not watch twice. */
|
|
18
18
|
watchedSessions = /* @__PURE__ */ new WeakSet();
|
|
19
19
|
constructor({
|
|
@@ -29,7 +29,7 @@ export class ElectronAuth {
|
|
|
29
29
|
cookiePrefix = "better-auth",
|
|
30
30
|
userIdCookieName = "userId",
|
|
31
31
|
logger,
|
|
32
|
-
|
|
32
|
+
beforePersistExternalSession
|
|
33
33
|
}, rc) {
|
|
34
34
|
this.scheme = scheme;
|
|
35
35
|
this.userSchema = userSchema;
|
|
@@ -49,7 +49,7 @@ export class ElectronAuth {
|
|
|
49
49
|
this.userIdCookieName = userIdCookieName;
|
|
50
50
|
this.useSecureCookies = new URL(publicServerUrl).protocol === "https:";
|
|
51
51
|
this.logger = logger;
|
|
52
|
-
this.
|
|
52
|
+
this.beforePersistExternalSession = beforePersistExternalSession;
|
|
53
53
|
}
|
|
54
54
|
/** Electron spells `sameSite: "none"` as `"no_restriction"`. */
|
|
55
55
|
get _cookieSetOpts() {
|
|
@@ -115,9 +115,7 @@ export class ElectronAuth {
|
|
|
115
115
|
});
|
|
116
116
|
}
|
|
117
117
|
if (!host || protocol !== "http:" && protocol !== "https:") {
|
|
118
|
-
throw new Error(
|
|
119
|
-
`ElectronAuth: cannot store the session cookie for publicServerUrl "${this.publicServerUrl}". Cookies need an http(s) origin, from getPaths().publicServerUrl for example.`
|
|
120
|
-
);
|
|
118
|
+
throw new Error(`ElectronAuth: cannot store the session cookie for publicServerUrl "${this.publicServerUrl}". Cookies need an http(s) origin, from getPaths().publicServerUrl for example.`);
|
|
121
119
|
}
|
|
122
120
|
return `${protocol}//${host}/`;
|
|
123
121
|
}
|
|
@@ -129,10 +127,12 @@ export class ElectronAuth {
|
|
|
129
127
|
* folder setup, reload) after the await. No hooks, the class stays
|
|
130
128
|
* unaware of app details.
|
|
131
129
|
*/
|
|
132
|
-
async
|
|
133
|
-
const ses = this.getSession();
|
|
134
|
-
if (!ses) throw new Error("ElectronAuth: finishLogin called before the window session existed");
|
|
130
|
+
async persistExternalSession(win, { user, sessionToken, expiresAt = Date.now() + this.sessionExpiresAt }) {
|
|
135
131
|
const parsedUser = this._parseUser(user);
|
|
132
|
+
await this.beforePersistExternalSession?.({ win, user: parsedUser });
|
|
133
|
+
const ses = this.getSession();
|
|
134
|
+
if (!ses) throw new Error("ElectronAuth: persistExternalSession called before the window session existed");
|
|
135
|
+
const targetWin = this.getWindow() ?? win;
|
|
136
136
|
const cookieUrl = this._cookieUrl();
|
|
137
137
|
const cookieExpiry = Math.floor(expiresAt / 1e3);
|
|
138
138
|
await ses.cookies.set({
|
|
@@ -153,13 +153,9 @@ export class ElectronAuth {
|
|
|
153
153
|
expirationDate: cookieExpiry,
|
|
154
154
|
httpOnly: true
|
|
155
155
|
});
|
|
156
|
-
await
|
|
157
|
-
`localStorage.setItem(${JSON.stringify(userStorageKey)}, ${JSON.stringify(JSON.stringify({ ...parsedUser, type: "external" }))});localStorage.setItem(${JSON.stringify(externalExpiryStorageKey)}, ${JSON.stringify(String(expiresAt))})`
|
|
158
|
-
);
|
|
156
|
+
await targetWin.webContents.executeJavaScript(`localStorage.setItem(${JSON.stringify(userStorageKey)}, ${JSON.stringify(JSON.stringify({ ...parsedUser, type: "external" }))});localStorage.setItem(${JSON.stringify(externalExpiryStorageKey)}, ${JSON.stringify(String(expiresAt))})`);
|
|
159
157
|
this._watchSessionCookies(ses);
|
|
160
|
-
this.logger?.debug({ ns: "auth:
|
|
161
|
-
const { id, username } = parsedUser;
|
|
162
|
-
await this.onFinishLogin?.({ win, user: { id, username } });
|
|
158
|
+
this.logger?.debug({ ns: "auth:persistExternalSession", win: targetWin.id });
|
|
163
159
|
}
|
|
164
160
|
/** Injects a local-only user into the window as the active user. */
|
|
165
161
|
async saveLocalUserSession(win, authUser) {
|
|
@@ -167,9 +163,7 @@ export class ElectronAuth {
|
|
|
167
163
|
if (parsedUser.id !== this.getActiveUserId()) {
|
|
168
164
|
throw new Error(`ElectronAuth: cannot save credentials for user ${parsedUser.id}, the active user is ${this.getActiveUserId()}.`);
|
|
169
165
|
}
|
|
170
|
-
await win.webContents.executeJavaScript(
|
|
171
|
-
`localStorage.setItem(${JSON.stringify(userStorageKey)}, ${JSON.stringify(JSON.stringify({ ...parsedUser, type: "local" }))})`
|
|
172
|
-
);
|
|
166
|
+
await win.webContents.executeJavaScript(`localStorage.setItem(${JSON.stringify(userStorageKey)}, ${JSON.stringify(JSON.stringify({ ...parsedUser, type: "local" }))})`);
|
|
173
167
|
}
|
|
174
168
|
_parseUser(value) {
|
|
175
169
|
const result = this.userSchema["~standard"].validate(value);
|
|
@@ -192,9 +186,7 @@ export class ElectronAuth {
|
|
|
192
186
|
const win = this.getWindow();
|
|
193
187
|
if (!win) return;
|
|
194
188
|
const expiresAt = cookie.expirationDate * 1e3;
|
|
195
|
-
void win.webContents.executeJavaScript(
|
|
196
|
-
`localStorage.setItem(${JSON.stringify(externalExpiryStorageKey)}, ${JSON.stringify(String(expiresAt))})`
|
|
197
|
-
).catch(() => void 0);
|
|
189
|
+
void win.webContents.executeJavaScript(`localStorage.setItem(${JSON.stringify(externalExpiryStorageKey)}, ${JSON.stringify(String(expiresAt))})`).catch(() => void 0);
|
|
198
190
|
});
|
|
199
191
|
}
|
|
200
192
|
}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { type BetterAuthClientOptions } from "better-auth/client";
|
|
3
|
-
import { type BrowserWindow, type Session } from "electron";
|
|
4
|
-
import { ElectronAuth } from "./ElectronAuth.js";
|
|
1
|
+
import type { BetterAuthClientOptions } from "better-auth/client";
|
|
5
2
|
import type { ModulePublicRuntimeConfig } from "../../../module.js";
|
|
3
|
+
import type { AuthUserStored } from "../../types.js";
|
|
4
|
+
import { ElectronAuth } from "./ElectronAuth.js";
|
|
6
5
|
/**
|
|
7
6
|
* Wires the main process side of an electron sign-in by setting up:
|
|
8
7
|
* - the better-auth client the preload bridges talk to
|
|
@@ -14,41 +13,18 @@ import type { ModulePublicRuntimeConfig } from "../../../module.js";
|
|
|
14
13
|
*
|
|
15
14
|
* Call it once, before `app.whenReady()`.
|
|
16
15
|
*/
|
|
17
|
-
export declare function setupElectronAuthMain(rc: ModulePublicRuntimeConfig["auth"], { publicServerUrl, getSession, userSchema, getWindow, getActiveUserId, clientOptions, userIdCookieName, enableMockingInTestEnvs,
|
|
16
|
+
export declare function setupElectronAuthMain<TUser extends AuthUserStored = AuthUserStored>(rc: ModulePublicRuntimeConfig["auth"], { publicServerUrl, getSession, userSchema, getWindow, getActiveUserId, clientOptions, userIdCookieName, enableMockingInTestEnvs, beforePersistExternalSession }: {
|
|
18
17
|
/** Public server url of the better-auth server, e.g. `getPaths().publicServerUrl`. */
|
|
19
18
|
publicServerUrl: string;
|
|
20
|
-
/** Returns the session the window uses, e.g. `() => ses`, undefined until the window is created. Its cookies are what the proxy sends. */
|
|
21
|
-
getSession: () => Session | undefined;
|
|
22
|
-
/**
|
|
23
|
-
* Parses the user before it is written to the window, e.g. `zAuthUserStored`.
|
|
24
|
-
* Build it from the db table so there is one source of truth for the user shape.
|
|
25
|
-
*/
|
|
26
|
-
userSchema: StandardSchemaV1<unknown, {
|
|
27
|
-
id: string;
|
|
28
|
-
}>;
|
|
29
|
-
/** Returns the window the bridges act on, null when none exists yet. */
|
|
30
|
-
getWindow: () => BrowserWindow | null | undefined;
|
|
31
|
-
/** Returns the id of the user the app treats as active, e.g. `() => activeUserId`. */
|
|
32
|
-
getActiveUserId: () => string | undefined;
|
|
33
19
|
/** Add options to the better-auth client, deep-merged (via `defuArrayFn`) over the options built here. */
|
|
34
20
|
clientOptions?: BetterAuthClientOptions;
|
|
35
|
-
/** Name of the cookie that records which user a window's session belongs to. @default "userId" */
|
|
36
|
-
userIdCookieName?: string;
|
|
37
|
-
/** Called after an external login is persisted, so the app can record the user (e.g. write its user dir). */
|
|
38
|
-
onFinishLogin?: (ctx: {
|
|
39
|
-
win: BrowserWindow;
|
|
40
|
-
user: {
|
|
41
|
-
id: string;
|
|
42
|
-
username: string | null;
|
|
43
|
-
};
|
|
44
|
-
}) => void | Promise<void>;
|
|
45
21
|
/**
|
|
46
22
|
* Enables mocking when TEST is true.
|
|
47
23
|
*
|
|
48
24
|
* @default true
|
|
49
25
|
*/
|
|
50
26
|
enableMockingInTestEnvs?: boolean;
|
|
51
|
-
}): {
|
|
27
|
+
} & Pick<ConstructorParameters<typeof ElectronAuth<TUser>>[0], "getSession" | "userSchema" | "getWindow" | "getActiveUserId" | "userIdCookieName" | "beforePersistExternalSession">): {
|
|
52
28
|
client: import("better-auth/client").AuthClient<Omit<BetterAuthClientOptions, "fetchOptions" | "plugins" | "baseURL"> & Omit<{
|
|
53
29
|
baseURL: string;
|
|
54
30
|
fetchOptions: {
|
|
@@ -206,7 +182,7 @@ export declare function setupElectronAuthMain(rc: ModulePublicRuntimeConfig["aut
|
|
|
206
182
|
csp?: boolean | undefined;
|
|
207
183
|
bridges?: boolean | undefined;
|
|
208
184
|
scheme?: boolean | undefined;
|
|
209
|
-
getWindow?: () => BrowserWindow | null | undefined;
|
|
185
|
+
getWindow?: () => Electron.CrossProcessExports.BrowserWindow | null | undefined;
|
|
210
186
|
}) => void;
|
|
211
187
|
$Infer: {
|
|
212
188
|
Bridges: {
|
|
@@ -424,7 +400,7 @@ export declare function setupElectronAuthMain(rc: ModulePublicRuntimeConfig["aut
|
|
|
424
400
|
csp?: boolean | undefined;
|
|
425
401
|
bridges?: boolean | undefined;
|
|
426
402
|
scheme?: boolean | undefined;
|
|
427
|
-
getWindow?: () => BrowserWindow | null | undefined;
|
|
403
|
+
getWindow?: () => Electron.CrossProcessExports.BrowserWindow | null | undefined;
|
|
428
404
|
}) => void;
|
|
429
405
|
$Infer: {
|
|
430
406
|
Bridges: {
|
|
@@ -616,7 +592,7 @@ export declare function setupElectronAuthMain(rc: ModulePublicRuntimeConfig["aut
|
|
|
616
592
|
csp?: boolean | undefined;
|
|
617
593
|
bridges?: boolean | undefined;
|
|
618
594
|
scheme?: boolean | undefined;
|
|
619
|
-
getWindow?: () => BrowserWindow | null | undefined;
|
|
595
|
+
getWindow?: () => Electron.CrossProcessExports.BrowserWindow | null | undefined;
|
|
620
596
|
}) => void;
|
|
621
597
|
$Infer: {
|
|
622
598
|
Bridges: {
|
|
@@ -661,5 +637,5 @@ export declare function setupElectronAuthMain(rc: ModulePublicRuntimeConfig["aut
|
|
|
661
637
|
})[];
|
|
662
638
|
baseURL: string;
|
|
663
639
|
}>;
|
|
664
|
-
electronAuth: ElectronAuth
|
|
640
|
+
electronAuth: ElectronAuth<TUser>;
|
|
665
641
|
};
|
|
@@ -4,8 +4,8 @@ import { createAuthClient } from "better-auth/client";
|
|
|
4
4
|
import { defuArrayFn } from "defu";
|
|
5
5
|
import { ipcMain, shell } from "electron";
|
|
6
6
|
import { createHash, randomBytes } from "node:crypto";
|
|
7
|
-
import { ElectronAuth } from "./ElectronAuth.js";
|
|
8
7
|
import { exchangeSessionChannel, mockRequestAuthChannel } from "../types.js";
|
|
8
|
+
import { ElectronAuth } from "./ElectronAuth.js";
|
|
9
9
|
function hasDevBypassParams(url) {
|
|
10
10
|
const raw = url.searchParams.get("additionalParams");
|
|
11
11
|
if (!raw) return false;
|
|
@@ -24,7 +24,7 @@ export function setupElectronAuthMain(rc, {
|
|
|
24
24
|
clientOptions,
|
|
25
25
|
userIdCookieName,
|
|
26
26
|
enableMockingInTestEnvs = true,
|
|
27
|
-
|
|
27
|
+
beforePersistExternalSession
|
|
28
28
|
}) {
|
|
29
29
|
const mockSignInUrl = `${publicServerUrl}${rc.authRoutes.mockAuth}`;
|
|
30
30
|
const isMocked = enableMockingInTestEnvs && process.env.TEST === "true" && !!rc.devBypassAuth;
|
|
@@ -34,18 +34,16 @@ export function setupElectronAuthMain(rc, {
|
|
|
34
34
|
// better-auth checks the origin once a request carries a session cookie, and main sends none
|
|
35
35
|
fetchOptions: { headers: { origin: publicServerUrl } },
|
|
36
36
|
plugins: [
|
|
37
|
-
electronClient(
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
}
|
|
48
|
-
)
|
|
37
|
+
electronClient({
|
|
38
|
+
channelPrefix: "better-auth",
|
|
39
|
+
protocol: { scheme: rc.deeplinkSchemes.electron },
|
|
40
|
+
callbackPath: rc.authRoutes.deeplink,
|
|
41
|
+
cookiePrefix: rc.cookiePrefix,
|
|
42
|
+
signInURL: signInUrl,
|
|
43
|
+
storage: storage(),
|
|
44
|
+
/* Disabled because the proxy registers its own scheme with protocol.registerSchemesAsPrivileged, and electron only honours the last of those calls: a second one replaces the first, so the app's scheme loses standard and secure and its window stops being a secure context, which also removes crypto.randomUUID from the page. It's not needed anyways since our proxy means we can directly load server image urls. */
|
|
45
|
+
userImageProxy: { enabled: false }
|
|
46
|
+
})
|
|
49
47
|
]
|
|
50
48
|
}));
|
|
51
49
|
client.setupMain({ bridges: true, csp: false, scheme: false, getWindow });
|
|
@@ -58,7 +56,7 @@ export function setupElectronAuthMain(rc, {
|
|
|
58
56
|
getWindow,
|
|
59
57
|
getActiveUserId,
|
|
60
58
|
userIdCookieName,
|
|
61
|
-
|
|
59
|
+
beforePersistExternalSession
|
|
62
60
|
}, rc);
|
|
63
61
|
const cookieName = `${new URL(publicServerUrl).protocol === "https:" ? "__Secure-" : ""}${rc.cookiePrefix}.session_token`;
|
|
64
62
|
ipcMain.removeHandler(exchangeSessionChannel);
|
|
@@ -75,11 +73,16 @@ export function setupElectronAuthMain(rc, {
|
|
|
75
73
|
createdAt: received.createdAt.toISOString(),
|
|
76
74
|
updatedAt: received.updatedAt.toISOString()
|
|
77
75
|
};
|
|
78
|
-
await electronAuth.
|
|
76
|
+
await electronAuth.persistExternalSession(win, {
|
|
79
77
|
user,
|
|
80
78
|
sessionToken: entry.slice(cookieName.length + 1),
|
|
81
79
|
expiresAt: new Date(data.session.expiresAt).getTime()
|
|
82
80
|
});
|
|
81
|
+
const targetWin = getWindow();
|
|
82
|
+
if (targetWin && targetWin !== win) {
|
|
83
|
+
const route = received.isRegistered ? rc.authRoutes.postRegisteredLogin : rc.authRoutes.register;
|
|
84
|
+
await targetWin.webContents.loadURL(new URL(route, targetWin.webContents.getURL()).toString());
|
|
85
|
+
}
|
|
83
86
|
});
|
|
84
87
|
if (isMocked) {
|
|
85
88
|
let pendingMockIdentity = {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { APIError, createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
|
|
2
2
|
import { setSessionCookie } from "better-auth/cookies";
|
|
3
|
+
import { Buffer } from "node:buffer";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
function derivedUsername(id, maxUsernameLength) {
|
|
5
6
|
return `username_${id.replace(/\W/g, "").slice(0, maxUsernameLength - "username_".length)}`;
|
|
@@ -23,7 +24,7 @@ export function devMock({
|
|
|
23
24
|
id,
|
|
24
25
|
devBypassRegistration
|
|
25
26
|
}) {
|
|
26
|
-
username
|
|
27
|
+
if (username === "") username = void 0;
|
|
27
28
|
if (username && usernameValidator && !await usernameValidator(username)) {
|
|
28
29
|
throw new APIError("BAD_REQUEST", {
|
|
29
30
|
message: `"${username}" is not a valid username for this app.`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Auth } from "better-auth";
|
|
2
|
-
import type { AuthSession } from "./createAuthSchema.js";
|
|
3
2
|
import type { AuthUser } from "../../types.js";
|
|
3
|
+
import type { AuthSession } from "./createAuthSchema.js";
|
|
4
4
|
export declare function createAuthMiddleware(auth: Auth<any>, logger: any): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void>>;
|
|
5
5
|
declare module "h3" {
|
|
6
6
|
interface H3EventContext {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
-
import {
|
|
2
|
+
import type { Auth, BetterAuthOptions } from "better-auth";
|
|
3
3
|
import type { AuthAccountsTable, AuthSessionsTable, AuthUsersTable, AuthVerificationsTable } from "./createAuthSchema.js";
|
|
4
4
|
export declare function createBetterAuth({ appUrl, db, schema, usernameSchema, minUsernameLength, maxUsernameLength, mockTransferCodeTtlMs, generateUser, betterAuthOptions, logger }: {
|
|
5
5
|
db: any;
|
|
@@ -31,4 +31,4 @@ export declare function createBetterAuth({ appUrl, db, schema, usernameSchema, m
|
|
|
31
31
|
generateUser?: (() => any);
|
|
32
32
|
/** Optional logger, used for warnings such as providers skipped for missing secrets. */
|
|
33
33
|
logger?: any;
|
|
34
|
-
}):
|
|
34
|
+
}): Auth<BetterAuthOptions>;
|
|
@@ -4,10 +4,11 @@ import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
|
4
4
|
import { createAuthEndpoint } from "better-auth/api";
|
|
5
5
|
import { username } from "better-auth/plugins";
|
|
6
6
|
import { defuArrayFn } from "defu";
|
|
7
|
+
import { Buffer } from "node:buffer";
|
|
7
8
|
import { z } from "zod";
|
|
8
|
-
import { registerAuthInstance } from "./getBetterAuthInstance.js";
|
|
9
9
|
import { useRuntimeConfig } from "#imports";
|
|
10
10
|
import { devMock } from "../../plugins/server/devMock.js";
|
|
11
|
+
import { registerAuthInstance } from "./getBetterAuthInstance.js";
|
|
11
12
|
const MIN_AUTH_SECRET_BYTES = 32;
|
|
12
13
|
export function createBetterAuth({
|
|
13
14
|
appUrl = useRuntimeConfig().public?.auth?.publicServerUrl,
|
|
@@ -47,7 +48,7 @@ export function createBetterAuth({
|
|
|
47
48
|
for (const [name, cfg] of Object.entries(providersFromConfig)) {
|
|
48
49
|
socialProviders[name] = { clientId: cfg.clientId, clientSecret: cfg.clientSecret };
|
|
49
50
|
}
|
|
50
|
-
const authSecretValue = rc.authSecret
|
|
51
|
+
const authSecretValue = rc.authSecret ?? "";
|
|
51
52
|
if (!authSecretValue) {
|
|
52
53
|
throw new Error("FATAL: Missing or empty runtimeConfig.authSecret (i.e. should be set via NUXT_AUTH_SECRET) in production.");
|
|
53
54
|
}
|
|
@@ -112,7 +113,7 @@ export function createBetterAuth({
|
|
|
112
113
|
verification: schema.authVerifications
|
|
113
114
|
}
|
|
114
115
|
}),
|
|
115
|
-
secret: authSecretValue
|
|
116
|
+
secret: authSecretValue ?? void 0,
|
|
116
117
|
baseURL: appUrl,
|
|
117
118
|
trustedOrigins: [appUrl],
|
|
118
119
|
logger: logger ? {
|
|
@@ -148,7 +149,7 @@ export function createBetterAuth({
|
|
|
148
149
|
if (user && "username" in user && user.username) {
|
|
149
150
|
return { data: { ...user, isRegistered: true } };
|
|
150
151
|
}
|
|
151
|
-
return;
|
|
152
|
+
return void 0;
|
|
152
153
|
}
|
|
153
154
|
}
|
|
154
155
|
}
|
package/dist/types.d.mts
CHANGED
|
@@ -10,5 +10,3 @@ export { default } from './module.mjs'
|
|
|
10
10
|
export { type ModuleOptions, type ModulePrivateRuntimeConfig, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig } from './module.mjs'
|
|
11
11
|
|
|
12
12
|
export * from '../dist/runtime/types.js'
|
|
13
|
-
|
|
14
|
-
export * from '../dist/runtime/server/utils/createAuthSchema.js'
|
package/package.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@witchcraft/nuxt-auth",
|
|
3
|
-
"version": "0.6.0-beta.
|
|
3
|
+
"version": "0.6.0-beta.5",
|
|
4
4
|
"description": "Nuxt module for logging.",
|
|
5
|
-
"repository":
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "witchcraftjs/nuxt-auth"
|
|
8
|
+
},
|
|
6
9
|
"license": "MIT",
|
|
7
10
|
"type": "module",
|
|
8
11
|
"sideEffects": false,
|
|
@@ -71,7 +74,7 @@
|
|
|
71
74
|
"zod": "^4.6.6"
|
|
72
75
|
},
|
|
73
76
|
"devDependencies": {
|
|
74
|
-
"@alanscodelog/eslint-config": "^
|
|
77
|
+
"@alanscodelog/eslint-config": "^7.1.3",
|
|
75
78
|
"@alanscodelog/semantic-release-config": "^6.0.2",
|
|
76
79
|
"@commitlint/cli": "^20.1.0",
|
|
77
80
|
"@nuxt/eslint-config": "^1.9.0",
|
|
@@ -117,7 +120,7 @@
|
|
|
117
120
|
"dev:playground": "pnpm test:server",
|
|
118
121
|
"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'",
|
|
119
122
|
"lint": "pnpm lint:eslint && pnpm lint:types && pnpm lint:commits",
|
|
120
|
-
"lint:eslint": "eslint \"{src,playground
|
|
123
|
+
"lint:eslint": "eslint \"{src,playground}/**/*.{ts,vue}\" \"*.{js,cjs,mjs,ts}\" --max-warnings=0",
|
|
121
124
|
"lint:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit -p .nuxt/tsconfig.app.json && vue-tsc --noEmit -p tsconfig.test.json",
|
|
122
125
|
"lint:commits": "commitlint --from-last-tag --to HEAD --verbose",
|
|
123
126
|
"lint:fix": "pnpm lint:eslint --fix && pnpm lint:types",
|