npm package: @meistrari/auth-core
Description: A TypeScript/JavaScript SDK for interacting with the Auth API service.
Latest version: 1.15.0

# Identity Provider SDK - Core

A TypeScript/JavaScript SDK for interacting with the Auth API service.

## Features

- **Multiple Authentication Methods**
  - Social providers (Google, Microsoft)
  - SAML-based SSO
  - Email and password
- **Organization Management**
  - Multi-tenant support
  - Role-based access control (RBAC)
  - Team management
  - Member invitations
- **JWT Token Validation**

## Installation

```bash
npm install @meistrari/auth-core
```

## Quick Start

```typescript
import { AuthClient } from '@meistrari/auth-core'

// Initialize the client
const authClient = new AuthClient('https://auth.example.com')

// Sign in with email and password
await authClient.session.signInWithEmailAndPassword({
    email: 'user@example.com',
    password: 'SecurePassword123!'
})

// List user's organizations
const organizations = await authClient.organization.listOrganizations()
console.log('Organizations:', organizations)
```

## API Reference

### AuthClient

The main entry point for the SDK. Provides access to session and organization services.

#### Constructor

```typescript
new AuthClient(apiUrl: string, headers?: Record<string, string>)
```

**Parameters:**
- `apiUrl` - The base URL of the Auth API
- `headers` (optional) - Custom headers to include in all requests

**Example:**
```typescript
const authClient = new AuthClient('https://auth.example.com', {
    'X-Custom-Header': 'value'
})
```

### Session Management

Access via `authClient.session`

#### signInWithEmailAndPassword

Authenticates a user with email and password credentials.

```typescript
await authClient.session.signInWithEmailAndPassword({
    email: 'user@example.com',
    password: 'password123'
})
```

#### signInWithSocialProvider

Initiates social authentication flow with Google or Microsoft.

```typescript
await authClient.session.signInWithSocialProvider({
    provider: 'google', // or 'microsoft'
    callbackURL: 'https://app.example.com/callback',
    errorCallbackURL: 'https://app.example.com/error', // optional
})
```

The error callback URL receives an `error` query parameter with the error status text.

#### signInWithSaml

Initiates SAML-based Single Sign-On authentication flow.

```typescript
await authClient.session.signInWithSaml({
    email: 'user@company.com',
    callbackURL: 'https://app.example.com/callback',
    errorCallbackURL: 'https://app.example.com/error', // optional
})
```

The error callback URL receives an `error` query parameter with the error status text.

#### signOut

Signs out the currently authenticated user.

```typescript
// Simple sign out
await authClient.session.signOut()

// Sign out with callback
await authClient.session.signOut(() => {
    console.log('User signed out')
    window.location.href = '/login'
})
```

#### requestPasswordReset

Initiates a password reset request.

```typescript
await authClient.session.requestPasswordReset(
    'user@example.com',
    'https://app.example.com/reset-password'
)
```

#### resetPassword

Completes the password reset process.

```typescript
await authClient.session.resetPassword(
    'reset-token-from-email',
    'NewSecurePassword123!'
)
```

### Organization Management

Access via `authClient.organization`

#### listOrganizations

Lists all organizations accessible to the current user.

```typescript
const organizations = await authClient.organization.listOrganizations()
```

#### getOrganization

Retrieves a single organization with teams, invites and members.

```typescript
const organization = await authClient.organization.getOrganization('org-123')
```

#### setActiveOrganization

Sets the active organization for the current user session.

```typescript
await authClient.organization.setActiveOrganization('org-123')
```

#### updateOrganization

Updates an organization's details.

```typescript
const updated = await authClient.organization.updateOrganization({
    name: 'New Organization Name',
    logo: 'https://example.com/logo.png',
    settings: {
        disableStorage: true,
        dataRetentionHours: 24
    }
})
```

### Member Management

#### listMembers

Lists members of the active organization.

```typescript
const members = await authClient.organization.listMembers({
    limit: 10,
    offset: 0
})
```

#### getActiveMember

Gets the currently active organization member for the authenticated user.

```typescript
const activeMember = await authClient.organization.getActiveMember()
console.log(`Role: ${activeMember.role}`)
```

#### inviteUserToOrganization

Invites a user to join the active organization.

