@witchcraft/nuxt-auth 0.5.2 → 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 +188 -336
- 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 +4 -10
- 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
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { electronClient } from "@better-auth/electron/client";
|
|
2
|
+
import { storage } from "@better-auth/electron/storage";
|
|
3
|
+
import { createAuthClient } from "better-auth/client";
|
|
4
|
+
import { defuArrayFn } from "defu";
|
|
5
|
+
import { ipcMain, shell } from "electron";
|
|
6
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
7
|
+
import { ElectronAuth } from "./ElectronAuth.js";
|
|
8
|
+
import { exchangeSessionChannel, mockRequestAuthChannel } from "../types.js";
|
|
9
|
+
function hasDevBypassParams(url) {
|
|
10
|
+
const raw = url.searchParams.get("additionalParams");
|
|
11
|
+
if (!raw) return false;
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(raw).devBypass === "true";
|
|
14
|
+
} catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function setupElectronAuthMain(rc, {
|
|
19
|
+
publicServerUrl,
|
|
20
|
+
getSession,
|
|
21
|
+
userSchema,
|
|
22
|
+
getWindow,
|
|
23
|
+
getActiveUserId,
|
|
24
|
+
clientOptions,
|
|
25
|
+
userIdCookieName,
|
|
26
|
+
enableMockingInTestEnvs = true,
|
|
27
|
+
onFinishLogin
|
|
28
|
+
}) {
|
|
29
|
+
const mockSignInUrl = `${publicServerUrl}${rc.authRoutes.mockAuth}`;
|
|
30
|
+
const isMocked = enableMockingInTestEnvs && process.env.TEST === "true" && !!rc.devBypassAuth;
|
|
31
|
+
const signInUrl = isMocked ? mockSignInUrl : `${publicServerUrl}${rc.authRoutes.login}`;
|
|
32
|
+
const client = createAuthClient(defuArrayFn(clientOptions ?? {}, {
|
|
33
|
+
baseURL: publicServerUrl,
|
|
34
|
+
// better-auth checks the origin once a request carries a session cookie, and main sends none
|
|
35
|
+
fetchOptions: { headers: { origin: publicServerUrl } },
|
|
36
|
+
plugins: [
|
|
37
|
+
electronClient(
|
|
38
|
+
{
|
|
39
|
+
channelPrefix: "better-auth",
|
|
40
|
+
protocol: { scheme: rc.deeplinkSchemes.electron },
|
|
41
|
+
callbackPath: rc.authRoutes.deeplink,
|
|
42
|
+
cookiePrefix: rc.cookiePrefix,
|
|
43
|
+
signInURL: signInUrl,
|
|
44
|
+
storage: storage(),
|
|
45
|
+
/* 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. */
|
|
46
|
+
userImageProxy: { enabled: false }
|
|
47
|
+
}
|
|
48
|
+
)
|
|
49
|
+
]
|
|
50
|
+
}));
|
|
51
|
+
client.setupMain({ bridges: true, csp: false, scheme: false, getWindow });
|
|
52
|
+
const electronAuth = new ElectronAuth({
|
|
53
|
+
scheme: rc.deeplinkSchemes.electron,
|
|
54
|
+
userSchema,
|
|
55
|
+
callbackPath: rc.authRoutes.deeplink,
|
|
56
|
+
publicServerUrl,
|
|
57
|
+
getSession,
|
|
58
|
+
getWindow,
|
|
59
|
+
getActiveUserId,
|
|
60
|
+
userIdCookieName,
|
|
61
|
+
onFinishLogin
|
|
62
|
+
}, rc);
|
|
63
|
+
const cookieName = `${new URL(publicServerUrl).protocol === "https:" ? "__Secure-" : ""}${rc.cookiePrefix}.session_token`;
|
|
64
|
+
ipcMain.removeHandler(exchangeSessionChannel);
|
|
65
|
+
ipcMain.handle(exchangeSessionChannel, async () => {
|
|
66
|
+
const win = getWindow();
|
|
67
|
+
if (!win) return;
|
|
68
|
+
const entry = client.getCookie().split(";").map((part) => part.trim()).find((part) => part.startsWith(`${cookieName}=`));
|
|
69
|
+
if (!entry) return;
|
|
70
|
+
const { data } = await client.$fetch("/get-session");
|
|
71
|
+
if (!data?.user) return;
|
|
72
|
+
const received = data.user;
|
|
73
|
+
const user = {
|
|
74
|
+
...received,
|
|
75
|
+
createdAt: received.createdAt.toISOString(),
|
|
76
|
+
updatedAt: received.updatedAt.toISOString()
|
|
77
|
+
};
|
|
78
|
+
await electronAuth.finishLogin(win, {
|
|
79
|
+
user,
|
|
80
|
+
sessionToken: entry.slice(cookieName.length + 1),
|
|
81
|
+
expiresAt: new Date(data.session.expiresAt).getTime()
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
if (isMocked) {
|
|
85
|
+
let pendingMockIdentity = {};
|
|
86
|
+
ipcMain.handle(mockRequestAuthChannel, async (_event, identity) => {
|
|
87
|
+
if (!identity.provider) {
|
|
88
|
+
throw new Error("mockRequestAuth: a provider is required, it has to be one of the configured providers.");
|
|
89
|
+
}
|
|
90
|
+
pendingMockIdentity = identity;
|
|
91
|
+
const state = randomBytes(16).toString("base64url");
|
|
92
|
+
const codeVerifier = randomBytes(32).toString("base64url");
|
|
93
|
+
const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
|
|
94
|
+
const mockStore = globalThis;
|
|
95
|
+
const verifiers = mockStore[Symbol.for("better-auth:electron")] ?? /* @__PURE__ */ new Map();
|
|
96
|
+
mockStore[Symbol.for("better-auth:electron")] = verifiers;
|
|
97
|
+
verifiers.set(state, codeVerifier);
|
|
98
|
+
const url = new URL(signInUrl);
|
|
99
|
+
url.searchParams.set("provider", identity.provider);
|
|
100
|
+
url.searchParams.set("additionalParams", JSON.stringify({ devBypass: "true" }));
|
|
101
|
+
url.searchParams.set("client_id", "electron");
|
|
102
|
+
url.searchParams.set("code_challenge", codeChallenge);
|
|
103
|
+
url.searchParams.set("state", state);
|
|
104
|
+
await shell.openExternal(url.toString());
|
|
105
|
+
});
|
|
106
|
+
const openExternal = shell.openExternal.bind(shell);
|
|
107
|
+
shell.openExternal = async (url) => {
|
|
108
|
+
if (!url.startsWith(publicServerUrl)) return openExternal(url);
|
|
109
|
+
const target = new URL(url);
|
|
110
|
+
const isMockPage = target.pathname === rc.authRoutes.mockAuth;
|
|
111
|
+
const isProviderRequest = target.pathname.endsWith("/electron/init-oauth-proxy");
|
|
112
|
+
if (!isMockPage && !isProviderRequest) return openExternal(url);
|
|
113
|
+
if (!hasDevBypassParams(target)) return openExternal(url);
|
|
114
|
+
const provider = target.searchParams.get("provider");
|
|
115
|
+
const codeChallenge = target.searchParams.get("code_challenge");
|
|
116
|
+
const state = target.searchParams.get("state");
|
|
117
|
+
if (!provider || !codeChallenge || !state) return;
|
|
118
|
+
const { data } = await client.$fetch("/dev/mock", {
|
|
119
|
+
method: "POST",
|
|
120
|
+
body: {
|
|
121
|
+
provider,
|
|
122
|
+
username: pendingMockIdentity.username,
|
|
123
|
+
id: pendingMockIdentity.id,
|
|
124
|
+
devBypassRegistration: pendingMockIdentity.devBypassRegistration ?? false,
|
|
125
|
+
client_id: "electron",
|
|
126
|
+
code_challenge: codeChallenge,
|
|
127
|
+
state,
|
|
128
|
+
verification_prefix: "electron",
|
|
129
|
+
deeplink_scheme: rc.deeplinkSchemes.electron
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
if (!data?.redirectUrl) return;
|
|
133
|
+
await electronAuth.handleUrl(data.redirectUrl);
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
return { client, electronAuth };
|
|
137
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ipcRenderer as IpcRenderer } from "electron";
|
|
2
|
+
import type { ElectronAuthApi } from "../types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Renderer side of the auth bridges: sets up better-auth's own bridges and returns
|
|
5
|
+
* the object to spread into the `electron.api` you expose in the preload.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createElectronAuthApi(ipcRenderer: typeof IpcRenderer): ElectronAuthApi;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { setupRenderer } from "@better-auth/electron/preload";
|
|
2
|
+
import { exchangeSessionChannel, mockRequestAuthChannel } from "../types.js";
|
|
3
|
+
export function createElectronAuthApi(ipcRenderer) {
|
|
4
|
+
setupRenderer();
|
|
5
|
+
return {
|
|
6
|
+
auth: {
|
|
7
|
+
exchangeSession: () => ipcRenderer.invoke(exchangeSessionChannel),
|
|
8
|
+
mockRequestAuth: (options) => ipcRenderer.invoke(mockRequestAuthChannel, options),
|
|
9
|
+
betterAuth: {
|
|
10
|
+
authenticate: (data) => ipcRenderer.invoke("better-auth:authenticate", data),
|
|
11
|
+
requestAuth: (options) => ipcRenderer.invoke("better-auth:requestAuth", options)
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { ElectronClientOptions, ExposedBridges } from "@better-auth/electron/client";
|
|
2
|
+
export type ElectronUserEntry = {
|
|
3
|
+
directory: string;
|
|
4
|
+
/** Absent until the user registers, the id is what identifies them. */
|
|
5
|
+
username?: string;
|
|
6
|
+
isLocal: boolean;
|
|
7
|
+
id: string;
|
|
8
|
+
};
|
|
9
|
+
export type ElectronAuthApi = {
|
|
10
|
+
auth: {
|
|
11
|
+
exchangeSession: () => Promise<void>;
|
|
12
|
+
/** Test only stand-in for better-auth's `requestAuth`, so the mock login can carry an identity. */
|
|
13
|
+
mockRequestAuth: (options: {
|
|
14
|
+
username?: string;
|
|
15
|
+
id?: string;
|
|
16
|
+
provider?: string;
|
|
17
|
+
devBypassRegistration?: boolean;
|
|
18
|
+
}) => Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* better-auth's own bridges. It puts each of them straight on `window`, ugly, so we put the 2 we actually use under a nice name space.
|
|
21
|
+
*/
|
|
22
|
+
betterAuth: Pick<ExposedBridges<ElectronClientOptions>, "authenticate" | "requestAuth">;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* What we expect to find at `window.electron.api`: our own auth bridges plus the app's user registry, which the app implements and exposes.
|
|
27
|
+
*
|
|
28
|
+
* Temporary, until `@witchcraft/nuxt-electron` implements plugins and exports its types.
|
|
29
|
+
*/
|
|
30
|
+
export type ExpectedElectronApi = ElectronAuthApi & {
|
|
31
|
+
users: {
|
|
32
|
+
/** Every stored user, local and external. Dir names carry the kind, `<id>` or `local-<id>`. */
|
|
33
|
+
list: () => Promise<ElectronUserEntry[]>;
|
|
34
|
+
create: (options: {
|
|
35
|
+
id: string;
|
|
36
|
+
username: string;
|
|
37
|
+
}) => Promise<void>;
|
|
38
|
+
update: (options: {
|
|
39
|
+
id: string;
|
|
40
|
+
patch: {
|
|
41
|
+
username?: string;
|
|
42
|
+
name?: string;
|
|
43
|
+
image?: string;
|
|
44
|
+
};
|
|
45
|
+
}) => Promise<void>;
|
|
46
|
+
delete: (id: string) => Promise<void>;
|
|
47
|
+
/** Persists the user as the active one and reopens the window in that user's partition. */
|
|
48
|
+
switchUserAndSoftReload: (id: string | undefined) => Promise<void>;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
/** Test-only bridge, preload invokes what main handles. */
|
|
52
|
+
export declare const mockRequestAuthChannel = "auth:mockRequestAuth";
|
|
53
|
+
/** Session exchange bridge, preload invokes what main handles. */
|
|
54
|
+
export declare const exchangeSessionChannel = "auth.exchangeSession";
|
|
@@ -2,34 +2,50 @@ import { jsonSafeParse } from "@alanscodelog/utils/jsonSafeParse";
|
|
|
2
2
|
import {
|
|
3
3
|
defineNuxtRouteMiddleware,
|
|
4
4
|
useFetch,
|
|
5
|
-
useRuntimeConfig,
|
|
6
5
|
useState
|
|
7
6
|
} from "#imports";
|
|
8
|
-
import {
|
|
7
|
+
import { useAuth } from "../composables/useAuth.js";
|
|
8
|
+
import { externalExpiryStorageKey, fetchStateKey, isExpiredStateKey, userStorageKey } from "../types.js";
|
|
9
|
+
import { deserializeAuthLocalUser } from "../utils/deserializeAuthLocalUser.js";
|
|
9
10
|
export default defineNuxtRouteMiddleware(async (_to, _from) => {
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
const
|
|
11
|
+
const auth = useAuth();
|
|
12
|
+
const doFetch = useState(fetchStateKey, () => true);
|
|
13
|
+
const userData = useState(userStorageKey, () => void 0);
|
|
14
|
+
const isExpired = useState(isExpiredStateKey, () => false);
|
|
13
15
|
if (import.meta.client && import.meta.dev) {
|
|
14
16
|
console.log({ ns: "auth:middleware:authGlobal", doFetch: doFetch.value, userData: userData.value });
|
|
15
17
|
}
|
|
18
|
+
const stored = import.meta.client ? jsonSafeParse(localStorage.getItem(userStorageKey) ?? "null") : void 0;
|
|
19
|
+
const storedUser = stored?.isOk && stored.value ? deserializeAuthLocalUser(stored.value) : void 0;
|
|
16
20
|
if (doFetch.value) {
|
|
17
|
-
const res = await useFetch(getAuthApiRoute(useRuntimeConfig().public, "usersInfo"));
|
|
18
21
|
doFetch.value = false;
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
if (import.meta.server) {
|
|
23
|
+
const session = await auth.client.useSession(useFetch);
|
|
24
|
+
userData.value = session?.data.value?.user ?? void 0;
|
|
25
|
+
} else {
|
|
26
|
+
const { data } = await auth.client.getSession().catch(() => ({ data: void 0 }));
|
|
27
|
+
const sessionUser = data?.user ? deserializeAuthLocalUser(data.user) : void 0;
|
|
28
|
+
if (sessionUser && storedUser?.type === "external") {
|
|
29
|
+
userData.value = { ...sessionUser, type: "external" };
|
|
30
|
+
localStorage.setItem(userStorageKey, JSON.stringify(userData.value));
|
|
31
|
+
if (data?.session?.expiresAt) {
|
|
32
|
+
localStorage.setItem(externalExpiryStorageKey, String(new Date(data.session.expiresAt).getTime()));
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
userData.value = sessionUser ?? storedUser;
|
|
36
|
+
}
|
|
26
37
|
}
|
|
38
|
+
} else if (storedUser?.type) {
|
|
39
|
+
userData.value = storedUser;
|
|
40
|
+
}
|
|
41
|
+
if (import.meta.client) {
|
|
42
|
+
isExpired.value = userData.value?.type === "external" ? auth.isExpired() : false;
|
|
27
43
|
}
|
|
28
44
|
if (import.meta.client && import.meta.dev) {
|
|
29
45
|
console.log({
|
|
30
46
|
ns: "auth:middleware:authGlobal:fetched",
|
|
31
47
|
userData: userData.value,
|
|
32
|
-
|
|
48
|
+
isExpired: isExpired.value
|
|
33
49
|
});
|
|
34
50
|
}
|
|
35
51
|
});
|
|
@@ -10,14 +10,14 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
|
|
|
10
10
|
const meta = to.meta.auth ?? {};
|
|
11
11
|
const isRegistered = auth.user.value?.isRegistered ?? false;
|
|
12
12
|
const isAuthenticated = !!auth.user.value;
|
|
13
|
-
const fallbackRedirectPath = isAuthenticated && isRegistered ? auth.authRoutes.postRegisteredLogin : isAuthenticated && !isRegistered ? auth.authRoutes.register : auth.authRoutes.
|
|
13
|
+
const fallbackRedirectPath = isAuthenticated && isRegistered ? auth.authRoutes.postRegisteredLogin : isAuthenticated && !isRegistered ? auth.authRoutes.register : auth.authRoutes.unauthenticated;
|
|
14
14
|
const query = typeof from.query === "object" && meta.keepQuery ? isArray(meta.keepQuery) ? pick(from.query, meta.keepQuery) : from.query : {};
|
|
15
15
|
if (typeof meta.redirectTo === "function") {
|
|
16
16
|
meta.redirectTo = meta.redirectTo();
|
|
17
17
|
}
|
|
18
18
|
const redirectTo = (!meta.redirectTo ? fallbackRedirectPath : meta.redirectTo === "$login" ? auth.authRoutes.login : meta.redirectTo === "$register" ? auth.authRoutes.register : meta.redirectTo === "$postRegisteredLogin" ? auth.authRoutes.postRegisteredLogin : meta.redirectTo === "$externalCode" ? auth.authRoutes.externalCode : meta.redirectTo && keys(config.additionalMiddlewarePaths ?? []).includes(meta.redirectTo) ? config.additionalMiddlewarePaths[meta.redirectTo] : meta.redirectTo) + (keys(query).length > 0 ? `?${new URLSearchParams(query).toString()}` : "");
|
|
19
19
|
const matchesCondition = typeof meta.only === "function" ? meta.only(auth) : !meta.only && !isAuthenticated && isRegistered ? true : meta.only === "authenticated" && isAuthenticated || meta.only === "authenticated-registered" && isAuthenticated && isRegistered || meta.only === "registered" && isRegistered || meta.only === "authenticated-unregistered" && isAuthenticated && !isRegistered || meta.only === "unauthenticated" && !isAuthenticated;
|
|
20
|
-
const doRedirect = !matchesCondition && to.path !== redirectTo;
|
|
20
|
+
const doRedirect = !matchesCondition && to.path !== redirectTo && !(import.meta.server && meta.disableServerRedirect);
|
|
21
21
|
if (import.meta.client && import.meta.dev) {
|
|
22
22
|
console.log({
|
|
23
23
|
ns: "auth:middleware:authProtected",
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { AuthUser } from "../../types.js";
|
|
2
|
+
/**
|
|
3
|
+
*{@link ExternalPlugin} for the renderer side of electron. useAuth will divert methods to it as needed when the plugin reports it is on electron.
|
|
4
|
+
*/
|
|
5
|
+
export declare function electronNuxtAuthPlugin(): {
|
|
6
|
+
id: "electron-nuxt-auth";
|
|
7
|
+
externalApiActionsKey: "electronNuxtAuthPlugin";
|
|
8
|
+
getActions: () => {
|
|
9
|
+
electronNuxtAuthPlugin: {
|
|
10
|
+
isActive: () => boolean;
|
|
11
|
+
/** Starts a login outside the app, in the system browser. */
|
|
12
|
+
login: ({ provider, isDevBypass, username, isDevBypassRegistration }?: {
|
|
13
|
+
/** The provider the system browser is sent to. */
|
|
14
|
+
provider?: string;
|
|
15
|
+
/** Use the mock sign-in instead of the real one, the server has to permit it. */
|
|
16
|
+
isDevBypass?: boolean;
|
|
17
|
+
/** The user the mock signs in as. */
|
|
18
|
+
username?: string;
|
|
19
|
+
/** Create the mock user already registered, so the app skips the registration page. Always true through the built in utils, see the `isDevBypassRegistration` option on {@link ExternalPlugin} for why. */
|
|
20
|
+
isDevBypassRegistration?: boolean;
|
|
21
|
+
}) => Promise<void>;
|
|
22
|
+
local: {
|
|
23
|
+
/** Every stored user, local and external, lifted to full users with a `type` marker. */
|
|
24
|
+
list: () => Promise<AuthUser[]>;
|
|
25
|
+
create: ({ id, username }: {
|
|
26
|
+
id: string;
|
|
27
|
+
username: string;
|
|
28
|
+
}) => Promise<void>;
|
|
29
|
+
/** Switches to this user, throwing if the registry no longer has them. */
|
|
30
|
+
activate: (id: string) => Promise<void>;
|
|
31
|
+
update: (id: string, patch: {
|
|
32
|
+
username?: string;
|
|
33
|
+
name?: string;
|
|
34
|
+
image?: string;
|
|
35
|
+
}) => Promise<void>;
|
|
36
|
+
delete: (id: string) => Promise<void>;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Tells the app's about an external user's new profile.
|
|
40
|
+
*/
|
|
41
|
+
onUserUpdate: (id: string, patch: {
|
|
42
|
+
username?: string;
|
|
43
|
+
name?: string;
|
|
44
|
+
image?: string;
|
|
45
|
+
}) => Promise<void>;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { navigateTo, useRuntimeConfig, useState } from "#app";
|
|
2
|
+
import { userStorageKey } from "../../types.js";
|
|
3
|
+
export function electronNuxtAuthPlugin() {
|
|
4
|
+
const api = !import.meta.server ? window.electron?.api : void 0;
|
|
5
|
+
function assertLoggedOut(method) {
|
|
6
|
+
if (useState(userStorageKey, () => void 0).value) {
|
|
7
|
+
throw new Error(`${method}: a user is signed in, sign out before managing local users.`);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
return {
|
|
11
|
+
id: "electron-nuxt-auth",
|
|
12
|
+
externalApiActionsKey: "electronNuxtAuthPlugin",
|
|
13
|
+
getActions: () => ({
|
|
14
|
+
electronNuxtAuthPlugin: {
|
|
15
|
+
isActive: () => !!api,
|
|
16
|
+
/** Starts a login outside the app, in the system browser. */
|
|
17
|
+
login: async ({
|
|
18
|
+
provider,
|
|
19
|
+
isDevBypass = false,
|
|
20
|
+
username,
|
|
21
|
+
isDevBypassRegistration = false
|
|
22
|
+
} = {}) => {
|
|
23
|
+
if (isDevBypass) {
|
|
24
|
+
void api.auth.mockRequestAuth({ provider, username, devBypassRegistration: isDevBypassRegistration });
|
|
25
|
+
} else {
|
|
26
|
+
void api.auth.betterAuth.requestAuth({ provider });
|
|
27
|
+
}
|
|
28
|
+
const callbackUrl = new URL(useRuntimeConfig().public.auth.authRoutes.deeplink, window.location.origin);
|
|
29
|
+
callbackUrl.searchParams.set("provider", `${provider}`);
|
|
30
|
+
await navigateTo(callbackUrl.toString(), { external: true });
|
|
31
|
+
},
|
|
32
|
+
local: {
|
|
33
|
+
/** Every stored user, local and external, lifted to full users with a `type` marker. */
|
|
34
|
+
list: async () => {
|
|
35
|
+
const now = /* @__PURE__ */ new Date();
|
|
36
|
+
const users = [];
|
|
37
|
+
for (const entry of await api.users.list()) {
|
|
38
|
+
if (entry.isLocal && !entry.username) {
|
|
39
|
+
console.error(`[nuxt-auth] local user ${entry.id} has no username, skipping it.`);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
users.push({
|
|
43
|
+
id: entry.id,
|
|
44
|
+
email: "",
|
|
45
|
+
emailVerified: false,
|
|
46
|
+
image: null,
|
|
47
|
+
isRegistered: true,
|
|
48
|
+
createdAt: now,
|
|
49
|
+
updatedAt: now,
|
|
50
|
+
name: entry.username ?? "",
|
|
51
|
+
type: entry.isLocal ? "local" : "external",
|
|
52
|
+
username: entry.username ?? null
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return users;
|
|
56
|
+
},
|
|
57
|
+
create: async ({ id, username }) => {
|
|
58
|
+
assertLoggedOut("electronNuxtAuthPlugin.local.create");
|
|
59
|
+
await api.users.create({ id, username });
|
|
60
|
+
},
|
|
61
|
+
/** Switches to this user, throwing if the registry no longer has them. */
|
|
62
|
+
activate: async (id) => {
|
|
63
|
+
assertLoggedOut("electronNuxtAuthPlugin.local.activate");
|
|
64
|
+
const stored = await api.users.list();
|
|
65
|
+
if (!stored.some((entry) => entry.id === id)) {
|
|
66
|
+
throw new Error("electronNuxtAuthPlugin.local.activate: the user no longer exists.");
|
|
67
|
+
}
|
|
68
|
+
await api.users.switchUserAndSoftReload(id);
|
|
69
|
+
},
|
|
70
|
+
update: async (id, patch) => {
|
|
71
|
+
await api.users.update({ id, patch });
|
|
72
|
+
},
|
|
73
|
+
delete: async (id) => {
|
|
74
|
+
await api.users.delete(id);
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
/**
|
|
78
|
+
* Tells the app's about an external user's new profile.
|
|
79
|
+
*/
|
|
80
|
+
onUserUpdate: async (id, patch) => {
|
|
81
|
+
await api.users.update({ id, patch });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
})
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
import type { AuthUser } from "../../types.js";
|
|
3
|
+
export declare function localOnlyUsers({ storageKey, userSchema }?: {
|
|
4
|
+
storageKey?: string;
|
|
5
|
+
/** Validates each stored user, e.g. `zAuthUserStored`. Anything that does not parse is dropped. */
|
|
6
|
+
userSchema?: StandardSchemaV1;
|
|
7
|
+
}): {
|
|
8
|
+
id: "local-only-users";
|
|
9
|
+
getActions: () => {
|
|
10
|
+
localOnlyUsers: {
|
|
11
|
+
list: () => AuthUser[];
|
|
12
|
+
create: (username: string, { switch: doSwitch }?: {
|
|
13
|
+
switch?: boolean;
|
|
14
|
+
}) => AuthUser;
|
|
15
|
+
activate: (username: string) => AuthUser | undefined;
|
|
16
|
+
update: (id: string, patch: {
|
|
17
|
+
username?: string;
|
|
18
|
+
name?: string;
|
|
19
|
+
image?: string;
|
|
20
|
+
}) => AuthUser | undefined;
|
|
21
|
+
delete: (id: string) => void;
|
|
22
|
+
logout: () => void;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { jsonSafeParse } from "@alanscodelog/utils/jsonSafeParse";
|
|
2
|
+
import { useState } from "#app";
|
|
3
|
+
import { localOnlyUsersStorageKey, userStorageKey } from "../../types.js";
|
|
4
|
+
import { deserializeAuthLocalUser } from "../../utils/deserializeAuthLocalUser.js";
|
|
5
|
+
export function localOnlyUsers({
|
|
6
|
+
storageKey = localOnlyUsersStorageKey,
|
|
7
|
+
userSchema
|
|
8
|
+
} = {}) {
|
|
9
|
+
function readStored() {
|
|
10
|
+
const parsed = jsonSafeParse(localStorage.getItem(storageKey) ?? "[]");
|
|
11
|
+
if (!parsed.isOk || !Array.isArray(parsed.value)) return [];
|
|
12
|
+
const users = [];
|
|
13
|
+
const dropped = [];
|
|
14
|
+
for (const entry of parsed.value) {
|
|
15
|
+
if (userSchema) {
|
|
16
|
+
const result = userSchema["~standard"].validate(entry);
|
|
17
|
+
if (result instanceof Promise) throw new Error("localOnlyUsers: async schemas cannot validate stored users.");
|
|
18
|
+
if ("issues" in result) {
|
|
19
|
+
dropped.push(String(entry.username ?? entry.id));
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
users.push(deserializeAuthLocalUser(result.value));
|
|
23
|
+
} else {
|
|
24
|
+
users.push(deserializeAuthLocalUser(entry));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (dropped.length) {
|
|
28
|
+
console.warn(`[nuxt-auth] localOnlyUsers dropped stored users that do not match userSchema: ${dropped.join(", ")}`);
|
|
29
|
+
}
|
|
30
|
+
return users;
|
|
31
|
+
}
|
|
32
|
+
function writeStored(users) {
|
|
33
|
+
localStorage.setItem(storageKey, JSON.stringify(users));
|
|
34
|
+
}
|
|
35
|
+
function assertLoggedOut(method) {
|
|
36
|
+
if (useState(userStorageKey, () => void 0).value) {
|
|
37
|
+
throw new Error(`${method}: a user is signed in, sign out before managing local users.`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
id: "local-only-users",
|
|
42
|
+
getActions: () => ({
|
|
43
|
+
localOnlyUsers: {
|
|
44
|
+
list: () => {
|
|
45
|
+
return readStored();
|
|
46
|
+
},
|
|
47
|
+
create: (username, { switch: doSwitch = true } = {}) => {
|
|
48
|
+
assertLoggedOut("localOnlyUsers.create");
|
|
49
|
+
const now = /* @__PURE__ */ new Date();
|
|
50
|
+
const user = {
|
|
51
|
+
id: crypto.randomUUID(),
|
|
52
|
+
email: "",
|
|
53
|
+
emailVerified: false,
|
|
54
|
+
name: username,
|
|
55
|
+
image: null,
|
|
56
|
+
username,
|
|
57
|
+
isRegistered: true,
|
|
58
|
+
createdAt: now,
|
|
59
|
+
updatedAt: now,
|
|
60
|
+
type: "local"
|
|
61
|
+
};
|
|
62
|
+
const stored = readStored();
|
|
63
|
+
if (stored.some((entry) => entry.username === username)) {
|
|
64
|
+
throw new Error(`localOnlyUsers.create: a user with the username "${username}" already exists.`);
|
|
65
|
+
}
|
|
66
|
+
writeStored([...stored, user]);
|
|
67
|
+
if (doSwitch) {
|
|
68
|
+
useState(userStorageKey, () => void 0).value = user;
|
|
69
|
+
localStorage.setItem(userStorageKey, JSON.stringify(user));
|
|
70
|
+
}
|
|
71
|
+
return user;
|
|
72
|
+
},
|
|
73
|
+
activate: (username) => {
|
|
74
|
+
assertLoggedOut("localOnlyUsers.activate");
|
|
75
|
+
const user = readStored().find((entry) => entry.username === username);
|
|
76
|
+
if (!user) return void 0;
|
|
77
|
+
useState(userStorageKey, () => void 0).value = user;
|
|
78
|
+
localStorage.setItem(userStorageKey, JSON.stringify(user));
|
|
79
|
+
return user;
|
|
80
|
+
},
|
|
81
|
+
update: (id, patch) => {
|
|
82
|
+
const stored = readStored();
|
|
83
|
+
const user = stored.find((entry) => entry.id === id);
|
|
84
|
+
if (!user) return void 0;
|
|
85
|
+
const updated = { ...user, ...patch, updatedAt: /* @__PURE__ */ new Date() };
|
|
86
|
+
writeStored(stored.map((entry) => entry.id === id ? updated : entry));
|
|
87
|
+
const userData = useState(userStorageKey, () => void 0);
|
|
88
|
+
if (userData.value?.id === id) {
|
|
89
|
+
userData.value = updated;
|
|
90
|
+
localStorage.setItem(userStorageKey, JSON.stringify(updated));
|
|
91
|
+
}
|
|
92
|
+
return updated;
|
|
93
|
+
},
|
|
94
|
+
delete: (id) => {
|
|
95
|
+
assertLoggedOut("localOnlyUsers.delete");
|
|
96
|
+
writeStored(readStored().filter((entry) => entry.id !== id));
|
|
97
|
+
const userData = useState(userStorageKey, () => void 0);
|
|
98
|
+
if (userData.value?.id === id) {
|
|
99
|
+
userData.value = void 0;
|
|
100
|
+
localStorage.removeItem(userStorageKey);
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
logout: () => {
|
|
104
|
+
useState(userStorageKey, () => void 0).value = void 0;
|
|
105
|
+
localStorage.removeItem(userStorageKey);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare function devMock({ generateUser, authRoutes, enabledProviders, usernameValidator, maxUsernameLength, transferCodeTtlMs }: {
|
|
3
|
+
generateUser?: (() => any);
|
|
4
|
+
authRoutes: any;
|
|
5
|
+
/** The providers the app configured, any other name is refused. */
|
|
6
|
+
enabledProviders: string[];
|
|
7
|
+
/** The app's username schema, so a bypassed user cannot pick a name the app would refuse. */
|
|
8
|
+
usernameValidator?: (username: string) => Promise<boolean>;
|
|
9
|
+
/** Longest username the mock name builder emits, defaults to 32. */
|
|
10
|
+
maxUsernameLength?: number;
|
|
11
|
+
/** How long a transfer code stays valid, defaults to 5 minutes. */
|
|
12
|
+
transferCodeTtlMs?: number;
|
|
13
|
+
}): {
|
|
14
|
+
id: string;
|
|
15
|
+
hooks: {
|
|
16
|
+
before: {
|
|
17
|
+
matcher: (context: any) => any;
|
|
18
|
+
handler: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<any>>;
|
|
19
|
+
}[];
|
|
20
|
+
};
|
|
21
|
+
endpoints: {
|
|
22
|
+
devMock: import("better-auth").StrictEndpoint<"/dev/mock", {
|
|
23
|
+
method: "POST";
|
|
24
|
+
body: z.ZodObject<{
|
|
25
|
+
username: z.ZodOptional<z.ZodString>;
|
|
26
|
+
id: z.ZodOptional<z.ZodString>;
|
|
27
|
+
provider: z.ZodString;
|
|
28
|
+
code_challenge: z.ZodOptional<z.ZodString>;
|
|
29
|
+
state: z.ZodOptional<z.ZodString>;
|
|
30
|
+
verification_prefix: z.ZodOptional<z.ZodString>;
|
|
31
|
+
deeplink_scheme: z.ZodOptional<z.ZodString>;
|
|
32
|
+
devBypassRegistration: z.ZodOptional<z.ZodBoolean>;
|
|
33
|
+
}, z.core.$strip>;
|
|
34
|
+
}, any>;
|
|
35
|
+
/**
|
|
36
|
+
* Moves the session row's expiry back, so a test can run a short session without
|
|
37
|
+
* waiting for a real one.
|
|
38
|
+
*
|
|
39
|
+
* The token has to arrive as a `Cookie` header (`headers: { cookie: "name=value" }`),
|
|
40
|
+
* because `getSignedCookie` reads the request's parsed cookies and a signed value in a
|
|
41
|
+
* body cannot be verified by it. Without the header it finds no cookie and updates
|
|
42
|
+
* nothing.
|
|
43
|
+
*/
|
|
44
|
+
devMockSession: import("better-auth").StrictEndpoint<"/dev/mock/session", {
|
|
45
|
+
method: "POST";
|
|
46
|
+
body: z.ZodObject<{
|
|
47
|
+
expiresAt: z.ZodNumber;
|
|
48
|
+
}, z.core.$strip>;
|
|
49
|
+
}, any>;
|
|
50
|
+
};
|
|
51
|
+
};
|