@dreamshive/better-auth-tauri

中文文档
0.1.5发布于 2026/11/10MITTypeScriptES Module构建来源已验证近 30 天下载 3064

Better Auth plugin for Tauri desktop apps — handles OAuth via the system browser with deep-link callbacks, cookie bridging via URL, and secure token storage hooks.

原始使用文档
文档目录23 节
  1. Why use this
  2. How it works
  3. Installation
  4. Tauri configuration
  5. 1. Register your URI scheme
  6. 2. Initialize the Rust plugins
  7. 3. Grant permissions
  8. 4. (Highly recommended) Add tauri-plugin-single-instance
  9. Server setup (Better Auth backend)
  10. CORS
  11. Client setup
  12. Secure storage
  13. Option A — OS keychain (recommended)
  14. Option B — tauri-plugin-stronghold
  15. Option C — @tauri-apps/plugin-store
  16. Options
  17. tauri(options?) — server plugin
  18. tauriClient(options) — client plugin
  19. Exports
  20. macOS dev workflow
  21. Known limitations
  22. Comparison to @better-auth/expo
  23. License

@dreamshive/better-auth-tauri

Better Auth plugin for Tauri desktop apps. OAuth happens in the user's system browser, not the embedded webview — the session cookie rides back through a custom URI scheme deep link, and every outgoing request in the app is transparently authenticated.

Mirrors the architecture of the official @better-auth/expo package, adapted for Tauri's browser-style webview.

Why use this

  • OAuth providers that block embedded webviews still work (Google's disallowed_useragent, enterprise SSO, upcoming Microsoft enforcement).
  • Users reuse their existing browser sessions — no re-logging-in for github.com / google.com from inside your app.
  • Full address bar + padlock — users can verify the provider's domain before signing in.
  • Same Better Auth API surface — you keep using authClient.signIn.social(...) and useSession() as if nothing changed.

How it works

┌──────────────────┐           ┌────────────────┐         ┌──────────────┐
│  Tauri app       │           │ System browser │         │ Auth service │
│  (WKWebView/     │           │ (Safari/Chrome)│         │              │
│   WebView2)      │           │                │         │              │
└────────┬─────────┘           └────────┬───────┘         └──────┬───────┘
         │ signIn.social()              │                        │
         │ ─────────────────────────────┼───────────────────────>│
         │                              │                        │
         │ <── { url, disableRedirect } ──────────────────────────│
         │                              │                        │
         │ shell.open(url)              │                        │
         │ ────────────────────────────>│                        │
         │                              │ /tauri-authz-proxy     │
         │                              │ ──────────────────────>│
         │                              │ Set-Cookie: state=...  │
         │                              │ <──────────────────────│
         │                              │                        │
         │                              │ github.com OAuth...    │
         │                              │ <─redirect to callback─│
         │                              │ /callback/github       │
         │                              │ ──────────────────────>│
         │                              │                        │
         │                              │ <── 302 sokudo://?cookie=<session>
         │                              │     (after-hook appends cookie
         │                              │     to custom-scheme redirect)
         │                              │                        │
         │ <── OS routes sokudo://  ────│                        │
         │                                                       │
         │ store cookie in OS keychain                           │
         │ inject as `x-tauri-cookie` header on future calls     │
         │ ─────────────────────────────────────────────────────>│
         │                                                       │
         │ <── server plugin rewrites x-tauri-cookie → Cookie ───│
         │     Better Auth validates, returns session           │

Two things worth calling out:

  1. x-tauri-cookie header smuggling. The Fetch spec marks Cookie as a forbidden header name. Webviews silently drop attempts to set it. We smuggle the session through x-tauri-cookie and the server plugin rewrites it back to Cookie before Better Auth inspects the request.
  2. disableRedirect: true auto-injection. Better Auth's Vue/React client normally navigates window.location.href to the OAuth URL — fine in a browser, catastrophic in a single-window Tauri app (the webview takes over with the provider's login page). The client plugin injects disableRedirect: true into /sign-in/social and /sign-in/oauth2 requests so the client stays put.
  3. Cookie mutations are serialized. Response cookies, deep-link callbacks, and signout share one local mutation queue. A delayed response may revoke only the session it was sent with, and an OAuth callback cannot restore a session after explicit signout.

