@vite-hub/auth 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +213 -41
  3. package/dist/agent.d.ts +25 -13
  4. package/dist/agent.js +19 -5
  5. package/dist/application-path-C290OAIs.js +18 -0
  6. package/dist/cli-mgXvsBtA.d.ts +85 -0
  7. package/dist/cli.d.ts +7 -0
  8. package/dist/cli.js +68 -0
  9. package/dist/console-B7eERmGv.d.ts +180 -0
  10. package/dist/console-runtime-bZQtnX2Y.d.ts +39 -0
  11. package/dist/console-runtime.d.ts +3 -0
  12. package/dist/console-runtime.js +819 -0
  13. package/dist/console-types-CmmnKGMx.js +38 -0
  14. package/dist/console.d.ts +7 -0
  15. package/dist/console.js +15 -0
  16. package/dist/error-diagnostics-CL0yjHiM.js +79 -0
  17. package/dist/events-BkmK2dFY.d.ts +486 -0
  18. package/dist/events-P7mI4IQb.js +196 -0
  19. package/dist/events-config-CjcFOhTE.js +177 -0
  20. package/dist/host-declarations.d.ts +17 -0
  21. package/dist/index.d.ts +6 -5
  22. package/dist/index.js +40 -28
  23. package/dist/inspect-DPtsW8dB.d.ts +36 -0
  24. package/dist/nuxt.d.ts +59 -0
  25. package/dist/nuxt.js +93 -0
  26. package/dist/presets-BGZi6Dfu.d.ts +25 -0
  27. package/dist/presets.d.ts +2 -0
  28. package/dist/presets.js +32 -0
  29. package/dist/runtime/console.d.ts +7 -0
  30. package/dist/runtime/console.js +42 -0
  31. package/dist/runtime/empty-definition.d.ts +1 -2
  32. package/dist/runtime/nuxt.d.ts +3 -0
  33. package/dist/runtime/nuxt.js +9 -0
  34. package/dist/runtime/vue-nuxt.d.ts +3 -0
  35. package/dist/runtime/vue-nuxt.js +8 -0
  36. package/dist/server-B7LU19dS.js +1730 -0
  37. package/dist/server-CTD_JAww.d.ts +77 -0
  38. package/dist/server.d.ts +3 -20
  39. package/dist/server.js +3 -2
  40. package/dist/set-cookie-2as_DbHe.js +75 -0
  41. package/dist/shared-DnpgYiLF.js +15 -0
  42. package/dist/vite-COWkwxsj.js +990 -0
  43. package/dist/vite.d.ts +34 -10
  44. package/dist/vite.js +2 -995
  45. package/dist/vue.d.ts +55 -0
  46. package/dist/vue.js +112 -0
  47. package/package.json +92 -17
  48. package/dist/server-Diw3mAbX.js +0 -322
  49. package/dist/shared-QSYBHaMG.js +0 -12
  50. package/dist/types-B0fg9XFd.d.ts +0 -106