```typescript
import { Roles } from '@meistrari/auth-core'

await authClient.organization.inviteUserToOrganization({
    userEmail: 'newuser@example.com',
    role: Roles.ORG_MEMBER,
    teamId: 'team-123' // optional
})
```

#### acceptInvitation

Accepts an organization invitation.

```typescript
await authClient.organization.acceptInvitation('invitation-123')
```

#### cancelInvitation

Cancels a pending invitation.

```typescript
await authClient.organization.cancelInvitation('invitation-123')
```

#### removeUserFromOrganization

Removes a user from the active organization.

```typescript
// Remove by member ID
await authClient.organization.removeUserFromOrganization({
    memberId: 'member-123'
})

// Remove by email
await authClient.organization.removeUserFromOrganization({
    userEmail: 'user@example.com'
})
```

#### updateMemberRole

Updates the role of an organization member.

```typescript
import { Roles } from '@meistrari/auth-core'

await authClient.organization.updateMemberRole({
    memberId: 'member-123',
    role: Roles.ORG_ADMIN
})
```

### Team Management

#### listTeams

Lists all teams in the active organization.

```typescript
const teams = await authClient.organization.listTeams()
```

#### createTeam

Creates a new team.

```typescript
const team = await authClient.organization.createTeam({
    name: 'Engineering Team'
})
```

#### updateTeam

Updates a team's details.

```typescript
const updated = await authClient.organization.updateTeam('team-123', {
    name: 'Updated Team Name'
})
```

#### deleteTeam

Deletes a team.

```typescript
await authClient.organization.deleteTeam('team-123')
```

#### listTeamMembers

Lists all members of a specific team.

```typescript
const members = await authClient.organization.listTeamMembers('team-123')
```

#### addTeamMember

Adds a user to a team.

```typescript
await authClient.organization.addTeamMember('team-123', 'user-456')
```

#### removeTeamMember

Removes a user from a team.

```typescript
await authClient.organization.removeTeamMember('team-123', 'user-456')
```

### Token Validation

Standalone utility functions for JWT token validation.

#### isTokenExpired

Checks if a JWT token has expired.

```typescript
import { isTokenExpired } from '@meistrari/auth-core'

const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'
if (isTokenExpired(token)) {
    console.log('Token has expired')
}
```

#### validateToken

Validates a JWT token by checking expiration and verifying signature.

```typescript
import { validateToken } from '@meistrari/auth-core'

const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'
const isValid = await validateToken(token, 'https://auth.example.com')

if (isValid) {
    console.log('Token is valid')
}
```

## Roles and Permissions

The SDK provides predefined organization roles with specific permissions:

```typescript
import { Roles } from '@meistrari/auth-core'

// Available roles
Roles.ORG_ADMIN // Full access: org updates, team/member management, invitations
Roles.ORG_MEMBER // Basic member access
Roles.ORG_REVIEWER // Read-only reviewer access
```

## Error Handling

The SDK provides typed error classes for better error handling:

### BaseError

Base class for all SDK errors with a `code` property.

```typescript
import { BaseError } from '@meistrari/auth-core'

try {
    // SDK operation
}
catch (error) {
    if (error instanceof BaseError) {
        console.log(`Error code: ${error.code}`)
        console.log(`Error message: ${error.message}`)
    }
}
```

### Specific Error Classes

- **InvalidSocialProvider** - Invalid social provider specified
- **InvalidCallbackURL** - Malformed callback URL
- **EmailRequired** - Email parameter required but not provided
- **APIError** (BetterFetchError) - API request failed

```typescript
import {
    InvalidSocialProvider,
    InvalidCallbackURL,
    EmailRequired,
    APIError
} from '@meistrari/auth-core'

try {
    await authClient.session.signInWithSocialProvider({
        provider: 'invalid' as any,
        callbackURL: 'https://app.example.com/callback'
    })
}
catch (error) {
    if (error instanceof InvalidSocialProvider) {
        console.log('Invalid provider specified')
    }
}
```

## Type Definitions

The SDK exports TypeScript types for all data structures:

```typescript
import type {
    User,
    Session,
    Organization,
    Member,
    Invitation,
    Team,
    TeamMember,
    Role
} from '@meistrari/auth-core'
```