@bigio/better-auth-electron 1.0.0 → 1.0.2

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 CHANGED
@@ -1,17 +1,63 @@
1
+ ## I'm currently studying the official implementation; the documentation is still rough but will be improved soon. I'm eager and looking forward to exchanging ideas with everyone.
2
+
3
+ Based on my study of the official implementation code, I have decided on the following to-do list:
4
+ **1. Architecture: The "Silent Handoff" (Stateless & Secure)**
5
+
6
+ * [ ] **Server-Side Cookie Interception**: Modify `electron-server-plugin` to intercept the OAuth callback response.
7
+ * *Action*: Strip the `Set-Cookie` header (specifically the session token) from the response to prevent overwriting the user's browser session.
8
+ * *Goal*: Achieve strict physical isolation between Web Session and Electron Session.
9
+
10
+
11
+ * [ ] **Stateless OAuth Flow**: Ensure the OAuth flow relies solely on the encrypted `Ticket` mechanism, making the browser a purely stateless transport layer for Electron authentication.
12
+
13
+ **2. Security & Hardening**
14
+
15
+ * [ ] **Secure Persistence**: Implement `safeStorage` (DPAPI/Keychain) for encrypting the persisted PKCE Verifier on disk.
16
+ * *Reason*: Prevent plaintext credentials from resting on the file system.
17
+
18
+
19
+ * [ ] **User-Agent Scrubbing**: Global removal of "Electron" tokens from the `User-Agent` string at the `app.on('ready')` stage.
20
+ * *Reason*: Bypass WAF/Anti-Bot protections that block Electron-based requests during the ticket exchange phase.
21
+
22
+
23
+ * [ ] **Automated CSP Injection**: Implement `onHeadersReceived` interceptor in the Main Process.
24
+ * *Action*: Automatically append the backend API URL to the `connect-src` directive.
25
+ * *Goal*: Provide a "Zero-Config" experience by preventing CSP violations without requiring users to manually edit `index.html`.
26
+
27
+
28
+
29
+ **3. Developer Experience (DX) & API**
30
+
31
+ * [ ] **Enhanced Renderer API**: Refactor `getActions` to introduce a dedicated `authClient.bigio` namespace.
32
+ * *Feature*: Implement `authClient.bigio.signIn({ provider: 'github' })` wrapper.
33
+ * *Implementation*: Utilize `window.open` (intercepted by Main) or IPC to trigger the flow, keeping the API consistent with the official web client style.
34
+
35
+
36
+ * [ ] **Smart Web Handoff UI (Optional/Next)**: Update the web-side confirmation page to detect and display the currently logged-in web user, offering a "Continue as [User]" button for a seamless transition.
37
+
38
+
1
39
  # @bigio/better-auth-electron
2
40
 
3
41
  > **Work In Progress:** This library is actively being developed. Detailed documentation and architecture diagrams are coming soon.
4
42
 
5
- **A type-safe, IPC-based Better Auth integration for Electron.**
43
+ **A type-safe, IPC-Event based Better Auth integration for Electron.**
6
44
 
7
45
  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
46
 
9
47
  ## Features
10
48
 
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.
49
+ - ** Native Secure Context & Origin Fix:**
50
+ Leverages `protocol.registerSchemesAsPrivileged` to treat your custom scheme as a secure context. This solves the infamous `Origin` header mismatch and enables `SameSite` cookies to work natively without hacks.
51
+
52
+ - ** Secure PKCE Flow:**
53
+ Implements the standard **Proof Key for Code Exchange** protocol out-of-the-box. Ensures enterprise-grade security for your OAuth exchanges without exposing secrets.
54
+
55
+ - ** Preact SSR Coming soon:**
56
+ Includes a dedicated, lightweight Preact entry point optimized for Server-Side Rendering (SSR) in login windows.
57
+ _(React 19 supported. Vue/Svelte support coming soon!)_
58
+
59
+ - ** Zero-IPC Session Handoff:**
60
+ Uses secure custom protocol deep links to transfer authentication states. Full TypeScript inference via Better Auth plugins — **no fragile IPC bridges** or manual message handling required.
15
61
 
