@bigio/better-auth-electron 1.0.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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bigmusic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,188 @@
1
+ # @bigio/better-auth-electron
2
+
3
+ > **Work In Progress:** This library is actively being developed. Detailed documentation and architecture diagrams are coming soon.
4
+
5
+ **A type-safe, IPC-based Better Auth integration for Electron.**
6
+
7
+ Designed for production-grade applications, this library provides a secure, "batteries-included" solution to integrate [Better Auth](https://www.better-auth.com) into Electron apps without the headache of writing manual IPC bridges or handling complex OAuth window flows.
8
+
9
+ ## Features
10
+
11
+ - ** Strict Process Isolation:** Zero leakage of server secrets into the Renderer.
12
+ - ** Type-Safe IPC:** Full type inference between Main and Renderer processes.
13
+ - ** React 19 & Preact Compatible:** Solves "Invalid Hook Call" and duplicate instance issues.
14
+ - ** Smart Session Handoff:** Seamlessly transfers authentication states from the web auth flow to the Electron app.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pnpm add @bigio/better-auth-electron
20
+ ```
21
+
22
+ Ensure peer dependencies are installed:(more framework support coming soon...)
23
+
24
+ ```bash
25
+ pnpm add better-auth electron react react-dom
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ### 1. Server Setup (`src/lib/auth.ts`)
31
+
32
+ Initialize Better Auth with the `electronServerPlugin`. This handles the ticket exchange and verification logic on your backend.
33
+
34
+ ```typescript
35
+ import { betterAuth } from 'better-auth'
36
+ import { electronServerPlugin } from '@bigio/better-auth-electron/server'
37
+
38
+ export const auth = betterAuth({
39
+ baseURL: 'http://localhost:3002',
40
+ // ... your database configuration
41
+ plugins: [
42
+ electronServerPlugin({
43
+ // The custom scheme your Electron app uses (e.g. bigio://)
44
+ ELECTRON_SCHEME: 'bigio',
45
+ // Allowed providers for Electron OAuth flow
46
+ PROVIDERS: ['github', 'google'],
47
+ }),
48
+ ],
49
+ database: {
50
+ //...
51
+ },
52
+ })
53
+ ```
54
+
55
+ ### 2. Electron Main Process (`src/main/index.ts`)
56
+
57
+ Use `mainInjection` to setup IPC handlers and deep linking strategies. This automatically handles the "protocol" opening events.
58
+
59
+ ```typescript
60
+ import { app, BrowserWindow } from 'electron'
61
+ import { mainInjection } from '@bigio/better-auth-electron/main'
62
+
63
+ // Initialize the plugin logic
64
+ const { windowInjection, whenReadyInjection } = mainInjection({
65
+ isOAuth: true,
66
+ ELECTRON_APP_NAME: 'bigio-electron-demo',
67
+ ELECTRON_SCHEME: 'bigio', // Must match the server config
68
+ PROVIDERS: ['github', 'google'],
69
+ BETTER_AUTH_BASEURL: 'http://localhost:3002',
70
+ FRONTEND_URL: 'http://localhost:3001/oauth',
71
+ // Use the classic 'onBeforeRequest' filter approach for auth code capture
72
+ OLD_SCHOOL_ONBEFORE_WAY: true,
73
+ })
74
+
75
+ function createWindow(): void {
76
+ const mainWindow = new BrowserWindow({
77
+ /* config */
78
+ })
79
+
80
+ // Inject IPC handlers into the specific window instance
81
+ windowInjection(mainWindow)
82
+ }
83
+
84
+ app.whenReady().then(() => {
85
+ // Register custom protocol schemes and deep link listeners
86
+ whenReadyInjection()
87
+ createWindow()
88
+ })
89
+ ```
90
+
91
+ ### 3. Web Client Initialization (`src/web/client.ts`)
92
+
93
+ Configure the client-side plugin. Note the usage of `setLazyClient` to handle circular dependencies or lazy initialization patterns effectively.
94
+
95
+ ```typescript
96
+ import { createAuthClient } from 'better-auth/react'
97
+ import { electronWebHandoffPlugin, setLazyClient } from '@bigio/better-auth-electron/web'
98
+ import type { auth } from '@/lib/auth' // Import type from your server file
99
+
100
+ export const authClient = createAuthClient({
101
+ baseURL: 'http://localhost:3002',
102
+ fetchOptions: {
103
+ credentials: 'include',
104
+ },
105
+ plugins: [
106
+ // Type-safe plugin initialization
107
+ electronWebHandoffPlugin<typeof auth>(),
108
+ ],
109
+ })
110
+
111
+ // Important: Register the client instance for plugin lazy access, this for soical signin
112
+ setLazyClient(authClient)
113
+ ```
114
+
115
+ ### 4. Electron Renderer / Login Page (`src/renderer/pages/login.tsx`)
116
+
117
+ In your Electron renderer (the UI), use the helper options to construct the correct OAuth URL that opens in the system's default browser.
118
+
119
+ ```typescript
120
+ import type { ElectronButtonOptions } from '@bigio/better-auth-electron/options'
121
+ import { defaultButtonOptions } from '@bigio/better-auth-electron/options'
122
+
123
+ // Merge default options with any custom overrides
124
+ const config: ElectronButtonOptions = { ...defaultButtonOptions }
125
+ const { FRONTEND_URL, PROVIDER_NAME_IN_URL } = config
126
+
127
+ const ElectronLoginButton = ({ provider }: { provider: string }) => {
128
+ const handleOpen = () => {
129
+ // Construct the auth URL
130
+ const targetUrl = `${FRONTEND_URL}?${PROVIDER_NAME_IN_URL}=${provider}`
131
+
132
+ // Open in external browser (e.g., Chrome/Safari) to start the flow
133
+ window.open(targetUrl, '_blank')
134
+ console.log('Opening External Browser for OAuth...')
135
+ }
136
+
137
+ return (
138
+ <button onClick={handleOpen}>
139
+ Sign in with {provider}
140
+ </button>
141
+ )
142
+ }
143
+ ```
144
+
145
+ ### 5. Web/App Component Usage (`src/web/components/user-session.tsx`)
146
+
147
+ The `useElectronOAuthSession` hook is the heart of the "Handoff" experience. It listens for the deep link callback and automatically verifies the session.
148
+
149
+ ```typescript
150
+ import { authClient } from '@/web/client'
151
+
152
+ export function UserSessionStatus() {
153
+ const {
154
+ // The validated session data (user, session token)
155
+ data: useSessionData,
156
+
157
+ // Any error that occurred during the deep link handoff
158
+ error,
159
+
160
+ // True when the initial check or handoff is in progress
161
+ isPending,
162
+
163
+ // True when explicitly refetching the session state
164
+ isRefetching,
165
+
166
+ // Function to manually re-trigger session validation
167
+ refetch,
168
+
169
+ // Real-time status messages from the main process
170
+ // (e.g., "Verifying ticket...", "Session established")
171
+ oauthMessage
172
+ } = authClient.bigio.useElectronOAuthSession()
173
+
174
+ if (isPending) return <div>Loading session... {oauthMessage}</div>
175
+ if (error) return <div>Error: {error.message}</div>
176
+
177
+ return (
178
+ <div>
179
+ <h1>Welcome, {useSessionData?.user.name}</h1>
180
+ <p>Status: {oauthMessage || 'Idle'}</p>
181
+ </div>
182
+ )
183
+ }
184
+ ```
185
+
186
+ ## License
187
+
188
+ MIT © [bigmusic](https://github.com/bigmusic/better-auth-electron)
package/dist/main.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { BrowserWindow } from 'electron';
2
+ import { ElectronMainPluginOptions } from './options.js';
3
+ import 'better-auth';
4
+
5
+ declare const mainInjection: (options?: ElectronMainPluginOptions) => {
6
+ windowInjection: (mainWindow: BrowserWindow) => void;
7
+ whenReadyInjection: () => void;
8
+ };
9
+
10
+ export { mainInjection };