package/dist/vue.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /// <reference path="./host-declarations.d.ts" />
2
+ import { SessionQueryParams } from "better-auth";
3
+ import { ComputedRef, DeepReadonly, Ref } from "vue";
4
+ import { BetterFetchError, VueAuthClient, VueAuthClient as VueAuthClient$1, createAuthClient as createAuthClient$1 } from "better-auth/vue";
5
+ //#region src/vue.d.ts
6
+ type NuxtApp = {
7
+ runWithContext<T>(run: () => T): T;
8
+ };
9
+ /** Internal bridge installed by the Nuxt module, without making `#app` a dependency of this entry. */
10
+ export declare function setNuxtAppResolver(resolver: (() => NuxtApp | undefined) | undefined): void;
11
+ /**
12
+ * Better Auth's Vue client with the same options, types, and calls, which loads `better-auth/vue` the first time it is
13
+ * used. Creating one costs nothing, so an app can create it up front and only pages that sign in pay for Better Auth.
14
+ * Calls such as `signIn.social()` wait for the load. Hooks such as `useSession()` return a ref at once that is
15
+ * pending until then, and stays pending during server rendering. Use `loadAuthClient()` for anything else, such as `$store`.
16
+ */
17
+ export declare const createAuthClient: typeof createAuthClient$1;
18
+ /** Better Auth's own Vue client behind one that `createAuthClient()` returned, once it has loaded. */
19
+ export declare function loadAuthClient<Client extends VueAuthClient$1<any>>(client: Client): Promise<Client>;
20
+ export declare const authClient: VueAuthClient$1<{}>;
21
+ export declare function useAuthClient(): typeof authClient;
22
+ export interface AuthSessionState<Client extends VueAuthClient$1<any> = typeof authClient> {
23
+ data: Client["$Infer"]["Session"] | null;
24
+ error: BetterFetchError | null;
25
+ isPending: boolean;
26
+ isRefetching: boolean;
27
+ refetch: (queryParams?: {
28
+ query?: SessionQueryParams;
29
+ }) => Promise<void>;
30
+ }
31
+ type AuthSessionRef<Client extends VueAuthClient$1<any> = typeof authClient> = DeepReadonly<Ref<AuthSessionState<Client>>>;
32
+ export declare function useSession<Client extends VueAuthClient$1<any> = typeof authClient>(client?: Client): AuthSessionRef<Client>;
33
+ type ClientSession<Client extends VueAuthClient$1<any>> = Client["$Infer"]["Session"];
34
+ export interface UserSession<Client extends VueAuthClient$1<any> = typeof authClient> {
35
+ data: ComputedRef<ClientSession<Client> | null>;
36
+ error: ComputedRef<BetterFetchError | null>;
37
+ /** The id of the administrator who opened this session as `user`, or `null`. Better Auth's admin plugin sets it. */
38
+ impersonatedBy: ComputedRef<string | null>;
39
+ loggedIn: ComputedRef<boolean>;
40
+ pending: ComputedRef<boolean>;
41
+ ready: ComputedRef<boolean>;
42
+ refresh: () => Promise<void>;
43
+ session: ComputedRef<ClientSession<Client>["session"] | null>;
44
+ signIn: Client["signIn"];
45
+ signOut: Client["signOut"];
46
+ signUp: Client["signUp"];
47
+ /** End the impersonation session and restore the administrator's own session. */
48
+ stopImpersonating: () => Promise<void>;
49
+ user: ComputedRef<ClientSession<Client>["user"] | null>;
50
+ }
51
+ export declare function useUserSession<Client extends VueAuthClient$1<any> = typeof authClient>(client?: Client): UserSession<Client>;
52
+ export declare function useSignIn(): typeof authClient.signIn;
53
+ export declare function useSignUp(): typeof authClient.signUp;
54
+ //#endregion
55
+ export type { VueAuthClient };
package/dist/vue.js ADDED
@@ -0,0 +1,112 @@
1
+ import { t as resolveAuthMountPath } from "./application-path-C290OAIs.js";
2
+ import { computed, getCurrentInstance, getCurrentScope, shallowRef, watch } from "vue";
3
+ //#region src/vue.ts
4
+ const LOAD = Symbol.for("vitehub.auth.client.load");
5
+ let nuxtAppResolver;
6
+ /** Internal bridge installed by the Nuxt module, without making `#app` a dependency of this entry. */
7
+ function setNuxtAppResolver(resolver) {
8
+ nuxtAppResolver = resolver;
9
+ }
10
+ /** The state of a client hook, such as `useSession()`, before Better Auth's client has loaded. */
11
+ const pendingState = (refetch) => ({
12
+ data: null,
13
+ error: null,
14
+ isPending: true,
15
+ isRefetching: false,
16
+ refetch
17
+ });
18
+ /**
19
+ * Better Auth's Vue client with the same options, types, and calls, which loads `better-auth/vue` the first time it is
20
+ * used. Creating one costs nothing, so an app can create it up front and only pages that sign in pay for Better Auth.
21
+ * Calls such as `signIn.social()` wait for the load. Hooks such as `useSession()` return a ref at once that is
22
+ * pending until then, and stays pending during server rendering. Use `loadAuthClient()` for anything else, such as `$store`.
23
+ */
24
+ const createAuthClient = (options) => {
25
+ let loaded;
26
+ const load = () => loaded ??= import("better-auth/vue").then((module) => module.createAuthClient(options));
27
+ function hook(name, args) {
28
+ const scope = getCurrentScope();
29
+ const nuxtApp = nuxtAppResolver?.() || getCurrentInstance()?.appContext.config.globalProperties.$nuxt;
30
+ const real = (client) => Reflect.get(client, name)(...args);
31
+ if (typeof args[0] === "function") return load().then((client) => runIn(scope, () => nuxtApp ? nuxtApp.runWithContext(() => real(client)) : real(client)));
32
+ const pending = pendingState(async (...query) => {
33
+ await load();
34
+ const current = state.value;
35
+ return current === pending ? void 0 : current.refetch?.(...query);
36
+ });
37
+ const state = shallowRef(pending);
38
+ if (!("window" in globalThis)) return state;
39
+ load().then((client) => {
40
+ if (scope && !scope.active) return;
41
+ runIn(scope, () => watch(real(client), (value) => state.value = value, { immediate: true }));
42
+ });
43
+ return state;
44
+ }
45
+ function call(path) {
46
+ return new Proxy(function() {}, {
47
+ get(_, key) {
48
+ if (key === LOAD && !path.length) return load;
49
+ if (typeof key !== "string" || key === "then" || key === "catch" || key === "finally") return void 0;
50
+ if (!path.length && /^use[A-Z]/.test(key)) return (...args) => hook(key, args);
51
+ return call([...path, key]);
52
+ },
53
+ async apply(_, __, args) {
54
+ const client = await load();
55
+ return path.reduce((node, key) => Reflect.get(Object(node), key), client)(...args);
56
+ }
57
+ });
58
+ }
59
+ return call([]);
60
+ };
61
+ /** Run `run` in the scope the hook was called in, so its watchers stop with the component that called it. */
62
+ function runIn(scope, run) {
63
+ return scope ? scope.run(run) : run();
64
+ }
65
+ /** Better Auth's own Vue client behind one that `createAuthClient()` returned, once it has loaded. */
66
+ async function loadAuthClient(client) {
67
+ const load = Reflect.get(client, LOAD);
68
+ return load ? await load() : client;
69
+ }
70
+ const authClient = createAuthClient({ basePath: resolveAuthMountPath("/api/auth") });
71
+ function useAuthClient() {
72
+ return authClient;
73
+ }
74
+ function useSession(client = authClient) {
75
+ return client.useSession();
76
+ }
77
+ function useUserSession(client = authClient) {
78
+ const state = client.useSession();
79
+ return {
80
+ data: computed(() => state.value.data),
81
+ error: computed(() => state.value.error),
82
+ impersonatedBy: computed(() => {
83
+ const value = state.value.data?.session ? Reflect.get(state.value.data.session, "impersonatedBy") : void 0;
84
+ return typeof value === "string" && value ? value : null;
85
+ }),
86
+ loggedIn: computed(() => Boolean(state.value.data?.session && state.value.data?.user)),
87
+ pending: computed(() => state.value.isPending || state.value.isRefetching),
88
+ ready: computed(() => !state.value.isPending),
89
+ refresh: () => state.value.refetch(),
90
+ session: computed(() => state.value.data?.session ?? null),
91
+ signIn: client.signIn,
92
+ signOut: client.signOut,
93
+ signUp: client.signUp,
94
+ async stopImpersonating() {
95
+ await client.$fetch("/admin/stop-impersonating", {
96
+ method: "POST",
97
+ body: {},
98
+ throw: true
99
+ });
100
+ await state.value.refetch();
101
+ },
102
+ user: computed(() => state.value.data?.user ?? null)
103
+ };
104
+ }
105
+ function useSignIn() {
106
+ return authClient.signIn;
107
+ }
108
+ function useSignUp() {
109
+ return authClient.signUp;
110
+ }
111
+ //#endregion
112
+ export { authClient, createAuthClient, loadAuthClient, setNuxtAppResolver, useAuthClient, useSession, useSignIn, useSignUp, useUserSession };
package/package.json CHANGED
@@ -1,15 +1,19 @@
1
1
  {
2
2
  "name": "@vite-hub/auth",
3
- "version": "0.0.3",
3
+ "version": "0.1.0",
4
4
  "description": "Better Auth-powered authentication primitives and Vite integration for ViteHub.",
5
5
  "keywords": [
6
6
  "auth",
7
7
  "authentication",
8
8
  "better-auth",
9
+ "nuxt",
10
+ "nuxt-module",
11
+ "session",
12
+ "typescript",
9
13
  "vite",
10
14
  "vitehub"
11
15
  ],
12
- "homepage": "https://github.com/vite-hub/vitehub#readme",
16
+ "homepage": "https://vitehub.dev",
13
17
  "bugs": "https://github.com/vite-hub/vitehub/issues",
14
18
  "license": "Apache-2.0",
15
19
  "author": "onmax <maximogarciamtnez@gmail.com>",
@@ -32,29 +36,97 @@
32
36
  }