16
62
  ## Installation
17
63
 
@@ -68,8 +114,8 @@ const { windowInjection, whenReadyInjection } = mainInjection({
68
114
  PROVIDERS: ['github', 'google'],
69
115
  BETTER_AUTH_BASEURL: 'http://localhost:3002',
70
116
  FRONTEND_URL: 'http://localhost:3001/oauth',
71
- // Use the classic 'onBeforeRequest' filter approach for auth code capture
72
- OLD_SCHOOL_ONBEFORE_WAY: true,
117
+ // Use the classic 'onBeforeRequest' filter approach for auth code capture if true
118
+ OLD_SCHOOL_ONBEFORE_WAY: false,
73
119
  })
74
120
 
75
121
  function createWindow(): void {
@@ -77,12 +123,12 @@ function createWindow(): void {
77
123
  /* config */
78
124
  })
79
125
 
80
- // Inject IPC handlers into the specific window instance
126
+ // Inject ipcRenderer event into the specific window instance
81
127
  windowInjection(mainWindow)
82
128
  }
83
129
 
84
130
  app.whenReady().then(() => {
85
- // Register custom protocol schemes and deep link listeners
131
+ // Register custom protocol schemes
86
132
  whenReadyInjection()
87
133
  createWindow()
88
134
  })
@@ -142,7 +188,31 @@ const ElectronLoginButton = ({ provider }: { provider: string }) => {
142
188
  }
143
189
  ```
144
190
 
145
- ### 5. Web/App Component Usage (`src/web/components/user-session.tsx`)
191
+ ### 5. Electron Renderer/Web Client (`src/renderer/lib/auth-client.ts`)
192
+
193
+ This is the auth client running **inside your Electron app**. It listens for the custom protocol deep link to hydrate the session.
194
+
195
+ > **Suggestion:** set `credentials: 'include'` to ensure the session cookie generated by the secure protocol is correctly persisted.
196
+
197
+ ```typescript
198
+ import { createAuthClient } from 'better-auth/react'
199
+ import { electronRendererPlugin } from '@bigio/better-auth-electron/renderer'
200
+
201
+ export const authClient = createAuthClient({
202
+ baseURL: 'http://localhost:3002',
203
+ fetchOptions: {
204
+ // It ensures cookies are sent/received correctly in the custom scheme.
205
+ credentials: 'include',
206
+ },
207
+ plugins: [
208
+ electronRendererPlugin({
209
+ ELECTRON_SCHEME: 'bigio', // Must match Main process config
210
+ }),
211
+ ],
212
+ })
213
+ ```
214
+
215
+ ### 6. Web/App Component Usage (`src/web/components/user-session.tsx`)
146
216
 
147
217
  The `useElectronOAuthSession` hook is the heart of the "Handoff" experience. It listens for the deep link callback and automatically verifies the session.
148
218
 
@@ -151,23 +221,13 @@ import { authClient } from '@/web/client'
151
221
 
152
222
  export function UserSessionStatus() {
153
223
  const {
154
- // The validated session data (user, session token)
155
224
  data: useSessionData,
156
-
157
- // Any error that occurred during the deep link handoff
158
225
  error,
159
-
160
- // True when the initial check or handoff is in progress
161
226
  isPending,
162
-
163
- // True when explicitly refetching the session state
164
227
  isRefetching,
165
-
166
- // Function to manually re-trigger session validation
167
228
  refetch,
168
-
169
- // Real-time status messages from the main process
170
- // (e.g., "Verifying ticket...", "Session established")
229
+ // // The current status of the handoff process on the client side
230
+ // (e.g., 'idle' | 'succeed' | 'failed')
171
231
  oauthMessage
172
232
  } = authClient.bigio.useElectronOAuthSession()
173
233