tauri-plugin-plauth 1.0.2

Tauri plugin for authentication (PLAUTH) supporting macOS and iOS platforms with ASWebAuthenticationSession
Documentation
# Cursor Rules for Tauri Plugin PLAUTH

## Project Overview

This is a Tauri plugin for authentication (PLAUTH) that currently supports **macOS and iOS platforms only**. The plugin implements ASWebAuthenticationSession for secure web-based authentication flows.

## Code Organization & Structure

### Rust Code Structure

- `src/lib.rs` - Main plugin entry point and exports
- `src/commands.rs` - Tauri command implementations
- `src/models.rs` - Data structures and types
- `src/error.rs` - Error handling and custom error types
- `src/desktop.rs` - macOS-specific implementations
- `src/mobile.rs` - iOS-specific implementations

### Platform-Specific Code

- `ios/` - iOS-specific Swift code with ASWebAuthenticationSession
  - `ios/Sources/PlauthPlugin.swift` - Main iOS implementation
  - `ios/Tests/PluginTests/` - iOS unit tests
  - `ios/Package.swift` - Swift package configuration
- `guest-js/` - JavaScript/TypeScript client code
- **Note**: Android support is not currently implemented

### Examples

- `examples/tauri-app/` - Example Tauri application demonstrating plugin usage on macOS

## Cross-Platform Data Consistency Rules

### CRITICAL: Multi-Layer Data Synchronization

This is a Tauri plugin repository where ANY changes to data structures, interfaces, or commands MUST be synchronized across ALL layers:

#### Data Flow Dependencies

```
guest-js/ (TypeScript interfaces)
    ↓
src/models.rs (Rust data structures)
    ↓
src/commands.rs (Rust command parameters/returns)
    ↓
ios/ (Swift implementations with ASWebAuthenticationSession)
    ↓
build.rs (Command registration)
```

**iOS Implementation Structure:**

- `ios/Sources/PlauthPlugin.swift` - Main plugin implementation
- `ios/Tests/PluginTests/` - Unit tests
- `ios/Package.swift` - Swift package configuration

#### Mandatory Synchronization Checklist

When making ANY changes to:

- **TypeScript interfaces** in `guest-js/`
- **Rust data structures** in `src/models.rs`
- **Command signatures** in `src/commands.rs`
- **Native implementations** in `ios/`
- **New commands** or **modified commands**

You MUST verify and update ALL of the following:

1. **TypeScript Client (`guest-js/`)**

   - Interface definitions
   - Type exports
   - Function signatures
   - Error types

2. **Rust Models (`src/models.rs`)**

   - Struct definitions
   - Serde attributes
   - Type conversions
   - Validation logic

3. **Rust Commands (`src/commands.rs`)**

   - Function signatures
   - Parameter types
   - Return types
   - Error handling

4. **Native Implementations**

   - **iOS (`ios/`)**: Swift structs, function signatures, ASWebAuthenticationSession integration
     - `ios/Sources/PlauthPlugin.swift` - Main implementation
     - `ios/Tests/PluginTests/` - Test coverage
     - `ios/Package.swift` - Package configuration

5. **Build Configuration (`build.rs`)**

   - Command registration
   - Permission definitions
   - Platform-specific configurations (macOS/iOS only)

6. **Permissions (`permissions/`)**

   - Command permissions
   - Schema definitions
   - ACL manifests

7. **Examples (`examples/tauri-app/`)**
   - Usage examples
   - Type imports
   - Function calls

#### Data Type Consistency Rules

- **Naming**: Use identical names across all platforms (following platform conventions)
- **Structure**: Maintain same field structure and types
- **Serialization**: Ensure proper serde attributes for cross-platform serialization
- **Validation**: Implement consistent validation logic
- **Error Handling**: Use consistent error types and messages

#### Command Synchronization Rules

- **Function Names**: Must match across Rust commands and native implementations
- **Parameters**: Same parameter types and order
- **Return Types**: Consistent return types across all layers
- **Error Types**: Unified error handling approach

#### Example Synchronization Pattern

```rust
// 1. Define in src/models.rs
#[derive(Serialize, Deserialize)]
pub struct AuthRequest {
    pub url: String,
    pub callback_url_scheme: String,
    pub presentation_context_provider: Option<String>,
}

// 2. Use in src/commands.rs
#[tauri::command]
pub async fn authenticate(
    app_handle: tauri::AppHandle,
    request: AuthRequest,
) -> Result<AuthResponse, Error> {
    // Implementation
}

// 3. Define in guest-js/index.ts
export interface AuthRequest {
    url: string;
    callback_url_scheme: string;
    presentation_context_provider?: string;
}

// 4. Implement in ios/AuthPlugin.swift
struct AuthRequest: Codable {
    let url: String
    let callbackUrlScheme: String
    let presentationContextProvider: String?
}

// 5. Register in build.rs
// Ensure command is properly registered for macOS/iOS
```

#### Validation Checklist

Before committing ANY changes, verify:

- [ ] TypeScript interfaces match Rust structs
- [ ] Command signatures are consistent across platforms
- [ ] Native implementations use correct data types
- [ ] Build configuration includes new commands
- [ ] Permissions are properly defined
- [ ] Examples are updated
- [ ] Error handling is consistent
- [ ] Serialization/deserialization works correctly

## ASWebAuthenticationSession Implementation Guidelines

### iOS Implementation Requirements

