Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .env.tauri
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Tauri 桌面版配置
NEXTAUTH_URL=http://localhost:19898
NEXTAUTH_SECRET=ose-desktop-secret-change-me
AUTH_URL=http://localhost:19898
AUTH_SECRET=ose-desktop-secret-change-me
# AUTH_SECRET and NEXTAUTH_SECRET are generated at runtime and injected by the
# Tauri sidecar startup code. For `tauri dev`, set them in a local .env.local
# file (which is gitignored).
40 changes: 37 additions & 3 deletions docs/desktop-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,43 @@ In production desktop mode, Tauri:
1. Selects an available local port.
2. Creates an app data directory.
3. Sets `DATABASE_URL` to the local SQLite database.
4. Starts `node start.js` — preferring the bundled `runtime/node[.exe]` when present, otherwise `node` from `PATH`.
5. Polls `/api/ai/status` until the Next.js server is ready.
6. Navigates the WebView to `http://127.0.0.1:<port>`.
4. Resolves or generates a per-install auth secret (see [Auth Secret](#auth-secret) below).
5. Starts `node start.js` — preferring the bundled `runtime/node[.exe]` when present, otherwise `node` from `PATH`.
6. Polls `/api/ai/status` until the Next.js server is ready.
7. Navigates the WebView to `http://127.0.0.1:<port>`.

## Auth Secret

Each desktop installation generates a unique auth secret on first launch. The secret is used to sign Auth.js / NextAuth session tokens and is never shared between installs.

### Storage location

The secret is stored in a file named `auth.secret` inside the app data directory:

- **Windows**: `%AppData%\com.ose.softwareexam\auth.secret`
- **macOS**: `~/Library/Application Support/com.ose.softwareexam/auth.secret`
- **Linux**: `~/.local/share/com.ose.softwareexam/auth.secret`

### Format and permissions

The file contains a 44-character Base64 string derived from 32 cryptographically random bytes. On Unix-like systems the file is created with `0600` (owner read/write only) permissions set at creation time, with no intermediate world-readable state.

### Secret reuse across restarts

On subsequent launches the app reads the existing `auth.secret` file and reuses the value. If the file is missing or empty, a new secret is generated automatically.

### Impact of deleting the file

Deleting `auth.secret` causes a new secret to be generated on the next launch. All existing sessions become invalid (users are signed out), but no study data is lost.

### Development mode

For `tauri dev`, `AUTH_SECRET` and `NEXTAUTH_SECRET` are **not** injected automatically. Set them in a local `.env.local` file (which is gitignored):

```env
AUTH_SECRET=any-local-dev-value
NEXTAUTH_SECRET=any-local-dev-value
```

## Portable Zip (Windows)

Expand Down
2 changes: 2 additions & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] }

[dependencies]
base64 = "0.22"
getrandom = "0.2"
portpicker = "0.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Expand Down
54 changes: 54 additions & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use base64::Engine as _;
use std::{
env, fs,
io::{BufRead, BufReader, Write},
Expand Down Expand Up @@ -122,6 +123,7 @@ fn start_next_server(app: &AppHandle) -> Result<u16, String> {
));
}

let auth_secret = resolve_or_create_auth_secret(&data_dir)?;
let port = pick_port()?;
let database_path = data_dir.join("ose.db");
let database_url = format!("file:{}", database_path.to_string_lossy());
Expand All @@ -144,6 +146,8 @@ fn start_next_server(app: &AppHandle) -> Result<u16, String> {
.env("PORT", port.to_string())
.env("HOSTNAME", "127.0.0.1")
.env("DATABASE_URL", database_url)
.env("AUTH_SECRET", &auth_secret)
.env("NEXTAUTH_SECRET", &auth_secret)
.env("AUTH_URL", format!("http://127.0.0.1:{port}"))
.env("NEXTAUTH_URL", format!("http://127.0.0.1:{port}"))
.env("NODE_ENV", "production")
Expand Down Expand Up @@ -370,6 +374,56 @@ where
}
}

fn resolve_or_create_auth_secret(data_dir: &PathBuf) -> Result<String, String> {
let secret_path = data_dir.join("auth.secret");

if secret_path.exists() {
let content = fs::read_to_string(&secret_path)
.map_err(|e| format!("读取 auth.secret 失败:{e}"))?;
let trimmed = content.trim().to_string();
if !trimmed.is_empty() {
return Ok(trimmed);
}
// Empty file — fall through and generate a fresh secret.
}

let mut bytes = [0u8; 32];
getrandom::getrandom(&mut bytes).map_err(|e| format!("生成随机 secret 失败:{e}"))?;
let secret = base64::engine::general_purpose::STANDARD.encode(bytes);
write_secret_atomic(&secret_path, &secret)?;
Ok(secret)
}

#[cfg(unix)]
fn create_secret_file(path: &std::path::Path) -> Result<fs::File, std::io::Error> {
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
}

#[cfg(not(unix))]
fn create_secret_file(path: &std::path::Path) -> Result<fs::File, std::io::Error> {
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
}

fn write_secret_atomic(secret_path: &PathBuf, secret: &str) -> Result<(), String> {
let tmp_path = secret_path.with_file_name("auth.secret.tmp");
// Remove any leftover temp file so create_new(true) can succeed.
let _ = fs::remove_file(&tmp_path);
let mut file = create_secret_file(&tmp_path)
.map_err(|e| format!("创建临时 secret 文件失败:{e}"))?;
file.write_all(secret.as_bytes())
.map_err(|e| format!("写入 secret 失败:{e}"))?;
drop(file);
fs::rename(&tmp_path, secret_path).map_err(|e| format!("移动 secret 文件失败:{e}"))
}

fn show_error_page(window: &WebviewWindow, message: &str) {
let escaped = message
.replace('&', "&amp;")
Expand Down
Loading