33
37
  },
34
38
  "exports": {
35
- ".": "./dist/index.js",
36
- "./agent": "./dist/agent.js",
37
- "./server": "./dist/server.js",
38
- "./vite": "./dist/vite.js",
39
+ ".": {
40
+ "types": "./dist/index.d.ts",
41
+ "import": "./dist/index.js",
42
+ "default": "./dist/index.js"
43
+ },
44
+ "./agent": {
45
+ "types": "./dist/agent.d.ts",
46
+ "import": "./dist/agent.js",
47
+ "default": "./dist/agent.js"
48
+ },
49
+ "./cli": {
50
+ "types": "./dist/cli.d.ts",
51
+ "import": "./dist/cli.js",
52
+ "default": "./dist/cli.js"
53
+ },
54
+ "./console": {
55
+ "types": "./dist/console.d.ts",
56
+ "import": "./dist/console.js",
57
+ "default": "./dist/console.js"
58
+ },
59
+ "./console-runtime": {
60
+ "types": "./dist/console-runtime.d.ts",
61
+ "import": "./dist/console-runtime.js",
62
+ "default": "./dist/console-runtime.js"
63
+ },
64
+ "./nuxt": {
65
+ "types": "./dist/nuxt.d.ts",
66
+ "import": "./dist/nuxt.js",
67
+ "default": "./dist/nuxt.js"
68
+ },
69
+ "./presets": {
70
+ "types": "./dist/presets.d.ts",
71
+ "import": "./dist/presets.js",
72
+ "default": "./dist/presets.js"
73
+ },
74
+ "./runtime/console": {
75
+ "types": "./dist/runtime/console.d.ts",
76
+ "import": "./dist/runtime/console.js",
77
+ "default": "./dist/runtime/console.js"
78
+ },
79
+ "./server": {
80
+ "types": "./dist/server.d.ts",
81
+ "import": "./dist/server.js",
82
+ "default": "./dist/server.js"
83
+ },
84
+ "./vite": {
85
+ "types": "./dist/vite.d.ts",
86
+ "import": "./dist/vite.js",
87
+ "default": "./dist/vite.js"
88
+ },
89
+ "./vue": {
90
+ "types": "./dist/vue.d.ts",
91
+ "import": "./dist/vue.js",
92
+ "default": "./dist/vue.js"
93
+ },
39
94
  "./package.json": "./package.json"
40
95
  },