Installation

bun add @dreamshive/better-auth-tauri
# or: npm install / pnpm add / yarn add

The server plugin requires better-auth 1.7.16 or later (the release with the 2026-11-03 security fixes).

Peer Tauri plugins (install only in the desktop app that consumes the client):

bun add @tauri-apps/plugin-shell @tauri-apps/plugin-deep-link
cd src-tauri
cargo add tauri-plugin-shell tauri-plugin-deep-link

If you want the included focus/online managers to work, you also need:

bun add @tauri-apps/api   # onFocusChanged lives here

Tauri configuration

1. Register your URI scheme

src-tauri/tauri.conf.json:

{
  "plugins": {
    "deep-link": {
      "desktop": {
        "schemes": ["yourapp"]
      }
    }
  }
}

2. Initialize the Rust plugins

src-tauri/src/lib.rs:

pub fn run() {
  tauri::Builder::default()
    .plugin(tauri_plugin_shell::init())
    .plugin(tauri_plugin_deep_link::init())
    // ... your other plugins
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

3. Grant permissions

src-tauri/capabilities/default.json:

{
  "permissions": [
    "core:default",
    "shell:allow-open",
    "deep-link:default"
  ]
}

Without this, opening a yourapp:// deep link from a browser while the Tauri app is already running may spawn a second window instead of reusing the first. Install:

cd src-tauri
cargo add tauri-plugin-single-instance --features deep-link

Register it before any other plugin in lib.rs:

use tauri::{Emitter, Manager};

pub fn run() {
  tauri::Builder::default()
    .plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
      if let Some(window) = app.get_webview_window("main") {
        let _ = window.unminimize();
        let _ = window.show();
        let _ = window.set_focus();
      }
      for arg in argv.iter().skip(1) {
        if arg.starts_with("yourapp://") {
          let _ = app.emit("deep-link://new-url", vec![arg.clone()]);
        }
      }
    }))
    .plugin(tauri_plugin_shell::init())
    .plugin(tauri_plugin_deep_link::init())
    // ...
}

Server setup (Better Auth backend)

import { betterAuth } from "better-auth";
import { tauri } from "@dreamshive/better-auth-tauri";

export const auth = betterAuth({
  // ... your existing config
  trustedOrigins: ["yourapp://"],
  plugins: [
    tauri(),
    // ... your other plugins
  ],
});

The server plugin:

  1. Remaps tauri-origin → origin so CSRF / trusted-origin checks accept the custom scheme.
  2. Rewrites x-tauri-cookie → Cookie so the session cookie smuggled by the client is visible to Better Auth.
  3. Appends ?cookie=<Set-Cookie> to OAuth redirect URLs targeting custom schemes so the Tauri app can bridge the cookie jar.
  4. Exposes a /tauri-authorization-proxy endpoint that plants the OAuth state cookie in the system browser's jar before redirecting to the provider (prevents callback state mismatch).

The proxy is a public endpoint, so it acts only on requests a real sign-in produces. It redirects only to an HTTPS URL on the authorization origin of a provider configured in socialProviders or genericOAuth, and it signs only a state this server issued that has not expired. Anything else gets a 400 with no cookie and no redirect. SSO identity providers (/sign-in/sso) are not routed through the proxy.

If you ran a version before 0.1.5 with the server plugin enabled, rotate BETTER_AUTH_SECRET: those versions signed any state they were given, and signatures issued before the fix stay valid until the secret changes.

CORS

Your auth server's CORS config must allow the custom headers this plugin sends:

