npm package: @rust-true/client
Description: TypeScript SDK for rust-true authentication server
Latest version: 0.1.1

# @rust-true/client

TypeScript SDK for [rust-true](https://github.com/perpetus/rust-true) authentication server with full SSR support and runtime validation.

## Features

- ✨ **Type-Safe** - 130+ auto-generated types from OpenAPI spec
- ✨ **Runtime Validation** - JSON Schema validation before API calls
- ✨ **SSR Ready** - Separate server and browser clients
- ✨ **Framework Support** - First-class support for React, Vue, Next.js, Nuxt.js, and React Router
- ✨ **OAuth Providers** - 20+ social login providers (Google, GitHub, Apple, Discord, and more)
- ✨ **Tree-Shakeable** - Only bundle what you use
- ✨ **Modular Architecture** - Split into Auth, User, Session, and MFA modules
- ✨ **Storage Adapters** - Built-in support for LocalStorage, Cookies, and Memory storage

## Installation

```bash
npm install @rust-true/client
# or
pnpm add @rust-true/client
# or
yarn add @rust-true/client
```

## Quick Start

```typescript
import { createBrowserClient } from '@rust-true/client/browser';

const client = createBrowserClient({
  baseUrl: 'http://localhost:8080',
});

// Sign up
await client.auth.signUp({
  email: 'user@example.com',
  password: 'SecurePassword123!',
});

// Sign in
const { data } = await client.auth.signIn({
  email: 'user@example.com',
  password: 'SecurePassword123!',
});

// Get user
const { data: user } = await client.user.get();
```

## Framework Support

### React

```tsx
import { useRustTrue } from '@rust-true/client/react';

function App() {
  const { user, loading, signIn } = useRustTrue({
    baseUrl: 'http://localhost:8080',
  });

  if (loading) return <div>Loading...</div>;
  
  return user ? (
    <div>Welcome {user.email}!</div>
  ) : (
    <button onClick={() => signIn('email', 'pass')}>Sign In</button>
  );
}
```

### Vue 3

```vue
<script setup>
import { useRustTrue } from '@rust-true/client/vue';

const { user, loading, signIn } = useRustTrue({
  baseUrl: 'http://localhost:8080',
});
</script>

<template>
  <div v-if="loading">Loading...</div>
  <div v-else-if="user">Welcome {{ user.email }}!</div>
  <button v-else @click="signIn('email', 'pass')">Sign In</button>
</template>
```

### Next.js (App Router)

```tsx
import { createServerClient } from '@rust-true/client/server';
import { cookies } from 'next/headers';

export default async function Page() {
  const client = createServerClient({
    baseUrl: process.env.API_URL!,
    getCookie: (name) => cookies().get(name)?.value,
    setCookie: (name, value, options) => {
      cookies().set(name, value, {
        httpOnly: true,
        secure: true,
        sameSite: 'lax',
        ...options,
      });
    },
  });

  const { data: user } = await client.user.get();
  return <div>Welcome {user?.email}</div>;
}
```

### Nuxt.js

```typescript
// plugins/auth.ts
import { createAuthMiddleware } from '@rust-true/client/nuxtjs';

export default defineNuxtPlugin((nuxtApp) => {
  const auth = createAuthMiddleware({
    baseUrl: 'http://localhost:8080'
  });
  
  nuxtApp.vueApp.use(auth);
});
```

### React Router

```tsx
import { createAuthLoader } from '@rust-true/client/react-router';

const router = createBrowserRouter([
  {
    path: "/",
    loader: createAuthLoader({ baseUrl: '...' }),
    element: <Root />,
  },
]);
```

## OAuth Authentication

Sign in with 20+ OAuth providers:

```typescript
// Sign in with Google
await client.auth.signInWithOAuth('google', {
  redirectTo: 'https://yourapp.com/auth/callback',
});

// Sign in with GitHub (with custom scopes)
await client.auth.signInWithOAuth('github', {
  scopes: 'user:email read:org',
});

// Get URL without redirecting (for SSR)
const { data } = await client.auth.signInWithOAuth('discord', {
  skipBrowserRedirect: true,
});
console.log(data.url); // Use URL manually
```

### Supported Providers

| Provider | Provider | Provider | Provider |
|----------|----------|----------|----------|
| Google | GitHub | Apple | Facebook |
| Twitter | Discord | Slack | LinkedIn |
| GitLab | Spotify | Twitch | Notion |
| Azure | Zoom | Figma | Bitbucket |
| Keycloak | WorkOS | Snapchat | SAML |

## Core Modules

The client is organized into focused modules:

- **AuthModule** (`client.auth`): Handle authentication flows (signup, login, logout, password recovery, OTP, OAuth).
- **UserModule** (`client.user`): Manage user profile and settings.
- **SessionModule** (`client.session`): Inspect and manage active sessions.
- **MfaModule** (`client.mfa`): Setup and verify Multi-Factor Authentication (TOTP).

## Storage Adapters

The SDK supports various storage strategies:

- **LocalStorage**: Default for browser environments.
- **CookieStorage**: Default for server/SSR environments.
- **MemoryStorage**: Useful for testing or non-persistent sessions.

You can also implement your own `StorageAdapter` interface for custom storage solutions.

## Runtime Validation

All API requests are automatically validated against JSON schemas at runtime to ensure data integrity before sending requests.

```typescript
import { ValidationException } from '@rust-true/client';

try {
  await client.auth.signUp({
    email: 'invalid-email',  // ❌ Will throw ValidationException
    password: '',             // ❌ Will throw ValidationException
  });
} catch (error) {
  if (error instanceof ValidationException) {
    console.log(error.errors); // Detailed validation errors
  }
}
```

## License

MIT

## Contributing

Contributions welcome! Please open an issue or PR at [https://github.com/perpetus/rust-true-js](https://github.com/perpetus/rust-true-js).