@witchcraft/nuxt-auth 0.5.1 → 0.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +189 -337
- package/dist/module.d.mts +64 -41
- package/dist/module.json +1 -1
- package/dist/module.mjs +25 -35
- package/dist/runtime/components/ExternalCallback.vue +11 -11
- package/dist/runtime/components/LoginProviderButtons.client.d.vue.ts +10 -15
- package/dist/runtime/components/LoginProviderButtons.client.vue +12 -11
- package/dist/runtime/components/LoginProviderButtons.client.vue.d.ts +10 -15
- package/dist/runtime/components/MockBypassRegistrationFields.d.vue.ts +13 -0
- package/dist/runtime/components/MockBypassRegistrationFields.vue +18 -0
- package/dist/runtime/components/MockBypassRegistrationFields.vue.d.ts +13 -0
- package/dist/runtime/components/Mocker.d.vue.ts +5 -1
- package/dist/runtime/components/Mocker.vue +7 -10
- package/dist/runtime/components/Mocker.vue.d.ts +5 -1
- package/dist/runtime/components/SessionStatus.d.vue.ts +86 -42
- package/dist/runtime/components/SessionStatus.vue +29 -8
- package/dist/runtime/components/SessionStatus.vue.d.ts +86 -42
- package/dist/runtime/components/UserRegistration.d.vue.ts +5 -0
- package/dist/runtime/components/UserRegistration.vue +2 -0
- package/dist/runtime/components/UserRegistration.vue.d.ts +5 -0
- package/dist/runtime/composables/useAuth.d.ts +382 -19
- package/dist/runtime/composables/useAuth.js +191 -28
- package/dist/runtime/composables/useAuthExternalCallback.d.ts +13 -6
- package/dist/runtime/composables/useAuthExternalCallback.js +27 -16
- package/dist/runtime/composables/useAuthExternalCode.d.ts +2 -2
- package/dist/runtime/composables/useAuthExternalCode.js +19 -18
- package/dist/runtime/composables/useAuthMocker.d.ts +11 -1
- package/dist/runtime/composables/useAuthMocker.js +21 -11
- package/dist/runtime/composables/useAuthUserRegistration.d.ts +5 -10
- package/dist/runtime/composables/useAuthUserRegistration.js +12 -25
- package/dist/runtime/core/providerStyles.js +12 -4
- package/dist/runtime/electron/index.d.ts +1 -0
- package/dist/runtime/electron/index.js +1 -0
- package/dist/runtime/electron/main/ElectronAuth.d.ts +123 -0
- package/dist/runtime/electron/main/ElectronAuth.js +200 -0
- package/dist/runtime/electron/main/index.d.ts +2 -0
- package/dist/runtime/electron/main/index.js +2 -0
- package/dist/runtime/electron/main/setupElectronAuthMain.d.ts +665 -0
- package/dist/runtime/electron/main/setupElectronAuthMain.js +137 -0
- package/dist/runtime/electron/preload/createElectronAuthApi.d.ts +7 -0
- package/dist/runtime/electron/preload/createElectronAuthApi.js +15 -0
- package/dist/runtime/electron/preload/index.d.ts +2 -0
- package/dist/runtime/electron/preload/index.js +2 -0
- package/dist/runtime/electron/types.d.ts +54 -0
- package/dist/runtime/electron/types.js +2 -0
- package/dist/runtime/middleware/authGlobal.js +30 -14
- package/dist/runtime/middleware/authProtected.js +2 -2
- package/dist/runtime/plugins/client/electronNuxtAuthPlugin.d.ts +48 -0
- package/dist/runtime/plugins/client/electronNuxtAuthPlugin.js +86 -0
- package/dist/runtime/plugins/client/localOnlyUsers.d.ts +25 -0
- package/dist/runtime/plugins/client/localOnlyUsers.js +110 -0
- package/dist/runtime/plugins/server/devMock.d.ts +51 -0
- package/dist/runtime/plugins/server/devMock.js +162 -0
- package/dist/runtime/server/utils/assertEventWithAuthorizedUser.d.ts +11 -0
- package/dist/runtime/server/utils/assertEventWithAuthorizedUser.js +10 -0
- package/dist/runtime/server/utils/createAuthMiddleware.d.ts +4 -4
- package/dist/runtime/server/utils/createAuthMiddleware.js +16 -23
- package/dist/runtime/server/utils/createAuthSchema.d.ts +391 -94
- package/dist/runtime/server/utils/createAuthSchema.js +43 -13
- package/dist/runtime/server/utils/createBetterAuth.d.ts +34 -0
- package/dist/runtime/server/utils/createBetterAuth.js +160 -0
- package/dist/runtime/server/utils/getBetterAuthInstance.d.ts +3 -0
- package/dist/runtime/server/utils/getBetterAuthInstance.js +10 -0
- package/dist/runtime/types.d.ts +358 -248
- package/dist/runtime/types.js +48 -25
- package/dist/runtime/utils/deserializeAuthLocalUser.d.ts +2 -0
- package/dist/runtime/utils/deserializeAuthLocalUser.js +9 -0
- package/package.json +44 -19
- package/dist/runtime/core/providers/github.d.ts +0 -84
- package/dist/runtime/core/providers/github.js +0 -55
- package/dist/runtime/core/providers/google.d.ts +0 -65
- package/dist/runtime/core/providers/google.js +0 -49
- package/dist/runtime/server/helpers/getSafeSecretsInfo.d.ts +0 -4
- package/dist/runtime/server/helpers/getSafeSecretsInfo.js +0 -10
- package/dist/runtime/server/helpers/logSafeRoute.d.ts +0 -1
- package/dist/runtime/server/helpers/logSafeRoute.js +0 -3
- package/dist/runtime/server/helpers/signJwt.d.ts +0 -3
- package/dist/runtime/server/helpers/signJwt.js +0 -16
- package/dist/runtime/server/helpers/verifyJwt.d.ts +0 -5
- package/dist/runtime/server/helpers/verifyJwt.js +0 -19
- package/dist/runtime/server/utils/Auth.d.ts +0 -85
- package/dist/runtime/server/utils/Auth.js +0 -671
- package/dist/runtime/server/utils/SessionManager.d.ts +0 -26
- package/dist/runtime/server/utils/SessionManager.js +0 -94
- package/dist/runtime/server/utils/createAuthHandler.d.ts +0 -9
- package/dist/runtime/server/utils/createAuthHandler.js +0 -29
- package/dist/runtime/utils/createExternalAuthLoginHandler.d.ts +0 -37
- package/dist/runtime/utils/createExternalAuthLoginHandler.js +0 -23
- package/dist/runtime/utils/getAuthApiRoute.d.ts +0 -6
- package/dist/runtime/utils/getAuthApiRoute.js +0 -14
|
@@ -1,17 +1,24 @@
|
|
|
1
|
-
import type { Ref } from "vue";
|
|
2
1
|
export type ExternalCallbackOptions = {
|
|
3
|
-
/**
|
|
4
|
-
|
|
2
|
+
/** Trades the token for a session, e.g. `window.authenticate` from the preload bridge. */
|
|
3
|
+
authenticate: (token: string) => Promise<unknown>;
|
|
4
|
+
/** Starts the login again while there is no token, supplied by the app for its platform. */
|
|
5
|
+
requestExternalAuth: (options: {
|
|
6
|
+
provider?: string;
|
|
7
|
+
}) => Promise<void>;
|
|
5
8
|
/** Path to navigate to on success. Defaults to `postRegisteredLogin` from runtime config. */
|
|
6
9
|
successPath?: string;
|
|
7
10
|
/** Path to navigate to on cancel. Defaults to `login` from runtime config. */
|
|
8
11
|
cancelPath?: string;
|
|
9
12
|
};
|
|
13
|
+
/**
|
|
14
|
+
* Reads the token from the deeplink route (fragment `#token=` or
|
|
15
|
+
* `?access_token=`) or a manual paste box, then trades it for a session.
|
|
16
|
+
*/
|
|
10
17
|
export declare function useAuthExternalCallback(opts: ExternalCallbackOptions): {
|
|
11
|
-
authUri: string | undefined;
|
|
12
18
|
initialAccessToken: string | undefined;
|
|
13
|
-
manualAccessToken: Ref<string, string>;
|
|
14
|
-
error: Ref<string | undefined, string | undefined>;
|
|
19
|
+
manualAccessToken: import("vue").Ref<string, string>;
|
|
20
|
+
error: import("vue").Ref<string | undefined, string | undefined>;
|
|
15
21
|
authorize: (accessToken?: string, isInitial?: boolean) => Promise<void>;
|
|
22
|
+
requestExternalAuth: () => Promise<void>;
|
|
16
23
|
cancel: () => Promise<void>;
|
|
17
24
|
};
|
|
@@ -1,23 +1,25 @@
|
|
|
1
1
|
import { ref } from "vue";
|
|
2
|
-
import
|
|
2
|
+
import { useAuth } from "./useAuth.js";
|
|
3
3
|
import {
|
|
4
4
|
navigateTo,
|
|
5
5
|
useRoute,
|
|
6
6
|
useRuntimeConfig
|
|
7
7
|
} from "#app";
|
|
8
|
-
import {
|
|
8
|
+
import { deserializeAuthLocalUser } from "../utils/deserializeAuthLocalUser.js";
|
|
9
9
|
export function useAuthExternalCallback(opts) {
|
|
10
10
|
const rc = useRuntimeConfig();
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
const initialAccessToken =
|
|
15
|
-
const
|
|
11
|
+
const route = useRoute();
|
|
12
|
+
const hashToken = typeof window !== "undefined" && window.location.hash.startsWith("#token=") ? window.location.hash.slice("#token=".length) : void 0;
|
|
13
|
+
const queryToken = typeof route.query.access_token === "string" ? route.query.access_token : void 0;
|
|
14
|
+
const initialAccessToken = hashToken ?? queryToken;
|
|
15
|
+
const provider = typeof route.query.provider === "string" ? route.query.provider : void 0;
|
|
16
|
+
const bridge = opts.requestExternalAuth;
|
|
17
|
+
const { client } = useAuth();
|
|
18
|
+
const manualAccessToken = ref("");
|
|
19
|
+
const error = ref(void 0);
|
|
16
20
|
if (initialAccessToken) {
|
|
17
21
|
void authorize(initialAccessToken, true);
|
|
18
22
|
}
|
|
19
|
-
const manualAccessToken = ref("");
|
|
20
|
-
const error = ref(void 0);
|
|
21
23
|
async function authorize(accessToken, isInitial = false) {
|
|
22
24
|
if (!accessToken || accessToken.length === 0) {
|
|
23
25
|
if (!isInitial) {
|
|
@@ -25,23 +27,32 @@ export function useAuthExternalCallback(opts) {
|
|
|
25
27
|
}
|
|
26
28
|
return;
|
|
27
29
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
await navigateTo(opts.successPath ?? rc.public.auth.authRoutes.postRegisteredLogin);
|
|
30
|
+
try {
|
|
31
|
+
await opts.authenticate(accessToken);
|
|
32
|
+
} catch (err) {
|
|
33
|
+
error.value = err instanceof Error ? err.message : String(err);
|
|
34
|
+
return;
|
|
34
35
|
}
|
|
36
|
+
const { data } = await client.getSession().catch(() => ({ data: void 0 }));
|
|
37
|
+
const user = data?.user ? deserializeAuthLocalUser(data.user) : void 0;
|
|
38
|
+
const routes = rc.public.auth.authRoutes;
|
|
39
|
+
const successPath = user && user.isRegistered === false ? routes.register : routes.postRegisteredLogin;
|
|
40
|
+
await navigateTo(opts.successPath ?? successPath);
|
|
41
|
+
}
|
|
42
|
+
async function requestExternalAuth() {
|
|
43
|
+
await bridge({ provider }).catch((err) => {
|
|
44
|
+
error.value = err instanceof Error ? err.message : String(err);
|
|
45
|
+
});
|
|
35
46
|
}
|
|
36
47
|
async function cancel() {
|
|
37
48
|
await navigateTo(opts.cancelPath ?? rc.public.auth.authRoutes.login);
|
|
38
49
|
}
|
|
39
50
|
return {
|
|
40
|
-
authUri,
|
|
41
51
|
initialAccessToken,
|
|
42
52
|
manualAccessToken,
|
|
43
53
|
error,
|
|
44
54
|
authorize,
|
|
55
|
+
requestExternalAuth,
|
|
45
56
|
cancel
|
|
46
57
|
};
|
|
47
58
|
}
|
|
@@ -1,28 +1,29 @@
|
|
|
1
1
|
import { copyToClipboard } from "@alanscodelog/utils/copyToClipboard";
|
|
2
|
-
import {
|
|
3
|
-
import { onMounted } from "vue";
|
|
2
|
+
import { computed, onUnmounted, ref } from "vue";
|
|
4
3
|
import {
|
|
5
|
-
|
|
6
|
-
useRoute
|
|
4
|
+
useRuntimeConfig
|
|
7
5
|
} from "#app";
|
|
8
|
-
import {
|
|
6
|
+
import { useAuth } from "../composables/useAuth.js";
|
|
9
7
|
export function useAuthExternalCode() {
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
8
|
+
const config = useRuntimeConfig().public.auth;
|
|
9
|
+
const auth = useAuth();
|
|
10
|
+
const client = auth.client;
|
|
11
|
+
const code = ref(client.electron?.getAuthorizationCode() ?? void 0);
|
|
12
|
+
let redirectInterval;
|
|
13
|
+
if (import.meta.client) redirectInterval = client.ensureElectronRedirect();
|
|
14
|
+
const deepLinkUrl = computed(() => {
|
|
15
|
+
const scheme = config.deeplinkSchemes?.electron;
|
|
16
|
+
if (!code.value || !scheme) return void 0;
|
|
17
|
+
return `${scheme}://${config.authRoutes.deeplink.replace(/^\//, "")}#token=${code.value}`;
|
|
18
|
+
});
|
|
19
|
+
onUnmounted(() => {
|
|
20
|
+
if (redirectInterval) clearInterval(redirectInterval);
|
|
21
|
+
});
|
|
16
22
|
function copyToken() {
|
|
17
|
-
copyToClipboard(
|
|
23
|
+
copyToClipboard(code.value ?? "");
|
|
18
24
|
}
|
|
19
|
-
onMounted(() => {
|
|
20
|
-
if (accessToken) {
|
|
21
|
-
void navigateTo(deepLinkUrl, { external: true });
|
|
22
|
-
}
|
|
23
|
-
});
|
|
24
25
|
return {
|
|
25
|
-
accessToken,
|
|
26
|
+
accessToken: code,
|
|
26
27
|
deepLinkUrl,
|
|
27
28
|
copyToken
|
|
28
29
|
};
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import type { Ref } from "vue";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* The mock stands in for the provider's login acceptance page, which only exists on the web, so electron should never render it.
|
|
4
|
+
*
|
|
5
|
+
* It supports electron because a built and *installed* app can receive the deeplink so technically an testing app can be configured for a browser side mocked flow, but this is usually not done because it involves the install of a desktop file.
|
|
6
|
+
*
|
|
7
|
+
* The playground tests, for example do not build and install the app, so they set the same things from the login page instead.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useAuthMocker({ deeplinkScheme }?: {
|
|
10
|
+
/** Scheme of the deeplink the mock redirects to, from `rc.auth.deeplinkSchemes`. Defaults to the electron scheme. */
|
|
11
|
+
deeplinkScheme?: string;
|
|
12
|
+
}): {
|
|
3
13
|
provider: string;
|
|
4
14
|
username: Ref<string, string>;
|
|
5
15
|
bypassRegistration: Ref<boolean, boolean>;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { ref } from "vue";
|
|
2
2
|
import {
|
|
3
|
+
$fetch,
|
|
3
4
|
navigateTo,
|
|
4
5
|
useRoute,
|
|
5
6
|
useRuntimeConfig
|
|
6
7
|
} from "#imports";
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
export function useAuthMocker({
|
|
9
|
+
deeplinkScheme = useRuntimeConfig().public.auth.deeplinkSchemes?.electron
|
|
10
|
+
} = {}) {
|
|
9
11
|
const route = useRoute();
|
|
10
12
|
const username = ref("");
|
|
11
13
|
const bypassRegistration = ref(false);
|
|
@@ -14,15 +16,23 @@ export function useAuthMocker() {
|
|
|
14
16
|
throw new Error("Missing provider query param.");
|
|
15
17
|
}
|
|
16
18
|
async function submit() {
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
19
|
+
const rc = useRuntimeConfig().public;
|
|
20
|
+
const { redirectUrl } = await $fetch(
|
|
21
|
+
`${rc.auth.authApiRouteBase}/dev/mock`,
|
|
22
|
+
{
|
|
23
|
+
method: "POST",
|
|
24
|
+
body: {
|
|
25
|
+
provider,
|
|
26
|
+
// a user who does not bypass registration has no username to choose yet
|
|
27
|
+
username: bypassRegistration.value ? username.value : void 0,
|
|
28
|
+
devBypassRegistration: bypassRegistration.value,
|
|
29
|
+
code_challenge: route.query.code_challenge,
|
|
30
|
+
state: route.query.state,
|
|
31
|
+
deeplink_scheme: deeplinkScheme
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
);
|
|
35
|
+
await navigateTo(redirectUrl, { external: true });
|
|
26
36
|
}
|
|
27
37
|
return {
|
|
28
38
|
provider,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
-
import
|
|
2
|
+
import { useAuth } from "../composables/useAuth.js";
|
|
3
3
|
/**
|
|
4
4
|
* Wraps all the async username validation and registration logic.
|
|
5
5
|
*
|
|
@@ -7,17 +7,12 @@ import type { NitroFetchOptions, NitroFetchRequest } from "nitropack";
|
|
|
7
7
|
*
|
|
8
8
|
* Notes:
|
|
9
9
|
* - Remember to gate the button with `v-if` canSubmit.
|
|
10
|
-
* - If wrapping handleSubmit, also remember to check `canSubmit` first.
|
|
10
|
+
* - If wrapping handleSubmit, also remember to check `canSubmit` first.
|
|
11
11
|
* - inputValid is only a visual indicator and is valid for empty inputs and when the server is validating a request. Username might still be invalid.
|
|
12
12
|
*/
|
|
13
|
-
export declare function useAuthUserRegistration({
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
method: "post";
|
|
17
|
-
body: {
|
|
18
|
-
username: string;
|
|
19
|
-
};
|
|
20
|
-
}) => NitroFetchOptions<NitroFetchRequest, any>;
|
|
13
|
+
export declare function useAuthUserRegistration({ auth, debounce, statusTextMap, usernameSchema }?: {
|
|
14
|
+
/** The auth instance to use, so a caller can hand in one that carries its platform plugins. */
|
|
15
|
+
auth?: ReturnType<typeof useAuth>;
|
|
21
16
|
debounce?: number;
|
|
22
17
|
usernameSchema?: StandardSchemaV1<string, string>;
|
|
23
18
|
statusTextMap?: {
|
|
@@ -3,10 +3,9 @@ import { useAsyncValidation } from "@witchcraft/nuxt-utils/composables/useAsyncV
|
|
|
3
3
|
import { computed, ref } from "vue";
|
|
4
4
|
import { navigateTo, useRoute, useRuntimeConfig } from "#app";
|
|
5
5
|
import { useAuth } from "../composables/useAuth.js";
|
|
6
|
-
import {
|
|
7
|
-
import { getAuthApiRoute } from "../utils/getAuthApiRoute.js";
|
|
6
|
+
import { defaultZodUsernameSchema, usernameValidFetchKey } from "../types.js";
|
|
8
7
|
export function useAuthUserRegistration({
|
|
9
|
-
|
|
8
|
+
auth = useAuth(),
|
|
10
9
|
debounce = 1e3,
|
|
11
10
|
statusTextMap = {
|
|
12
11
|
loading: "Checking availability...",
|
|
@@ -29,11 +28,8 @@ export function useAuthUserRegistration({
|
|
|
29
28
|
_internal
|
|
30
29
|
} = useAsyncValidation(
|
|
31
30
|
debouncedUsername,
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
config,
|
|
35
|
-
"usernameValid"
|
|
36
|
-
),
|
|
31
|
+
usernameValidFetchKey,
|
|
32
|
+
`${useRuntimeConfig().public.auth.authApiRouteBase}/username/valid`,
|
|
37
33
|
submitErrors,
|
|
38
34
|
{
|
|
39
35
|
debounce: 0,
|
|
@@ -48,26 +44,17 @@ export function useAuthUserRegistration({
|
|
|
48
44
|
}
|
|
49
45
|
);
|
|
50
46
|
const deeplink = typeof query.deeplink === "string" ? query.deeplink : void 0;
|
|
51
|
-
const redirectUrl = deeplink ? config.auth.authRoutes.externalCode : config.auth.authRoutes.
|
|
52
|
-
if (!redirectUrl) throw new Error("No externalCode or
|
|
47
|
+
const redirectUrl = deeplink ? config.auth.authRoutes.externalCode : config.auth.authRoutes.postRegisteredLogin;
|
|
48
|
+
if (!redirectUrl) throw new Error("No externalCode or postRegisteredLogin route defined.");
|
|
53
49
|
async function handleSubmit(_event) {
|
|
54
50
|
if (!canSubmit.value) return;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
body: { username: username.value }
|
|
59
|
-
};
|
|
60
|
-
if (modifyFetch) request = modifyFetch(request);
|
|
61
|
-
const res = await $fetch(`${getAuthApiRoute(config, "register")}${deeplink ? `?deeplink=${deeplink}` : ""}`, request).catch(async (e) => {
|
|
62
|
-
submitErrors.value = [`Registration Error: ${e.data.message}`];
|
|
63
|
-
if (e?.data?.code === AUTH_ERROR.USER_ALREADY_REGISTERED) {
|
|
64
|
-
useAuth().setFetchUserOnNavigation(true);
|
|
65
|
-
await navigateTo(redirectUrl, { external: true });
|
|
66
|
-
}
|
|
51
|
+
submitErrors.value = [];
|
|
52
|
+
await auth.update({ username: username.value }).catch((e) => {
|
|
53
|
+
submitErrors.value = [`Registration Error: ${e?.message ?? e}`];
|
|
67
54
|
});
|
|
68
|
-
if (
|
|
69
|
-
|
|
70
|
-
}
|
|
55
|
+
if (submitErrors.value.length > 0) return;
|
|
56
|
+
auth.setFetchUserOnNavigation(true);
|
|
57
|
+
await navigateTo(redirectUrl, { external: true });
|
|
71
58
|
}
|
|
72
59
|
const isDebouncing = computed(() => debouncedUsername.value !== username.value);
|
|
73
60
|
return {
|
|
@@ -1,6 +1,14 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import GithubLogo from "~icons/logos/github-icon";
|
|
2
|
+
import GoogleLogo from "~icons/logos/google-icon";
|
|
3
3
|
export const providerStyles = {
|
|
4
|
-
github:
|
|
5
|
-
|
|
4
|
+
github: {
|
|
5
|
+
name: "Github",
|
|
6
|
+
logo: GithubLogo,
|
|
7
|
+
class: "bg-white text-black dark:bg-black dark:text-white"
|
|
8
|
+
},
|
|
9
|
+
google: {
|
|
10
|
+
name: "Google",
|
|
11
|
+
logo: GoogleLogo,
|
|
12
|
+
class: "bg-white text-black dark:bg-black dark:text-white"
|
|
13
|
+
}
|
|
6
14
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./types.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./types.js";
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
import type { BaseLogger } from "@witchcraft/nuxt-logger/types";
|
|
3
|
+
import type { BrowserWindow, Session } from "electron";
|
|
4
|
+
import type { ModulePublicRuntimeConfig } from "../../../module.js";
|
|
5
|
+
import { type SessionCookieOptions } from "../../types.js";
|
|
6
|
+
/**
|
|
7
|
+
* Main-process auth helper for Electron apps.
|
|
8
|
+
*
|
|
9
|
+
* Replaces hand-rolled scheme regexes and cookie writing. The token exchange itself runs through better-auth (`window.authenticate` in the callback page calls main, main calls `authenticate`).
|
|
10
|
+
*
|
|
11
|
+
* This class owns intake and persistence around it:
|
|
12
|
+
* - matching scheme urls and loading the callback page with the token
|
|
13
|
+
* - mirroring the session cookie into the window session
|
|
14
|
+
* - writing the user and the session expiry into the window's `localStorage`
|
|
15
|
+
* - keeping the stored expiry in step when the server rolls the session
|
|
16
|
+
* - local-user session injection
|
|
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 onFinishLogin;
|
|
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, onFinishLogin }: {
|
|
36
|
+
/** Custom protocol scheme, from `rc.auth.deeplinkSchemes.electron`. No trailing colon. */
|
|
37
|
+
scheme: string;
|
|
38
|
+
/**
|
|
39
|
+
* Parses the user before it is written to the window, e.g. `zAuthUserStored`.
|
|
40
|
+
* Build it from the db table so there is one source of truth for the user shape.
|
|
41
|
+
*/
|
|
42
|
+
userSchema: StandardSchemaV1<unknown, {
|
|
43
|
+
id: string;
|
|
44
|
+
}>;
|
|
45
|
+
/** Deeplink path the code page bounces to, from `rc.auth.authRoutes.deeplink`. */
|
|
46
|
+
callbackPath: string;
|
|
47
|
+
/**
|
|
48
|
+
* The better-auth server the app proxies to, e.g. `getPaths().publicServerUrl` so we know what site to store the cookies securely on.
|
|
49
|
+
*/
|
|
50
|
+
publicServerUrl: string;
|
|
51
|
+
/** Returns the session the window uses, e.g. `() => ses`, undefined until the window is created. Its cookies are what the proxy sends. */
|
|
52
|
+
getSession: () => Session | undefined;
|
|
53
|
+
/** Returns the window auth urls load into, e.g. `() => win`, null when none exists yet. */
|
|
54
|
+
getWindow: () => BrowserWindow | undefined | null;
|
|
55
|
+
/** Returns the id of the user the app treats as active, e.g. `() => activeUserId`. */
|
|
56
|
+
getActiveUserId: () => string | undefined;
|
|
57
|
+
/** From runtime config, `rc.auth.sessionCookieOpts`. Required if `rc` is not passed. */
|
|
58
|
+
sessionCookieOpts?: Pick<SessionCookieOptions, "path" | "sameSite">;
|
|
59
|
+
/** From runtime config, `rc.auth.sessionExpiresAt`. Required if `rc` is not passed. */
|
|
60
|
+
sessionExpiresAt?: number;
|
|
61
|
+
/** better-auth cookie prefix, from `rc.auth.cookiePrefix`. @default "better-auth" */
|
|
62
|
+
cookiePrefix?: string;
|
|
63
|
+
/** Name of the cookie that records which user a window's session belongs to. @default "userId" */
|
|
64
|
+
userIdCookieName?: string;
|
|
65
|
+
logger?: BaseLogger;
|
|
66
|
+
/** Called after an external login is persisted, so the app can record the user (e.g. write its user dir). */
|
|
67
|
+
onFinishLogin?: (info: {
|
|
68
|
+
win: BrowserWindow;
|
|
69
|
+
user: {
|
|
70
|
+
id: string;
|
|
71
|
+
username: string;
|
|
72
|
+
};
|
|
73
|
+
}) => void | Promise<void>;
|
|
74
|
+
},
|
|
75
|
+
/**
|
|
76
|
+
* The auth runtime config, e.g. `rc.auth`. Takes precedence over the individual
|
|
77
|
+
* options above so they do not have to be copied over one by one.
|
|
78
|
+
*/
|
|
79
|
+
rc?: Pick<ModulePublicRuntimeConfig["auth"], "sessionCookieOpts" | "sessionExpiresAt" | "cookiePrefix">);
|
|
80
|
+
/** Electron spells `sameSite: "none"` as `"no_restriction"`. */
|
|
81
|
+
private get _cookieSetOpts();
|
|
82
|
+
private get _sessionCookieName();
|
|
83
|
+
private _parseToken;
|
|
84
|
+
private _loadCallback;
|
|
85
|
+
/**
|
|
86
|
+
* Intake for scheme urls from second-instance and open-url, which only fire while the
|
|
87
|
+
* app is already open, so there is always a window and a session to load into.
|
|
88
|
+
*/
|
|
89
|
+
handleUrl(url: string): Promise<boolean>;
|
|
90
|
+
/** Window-side session cookie check for an external user. */
|
|
91
|
+
getHasCookies(): Promise<boolean>;
|
|
92
|
+
/**
|
|
93
|
+
* Cookie url, always the server origin. Chromium only stores cookies for
|
|
94
|
+
* http(s) schemes, so a window loaded over `app://bundle` or `file://` can
|
|
95
|
+
* never hold one. The window's session still carries the cookie, and the
|
|
96
|
+
* proxy is what sends it to the server.
|
|
97
|
+
*/
|
|
98
|
+
private _cookieUrl;
|
|
99
|
+
/**
|
|
100
|
+
* Generic post-exchange persistence: mirrors the session cookie into the
|
|
101
|
+
* window session (`httpOnly`), the user into window `localStorage` and the
|
|
102
|
+
* cookie's expiry next to it.
|
|
103
|
+
* Returns, the app does whatever post-login it needs (user switching,
|
|
104
|
+
* folder setup, reload) after the await. No hooks, the class stays
|
|
105
|
+
* unaware of app details.
|
|
106
|
+
*/
|
|
107
|
+
finishLogin(win: BrowserWindow, { user, sessionToken, expiresAt }: {
|
|
108
|
+
user: unknown;
|
|
109
|
+
sessionToken: string;
|
|
110
|
+
/** Epoch ms, written to both cookies and to the expiry key. Defaults to `sessionExpiresAt` from now. */
|
|
111
|
+
expiresAt?: number;
|
|
112
|
+
}): Promise<void>;
|
|
113
|
+
/** Injects a local-only user into the window as the active user. */
|
|
114
|
+
saveLocalUserSession(win: BrowserWindow, authUser: unknown): Promise<void>;
|
|
115
|
+
private _parseUser;
|
|
116
|
+
/**
|
|
117
|
+
* Keeps the expiry key in step with the cookie, for the session the server rolls or
|
|
118
|
+
* replaces. Chromium reports a cookie set by us as `explicit` and its removal as one of
|
|
119
|
+
* the other causes, so those are ignored and the last expiry stays, which keeps the clock
|
|
120
|
+
* comparison answering true once it has passed.
|
|
121
|
+
*/
|
|
122
|
+
private _watchSessionCookies;
|
|
123
|
+
}
|