cors({
  origin: [/* your frontend origins */, "yourapp://"],
  credentials: true,
  allowedHeaders: [
    "Content-Type",
    "Authorization",
    "Cookie",
    "tauri-origin",
    "x-tauri-cookie",
    "x-skip-oauth-proxy",
  ],
})

Client setup

import { createAuthClient } from "better-auth/vue"; // or /react, /solid, etc.
import { tauriClient } from "@dreamshive/better-auth-tauri/client";
import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import { isTauri } from "@tauri-apps/api/core";

export const authClient = createAuthClient({
  baseURL: "https://auth.example.com",
  fetchOptions: {
    // Always use tauriFetch in Tauri — the webview's native fetch() drops
    // our smuggled headers and hits CORS on custom schemes.
    customFetchImpl: (...args) =>
      isTauri() ? tauriFetch(...args) : fetch(...args),
  },
  plugins: [
    tauriClient({
      scheme: "yourapp",        // must match tauri.conf.json
      cookiePrefix: "yourapp",  // must match your server's cookie prefix
      storage: {
        // See "Secure storage" below — localStorage is dev-only.
        getItem: (k) => localStorage.getItem(k),
        setItem: (k, v) => localStorage.setItem(k, v),
      },
    }),
  ],
});

Then use Better Auth normally:

await authClient.signIn.social({
  provider: "github",
  callbackURL: "/", // auto-rewritten to yourapp:///
});

The plugin takes it from there.

Secure storage

localStorage is not appropriate for production — any XSS in your Tauri webview can read it directly.

For production, back the storage option with an encrypted store. Options, ranked by ergonomics:

Expose keyring-rs via custom Tauri commands. Per-platform native secret store (Apple Keychain, Windows Credential Manager, Secret Service on Linux).

cd src-tauri
cargo add keyring --features apple-native,windows-native,linux-native-sync-persistent
// src-tauri/src/keyring.rs
use keyring::Entry;

#[tauri::command]
pub fn keyring_get(service: String, key: String) -> Result<Option<String>, String> {
  let entry = Entry::new(&service, &key).map_err(|e| e.to_string())?;
  match entry.get_password() {
    Ok(v) => Ok(Some(v)),
    Err(keyring::Error::NoEntry) => Ok(None),
    Err(e) => Err(e.to_string()),
  }
}

#[tauri::command]
pub fn keyring_set(service: String, key: String, value: String) -> Result<(), String> {
  let entry = Entry::new(&service, &key).map_err(|e| e.to_string())?;
  entry.set_password(&value).map_err(|e| e.to_string())
}

Register in lib.rs:

mod keyring;

tauri::Builder::default()
  .invoke_handler(tauri::generate_handler![
    keyring::keyring_get,
    keyring::keyring_set,
  ])

And in your client storage adapter:

import { invoke } from "@tauri-apps/api/core";
const SERVICE = "com.yourapp.session";

const keyringStorage = {
  getItem: (key: string) => invoke<string | null>("keyring_get", { service: SERVICE, key }),
  setItem: (key: string, value: string) => invoke("keyring_set", { service: SERVICE, key, value }),
};

Option B — tauri-plugin-stronghold

Official Tauri encrypted vault (IOTA Stronghold). Requires a master passphrase that the app supplies.

Option C — @tauri-apps/plugin-store

On-disk JSON, not encrypted, but lives behind Tauri IPC (not accessible from document.localStorage). Marginal improvement over localStorage.

Options

tauri(options?) — server plugin

OptionDefaultDescription
disableOriginOverridefalseDon't remap tauri-origin → origin.

tauriClient(options) — client plugin

OptionDefaultDescription
scheme— (required)Custom URI scheme registered in tauri.conf.json.
storage— (required)Key/value storage adapter. Async methods supported.
storagePrefix"better-auth"Prefix for storage keys.
cookiePrefix"better-auth"Server cookie-name prefix(es).
disableCachefalseDisable local /get-session response cache.
refetchOnWindowFocustrueRefetch session when the Tauri window regains focus.
refetchOnReconnecttrueRefetch session when the network comes back online.