41
96
  "dependencies": {
42
- "better-auth": "^1.6.23",
43
- "@vite-hub/runtime": "0.0.3"
97
+ "@cloudflare/workers-types": "^5.20261016.1",
98
+ "@types/node": "^24.19.1",
99
+ "@vite-hub/env": "0.1.0",
100
+ "@vite-hub/runtime": "0.1.0",
101
+ "better-auth": "1.7.7",
102
+ "bun-types": "^1.4.3",
103
+ "drizzle-orm": "^0.45.3",
104
+ "nostics": "1.3.0",
105
+ "valibot": "^1.5.0"
44
106
  },
45
107
  "devDependencies": {
46
- "@types/node": "^24.13.3",
47
- "publint": "^0.3.21",
108
+ "@types/json-schema": "^7.0.15",
109
+ "@types/mdast": "^4.0.4",
110
+ "@types/node": "^24.19.1",
111
+ "@vite-hub/agent": "0.1.0",
112
+ "happy-dom": "20.14.5",
113
+ "miniflare": "4.20260730.0",
114
+ "publint": "^0.3.25",
48
115
  "typescript": "^6.0.3",
49
- "vite": "^8.0.8",
50
- "vite-plus": "^0.1.24",
51
- "vitest": "^4.1.4",
52
- "@vite-hub/internal": "0.0.1",
53
- "@vite-hub/agent": "0.0.3"
116
+ "undici": "8.12.2",
117
+ "vite": "^8.2.2",
118
+ "vite-plus": "^0.3.3",
119
+ "vitest": "^4.1.11",
120
+ "vue": "3.5.44",
121
+ "@better-auth/oauth-provider": "1.7.7",
122
+ "@vite-hub/internal": "0.0.1"
54
123
  },