- **ASWebAuthenticationSession**: Use ASWebAuthenticationSession for secure web authentication
- **Presentation Context**: Implement proper presentation context providers
- **Callback Handling**: Handle authentication callbacks and URL schemes correctly
- **Error Handling**: Implement comprehensive error handling for authentication failures
- **Session Management**: Properly manage authentication session lifecycle

### macOS Implementation Requirements

- **WebView Integration**: Use appropriate web view components for desktop authentication
- **Callback Handling**: Implement desktop-specific callback handling
- **Window Management**: Handle authentication windows and dialogs properly

### Authentication Flow Structure

```swift
// iOS Implementation Pattern
class AuthPlugin: NSObject {
    private var authSession: ASWebAuthenticationSession?

    func authenticate(url: String, callbackURLScheme: String) -> Promise<AuthResult> {
        return Promise { resolve, reject in
            let authSession = ASWebAuthenticationSession(
                url: URL(string: url)!,
                callbackURLScheme: callbackURLScheme
            ) { callbackURL, error in
                // Handle authentication result
            }

            authSession.presentationContextProvider = self
            authSession.start()
        }
    }
}
```

## Development Guidelines

### Rust Code Standards

- Use `anyhow` for error handling in command implementations
- Follow Rust naming conventions (snake_case for functions/variables, PascalCase for types)
- Implement proper error types in `src/error.rs`
- Use `serde` for serialization/deserialization
- Add comprehensive documentation comments for public APIs

### Command Implementation Pattern

```rust
#[tauri::command]
pub async fn command_name(
    app_handle: tauri::AppHandle,
    // other parameters
) -> Result<ResponseType, ErrorType> {
    // Implementation
}
```

### Error Handling

- Use custom error types defined in `src/error.rs`
- Return `Result<T, E>` from all command functions
- Provide meaningful error messages
- Handle platform-specific errors appropriately

### Platform-Specific Code

- **macOS**: Implement in `src/desktop.rs` with web view integration
- **iOS**: Implement in `src/mobile.rs` with ASWebAuthenticationSession
- **iOS Native**: Implement in `ios/Sources/PlauthPlugin.swift` with ASWebAuthenticationSession
- Use conditional compilation with `#[cfg(target_os = "macos")]` and `#[cfg(target_os = "ios")]`

### TypeScript/JavaScript Client

- Maintain type safety with proper TypeScript definitions
- Follow async/await patterns for command calls
- Implement proper error handling on the client side
- Use the plugin API consistently

## Testing & Examples

### Example Application

- Keep `examples/tauri-app/` updated with latest plugin features
- Demonstrate authentication flows on macOS
- Include proper error handling examples
- Show authentication callback handling

### Testing Strategy

- Unit tests for Rust code
- Integration tests for command functionality
- Platform-specific tests for macOS/iOS
- Example app should serve as integration test

## Build & Configuration

### Cargo.toml

- Maintain proper dependencies and versions
- Include all necessary features for macOS/iOS platforms
- Keep build scripts updated

### Platform Configuration

- **iOS**: Maintain `ios/` directory structure with ASWebAuthenticationSession
  - `ios/Sources/PlauthPlugin.swift` - Main iOS implementation
  - `ios/Tests/PluginTests/` - iOS unit tests
  - `ios/Package.swift` - Swift package configuration
- **macOS**: Ensure proper web view integration
- Ensure proper permissions and capabilities for authentication

## Documentation

### Code Documentation

- Document all public APIs with `///` comments
- Include usage examples in documentation
- Maintain README.md with setup and usage instructions
- Document platform-specific requirements (macOS/iOS only)

### API Documentation

- Keep `permissions/` directory updated
- Maintain schema definitions
- Document command parameters and return types
- Document authentication flow requirements

## Git Workflow

### Commit Messages

- Use conventional commit format
- Include platform-specific tags when relevant (macOS/iOS)
- Reference issues/PRs when applicable

### Branch Strategy

- `main` - stable releases
- `develop` - development branch
- Feature branches for new functionality
- Platform-specific branches when needed

## Performance & Best Practices

### Memory Management

- Avoid unnecessary allocations in hot paths
- Use proper ownership patterns in Rust
- Minimize data copying between platforms

### Async Operations

- Use async/await consistently
- Handle long-running operations properly
- Implement proper cancellation patterns

### Platform Integration

- Follow platform-specific best practices for macOS/iOS
- Handle platform differences gracefully
- Implement proper fallbacks when possible

## Security Considerations

### Authentication Security

- Implement proper URL validation for authentication URLs
- Handle callback URL schemes securely
- Validate authentication responses
- Implement proper session management

### Input Validation

- Validate all command inputs
- Sanitize data before processing
- Implement proper access controls

### Error Information

- Don't expose sensitive information in error messages
- Log errors appropriately for debugging
- Handle authentication/authorization properly

## Maintenance

### Dependencies

- Keep dependencies updated
- Monitor for security vulnerabilities
- Test thoroughly after dependency updates

### Platform Updates

- Stay current with Tauri updates
- Monitor iOS SDK changes (especially ASWebAuthenticationSession)
- Update platform-specific code as needed

### Code Quality

- Use clippy for Rust code quality
- Maintain consistent formatting
- Regular code reviews and refactoring

## Platform Limitations

### Current Support

- **macOS**: Full support with web view integration
- **iOS**: Full support with ASWebAuthenticationSession
- **Android**: Not currently supported
- **Linux**: Not currently supported
- **Windows**: Not currently supported

### Future Considerations

- Android support may be added in future versions
- Cross-platform authentication standards should be considered
- Maintain extensible architecture for future platform additions