Exports

// Server
import { tauri, tauriAuthorizationProxy } from "@dreamshive/better-auth-tauri";

// Client
import {
  tauriClient,
  setupTauriFocusManager,   // manual wiring if you disabled auto-setup
  setupTauriOnlineManager,
} from "@dreamshive/better-auth-tauri/client";

macOS dev workflow

Deep-link URI schemes on macOS are registered with Launch Services through the app's .app bundle's Info.plist. tauri dev does not produce a bundle — it runs a raw binary which macOS can't route deep links to.

Official Tauri guidance for developing against the deep-link plugin on macOS:

# Build once (also run after any Rust/plugin/capability change)
bun tauri build --debug
# Open the bundle so Launch Services indexes it
open src-tauri/target/debug/bundle/macos/your-app.app

Frontend (Vue/React/Svelte) HMR works fine through the built app if you point frontendDist at your dev server:

// src-tauri/tauri.dev.conf.json
{
  "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
  "build": {
    "frontendDist": "http://localhost:3000",
    "beforeBuildCommand": ""
  }
}
bun tauri build --debug --config src-tauri/tauri.dev.conf.json

Known limitations

  • macOS dev loop requires a bundle (see above). Windows and Linux don't have this friction.
  • Scheme hijacking — any app can register itself as a handler for your custom scheme. Production apps with meaningful attack surface should consider Universal Links (macOS) or App Links (Android equivalent).
  • Storage is the caller's responsibility. This plugin doesn't bundle a secure-storage primitive; you provide the adapter.
  • No SSR support. Tauri apps are client-only.

Comparison to @better-auth/expo

Feature-for-feature parity on the auth flow, plus two Tauri-specific additions:

FeatureExpoTauri (this)
OAuth via system browser✅✅
Cookie bridge via URL query param✅✅
Authorization proxy endpoint for state✅✅
Redirect-to-scheme callback rewrite✅✅
Sign-out local cleanup✅✅
Third-party cookie filter✅✅
Focus refetch manager✅ (React Query)✅ (notifies Better Auth session signal)
Online refetch manager✅ (React Query)✅ (notifies Better Auth session signal)
x-tauri-cookie smuggling—✅ required (browser forbids Cookie)
disableRedirect: true injection—✅ required (browser has window.location)

License

MIT © Rully Ardiansyah

版本与发布记录

@dreamshive/better-auth-tauri 共发布 6 个版本,首次发布于 2026/04/20;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.5latest2026/11/103 天前
0.1.42026/09/132 个月前
0.1.32026/09/082 个月前
0.1.22026/09/082 个月前
0.1.12026/07/223 个月前
0.1.02026/04/206 个月前

关于 @dreamshive/better-auth-tauri 的常见问题

@dreamshive/better-auth-tauri 是什么?

Better Auth plugin for Tauri desktop apps — handles OAuth via the system browser with deep-link callbacks, cookie bridging via URL, and secure token storage hooks.

如何安装 @dreamshive/better-auth-tauri?

在项目目录运行 npm install @dreamshive/better-auth-tauri,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:better-auth(^1.7.16)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dreamshive/better-auth-tauri 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dreamshive/better-auth-tauri 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@dreamshive/better-auth-tauri 可以商用吗?

@dreamshive/better-auth-tauri 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dreamshive/better-auth-tauri 的下载量有多少?

根据 npm 官方下载统计,@dreamshive/better-auth-tauri 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,064 次,日均约 102 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dreamshive/better-auth-tauri 还在维护吗?

最新版本 0.1.5 发布于 2026/11/10(3 天前);至今共发布 6 个版本,其中过去 12 个月发布了 6 个;首次发布于 2026/04/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。