55
124
  "peerDependencies": {
125
+ "@types/json-schema": "^7.0.15",
126
+ "@types/mdast": "^4.0.4",
127
+ "@vite-hub/agent": "0.1.0",
56
128
  "vite": ">=8.0.0",
57
- "@vite-hub/agent": "0.0.3"
129
+ "vue": "3.5.44"
58
130
  },
59
131
  "peerDependenciesMeta": {
60
132
  "@vite-hub/agent": {
@@ -62,6 +134,9 @@
62
134
  },
63
135
  "vite": {
64
136
  "optional": true
137
+ },
138
+ "vue": {
139
+ "optional": true
65
140
  }
66
141
  },
67
142
  "engines": {
@@ -70,7 +145,7 @@
70
145
  "scripts": {
71
146
  "build": "vp pack",
72
147
  "dev": "vp pack --watch",
73
- "typecheck": "tsc --noEmit -p ./tsconfig.json",
148
+ "typecheck": "vp run --cache -t @vite-hub/auth#build && node ../../test/package-typecheck.mjs --noEmit -p ./tsconfig.json",
74
149
  "test": "vp run -t @vite-hub/auth#build && vp test"
75
150
  }
76
151
  }
@@ -1,322 +0,0 @@
1
- import { n as normalizeAuthBasePath } from "./shared-QSYBHaMG.js";
2
- import discoveredDefinition from "#vitehub/auth/definition";
3
- import { betterAuth } from "better-auth";
4
- import { ViteHubError, isViteHubError } from "@vite-hub/runtime";
5
- //#region src/errors.ts
6
- function invalidAuthenticationErrorOptions() {
7
- throw new TypeError("[vitehub] Invalid authentication error options.");
8
- }
9
- function readAuthenticationErrorOption(value, key) {
10
- if (typeof value !== "object" || value === null) invalidAuthenticationErrorOptions();
11
- try {
12
- if (Array.isArray(value)) invalidAuthenticationErrorOptions();
13
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
14
- if (descriptor === void 0) return void 0;
15
- if (!("value" in descriptor)) invalidAuthenticationErrorOptions();
16
- return descriptor.value;
17
- } catch {
18
- invalidAuthenticationErrorOptions();
19
- }
20
- }
21
- function createAuthenticationProviderError(options) {
22
- const cause = readAuthenticationErrorOption(options, "cause");
23
- const operation = readAuthenticationErrorOption(options, "operation");
24
- if (operation !== "get-auth-for-request" && operation !== "get-session") invalidAuthenticationErrorOptions();
25
- return new ViteHubError("AUTH_PROVIDER_OPERATION_FAILED", "[vitehub] Authentication provider operation failed.", {
26
- cause,
27
- details: {
28
- operation,
29
- provider: "better-auth"
30
- }
31
- });
32
- }
33
- function throwAuthenticationProviderError(cause, operation) {
34
- if (isViteHubError(cause) || isAuthenticationAbortError(cause)) throw cause;
35
- throw createAuthenticationProviderError({
36
- cause,
37
- operation
38
- });
39
- }
40
- function isAuthenticationAbortError(error) {
41
- if (typeof error !== "object" || error === null) return false;
42
- try {
43
- return Reflect.get(error, "name") === "AbortError";
44
- } catch {
45
- return false;
46
- }
47
- }
48
- //#endregion
49
- //#region src/session.ts
50
- async function getAuthenticationSession(auth, input) {
51
- const [api, getSession] = await readProvider(() => {
52
- const api = readRecordProperty(auth, "api");
53
- return [api, api && readProperty(api, "getSession")];
54
- });
55
- if (typeof getSession !== "function") throw new TypeError("Better Auth did not expose api.getSession().");
56
- const value = await readProvider(() => Reflect.apply(getSession, api, [input]));
57
- if (value == null) return value;
58
- const session = await readProvider(() => resolveAuthenticationSession(value));
59
- if (!session) throw new TypeError("Better Auth returned an invalid session response.");
60
- return session;
61
- }
62
- async function readProvider(read) {
63
- try {
64
- return await read();
65
- } catch (cause) {
66
- throwAuthenticationProviderError(cause, "get-session");
67
- }
68
- }
69
- function readRecordProperty(value, property) {
70
- if (!isRecord(value)) return;
71
- const nested = readProperty(value, property);
72
- return isRecord(nested) ? nested : void 0;
73
- }
74
- function resolveAuthenticationSession(value) {
75
- if (!isRecord(value)) return;
76
- const session = value.session;
77
- const user = value.user;
78
- if (!isRecord(session) || !isRecord(user)) return;
79
- const userId = user.id;
80
- if (typeof userId !== "string" || userId.length === 0) return;
81
- return {
82
- auth: value,
83
- session,
84
- user,
85
- userId
86
- };
87
- }
88
- function readProperty(value, property) {
89
- return value[property];
90
- }
91
- function isRecord(value) {
92
- return typeof value === "object" && value !== null && !Array.isArray(value);
93
- }
94
- //#endregion
95
- //#region src/server.ts
96
- function hasRuntimeOptions(options) {
97
- return Boolean(options && Object.keys(options).length > 0);
98
- }
99
- function hasRequestRuntimeOptions(definition) {
100
- if (typeof definition.options === "function") return true;
101
- return typeof definition.options.runtime === "function";
102
- }
103
- let authRuntimeEnvResolver;
104
- function setAuthRuntimeEnvResolver(resolver) {
105
- authRuntimeEnvResolver = resolver;
106
- }
107
- function resolveAuthRuntimeEnv(event) {
108
- return authRuntimeEnvResolver?.(event) ?? {};
109
- }
110
- function requestOrigin(request) {
111
- return request ? new URL(request.url).origin : "http://localhost";
112
- }
113
- function createAuthRuntimeContext(request, event) {
114
- return {
115
- env: resolveAuthRuntimeEnv(event ?? request),
116
- ...request ? { request } : {},
117
- requestOrigin: requestOrigin(request)
118
- };
119
- }
120
- function isPlainObject(value) {
121
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
122
- }
123
- function isAuthDatabaseMetadata(value) {
124
- return value === true || isPlainObject(value) && typeof value.name === "string" && Object.keys(value).every((key) => key === "dedicated" || key === "name");
125
- }
126
- function isAuthSecondaryStorageMetadata(value) {
127
- return value === true || isPlainObject(value) && typeof value.store === "string" && Object.keys(value).every((key) => key === "store");
128
- }
129
- function resolveDefinitionOptions(definition, request, event, runtimeOptions = {}) {
130
- const context = createAuthRuntimeContext(request, event);
131
- const options = typeof definition.options === "function" ? definition.options(context) : definition.options;
132
- const runtime = options.runtime;
133
- const resolvedRuntime = !runtime ? {} : typeof runtime === "function" ? runtime(context) : runtime;
134
- return {
135
- ...options,
136
- ...resolvedRuntime,
137
- ...runtimeOptions
138
- };
139
- }
140
- function resolveRequestRuntimeOptions(definition, request, event) {
141
- if (typeof definition.options === "function") return resolveDefinitionOptions(definition, request, event);
142
- const runtime = definition.options.runtime;
143
- if (!runtime) return {};
144
- const context = createAuthRuntimeContext(request, event);
145
- return typeof runtime === "function" ? runtime(context) : runtime;
146
- }
147
- function hasStaticTrustedOrigins(definition) {
148
- return typeof definition.options !== "function" && "trustedOrigins" in definition.options;
149
- }
150
- function definitionBasePath(definition) {
151
- if (typeof definition.options === "function") return;
152
- return definition.options.basePath;
153
- }
154
- function stripViteHubOptions(options) {
155
- const { access: _access, database, route: _route, runtime: _runtime, secondaryStorage, ...rest } = options;
156
- return {
157
- ...rest,
158
- ...!isAuthDatabaseMetadata(database) ? { database } : {},
159
- ...!isAuthSecondaryStorageMetadata(secondaryStorage) ? { secondaryStorage } : {},
160
- basePath: normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : void 0)
161
- };
162
- }
163
- function hasTrustedOrigins(options) {
164
- return "trustedOrigins" in options;
165
- }
166
- function toRequest(request) {
167
- if (request instanceof Request) return request;
168
- const init = {
169
- headers: request.headers,
170
- method: request.method,
171
- signal: request.signal
172
- };
173
- if (request.body) {
174
- init.body = request.body;
175
- init.duplex = "half";
176
- }
177
- return new Request(request.url, init);
178
- }
179
- function unwrapAuthRequest(input) {
180
- return "req" in input ? input.req : input;
181
- }
182
- function createAuthRequestRuntimeOptions(definition, request, runtimeOptions = {}, event) {
183
- const requestRuntimeOptions = {
184
- ...resolveRequestRuntimeOptions(definition, request, event),
185
- ...runtimeOptions
186
- };
187
- const baseURL = requestRuntimeOptions.baseURL || new URL(request.url).origin;
188
- return {
189
- baseURL,
190
- ...!hasTrustedOrigins(requestRuntimeOptions) && !hasStaticTrustedOrigins(definition) ? { trustedOrigins: [baseURL] } : {},
191
- ...requestRuntimeOptions
192
- };
193
- }
194
- const authRuntimeStateKey = Symbol.for("vitehub.auth.runtime");
195
- function getAuthRuntimeState() {
196
- const globalScope = globalThis;
197
- globalScope[authRuntimeStateKey] ??= {};
198
- return globalScope[authRuntimeStateKey];
199
- }
200
- function resolveDefaultDefinition() {
201
- if (!discoveredDefinition) throw new Error("[vitehub] No Auth Definition was discovered. Add `server/auth.ts` or `server.auth.ts`.");
202
- return discoveredDefinition;
203
- }
204
- function createBetterAuthOptions(definition, runtimeOptions = {}) {
205
- return stripViteHubOptions(resolveDefinitionOptions(definition, void 0, void 0, runtimeOptions));
206
- }
207
- function createBetterAuthOptionsFromResolved(options) {
208
- return stripViteHubOptions(options);
209
- }
210
- function createAuthenticationProvider(options) {
211
- try {
212
- return betterAuth(options);
213
- } catch (cause) {
214
- throwAuthenticationProviderError(cause, "get-auth-for-request");
215
- }
216
- }
217
- function resolveBetterAuthOptionsForRequest(definition, request, runtimeOptions, event) {
218
- return createBetterAuthOptionsFromResolved(resolveDefinitionOptions(definition, request, event, createAuthRequestRuntimeOptions(definition, request, runtimeOptions, event)));
219
- }
220
- function createAuth(definition, runtimeOptions) {
221
- return betterAuth(createBetterAuthOptions(definition, runtimeOptions));
222
- }
223
- function createAuthForRequest(definition, request, runtimeOptions, event) {
224
- return betterAuth(resolveBetterAuthOptionsForRequest(definition, request, runtimeOptions, event));
225
- }
226
- function handleAuthRequest(definition, request, runtimeOptions, event) {
227
- return createAuthForRequest(definition, request, runtimeOptions, event).handler(toRequest(request));
228
- }
229
- function createAuthHandler(definition, runtimeOptions) {
230
- return createAuth(definition, runtimeOptions).handler;
231
- }
232
- function resetAuth() {
233
- const state = getAuthRuntimeState();
234
- state.auth = void 0;
235
- state.definition = void 0;
236
- }
237
- function getAuthForDefinition(definition, runtimeOptions) {
238
- if (hasRuntimeOptions(runtimeOptions)) return createAuthenticationProvider(createBetterAuthOptions(definition, runtimeOptions));
239
- const state = getAuthRuntimeState();
240
- if (!state.auth || state.definition !== definition) {
241
- state.auth = createAuthenticationProvider(createBetterAuthOptions(definition));
242
- state.definition = definition;
243
- }
244
- return state.auth;
245
- }
246
- function getAuth(runtimeOptions) {
247
- return getAuthForDefinition(resolveDefaultDefinition(), runtimeOptions);
248
- }
249
- function getAuthForRequest(request, runtimeOptions, event) {
250
- const definition = resolveDefaultDefinition();
251
- if (!hasRequestRuntimeOptions(definition) && !hasRuntimeOptions(runtimeOptions)) return getAuthForDefinition(definition);
252
- return createAuthenticationProvider(resolveBetterAuthOptionsForRequest(definition, request, runtimeOptions, event));
253
- }
254
- function handleAuth(input, runtimeOptions) {
255
- const request = unwrapAuthRequest(input);
256
- return handleAuthRequest(resolveDefaultDefinition(), request, runtimeOptions, input);
257
- }
258
- function authRequestBasePath(definition, request, event) {
259
- const options = createAuthRequestRuntimeOptions(definition, request, {}, event);
260
- return normalizeAuthBasePath(typeof options.basePath === "string" ? options.basePath : definitionBasePath(definition));
261
- }
262
- function authBaseURL(definition, request, event) {
263
- return new URL(createAuthRequestRuntimeOptions(definition, request, {}, event).baseURL).origin;
264
- }
265
- function wantsHtml(request) {
266
- return request.method === "GET" && request.headers.get("accept")?.includes("text/html") === true;
267
- }
268
- async function createSignInResponse(definition, request, signIn, event) {
269
- const origin = authBaseURL(definition, request, event);
270
- const response = await handleAuthRequest(definition, new Request(`${origin}${authRequestBasePath(definition, request, event)}/sign-in/social`, {
271
- body: JSON.stringify({
272
- callbackURL: signIn.callbackURL,
273
- errorCallbackURL: signIn.errorCallbackURL,
274
- provider: signIn.provider,
275
- requestSignUp: signIn.requestSignUp,
276
- scopes: signIn.scopes
277
- }),
278
- headers: {
279
- "content-type": "application/json",
280
- "accept": "application/json",
281
- "origin": origin
282
- },
283
- method: "POST"
284
- }), void 0, event);
285
- if (!response.ok) return response;
286
- const body = await response.json().catch(() => void 0);
287
- if (typeof body?.url !== "string") return Response.json({ error: "Auth sign-in did not return a redirect URL." }, { status: 502 });
288
- const headers = new Headers(response.headers);
289
- headers.delete("content-type");
290
- headers.set("location", body.url);
291
- return new Response(null, {
292
- headers,
293
- status: 302
294
- });
295
- }
296
- async function requireAuth(input, definition = resolveDefaultDefinition()) {
297
- const request = unwrapAuthRequest(input);
298
- if (await getAuthenticationSession(createAuthenticationProvider(resolveBetterAuthOptionsForRequest(definition, request, void 0, input)), { headers: request.headers })) return;
299
- if (!wantsHtml(request)) return Response.json({ error: "Unauthorized." }, { status: 401 });
300
- if (new URL(request.url).searchParams.has("auth_error")) return new Response("Unauthorized.", {
301
- headers: { "content-type": "text/plain; charset=utf-8" },
302
- status: 403
303
- });
304
- const signIn = resolveDefinitionOptions(definition, request, input).access?.signIn;
305
- return signIn ? await createSignInResponse(definition, request, signIn, input) : Response.json({ error: "Unauthorized." }, { status: 401 });
306
- }
307
- const auth = new Proxy({}, {
308
- get(_target, property, receiver) {
309
- return Reflect.get(getAuth(), property, receiver);
310
- },
311
- getOwnPropertyDescriptor(_target, property) {
312
- return Reflect.getOwnPropertyDescriptor(getAuth(), property);
313
- },
314
- has(_target, property) {
315
- return Reflect.has(getAuth(), property);
316
- },
317
- ownKeys() {
318
- return Reflect.ownKeys(getAuth());
319
- }
320
- });
321
- //#endregion
322
- export { throwAuthenticationProviderError as _, createAuthRequestRuntimeOptions as a, getAuthForDefinition as c, handleAuthRequest as d, requireAuth as f, invalidAuthenticationErrorOptions as g, getAuthenticationSession as h, createAuthHandler as i, getAuthForRequest as l, setAuthRuntimeEnvResolver as m, createAuth as n, createBetterAuthOptions as o, resetAuth as p, createAuthForRequest as r, getAuth as s, auth as t, handleAuth as u };
@@ -1,12 +0,0 @@
1
- //#region src/shared.ts
2
- const defaultAuthBasePath = "/api/auth";
3
- function normalizeAuthBasePath(value) {
4
- const path = value?.trim() || defaultAuthBasePath;
5
- if (!path.startsWith("/")) throw new TypeError("`defineAuth()` basePath must start with `/`.");
6
- return path.length > 1 ? path.replace(/\/+$/g, "") : path;
7
- }
8
- function isAuthRequestPath(pathname, basePath) {
9
- return pathname === basePath || pathname.startsWith(`${basePath}/`);
10
- }
11
- //#endregion
12
- export { normalizeAuthBasePath as n, isAuthRequestPath as t };